πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(dashboard): chart polish, hover interactivity, and cross-chart sync (LFE-10549) (#14618)
Nikita Kabardine88146ff1675
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.mdindex aa2fa18481..7537e605d4 100644--- a/.agents/AGENTS.md+++ b/.agents/AGENTS.md@@ -26,6 +26,10 @@ evaluating, and debugging AI applications.cross-view extension playbook β the bar is intended to become the primaryfilter interface for every filterable view, so new filtering work extends itthrough that contract rather than forking it.+- When adding or modifying any chart, dashboard, or chart formatter, read+ `web/src/features/widgets/chart-library/ARCHITECTURE.md` first β the charts+ manifesto. It owns the data β preparer β visualiser contract: presentation+ decisions live in the preparer, not the chart components.- Do not add or widen ESLint disable comments or config overrideswithout explicit user approval for the exact rule and scope.- Always quote file paths in shell commands, or use `noglob` for path-heavydiff --git a/packages/shared/scripts/seeder/utils/clickhouse-builder.ts b/packages/shared/scripts/seeder/utils/clickhouse-builder.tsindex 5f3fa217e2..83e4bfdc73 100644--- a/packages/shared/scripts/seeder/utils/clickhouse-builder.ts+++ b/packages/shared/scripts/seeder/utils/clickhouse-builder.ts@@ -129,7 +129,7 @@ export class ClickHouseQueryBuilder {SELECTconcat('${idPrefix}trace-bulk-', toString(number), '-${idSuffix}') AS id,toDateTime(${anchorSeconds} - intDiv(number * ${spreadSeconds}, ${Math.max(count, 1)})) AS timestamp,- concat('trace-', toString(number % 10)) AS name,+ arrayElement(['chat-completion','summarize-document','extract-entities','embed-documents','classify-intent','generate-title','translate-text','moderate-content','rerank-results','answer-question'], 1 + (number % 10)) AS name,if(h1 % 10 < 3, concat('${idPrefix}user_', toString(h1 % 1000)), NULL) AS user_id,${this.buildNestedMetadataMapSql(["'generated'", "'bulk'"])} AS metadata,NULL AS release,@@ -242,7 +242,10 @@ export class ClickHouseQueryBuilder {if(type = 'GENERATION',if(h2 % 10 >= 7, '${escapedNestedJson}', '${escapedChatMl}'),NULL) AS output,- if(type = 'GENERATION', 'gpt-4', NULL) AS provided_model_name,+ -- Spread generations across a realistic model pool (keyed on the stable+ -- per-row hash h4) so model-usage / cost / latency-by-model dashboards+ -- show multiple series instead of a single hardcoded model.+ if(type = 'GENERATION', arrayElement(['gpt-4o-mini','gpt-3.5-turbo','claude-3-haiku-20240307','gpt-4o','claude-3-5-sonnet-20241022'], 1 + (h4 % 5)), NULL) AS provided_model_name,NULL AS internal_model_id,if(type = 'GENERATION', '{"temperature": 0.7}', '{}') AS model_parameters,if(type = 'GENERATION', map('input', toUInt64(20 + h1 % 181), 'output', toUInt64(10 + h2 % 91), 'total', toUInt64(30 + h1 % 181 + h2 % 91)), map()) AS provided_usage_details,@@ -288,7 +291,8 @@ export class ClickHouseQueryBuilder {number,xxHash32(toUInt64(number * 4 + ${seedSalt})) AS h1,xxHash32(toUInt64(number * 4 + 1 + ${seedSalt})) AS h2,- xxHash32(toUInt64(number * 4 + 2 + ${seedSalt})) AS h3+ xxHash32(toUInt64(number * 4 + 2 + ${seedSalt})) AS h3,+ xxHash32(toUInt64(number * 4 + 3 + ${seedSalt})) AS h4FROM numbers(${totalObservations}));`;diff --git a/web/.storybook/preview.tsx b/web/.storybook/preview.tsxindex 4d24431fc9..c29f2a3982 100644--- a/web/.storybook/preview.tsx+++ b/web/.storybook/preview.tsx@@ -1,6 +1,14 @@import { definePreview } from "@storybook/nextjs-vite";import addonA11y from "@storybook/addon-a11y";-import { useEffect, type ReactNode } from "react";+import addonDocs from "@storybook/addon-docs";+import { DocsContainer } from "@storybook/addon-docs/blocks";+import { themes } from "storybook/theming";+import {+ useEffect,+ useState,+ type ComponentProps,+ type ReactNode,+} from "react";import { TooltipProvider } from "../src/components/ui/tooltip";import { MarkdownContextProvider } from "../src/features/theming/useMarkdownContext";import { LAYER_ORDER } from "../src/components/ui/layer";@@ -13,9 +21,17 @@ import "streamdown/styles.css";function StorybookThemeProvider({children,theme,+ fullHeight,}: {children?: ReactNode;theme: "light" | "dark";+ /**+ * Give `#__next` a real viewport height so the app's `height: 100%` chains+ * resolve (canvas/story view). In docs view this must be OFF, or every inline+ * story block stretches to 100vh and leaves a tall empty gap below its+ * content. (LFE-10549)+ */+ fullHeight: boolean;}) {useEffect(() => {document.documentElement.classList.toggle("dark", theme === "dark");@@ -37,7 +53,7 @@ function StorybookThemeProvider({<divid="__next"className="bg-background text-foreground"- style={{ height: "100vh" }}+ style={{ height: fullHeight ? "100vh" : "auto" }}><div>{children}</div></div>@@ -56,8 +72,48 @@ function StorybookThemeProvider({);}+/**+ * Docs/guide pages render outside the story decorator, so they don't get our+ * theme β Storybook's own docs theme is light and makes prose unreadable in+ * dark mode (and the page stays white). This container switches Storybook's+ * docs theme to match the app's `.dark` class (which the story decorators+ * toggle on <html>), so every guide's prose, chrome, and example cards follow+ * the theme. It also bumps the base type β the default docs body is too small.+ * (LFE-10549)+ */+function ThemedDocsContainer({+ context,+ children,+}: {+ context: ComponentProps<typeof DocsContainer>["context"];+ children?: ReactNode;+}) {+ const [dark, setDark] = useState(false);+ useEffect(() => {+ const root = document.documentElement;+ const sync = () => setDark(root.classList.contains("dark"));+ sync();+ const observer = new MutationObserver(sync);+ observer.observe(root, { attributes: true, attributeFilter: ["class"] });+ return () => observer.disconnect();+ }, []);++ return (+ <DocsContainer context={context} theme={dark ? themes.dark : themes.light}>+ <style>{`+ .sbdocs-content { font-size: 16px; }+ .sbdocs-content p, .sbdocs-content li { font-size: 1.0625rem; line-height: 1.7; }+ `}</style>+ {children}+ </DocsContainer>+ );+}+export default definePreview({- addons: [addonA11y()],+ // addonDocs() registers the docs preview renderer (parameters.docs.renderer)+ // that MDX pages and autodocs need; the CSF-factory preview must compose it+ // explicitly (the main.ts addons entry only wires the manager/preset side).+ addons: [addonA11y(), addonDocs()],globalTypes: {theme: {description: "Global theme for components",@@ -80,7 +136,10 @@ export default definePreview({const theme = context.globals.theme === "dark" ? "dark" : "light";return (- <StorybookThemeProvider theme={theme}>+ <StorybookThemeProvider+ theme={theme}+ fullHeight={context.viewMode !== "docs"}+ >{/* MarkdownContextProvider mirrors the app: pages render inside it sothe JSON/IO viewers (CodeJsonViewer's JSONView callsuseMarkdownContext) work identically to production. Without it,@@ -98,5 +157,8 @@ export default definePreview({a11y: {test: "todo",},+ docs: {+ container: ThemedDocsContainer,+ },},});diff --git a/web/AGENTS.md b/web/AGENTS.mdindex fea86437ad..6ad6a8b6c2 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -77,6 +77,11 @@ changes.## Web Conventions+- **Before adding or modifying a chart, dashboard, or chart formatter, read+ `src/features/widgets/chart-library/ARCHITECTURE.md` first** β the charts+ manifesto. It owns the data β preparer β visualiser contract: presentation+ decisions (formatting, colors, axis scale, overload) live in the preparer,+ not the chart components.- Put net-new feature code under `src/features/<feature>/*`; put broadly reusablecomponents under `src/components/*`.- We use tRPC for full-stack web features; register routers indiff --git a/web/src/components/ui/chart.tsx b/web/src/components/ui/chart.tsxindex 20db04f393..2cea9d4265 100644--- a/web/src/components/ui/chart.tsx+++ b/web/src/components/ui/chart.tsx@@ -9,6 +9,7 @@ import type {} from "recharts";import { cn } from "@/src/utils/tailwind";+import { Layer } from "@/src/components/ui/layer";// Format: { THEME_NAME: CSS_SELECTOR }const THEMES = { light: "", dark: ".dark" } as const;@@ -150,6 +151,8 @@ const ChartTooltipContent = React.forwardRef<valueFormatter?: (value: number) => string;nameFormatter?: (name: string) => string;sortPayloadByValue?: "asc" | "desc";+ /** dataKeys to emphasize (e.g. the hover-proximity series); their rows are bolded. */+ highlightedKeys?: ReadonlySet<string>;}>((@@ -170,6 +173,7 @@ const ChartTooltipContent = React.forwardRef<valueFormatter,nameFormatter,sortPayloadByValue,+ highlightedKeys,},ref,) => {@@ -244,13 +248,16 @@ const ChartTooltipContent = React.forwardRef<getFillColor(item.payload) ||item.color ||"currentColor";+ const highlighted =+ highlightedKeys?.has(String(item.dataKey ?? item.name ?? "")) ??+ false;return (<divkey={String(item.dataKey ?? item.name ?? index)}className={cn(- "[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",- indicator === "dot" && "items-center",+ "[&>svg]:text-muted-foreground flex w-full items-center gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",+ highlighted && "bg-muted -mx-1.5 rounded px-1.5",)}>{formatter && item?.value !== undefined && item.name != null ? (@@ -266,8 +273,11 @@ const ChartTooltipContent = React.forwardRef<"border-border shrink-0 rounded-[2px] bg-(--color-bg)",{"h-2.5 w-2.5": indicator === "dot",- "w-1": indicator === "line",- "w-0 border-[1.5px] border-dashed bg-transparent":+ // line/dashed need an explicit height: the row is+ // items-center, so a height-less swatch collapses+ // to 0px and the series color is invisible.+ "h-2.5 w-1": indicator === "line",+ "h-2.5 w-0 border-[1.5px] border-dashed bg-transparent":indicator === "dashed","my-0.5": nestLabel && indicator === "dashed",},@@ -283,13 +293,18 @@ const ChartTooltipContent = React.forwardRef<)}<divclassName={cn(- "flex flex-1 justify-between gap-x-2 leading-none",+ "flex min-w-0 flex-1 justify-between gap-x-3 leading-none",nestLabel ? "items-end" : "items-center",)}>- <div className="grid gap-1.5">+ <div className="grid min-w-0 gap-1.5">{nestLabel ? tooltipLabel : null}- <span className="text-muted-foreground">+ <span+ className={cn(+ "text-muted-foreground truncate",+ highlighted && "text-foreground font-medium",+ )}+ >{nameFormatter? nameFormatter(String(item.name ?? item.dataKey ?? ""),@@ -298,7 +313,7 @@ const ChartTooltipContent = React.forwardRef<</span></div>{item.value !== undefined && item.value !== null && (- <span className="text-foreground font-mono font-medium tabular-nums">+ <span className="text-foreground shrink-0 font-mono font-medium whitespace-nowrap tabular-nums">{valueFormatter? valueFormatter(Number(item.value)): item.value.toLocaleString()}@@ -317,6 +332,67 @@ const ChartTooltipContent = React.forwardRef<);ChartTooltipContent.displayName = "ChartTooltip";+/**+ * Renders a chart tooltip into the app's `tooltip` overlay layer (see+ * `ui/layer.tsx`) so it escapes the chart card's `overflow` clipping and always+ * paints on top β never cut off at the chart frame. Positioned at the hovered+ * point (recharts' `coordinate`, relative to the chart box) translated to screen+ * coordinates, and flipped to the left near the right edge of the viewport.+ * (LFE-10549)+ */+function ChartTooltipPortal({+ active,+ coordinate,+ anchorRef,+ children,+}: {+ active?: boolean;+ coordinate?: { x?: number; y?: number };+ anchorRef: React.RefObject<HTMLElement | null>;+ children: React.ReactNode;+}) {+ if (+ !active ||+ !coordinate ||+ coordinate.x == null ||+ coordinate.y == null ||+ typeof window === "undefined"+ ) {+ return null;+ }+ const anchor = anchorRef.current;+ if (!anchor) return null;+ const rect = anchor.getBoundingClientRect();+ const x = rect.left + coordinate.x;+ const y = rect.top + coordinate.y;+ // Flip past the cursor near the right edge; anchor the tooltip's bottom/top to+ // the point near the viewport's bottom/top so a tall multi-series tooltip can't+ // spill its rows out of view (the overlay layer no longer clips it). (LFE-10549)+ const flipLeft = x > window.innerWidth * 0.6;+ const translateY =+ y > window.innerHeight * 0.65+ ? "-100%"+ : y < window.innerHeight * 0.2+ ? "0%"+ : "-50%";++ return (+ <Layer name="tooltip">+ <div+ style={{+ position: "fixed",+ left: x,+ top: y,+ transform: `translate(${flipLeft ? "calc(-100% - 14px)" : "14px"}, ${translateY})`,+ pointerEvents: "none",+ }}+ >+ {children}+ </div>+ </Layer>+ );+}+type ChartLegendProps = React.ComponentProps<typeof RechartsPrimitive.Legend>;function ChartLegend({ itemSorter = null, ...props }: ChartLegendProps) {@@ -349,6 +425,9 @@ function ChartActiveReferenceLine({strokeOpacity={strokeOpacity}ifOverflow="extendDomain"zIndex={zIndex}+ // The crosshair must never intercept pointer events, otherwise it creates+ // a dead "no-hover" strip down the middle of the hovered bar/point. (LFE-10549)+ style={{ pointerEvents: "none" }}/>);}@@ -411,6 +490,7 @@ export {ChartContainer,ChartTooltip,ChartTooltipContent,+ ChartTooltipPortal,ChartLegend,ChartActiveReferenceLine,useChart,diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsxindex 0334286eaa..79f6e09616 100644--- a/web/src/features/dashboard/components/ChartScores.tsx+++ b/web/src/features/dashboard/components/ChartScores.tsx@@ -1,3 +1,4 @@+import { useMemo } from "react";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { type ScoreDataTypeType, type FilterState } from "@langfuse/shared";import {@@ -18,6 +19,14 @@ import { Chart } from "@/src/features/widgets/chart-library/Chart";import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";+// Static β hoisted so its reference is stable across re-renders (keeps the+// memoized <Chart> from reconciling on dashboard scheduler re-renders).+const SCORES_CHART_CONFIG = {+ type: "LINE_TIME_SERIES",+ show_data_point_dots: false,+ subtle_fill: true,+} as const;+export function ChartScores(props: {className?: string;agg: DashboardDateRangeAggregationOption;@@ -28,6 +37,7 @@ export function ChartScores(props: {isLoading?: boolean;metricsVersion?: ViewVersion;schedulerId?: string;+ syncId?: string;}) {const scoresQuery: QueryType = {view: "scores-numeric",@@ -63,27 +73,42 @@ export function ChartScores(props: {},);- const extractedScores = scores.data- ? fillMissingValuesAndTransform(- extractTimeSeriesData(scores.data as DatabaseRow[], "time_dimension", [- {- uniqueIdentifierColumns: [- {- accessor: "data_type",- formatFct: (value) =>- getScoreDataTypeIcon(value as ScoreDataTypeType),- },- { accessor: "name" },- {- accessor: "source",- formatFct: (value) => `(${value.toLowerCase()})`,- },- ],- valueColumn: "avg_value",- },- ]),- )- : [];+ // Memoize the transform on the (scheduler-stable) query result so the chart's+ // data prop keeps a stable reference across dashboard re-renders. (LFE-10549)+ const extractedScores = useMemo(+ () =>+ scores.data+ ? fillMissingValuesAndTransform(+ extractTimeSeriesData(+ scores.data as DatabaseRow[],+ "time_dimension",+ [+ {+ uniqueIdentifierColumns: [+ {+ accessor: "data_type",+ formatFct: (value) =>+ getScoreDataTypeIcon(value as ScoreDataTypeType),+ },+ { accessor: "name" },+ {+ accessor: "source",+ formatFct: (value) => `(${value.toLowerCase()})`,+ },+ ],+ valueColumn: "avg_value",+ },+ ],+ ),+ )+ : [],+ [scores.data],+ );++ const chartData = useMemo(+ () => timeSeriesToDataPoints(extractedScores),+ [extractedScores],+ );return (<DashboardCard@@ -96,14 +121,11 @@ export function ChartScores(props: {<div className="min-h-80"><ChartchartType="LINE_TIME_SERIES"- data={timeSeriesToDataPoints(extractedScores, props.agg)}+ data={chartData}rowLimit={100}- chartConfig={{- type: "LINE_TIME_SERIES",- show_data_point_dots: false,- subtle_fill: true,- }}+ chartConfig={SCORES_CHART_CONFIG}legendPosition="above"+ syncId={props.syncId}/></div>) : (diff --git a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsxnew file mode 100644index 0000000000..62cc115ed3--- /dev/null+++ b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx@@ -0,0 +1,62 @@+import React, { useMemo } from "react";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { type TimeSeriesChartDataPoint } from "@/src/features/dashboard/components/hooks";+import { type LegendSummaryMode } from "@/src/features/widgets/chart-library/chart-props";++/**+ * Memoized LINE_TIME_SERIES card shared by the dashboard time-series panels.+ *+ * Building `data`/`config`/`chartConfig` inline at each call site produced fresh+ * object literals on every render, which defeated `Chart`'s `React.memo` β and+ * the dashboard query scheduler re-renders the whole page on every queue tick,+ * so the chart subtree reconciled needlessly each time. Centralizing it here,+ * keyed on the raw series plus the primitive label/unit/etc., lets the memo bail+ * whenever nothing actually changed. Callers must pass a STABLE `data` reference+ * (memoize the upstream transform) for the bail to take effect. (LFE-10549)+ */+export const DashboardLineTimeSeriesChart = React.memo(+ function DashboardLineTimeSeriesChart({+ data,+ label,+ unit,+ legendSummary,+ syncId,+ subtleFill,+ }: {+ data: TimeSeriesChartDataPoint[];+ label?: string;+ unit?: string;+ legendSummary?: LegendSummaryMode;+ syncId?: string;+ subtleFill?: boolean;+ }) {+ const points = useMemo(() => timeSeriesToDataPoints(data), [data]);+ const config = useMemo(+ () => (label ? { metric: { label } } : undefined),+ [label],+ );+ const chartConfig = useMemo(+ () => ({+ type: "LINE_TIME_SERIES" as const,+ unit,+ show_data_point_dots: false,+ subtle_fill: subtleFill,+ }),+ [unit, subtleFill],+ );++ return (+ <Chart+ chartType="LINE_TIME_SERIES"+ data={points}+ config={config}+ rowLimit={100}+ chartConfig={chartConfig}+ legendPosition="above"+ legendSummary={legendSummary}+ syncId={syncId}+ />+ );+ },+);diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsxindex c90580a1fe..38f6a7ddcb 100644--- a/web/src/features/dashboard/components/LatencyChart.tsx+++ b/web/src/features/dashboard/components/LatencyChart.tsx@@ -18,9 +18,9 @@ import {import { type QueryType, type ViewVersion } from "@langfuse/shared/query";import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";import type { DatabaseRow } from "@/src/server/api/services/sqlInterface";-import { Chart } from "@/src/features/widgets/chart-library/Chart";-import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { DashboardLineTimeSeriesChart } from "@/src/features/dashboard/components/DashboardLineTimeSeriesChart";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";+import { useMemo } from "react";export const GenerationLatencyChart = ({className,@@ -32,6 +32,7 @@ export const GenerationLatencyChart = ({isLoading = false,metricsVersion,schedulerId,+ syncId,}: {className?: string;projectId: string;@@ -42,6 +43,7 @@ export const GenerationLatencyChart = ({isLoading?: boolean;metricsVersion?: ViewVersion;schedulerId?: string;+ syncId?: string;}) => {const {allModels,@@ -116,46 +118,33 @@ export const GenerationLatencyChart = ({},);- const getData = (valueColumn: string) => {- return latencies.data && selectedModels.length > 0- ? fillMissingValuesAndTransform(- extractTimeSeriesData(- latencies.data as DatabaseRow[],- "time_dimension",- [- {- uniqueIdentifierColumns: [{ accessor: "providedModelName" }],- valueColumn: valueColumn,- },- ],- ),- selectedModels,- )- : [];- };-- const data = [- {- tabTitle: "50th Percentile",- data: getData("p50_latency"),- },- {- tabTitle: "75th Percentile",- data: getData("p75_latency"),- },- {- tabTitle: "90th Percentile",- data: getData("p90_latency"),- },- {- tabTitle: "95th Percentile",- data: getData("p95_latency"),- },- {- tabTitle: "99th Percentile",- data: getData("p99_latency"),- },- ];+ // Memoized on the raw query result + model selection so each series ref is+ // stable across the scheduler's page re-renders (lets the chart memo bail).+ const data = useMemo(() => {+ const getData = (valueColumn: string) =>+ latencies.data && selectedModels.length > 0+ ? fillMissingValuesAndTransform(+ extractTimeSeriesData(+ latencies.data as DatabaseRow[],+ "time_dimension",+ [+ {+ uniqueIdentifierColumns: [{ accessor: "providedModelName" }],+ valueColumn: valueColumn,+ },+ ],+ ),+ selectedModels,+ )+ : [];+ return [+ { tabTitle: "50th Percentile", data: getData("p50_latency") },+ { tabTitle: "75th Percentile", data: getData("p75_latency") },+ { tabTitle: "90th Percentile", data: getData("p90_latency") },+ { tabTitle: "95th Percentile", data: getData("p95_latency") },+ { tabTitle: "99th Percentile", data: getData("p99_latency") },+ ];+ }, [latencies.data, selectedModels]);return (<DashboardCard@@ -186,21 +175,11 @@ export const GenerationLatencyChart = ({<>{!isEmptyTimeSeries({ data: item.data }) ? (<div className="h-80 w-full shrink-0">- <Chart- chartType="LINE_TIME_SERIES"- data={timeSeriesToDataPoints(item.data, agg)}- config={{- metric: {- label: "Latency",- },- }}- rowLimit={100}- chartConfig={{- type: "LINE_TIME_SERIES",- unit: "millisecond",- show_data_point_dots: false,- }}- legendPosition="above"+ <DashboardLineTimeSeriesChart+ data={item.data}+ label="Latency"+ unit="millisecond"+ syncId={syncId}/></div>) : (diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsxindex e91204cce0..99fa49227f 100644--- a/web/src/features/dashboard/components/ModelUsageChart.tsx+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx@@ -22,9 +22,9 @@ import {import { type QueryType, type ViewVersion } from "@langfuse/shared/query";import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";-import { Chart } from "@/src/features/widgets/chart-library/Chart";-import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { DashboardLineTimeSeriesChart } from "@/src/features/dashboard/components/DashboardLineTimeSeriesChart";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";+import { useMemo } from "react";export const ModelUsageChart = ({className,@@ -37,6 +37,7 @@ export const ModelUsageChart = ({isLoading = false,metricsVersion,schedulerId,+ syncId,}: {className?: string;projectId: string;@@ -48,6 +49,7 @@ export const ModelUsageChart = ({isLoading?: boolean;metricsVersion?: ViewVersion;schedulerId?: string;+ syncId?: string;}) => {const {allModels,@@ -221,65 +223,80 @@ export const ModelUsageChart = ({},);- const costByType =- queryCostByType.data && allModels.length > 0- ? fillMissingValuesAndTransform(- extractTimeSeriesData(queryCostByType.data, "intervalStart", [- {- uniqueIdentifierColumns: [{ accessor: "key" }],- valueColumn: "sum",- },- ]),- [],- )- : [];-- const unitsByType =- queryUsageByType.data && allModels.length > 0- ? fillMissingValuesAndTransform(- extractTimeSeriesData(queryUsageByType.data, "intervalStart", [- {- uniqueIdentifierColumns: [{ accessor: "key" }],- valueColumn: "sum",- },- ]),- [],- )- : [];-- const unitsByModel =- queryResult.data && allModels.length > 0- ? fillMissingValuesAndTransform(- extractTimeSeriesData(- queryResult.data as DatabaseRow[],- "time_dimension",- [+ // Each series is memoized on its raw query result (+ model selection) so the+ // reference stays stable across the scheduler's page re-renders β that's what+ // lets the chart's React.memo bail. (LFE-10549)+ const costByType = useMemo(+ () =>+ queryCostByType.data && allModels.length > 0+ ? fillMissingValuesAndTransform(+ extractTimeSeriesData(queryCostByType.data, "intervalStart", [{- uniqueIdentifierColumns: [{ accessor: "providedModelName" }],- valueColumn: "sum_totalTokens",+ uniqueIdentifierColumns: [{ accessor: "key" }],+ valueColumn: "sum",},- ],- ),- selectedModels,- )- : [];+ ]),+ [],+ )+ : [],+ [queryCostByType.data, allModels],+ );- const costByModel =- queryResult.data && allModels.length > 0- ? fillMissingValuesAndTransform(- extractTimeSeriesData(- queryResult.data as DatabaseRow[],- "time_dimension",- [+ const unitsByType = useMemo(+ () =>+ queryUsageByType.data && allModels.length > 0+ ? fillMissingValuesAndTransform(+ extractTimeSeriesData(queryUsageByType.data, "intervalStart", [{- uniqueIdentifierColumns: [{ accessor: "providedModelName" }],- valueColumn: "sum_totalCost",+ uniqueIdentifierColumns: [{ accessor: "key" }],+ valueColumn: "sum",},- ],- ),- selectedModels,- )- : [];+ ]),+ [],+ )+ : [],+ [queryUsageByType.data, allModels],+ );++ const unitsByModel = useMemo(+ () =>+ queryResult.data && allModels.length > 0+ ? fillMissingValuesAndTransform(+ extractTimeSeriesData(+ queryResult.data as DatabaseRow[],+ "time_dimension",+ [+ {+ uniqueIdentifierColumns: [{ accessor: "providedModelName" }],+ valueColumn: "sum_totalTokens",+ },+ ],+ ),+ selectedModels,+ )+ : [],+ [queryResult.data, allModels, selectedModels],+ );++ const costByModel = useMemo(+ () =>+ queryResult.data && allModels.length > 0+ ? fillMissingValuesAndTransform(+ extractTimeSeriesData(+ queryResult.data as DatabaseRow[],+ "time_dimension",+ [+ {+ uniqueIdentifierColumns: [{ accessor: "providedModelName" }],+ valueColumn: "sum_totalCost",+ },+ ],+ ),+ selectedModels,+ )+ : [],+ [queryResult.data, allModels, selectedModels],+ );const totalCost = queryResult.data?.reduce((acc, curr) =>@@ -373,23 +390,13 @@ export const ModelUsageChart = ({/>) : (<div className="h-80 w-full shrink-0">- <Chart- chartType="LINE_TIME_SERIES"- data={timeSeriesToDataPoints(item.data, agg)}- config={{- metric: {- label: item.chartMetricLabel,- },- }}- rowLimit={100}- chartConfig={{- type: "LINE_TIME_SERIES",- unit: item.chartUnit,- show_data_point_dots: false,- }}- legendPosition="above"+ <DashboardLineTimeSeriesChart+ data={item.data}+ label={item.chartMetricLabel}+ unit={item.chartUnit}// Token/cost totals are additive sums. (LFE-10498)legendSummary="sum"+ syncId={syncId}/></div>)}diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsxindex 42fd592305..20f9f2ae0e 100644--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx@@ -11,9 +11,9 @@ import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";import { type QueryType, type ViewVersion } from "@langfuse/shared/query";import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";-import { Chart } from "@/src/features/widgets/chart-library/Chart";-import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { DashboardLineTimeSeriesChart } from "@/src/features/dashboard/components/DashboardLineTimeSeriesChart";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";+import { useMemo } from "react";export const TracesAndObservationsTimeSeriesChart = ({className,@@ -25,6 +25,7 @@ export const TracesAndObservationsTimeSeriesChart = ({isLoading = false,metricsVersion,schedulerId,+ syncId,}: {className?: string;projectId: string;@@ -35,6 +36,7 @@ export const TracesAndObservationsTimeSeriesChart = ({isLoading?: boolean;metricsVersion?: ViewVersion;schedulerId?: string;+ syncId?: string;}) => {const isV2 = metricsVersion === "v2";@@ -69,19 +71,19 @@ export const TracesAndObservationsTimeSeriesChart = ({},);- const transformedTraces = traces.data- ? traces.data.map((item) => {- return {- ts: new Date(item.time_dimension as any).getTime(),- values: [- {- label: "Traces",- value: Number(item.count_count),- },- ],- };- })- : [];+ // Memoized on the raw query result so the reference is stable across the+ // dashboard scheduler's page re-renders β that's what lets the chart's+ // React.memo bail. (LFE-10549)+ const transformedTraces = useMemo(+ () =>+ traces.data+ ? traces.data.map((item) => ({+ ts: new Date(item.time_dimension as any).getTime(),+ values: [{ label: "Traces", value: Number(item.count_count) }],+ }))+ : [],+ [traces.data],+ );const total = traces.data?.reduce((acc, item) => {return acc + Number(item.count_count);@@ -118,33 +120,37 @@ export const TracesAndObservationsTimeSeriesChart = ({},);- const transformedObservations = observations.data- ? Object.values(- observations.data.reduce<- Record<- number,- {- ts: number;- values: { label: string; value: number | undefined }[];- }- >- >((acc, item) => {- const ts = new Date(item.time_dimension as any).getTime();- if (!acc[ts]) {- acc[ts] = {- ts,- values: [],- };- }- acc[ts].values.push({- label: item.level as string,- value: Number(item.count_count),- });+ const transformedObservations = useMemo(+ () =>+ observations.data+ ? Object.values(+ observations.data.reduce<+ Record<+ number,+ {+ ts: number;+ values: { label: string; value: number | undefined }[];+ }+ >+ >((acc, item) => {+ const ts = new Date(item.time_dimension as any).getTime();+ if (!acc[ts]) {+ acc[ts] = {+ ts,+ values: [],+ };+ }+ acc[ts].values.push({+ label: item.level as string,+ value: Number(item.count_count),+ });- return acc;- }, {}),- )- : [];+ return acc;+ }, {}),+ )+ : [],+ [observations.data],+ );const totalObservations = observations.data?.reduce((acc, item) => {return acc + Number(item.count_count);@@ -202,23 +208,13 @@ export const TracesAndObservationsTimeSeriesChart = ({/>{!isEmptyTimeSeries({ data: item.data }) ? (<div className="h-80 w-full shrink-0">- <Chart- chartType="LINE_TIME_SERIES"- data={timeSeriesToDataPoints(item.data, agg)}- config={{- metric: {- label: item.chartMetricLabel,- },- }}- rowLimit={100}- chartConfig={{- type: "LINE_TIME_SERIES",- show_data_point_dots: false,- }}- legendPosition="above"+ <DashboardLineTimeSeriesChart+ data={item.data}+ label={item.chartMetricLabel}// Counts are additive: the legend total reconciles with// the card headline. (LFE-10498)legendSummary="sum"+ syncId={syncId}/></div>) : (diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsxindex 4203fedcd3..34f57f3064 100644--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx@@ -18,8 +18,7 @@ import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";import { type QueryType, type ViewVersion } from "@langfuse/shared/query";import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";-import { Chart } from "@/src/features/widgets/chart-library/Chart";-import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { DashboardLineTimeSeriesChart } from "@/src/features/dashboard/components/DashboardLineTimeSeriesChart";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export function NumericScoreTimeSeriesChart(props: {@@ -33,6 +32,8 @@ export function NumericScoreTimeSeriesChart(props: {toTimestamp: Date;metricsVersion?: ViewVersion;schedulerId?: string;+ /** Shared hover-sync group so this chart joins the dashboard crosshair. */+ syncId?: string;}) {const scoresQuery: QueryType = {view: "scores-numeric",@@ -109,16 +110,10 @@ export function NumericScoreTimeSeriesChart(props: {isNullValueAllowed: true,}) ? (<div className="h-80 w-full shrink-0">- <Chart- chartType="LINE_TIME_SERIES"- data={timeSeriesToDataPoints(extractedScores, props.agg)}- rowLimit={100}- chartConfig={{- type: "LINE_TIME_SERIES",- show_data_point_dots: false,- subtle_fill: true,- }}- legendPosition="above"+ <DashboardLineTimeSeriesChart+ data={extractedScores}+ subtleFill+ syncId={props.syncId}/></div>) : (diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsxindex cae1822da5..788b246cf8 100644--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx@@ -32,6 +32,8 @@ export function ScoreAnalytics(props: {isLoading?: boolean;metricsVersion?: ViewVersion;schedulerId?: string;+ /** Shared hover-sync group so the per-score line charts join the dashboard crosshair. */+ syncId?: string;}) {// Stale score selections in localStorage are ignored as we only show scores that exist in scoreAnalyticsOptionsconst [selectedDashboardScoreKeys, setSelectedDashboardScoreKeys] =@@ -185,6 +187,7 @@ export function ScoreAnalytics(props: {toTimestamp={props.toTimestamp}metricsVersion={props.metricsVersion}schedulerId={props.schedulerId}+ syncId={props.syncId}/>)}</div>diff --git a/web/src/features/dashboard/lib/chart-data-adapters.ts b/web/src/features/dashboard/lib/chart-data-adapters.tsindex 27ce047b6c..a939b07335 100644--- a/web/src/features/dashboard/lib/chart-data-adapters.ts+++ b/web/src/features/dashboard/lib/chart-data-adapters.ts@@ -5,70 +5,21 @@import type { DataPoint } from "@/src/features/widgets/chart-library/chart-props";import type { TimeSeriesChartDataPoint } from "@/src/features/dashboard/components/hooks";import type { ChartBin } from "@/src/features/scores/types";-import {- dashboardDateRangeAggregationSettings,- type DashboardDateRangeAggregationOption,-} from "@/src/utils/date-range-utils";-/** Histogram bin shape: binLabel plus numeric fields (e.g. count). Compatible with createHistogramData return type. */type HistogramBinLike = { binLabel: string; [key: string]: string | number };-function convertDate(- date: number,- agg: DashboardDateRangeAggregationOption,-): string {- const parsedDate = new Date(date);- const { dateTrunc, minutes } = dashboardDateRangeAggregationSettings[agg];-- switch (dateTrunc) {- case "minute":- return parsedDate.toLocaleTimeString("en-US", {- hour: "numeric",- minute: "2-digit",- });- case "hour":- if (minutes && minutes <= 24 * 60) {- return parsedDate.toLocaleString("en-US", {- month: "numeric",- day: "numeric",- hour: "numeric",- });- }- return parsedDate.toLocaleString("en-US", {- month: "numeric",- day: "numeric",- hour: "numeric",- });- case "day":- case "week":- return parsedDate.toLocaleDateString("en-US", {- month: "short",- day: "numeric",- });- case "month":- return parsedDate.toLocaleDateString("en-US", {- month: "short",- year: "numeric",- });- default:- return parsedDate.toLocaleDateString("en-US", {- month: "numeric",- day: "numeric",- });- }-}-/**- * Converts legacy time series data (ts + values per point) to widget Chart DataPoint[].- * One row per (timestamp, label) with dimension = label, metric = value.+ * Converts legacy time series data (ts + values per point) to widget Chart+ * DataPoint[]. One row per (timestamp, label). The timestamp is passed through+ * as a raw ISO string β all date/time *formatting* is decided later by the+ * `prepareTimeAxis` preparer, so every chart formats time identically. (LFE-10549)*/export function timeSeriesToDataPoints(data: TimeSeriesChartDataPoint[],- agg: DashboardDateRangeAggregationOption,): DataPoint[] {const result: DataPoint[] = [];for (const point of data) {- const timeDimension = convertDate(point.ts, agg);+ const timeDimension = new Date(point.ts).toISOString();for (const v of point.values) {result.push({time_dimension: timeDimension,diff --git a/web/src/features/widgets/chart-library/ARCHITECTURE.md b/web/src/features/widgets/chart-library/ARCHITECTURE.mdnew file mode 100644index 0000000000..a2fec424f0--- /dev/null+++ b/web/src/features/widgets/chart-library/ARCHITECTURE.md@@ -0,0 +1,152 @@+# Charts & Dashboards β Architecture Manifesto++> A short, opinionated statement of how charting works here and where it's going.+> Read this before adding a chart type, a formatter, or a dashboard.++## The goal++**Show _any_ data clearly.** Unknown shape, any time range or scale, one series or+two hundred, clean or noisy, sparse or overloaded β a chart should render it+legibly and consistently, and let a person _read_ it through interaction. We do+not special-case per chart. We build one adaptable pipeline and feed everything+through it.++## The one rule: one-way flow, two layers++```+ data βββΆ PREPARE βββΆ VISUALISE βββΆ pixels+ (decide) (render)+```++- **Prepare** owns every _decision_: parsing, units, date/number/duration+ formatting, colors, series order, legend summaries, topβN, axis type, scale,+ null handling. Pure functions. No React. Unit-tested.+- **Visualise** owns _only rendering_: it maps a presentation-ready model onto+ the chart library and decides nothing. If a component is reaching back to+ reformat or re-derive, the decision is in the wrong layer.++Strictly one direction. The visualiser never re-decides what the preparer+resolved. (When the same value got formatted in three places, we got three+different β and sometimes wrong β dates. One source of truth per decision.)++## Principles β the "show whatever data" doctrine++1. **One normalized model is the pivot.** Every source lowers into a single+ typed, presentation-agnostic shape _once_, up front. Everything downstream+ targets that shape and never knows where the data came from.++2. **Decide presentation once, upstream.** Units, decimals, thresholds, colors,+ labels, and time format are resolved in the preparer into ready-to-render+ values. The renderer reads derived properties; it never re-derives them.++3. **Infer what the data didn't declare.** Assume input is under-specified and+ messy. Have a default for every missing piece β type from values, the time+ field, the bucket granularity (from spacing), series names from labels.++4. **Adapt to scale reactively, not predictively.** Don't compute "nice" ticks+ yourself β let the scale place them and _format the spacing you're given_.+ Pick number/date/duration formats by magnitude and granularity. Size axes by+ measuring labels, not guessing.++5. **Messy and overloaded is a first-class, _bounded_ case.** Bound cost at the+ source (β one point per pixel), not in the renderer. Cap unbounded series+ with an explicit, reversible limit (+ an "others" rollup where it's+ meaningful); never silently truncate without saying so.++6. **Null means something β say which.** Distinguish "no data here" (a gap)+ from "connect across" from "zero". Make the choice explicit; most+ "messy data looks wrong" bugs live in implicit null handling.++7. **Group by meaning, not position.** Series that share a unit share an axis;+ mismatched units earn a second axis β automatically, by derived key, so the+ layout adapts to an unknown number of series.++8. **Fail into guidance, not a blank box.** When data can't be drawn, detect+ _why_ (missing time field? no numeric field? empty?) and offer the next+ action.++9. **Interaction is readability.** Dense data is made legible by hovering,+ focusing, and a crosshair synced across a shared timeline β not only by+ throwing data away. Precise-on-hover beats sparse-by-default.++10. **Split "how to draw" from "what to draw."** Rebuild render config only when+ the structure changes; a new data tick should just swap arrays. Stable,+ memoized inputs; the heavy reconciliation happens rarely.++## Visual & interaction direction++> The architectural rules above say _where_ a decision lives. These say _what_ to+> decide when you draw. One stance underlies all of them: **the data carries the+> visual weight; the frame stays quiet.** Chrome β grid, axes, labels β is pushed+> to low contrast so series shape and color are what the eye lands on. High+> data-ink, always.++- **V1 β Draw what was measured; don't invent shape between points.** Straight+ segments by default. A smooth/spline curve _implies values that were never+ sampled_ β treat it as an explicit opt-in, not a prettifier. Use stepped lines+ only for hold-until-change (state/counter) data.++- **V2 β Missing is a gap, not a zero.** A null breaks the line. Bridge a gap+ only when the series semantically continues across it; never substitute `0` to+ "fill" a hole β that invents a measurement. Break the line when a gap exceeds+ the expected sampling cadence. Zero-fill is permitted only where stacking math+ needs a number. (This is principle 6, made visual.)++- **V3 β Encode certainty with one consistent grammar.** Less-trustworthy data β+ a still-aggregating final bucket, a comparison/previous period β renders+ _dotted and paled_, never dropped and never identical to confirmed data. One+ treatment, so a reader learns it once.++- **V4 β Hover reads a vertical slice, snapped to real samples.** The crosshair+ tracks the cursor, but the readout snaps to the nearest actual point β never a+ fabricated value at an arbitrary x. Near a gap the snap tolerance tightens so a+ tooltip never floats over emptiness.++- **V5 β Crosshair is shared across the timeline; the tooltip is the hovered+ chart's alone.** Charts on one time range share a single vertical time-marker;+ only the chart under the cursor opens a tooltip, listing every series at that+ instant, sorted by value, the focused one emphasized. Emphasis lives in the+ tooltip and the legend β the canvas stays calm. Dimming series _on the canvas_+ is reserved for one deliberate gesture (vertical proximity to a line) and must+ be flicker-free, never a side effect of ordinary hover.++- **V6 β Color is identity, assigned once.** A series' color is derived from the+ series and read back by the legend, so swatch and line can never diverge, and+ the same entity keeps its color across every chart. The palette is bounded; a+ colorblind-safe option exists.++- **V7 β Formatting is type-driven and adaptive β trust the scale.** Numbers,+ durations, bytes, percentages, currency, and dates each format by their kind+ and by the magnitude/granularity the scale chose; one common unit per axis.+ Tick precision follows the scale (don't truncate a narrow range); tooltip+ precision is capped for reading; digits are tabular so they don't jitter.++- **V8 β Bound the frame, not the data.** Cap drawn series at a legible top-N+ with an honest "N of M" (and an "others" rollup where it sums); bound the+ legend (scroll / "+N more"); bound density upstream (β one point per pixel).+ Never reach legibility by silently dropping data in the renderer.++## Where we are / where we're going++- **Now:** the visualiser is a set of recharts components behind one `Chart`+ dispatcher. Two preparer seams are in place: the **time axis**+ (`prepareTimeAxis` β raw timestamps in, granularity-adaptive labels out, one+ formatter for every chart) and the **series cap** (`prepareVisibleSeries` β+ ranks a breakdown by magnitude and keeps the topβN so a high-cardinality+ group-by of hundreds of series stays both legible and fast, with an honest+ "top N of M" note rather than a silent truncation; see principle 5).+ The interaction direction (V4/V5) is largely in place: a synced vertical+ crosshair, a tooltip that opens only on the hovered chart, and a vertical+ proximity highlight.+- **Known visual debts** (drawn but not yet matching the direction above): lines+ currently smooth (`type="monotone"`) rather than draw straight (V1), and series+ color is assigned by index and cycles every 8 rather than being a stable+ identity (V6). Both are visualiser defaults to migrate into the preparer.+- **Next:** move the remaining decisions β series colors (V6), curve/interpolation+ (V1), legend summaries, units, axis type & scale β out of the components and+ into the preparer, until the visualiser is purely presentational and the+ preparer is the single, tested place where "what should this look like" is+ answered.++The target: adding a new chart should mean teaching the **preparer** a new shape,+not teaching every component a new special case.diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsxindex d8cfb2b199..5eeb779a3e 100644--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx@@ -1,20 +1,28 @@-import React, { useMemo, useState } from "react";+import React, { useMemo, useRef, useState } from "react";import {ChartActiveReferenceLine,ChartContainer,ChartTooltip,ChartTooltipContent,+ ChartTooltipPortal,} from "@/src/components/ui/chart";import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";import {formatMetric,- getDimensionSummaries,getUniqueDimensions,groupDataByTimeDimension,toFullMetricString,} from "@/src/features/widgets/chart-library/utils";-import { cn } from "@/src/utils/tailwind";+import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";+import { prepareTimeAxis } from "@/src/features/widgets/chart-library/prepareTimeAxis";+import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepareVisibleSeries";+import {+ seriesColor,+ SeriesOverflowNote,+ TimeSeriesLegend,+ useSeriesLegend,+} from "@/src/features/widgets/chart-library/TimeSeriesLegend";export const AreaChartTimeSeries: React.FC<ChartProps> = ({data,@@ -30,74 +38,84 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({metricFormatter = (value, options) => formatMetric(value, options),legendPosition = "none",legendSummary = "none",+ legendInteraction = "highlight",+ maxVisibleSeries,+ syncId,subtleFill = false,}) => {- const [highlightedDimension, setHighlightedDimension] = useState<- string | null- >(null);-+ const [selfHovered, setSelfHovered] = useState(false);const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);- const dimensions = useMemo(() => getUniqueDimensions(data), [data]);- const dimensionSummaries = useMemo(- () => (legendSummary === "none" ? null : getDimensionSummaries(data)),- [data, legendSummary],+ const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);+ // Cap how many series we draw (data -> preparer seam): a high-cardinality+ // breakdown of hundreds of series is both unreadable and slow to hover. (LFE-10549)+ const series = useMemo(+ () => prepareVisibleSeries(data, allDimensions),+ [data, allDimensions],+ );+ const dimensions = series.visible;+ const { ref: containerRef, maxTicks } = useChartTickBudget();+ const chartBoxRef = useRef<HTMLDivElement>(null);+ const timeAxis = useMemo(+ () =>+ prepareTimeAxis(+ groupedData.map((d) => d.time_dimension),+ maxTicks,+ ),+ [groupedData, maxTicks],);+ const { legendItems, onLegendClick, isRendered, isDimmed } = useSeriesLegend({+ data,+ dimensions,+ legendSummary,+ legendInteraction,+ maxVisibleSeries,+ });+const tooltipFormatter = (value: number) =>toFullMetricString(metricFormatter(value, { style: "compact" }));- const handleLegendClick = (dimension: string) => {- setHighlightedDimension((prev) => (prev === dimension ? null : dimension));- };-return (- <div className="flex h-full w-full min-w-0 flex-col">- {legendPosition === "above" && dimensions.length > 0 && (- <div className="min-w-0 shrink-0 overflow-x-auto overflow-y-hidden pb-3">- <div className="flex w-max min-w-full flex-nowrap justify-end gap-4">- {dimensions.map((dimension, index) => {- const isHighlighted =- highlightedDimension === null ||- highlightedDimension === dimension;- const isMuted = highlightedDimension !== null && !isHighlighted;- // A `0` summary is a real value and must be shown; only a `null`- // summary (series with no data) is omitted. (LFE-10498)- const summary = dimensionSummaries?.get(dimension) ?? null;- return (- <button- key={dimension}- type="button"- onClick={() => handleLegendClick(dimension)}- className={cn(- "flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap transition-opacity",- "cursor-pointer hover:opacity-80",- isMuted && "opacity-40",- )}- aria-pressed={isHighlighted}- aria-label={- isHighlighted ? `Show only ${dimension}` : "Show all series"- }- >- <div- className="h-2 w-2 shrink-0 rounded-[2px]"- style={{- backgroundColor: `hsl(var(--chart-${(index % 8) + 1}))`,- }}- />- <span className="text-muted-foreground">{dimension}</span>- {summary !== null && (- <span className="text-foreground font-medium">- {tooltipFormatter(summary)}- </span>- )}- </button>- );- })}- </div>- </div>+ <div+ ref={containerRef}+ className="flex h-full w-full min-w-0 flex-col"+ // onMouseMove (not just onMouseEnter) so the tooltip un-gates even when the+ // cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)+ onMouseEnter={() => setSelfHovered(true)}+ onMouseMove={() => setSelfHovered(true)}+ onMouseLeave={() => setSelfHovered(false)}+ // Keyboard parity: recharts' accessibilityLayer lets Tab/arrow users move+ // the crosshair, but that fires no mouse event β un-gate the tooltip on+ // focus too, and re-gate only when focus leaves the chart. (LFE-10549)+ onFocus={() => setSelfHovered(true)}+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null))+ setSelfHovered(false);+ }}+ >+ {legendPosition === "above" && (+ <TimeSeriesLegend+ items={legendItems}+ interaction={legendInteraction}+ onItemClick={onLegendClick}+ formatSummary={tooltipFormatter}+ />)}- <ChartContainer config={config} className="min-h-0 flex-1">- <AreaChart accessibilityLayer={accessibilityLayer} data={groupedData}>+ <SeriesOverflowNote+ visibleCount={dimensions.length}+ totalCount={series.total}+ />+ <ChartContainer+ ref={chartBoxRef}+ config={config}+ className="min-h-0 flex-1"+ >+ <AreaChart+ accessibilityLayer={accessibilityLayer}+ data={groupedData}+ syncId={syncId}+ syncMethod="value"+ ><CartesianGrid stroke="hsl(var(--chart-grid))" vertical={false} /><XAxisdataKey="time_dimension"@@ -105,8 +123,8 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({fontSize={12}tickLine={false}axisLine={false}- interval="preserveStartEnd"- minTickGap={24}+ interval={timeAxis.interval}+ tickFormatter={timeAxis.formatTick}/><YAxistype="number"@@ -118,36 +136,46 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({tickFormatter={(value) => tooltipFormatter(Number(value))}/>{dimensions.map((dimension, index) => {- const isMuted =- highlightedDimension !== null &&- highlightedDimension !== dimension;+ if (!isRendered(dimension)) return null;+ const muted = isDimmed(dimension);return (<Areakey={dimension}type="monotone"dataKey={dimension}- stroke={`hsl(var(--chart-${(index % 8) + 1}))`}- fill={`hsl(var(--chart-${(index % 8) + 1}))`}- fillOpacity={isMuted ? 0.15 : subtleFill ? 0.3 : 0.75}+ stroke={seriesColor(index)}+ fill={seriesColor(index)}+ fillOpacity={muted ? 0.15 : subtleFill ? 0.3 : 0.75}strokeWidth={2.5}- strokeOpacity={isMuted ? 0.2 : 1}+ strokeOpacity={muted ? 0.2 : 1}connectNulls+ isAnimationActive={false}/>);})}<ChartActiveReferenceLine /><ChartTooltip- contentStyle={{ backgroundColor: "hsl(var(--background))" }}- content={({ active, payload, label }) => (- <ChartTooltipContent- active={active}- payload={payload}- label={label}- indicator="line"- valueFormatter={tooltipFormatter}- sortPayloadByValue="desc"- />- )}+ content={({ active, payload, label, coordinate }) =>+ // Synced siblings show only the crosshair; the tooltip is the+ // hovered chart's, portaled out of the chart frame. (LFE-10549)+ selfHovered ? (+ <ChartTooltipPortal+ active={active}+ coordinate={coordinate}+ anchorRef={chartBoxRef}+ >+ <ChartTooltipContent+ active={active}+ payload={payload}+ label={label}+ indicator="line"+ labelFormatter={(value) => timeAxis.formatTooltip(value)}+ valueFormatter={tooltipFormatter}+ sortPayloadByValue="desc"+ />+ </ChartTooltipPortal>+ ) : null+ }/></AreaChart></ChartContainer>diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxindex 910c4d69cd..da446ebb4c 100644--- a/web/src/features/widgets/chart-library/Chart.tsx+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -5,6 +5,7 @@ import {type DataPoint,type ChartThreshold,type LegendSummaryMode,+ type LegendInteraction,} from "@/src/features/widgets/chart-library/chart-props";import { formatMetric } from "@/src/features/widgets/chart-library/utils";import { CardContent } from "@/src/components/ui/card";@@ -28,7 +29,7 @@ const DEFAULT_METRIC_THEME = {dark: "hsl(var(--chart-1))",} as const;-export const Chart = ({+const ChartComponent = ({chartType,data,rowLimit,@@ -39,6 +40,9 @@ export const Chart = ({isLoading = false,legendPosition,legendSummary,+ legendInteraction,+ maxVisibleSeries,+ syncId,overrideWarning = false,metricFormatter: metricFormatterOverride,thresholds,@@ -65,6 +69,9 @@ export const Chart = ({isLoading?: boolean;legendPosition?: "above" | "none";legendSummary?: LegendSummaryMode;+ legendInteraction?: LegendInteraction;+ maxVisibleSeries?: number;+ syncId?: string;overrideWarning?: boolean;metricFormatter?: MetricFormatterFunction;thresholds?: ChartThreshold[];@@ -80,38 +87,11 @@ export const Chart = ({[metricFormatterOverride, chartConfig?.unit],);- const renderedData = useMemo(() => {- return data.map((item) => {- if (!item.time_dimension) return { ...item, time_dimension: undefined };- const value = item.time_dimension;- const looksLikeIso =- value.includes("T") || /^\d{4}-\d{2}-\d{2}$/.test(value);- if (!looksLikeIso) {- return { ...item, time_dimension: value };- }- const parsed = new Date(value);- if (Number.isNaN(parsed.getTime())) return { ...item };- const isMidnight =- parsed.getUTCHours() === 0 &&- parsed.getUTCMinutes() === 0 &&- parsed.getUTCSeconds() === 0 &&- parsed.getUTCMilliseconds() === 0;- const time_dimension = isMidnight- ? parsed.toLocaleDateString("en-US", {- year: "2-digit",- month: "numeric",- day: "numeric",- })- : parsed.toLocaleTimeString("en-US", {- year: "2-digit",- month: "numeric",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- });- return { ...item, time_dimension };- });- }, [data]);+ // Time-axis formatting is NOT decided here. Raw time_dimension values flow+ // straight to the visualiser, which formats them via the prepareTimeAxis+ // preparer β one source of truth, so every chart formats time the same way.+ // (LFE-10549)+ const renderedData = data;const resolvedConfig = useMemo(() => {if (!config) return undefined;@@ -143,7 +123,10 @@ export const Chart = ({metricFormatter={metricFormatter}legendPosition={legendPosition}legendSummary={legendSummary}- showDataPointDots={chartConfig?.show_data_point_dots ?? true}+ legendInteraction={legendInteraction}+ maxVisibleSeries={maxVisibleSeries}+ syncId={syncId}+ showDataPointDots={chartConfig?.show_data_point_dots ?? false}thresholds={thresholds}/>);@@ -155,6 +138,9 @@ export const Chart = ({metricFormatter={metricFormatter}legendPosition={legendPosition}legendSummary={legendSummary}+ legendInteraction={legendInteraction}+ maxVisibleSeries={maxVisibleSeries}+ syncId={syncId}subtleFill={chartConfig?.subtle_fill}/>);@@ -164,6 +150,11 @@ export const Chart = ({data={renderedData}config={resolvedConfig}metricFormatter={metricFormatter}+ legendPosition={legendPosition}+ legendSummary={legendSummary}+ legendInteraction={legendInteraction}+ maxVisibleSeries={maxVisibleSeries}+ syncId={syncId}subtleFill={chartConfig?.subtle_fill}/>);@@ -269,3 +260,11 @@ export const Chart = ({</CardContent>);};++/**+ * Memoized so a parent re-render (e.g. the dashboard query scheduler bumping its+ * version during load) doesn't reconcile the recharts subtree when the chart's+ * inputs are unchanged. Effective only when callers pass stable `data`/`config`+ * references β the dashboard time-series consumers memoize those. (LFE-10549)+ */+export const Chart = React.memo(ChartComponent);diff --git a/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx b/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsxnew file mode 100644index 0000000000..967318d826--- /dev/null+++ b/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx@@ -0,0 +1,135 @@+import preview from "../../../../.storybook/preview";+import { LineChartTimeSeries } from "./LineChartTimeSeries";+import { formatMetric } from "./utils";+import { type DataPoint, type MetricFormatterFunction } from "./chart-props";++// Shared time buckets so the synced crosshair lines up across panels (recharts+// syncId matches by index). Deterministic β no Math.random.+const HOURS = 48;+const labelAt = (i: number) => {+ const h = (13 + Math.floor(i / 2)) % 24;+ return `${String(h).padStart(2, "0")}:${i % 2 === 0 ? "00" : "30"}`;+};++const buildPanel = (+ series: { name: string; base: number; amp: number; spike?: number }[],+): DataPoint[] => {+ const points: DataPoint[] = [];+ for (let i = 0; i < HOURS; i++) {+ const time = labelAt(i);+ series.forEach(({ name, base, amp, spike }, seed) => {+ const wave = 0.5 + 0.5 * Math.sin((i + seed * 2.1) / 3.3);+ const jitter = ((seed * 31 + i * 17) % 13) / 13;+ const spikeAdd = spike && i === 30 ? spike : 0;+ points.push({+ time_dimension: time,+ dimension: name,+ metric: Math.round(base + amp * wave + amp * 0.3 * jitter + spikeAdd),+ });+ });+ }+ return points;+};++const requestsData = buildPanel([+ { name: "web", base: 14_000, amp: 6_000 },+ { name: "worker", base: 9_000, amp: 4_000 },+]);+const latencyData = buildPanel([+ { name: "post /api/chat-completion", base: 800, amp: 700, spike: 9_000 },+ { name: "get /api/traces", base: 300, amp: 200 },+ { name: "post /api/ingestion", base: 500, amp: 400 },+]);+const errorsData = buildPanel([{ name: "5xx", base: 1, amp: 3, spike: 8 }]);++// The common "spaghetti" case β many series at once. Magnitudes are spread so+// the lines occupy different vertical bands (good for the proximity highlight).+const spaghettiData = buildPanel(+ Array.from({ length: 14 }, (_, i) => ({+ name: `model-${String.fromCharCode(97 + i)}`,+ base: 150 + i * 120,+ amp: 80 + (i % 4) * 70,+ })),+);++const msFormatter: MetricFormatterFunction = (value, options) =>+ formatMetric(value, { ...options, unit: "millisecond" });++const PANELS: {+ title: string;+ data: DataPoint[];+ formatter?: MetricFormatterFunction;+}[] = [+ { title: "Requests", data: requestsData },+ { title: "p95 Latency", data: latencyData, formatter: msFormatter },+ { title: "Errors", data: errorsData },+];++/**+ * A mini-dashboard of charts that share a `syncId`. Hovering any panel drives a+ * synced vertical crosshair + tooltip across ALL panels at the same timestamp;+ * tooltips can escape a panel's bounds (allowEscapeViewBox). This is the+ * interactivity prototype for LFE-10549 β best viewed live, not as a screenshot.+ */+const SyncedDashboardDemo = ({+ syncId = "lfe10549-demo",+}: {+ syncId?: string;+}) => (+ <div className="flex flex-col gap-4">+ <p className="text-muted-foreground text-xs">+ Hover any chart β the time crosshair + tooltip track across all three.+ </p>+ {PANELS.map((panel) => (+ <div key={panel.title} className="bg-background rounded-md border p-3">+ <div className="mb-1 text-sm font-medium">{panel.title}</div>+ <div className="h-[180px] w-full">+ <LineChartTimeSeries+ data={panel.data}+ syncId={syncId}+ legendPosition="above"+ legendSummary="none"+ showDataPointDots={false}+ metricFormatter={panel.formatter}+ />+ </div>+ </div>+ ))}+ </div>+);++const meta = preview.meta({+ component: SyncedDashboardDemo,+ args: { syncId: "lfe10549-demo" },+ decorators: [+ (Story) => (+ <div className="w-[560px]">+ <Story />+ </div>+ ),+ ],+});++export const SyncedTimeline = meta.story({});++/**+ * The common overloaded case. Move the cursor vertically near a line: the+ * nearest line(s) emphasize and the rest dim; two lines within the pixel+ * threshold both light up; away from any line it renders normally.+ */+export const Spaghetti = meta.story({+ render: () => (+ <div className="bg-background h-[380px] w-full rounded-md border p-3">+ <div className="mb-1 text-sm font-medium">p95 Latency β 14 models</div>+ <div className="h-[330px] w-full">+ <LineChartTimeSeries+ data={spaghettiData}+ legendPosition="above"+ legendSummary="none"+ showDataPointDots={false}+ metricFormatter={msFormatter}+ />+ </div>+ </div>+ ),+});diff --git a/web/src/features/widgets/chart-library/ChartingPrinciples.mdx b/web/src/features/widgets/chart-library/ChartingPrinciples.mdxnew file mode 100644index 0000000000..683237b5f9--- /dev/null+++ b/web/src/features/widgets/chart-library/ChartingPrinciples.mdx@@ -0,0 +1,319 @@+import { Meta, Canvas } from "@storybook/addon-docs/blocks";+import * as Principles from "./ChartingPrinciples.stories";++<Meta title="Design System/Charts/Principles" />++export const RED = "#E4002B";+export const FG = "hsl(var(--foreground))";+export const BG = "hsl(var(--background))";+export const MUTED = "hsl(var(--muted-foreground))";+export const BORDER = "hsl(var(--border))";+// RED is the one fixed accent (reads on both themes); FG/BG/MUTED/BORDER track+// the app theme. The bold slabs (hero, principle numbers) stay a fixed+// ink/paper in BOTH themes β flipping them to a light block via the theme vars+// looked washed-out and wrong in dark.+export const INK = "#0B0B0B";+export const PAPER = "#F3F1EA";++export const Page = ({ children }) => (+ <div+ style={{+ background: BG,+ color: FG,+ padding: "56px clamp(24px, 6vw, 88px)",+ fontFamily:+ "ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif",+ }}+ >+ {/* Storybook's docs theme paints the whole page (and every example card)+ light, and can't follow our per-toggle theme. Pull the page background,+ the side padding, and the example-card chrome onto the app's themed+ vars so the article is fully dark in dark mode β no white frame, no+ white padding. */}+ <style>{`+ .sbdocs-wrapper{background:hsl(var(--background)) !important;padding:0 !important;}+ .sbdocs-content{max-width:none !important;padding:0 !important;}+ .sbdocs.sbdocs-preview{background:transparent !important;border:0 !important;box-shadow:none !important;}+ `}</style>+ <div style={{ maxWidth: 880, margin: "0 auto" }}>{children}</div>+ </div>+);++export const Hero = () => (+ <div+ style={{+ position: "relative",+ overflow: "hidden",+ background: INK,+ color: PAPER,+ border: `1px solid ${BORDER}`,+ padding: "72px 48px 64px",+ marginBottom: 64,+ }}+ >+ <div+ style={{+ position: "absolute",+ right: -60,+ top: -60,+ width: 280,+ height: 280,+ background: RED,+ transform: "rotate(18deg)",+ }}+ />+ <div style={{ position: "relative" }}>+ <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: "0.4em" }}>+ LANGFUSE Β· CHART LIBRARY+ </div>+ <h1+ style={{+ color: PAPER,+ fontSize: "clamp(56px, 11vw, 104px)",+ lineHeight: 0.88,+ fontWeight: 900,+ letterSpacing: "-0.045em",+ margin: "16px 0 0",+ }}+ >+ DRAW+ <br />+ ANYTHING.+ </h1>+ <p+ style={{+ color: PAPER,+ fontSize: 22,+ fontWeight: 600,+ maxWidth: 540,+ marginTop: 24,+ opacity: 0.85,+ }}+ >+ Eight moves for rendering any data β clean or noisy, sparse or+ overloaded β legibly, every time.+ </p>+ </div>+ </div>+);++export const Lede = () => (+ <div+ style={{+ borderLeft: `10px solid ${RED}`,+ paddingLeft: 24,+ margin: "0 0 56px",+ fontSize: "clamp(24px, 4vw, 34px)",+ fontWeight: 900,+ lineHeight: 1.12,+ letterSpacing: "-0.02em",+ maxWidth: 680,+ }}+ >+ The data carries the weight.+ <br />+ The frame stays quiet.+ </div>+);++export const Slab = ({ n, t, lead, children }) => (+ <section style={{ margin: "0 0 24px" }}>+ <div style={{ display: "flex", gap: 22, alignItems: "flex-start" }}>+ <div+ style={{+ flex: "0 0 auto",+ width: 60,+ height: 60,+ background: INK,+ color: PAPER,+ border: `1px solid ${BORDER}`,+ fontSize: 28,+ fontWeight: 900,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ {n}+ </div>+ <div style={{ paddingTop: 2 }}>+ <h2+ style={{+ fontSize: "clamp(22px, 3.4vw, 30px)",+ fontWeight: 900,+ letterSpacing: "-0.02em",+ textTransform: "uppercase",+ margin: "0 0 8px",+ lineHeight: 1.02,+ }}+ >+ {t}+ </h2>+ {lead && (+ <p+ style={{+ fontSize: 18,+ fontWeight: 700,+ margin: "0 0 6px",+ color: RED,+ }}+ >+ {lead}+ </p>+ )}+ <div style={{ fontSize: 16, lineHeight: 1.55, maxWidth: 660 }}>+ {children}+ </div>+ </div>+ </div>+ </section>+);++export const Plate = ({ children }) => (+ <div style={{ margin: "20px 0 44px", paddingLeft: 82 }}>{children}</div>+);++export const Rule = () => (+ <div style={{ height: 6, background: FG, margin: "8px 0 40px" }} />+);++<Page>++<Hero />++<Lede />++A chart here is not a picture we compose by hand. It is the last step of a+pipeline β **data β prepare β visualise β pixels** β and the renderer decides+nothing. These eight moves are what the _prepare_ step decides so that any+data, from one clean series to two hundred noisy ones, comes out legible. They+are deliberately absolute. Read them as commandments, argue with them in the+preparer, never in the chart component.++<Rule />++<Slab n="1" t="Draw what was measured" lead="No invented shape between points.">+ Straight segments are the honest default β they claim only the points we have.+ A smooth curve <strong>invents values that were never sampled</strong>; reach+ for it only when you mean to. Stepped lines are for data that holds until it+ changes (states, counters). The line is a record, not a decoration.+</Slab>++<Plate>+ <Canvas of={Principles.Interpolation} sourceState="none" />+</Plate>++<Slab+ n="2"+ t="Missing is a gap, not a zero"+ lead="A hole in the data is the truth."+>+ A null breaks the line. Substituting <strong>0</strong> to "fill" the hole+ manufactures a measurement that never happened β the single most common way a+ chart lies. Bridge a gap only when the series genuinely continues across it;+ break the line when a gap runs longer than the sampling cadence. Zero is a+ value, not a synonym for absence.+</Slab>++<Plate>+ <Canvas of={Principles.NullHandling} sourceState="none" />+</Plate>++<Slab+ n="3"+ t="Show certainty in the ink"+ lead="One grammar for less-sure data."+>+ A still-aggregating final bucket and a previous-period comparison are real,+ but they are <strong>less certain</strong> than confirmed history. Don't drop+ them and don't draw them as solid fact β render them dotted and paled. One+ treatment, used everywhere, so a reader learns the grammar once and trusts it.+</Slab>++<Plate>+ <Canvas of={Principles.Certainty} sourceState="none" />+</Plate>++<Slab+ n="4"+ t="Hover is a timeline, not a panel"+ lead="Snap to real samples; share the crosshair."+>+ The cursor between two points must never conjure a reading that isn't there β+ the crosshair tracks the cursor, the value snaps to the nearest real sample,+ and near a gap the snap tightens so a tooltip never floats over emptiness.+ Charts on one time range share <strong>one</strong> vertical marker; only the+ chart under the cursor opens a tooltip. Emphasis lives in the tooltip and the+ legend β the canvas stays calm.+</Slab>++<Plate>+ <Canvas of={Principles.HoverTimeline} sourceState="none" />+</Plate>++<Slab n="5" t="Color is identity" lead="Assign once. Read it back.">+ A series' color belongs to the series, not to its position in a list. Derive+ it once and let the legend read it back, so swatch and line can never diverge+ and the same entity keeps its color across every chart on the board. The+ palette is bounded, and a colorblind-safe option always exists.+</Slab>++<Slab n="6" t="Trust the scale" lead="Type-driven, adaptive formatting.">+ Numbers, durations, bytes, percentages, currency, dates β each formats by its+ kind and by the magnitude the scale chose. One unit per axis. Tick precision+ follows the scale; tooltip precision is capped for reading; digits are tabular+ so they never jitter. Don't out-clever the axis engine β format the spacing it+ gives you.+</Slab>++<Plate>+ <Canvas of={Principles.QuietChrome} sourceState="none" />+</Plate>++<Slab n="7" t="Spend ink on data" lead="Quiet the frame.">+ Faint horizontal gridlines, no axis spine, muted labels, no data-point dots by+ default, fills barely there, no animation on the series. Every pixel of chrome+ is a pixel stolen from the data. The grid is scaffolding β build the building,+ then take the scaffolding down.+</Slab>++<Slab n="8" t="Bound the frame, not the data" lead="Top-N, and say so.">+ Two hundred series is not a chart, it is a wall. Draw a legible top-N, rolled+ by magnitude, and state the truth in the open β{" "}+ <em>βshowing top 25 of 487.β</em>+ Bound the legend, bound the density upstream (about one point per pixel).+ Never buy legibility by silently throwing data away where no one can see you+ do it.+</Slab>++<Plate>+ <Canvas of={Principles.BoundTheFrame} sourceState="none" />+</Plate>++<Rule />++<div+ style={{+ background: RED,+ color: "#fff",+ padding: "40px 44px",+ fontSize: "clamp(22px, 4vw, 32px)",+ fontWeight: 900,+ lineHeight: 1.15,+ letterSpacing: "-0.02em",+ }}+>+ One adaptable pipeline. No special cases.+ <br />+ Teach the preparer a new shape β never the component a new exception.+</div>++<p style={{ fontSize: 14, color: MUTED, marginTop: 28 }}>+ The full architecture and the one-way{" "}+ <strong>data β prepare β visualise</strong> rule live in{" "}+ <code>web/src/features/widgets/chart-library/ARCHITECTURE.md</code>. For how+ overlays escape the chart frame, see the layer system in{" "}+ <code>web/src/components/ui/layer.tsx</code> (Design System β Overlay Layers).+</p>++</Page>diff --git a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsxnew file mode 100644index 0000000000..eed5801057--- /dev/null+++ b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx@@ -0,0 +1,351 @@+import preview from "../../../../.storybook/preview";+import {+ CartesianGrid,+ Line,+ LineChart,+ ResponsiveContainer,+ XAxis,+ YAxis,+} from "recharts";+import { LineChartTimeSeries } from "./LineChartTimeSeries";+import { formatMetric } from "./utils";+import { type DataPoint, type MetricFormatterFunction } from "./chart-props";++/**+ * Illustrations for the charting-principles article (`ChartingPrinciples.mdx`).+ * The didactic ones (interpolation, null handling, certainty) draw raw recharts+ * so the contrast is unmistakable; the rest reuse the real+ * `LineChartTimeSeries` so the article shows production behavior, not a mockup.+ * Deterministic data only β no Math.random β so the renders are stable.+ */++// ββ shared didactic data βββββββββββββββββββββββββββββββββββββββββββββββββββββ+// Sparse + jagged so the interpolation choice is obvious at a glance.+const sparse = [+ { x: "1", y: 20 },+ { x: "2", y: 82 },+ { x: "3", y: 34 },+ { x: "4", y: 90 },+ { x: "5", y: 46 },+ { x: "6", y: 68 },+];++const Mini = ({+ label,+ caption,+ children,+}: {+ label: string;+ caption: string;+ children: React.ReactNode;+}) => (+ <div className="flex flex-col gap-1">+ <div className="text-xs font-bold tracking-wide uppercase">{label}</div>+ <div className="bg-background h-[150px] w-[210px] rounded-md border p-2">+ {children}+ </div>+ <div className="text-muted-foreground w-[210px] text-xs">{caption}</div>+ </div>+);++const Row = ({ children }: { children: React.ReactNode }) => (+ <div className="flex flex-wrap gap-5">{children}</div>+);++const axes = (+ <>+ <CartesianGrid stroke="hsl(var(--chart-grid))" vertical={false} />+ <XAxis+ dataKey="x"+ stroke="hsl(var(--chart-grid))"+ fontSize={11}+ tickLine={false}+ axisLine={false}+ />+ <YAxis+ stroke="hsl(var(--chart-grid))"+ fontSize={11}+ tickLine={false}+ axisLine={false}+ width={26}+ />+ </>+);++const meta = preview.meta({+ title: "Design System/Charts/Illustrations",+ component: LineChartTimeSeries,+ decorators: [+ (Story) => (+ <div className="max-w-[720px] p-1">+ <Story />+ </div>+ ),+ ],+});++// ββ V1 Β· Draw what was measured ββββββββββββββββββββββββββββββββββββββββββββββ+export const Interpolation = meta.story({+ render: () => (+ <Row>+ {(+ [+ ["Straight", "linear", "What we measured. The honest default."],+ ["Smooth", "monotone", "Invents values between points. Opt-in only."],+ [+ "Stepped",+ "stepAfter",+ "Holds until it changes. For state/counters.",+ ],+ ] as const+ ).map(([label, type, caption]) => (+ <Mini key={type} label={label} caption={caption}>+ <ResponsiveContainer>+ <LineChart data={sparse} margin={{ top: 8, right: 8, bottom: 0 }}>+ {axes}+ <Line+ type={type}+ dataKey="y"+ stroke="hsl(var(--chart-1))"+ strokeWidth={2.5}+ dot={false}+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </Mini>+ ))}+ </Row>+ ),+});++// ββ V2 Β· Missing is a gap, not a zero ββββββββββββββββββββββββββββββββββββββββ+const withHole: { x: string; y: number | null }[] = [+ { x: "1", y: 30 },+ { x: "2", y: 58 },+ { x: "3", y: null },+ { x: "4", y: null },+ { x: "5", y: 62 },+ { x: "6", y: 40 },+];+const zeroFilled = withHole.map((d) => ({ ...d, y: d.y ?? 0 }));++export const NullHandling = meta.story({+ render: () => (+ <Row>+ <Mini+ label="Gap β"+ caption="Null breaks the line. The truth: no data here."+ >+ <ResponsiveContainer>+ <LineChart data={withHole} margin={{ top: 8, right: 8, bottom: 0 }}>+ {axes}+ <Line+ type="linear"+ dataKey="y"+ stroke="hsl(var(--chart-1))"+ strokeWidth={2.5}+ dot={false}+ connectNulls={false}+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </Mini>+ <Mini+ label="Bridge"+ caption="Only when the series truly continues across the gap."+ >+ <ResponsiveContainer>+ <LineChart data={withHole} margin={{ top: 8, right: 8, bottom: 0 }}>+ {axes}+ <Line+ type="linear"+ dataKey="y"+ stroke="hsl(var(--chart-1))"+ strokeWidth={2.5}+ strokeDasharray="4 3"+ dot={false}+ connectNulls+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </Mini>+ <Mini+ label="Zero-fill β"+ caption="Invents a measurement of 0. A lie, unless stacking demands it."+ >+ <ResponsiveContainer>+ <LineChart data={zeroFilled} margin={{ top: 8, right: 8, bottom: 0 }}>+ {axes}+ <Line+ type="linear"+ dataKey="y"+ stroke="hsl(var(--destructive))"+ strokeWidth={2.5}+ dot={false}+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </Mini>+ </Row>+ ),+});++// ββ V3 Β· Encode certainty with one grammar βββββββββββββββββββββββββββββββββββ+// `solid` = confirmed buckets; `faded` = still-aggregating tail (overlaps at the+// boundary so the dotted+pale segment touches the solid one).+const certainty = [+ { x: "1", solid: 32, faded: null as number | null },+ { x: "2", solid: 50, faded: null as number | null },+ { x: "3", solid: 44, faded: null as number | null },+ { x: "4", solid: 61, faded: 61 as number | null },+ { x: "5", solid: null as number | null, faded: 54 },+ { x: "6", solid: null as number | null, faded: 30 },+];++export const Certainty = meta.story({+ render: () => (+ <Mini+ label="Confirmed vs. forming"+ caption="The still-aggregating tail is dotted + pale β present, but visibly less certain."+ >+ <ResponsiveContainer>+ <LineChart data={certainty} margin={{ top: 8, right: 8, bottom: 0 }}>+ {axes}+ <Line+ type="linear"+ dataKey="solid"+ stroke="hsl(var(--chart-1))"+ strokeWidth={2.5}+ dot={false}+ connectNulls={false}+ isAnimationActive={false}+ />+ <Line+ type="linear"+ dataKey="faded"+ stroke="hsl(var(--chart-1))"+ strokeWidth={2.5}+ strokeOpacity={0.45}+ strokeDasharray="3 3"+ dot={false}+ connectNulls={false}+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </Mini>+ ),+});++// ββ Reused production component (V4βV8) βββββββββββββββββββββββββββββββββββββββ+const msFormatter: MetricFormatterFunction = (value, options) =>+ formatMetric(value, { ...options, unit: "millisecond" });++const buildSeries = (+ series: { name: string; base: number; amp: number }[],+ days = 14,+): DataPoint[] => {+ const points: DataPoint[] = [];+ for (let day = 0; day < days; day++) {+ const label = `2026-06-${String(day + 1).padStart(2, "0")}T00:00:00Z`;+ series.forEach(({ name, base, amp }, seed) => {+ const wave = 0.5 + 0.5 * Math.sin((day + seed * 1.7) / 2.3);+ const jitter = ((seed * 37 + day * 13) % 17) / 17;+ points.push({+ time_dimension: label,+ dimension: name,+ metric: Math.round(base + amp * wave + amp * 0.25 * jitter),+ });+ });+ }+ return points;+};++const fewSeries = buildSeries([+ { name: "gpt-4o", base: 800, amp: 600 },+ { name: "claude-3-5-sonnet", base: 1200, amp: 900 },+ { name: "gpt-4o-mini", base: 300, amp: 250 },+]);++// 30 series β over the render cap (25) β "Showing top 25 of 30 series".+const manySeries = buildSeries(+ Array.from({ length: 30 }, (_, i) => ({+ name: `model-${String.fromCharCode(97 + (i % 26))}${Math.floor(i / 26)}`,+ base: 200 + i * 70,+ amp: 120 + (i % 5) * 60,+ })),+);++const Frame = ({+ title,+ children,+}: {+ title: string;+ children: React.ReactNode;+}) => (+ <div className="bg-background w-[680px] rounded-md border p-3">+ <div className="mb-1 text-sm font-medium">{title}</div>+ <div className="h-[280px] w-full">{children}</div>+ </div>+);++// V4/V5 β hover snaps to a real sample; one synced crosshair, one tooltip.+export const HoverTimeline = meta.story({+ render: () => (+ <div className="flex flex-col gap-3">+ <Frame title="p95 latency by model">+ <LineChartTimeSeries+ data={fewSeries}+ syncId="charting-principles"+ legendPosition="above"+ showDataPointDots={false}+ metricFormatter={msFormatter}+ />+ </Frame>+ <Frame title="requests by model (same timeline)">+ <LineChartTimeSeries+ data={buildSeries([+ { name: "gpt-4o", base: 14_000, amp: 6_000 },+ { name: "claude-3-5-sonnet", base: 9_000, amp: 4_000 },+ { name: "gpt-4o-mini", base: 22_000, amp: 8_000 },+ ])}+ syncId="charting-principles"+ legendPosition="above"+ showDataPointDots={false}+ />+ </Frame>+ </div>+ ),+});++// V6/V7 β quiet chrome, identity color, adaptive labels (production component).+export const QuietChrome = meta.story({+ render: () => (+ <Frame title="High data-ink: faint grid, no axis spine, muted labels">+ <LineChartTimeSeries+ data={fewSeries}+ legendPosition="above"+ showDataPointDots={false}+ metricFormatter={msFormatter}+ />+ </Frame>+ ),+});++// V8 β bound the frame, not the data: top-N + an honest "N of M" note.+export const BoundTheFrame = meta.story({+ render: () => (+ <Frame title="30 series in, 25 drawn β and it says so">+ <LineChartTimeSeries+ data={manySeries}+ legendPosition="above"+ showDataPointDots={false}+ metricFormatter={msFormatter}+ />+ </Frame>+ ),+});diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsxindex e0577c9267..144981c2a7 100644--- a/web/src/features/widgets/chart-library/HistogramChart.tsx+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx@@ -108,6 +108,7 @@ const HistogramChart = ({fill="hsl(var(--chart-1))"radius={[2, 2, 0, 0]}fillOpacity={subtleFill ? 0.3 : 1}+ isAnimationActive={false}/><ChartTooltipcursor={false}diff --git a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx b/web/src/features/widgets/chart-library/HorizontalBarChart.tsxindex 695cf0b3c6..4cd109232a 100644--- a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx+++ b/web/src/features/widgets/chart-library/HorizontalBarChart.tsx@@ -127,6 +127,7 @@ export const HorizontalBarChart: React.FC<ChartProps> = ({maxBarSize={28}className="fill-(--color-metric)"fillOpacity={subtleFill ? 0.3 : 1}+ isAnimationActive={false}>{showValueLabels ? (<LabelListdiff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsxnew file mode 100644index 0000000000..0281de395e--- /dev/null+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx@@ -0,0 +1,125 @@+import preview from "../../../../.storybook/preview";+import { LineChartTimeSeries } from "./LineChartTimeSeries";+import { formatMetric } from "./utils";+import {+ type ChartProps,+ type DataPoint,+ type MetricFormatterFunction,+} from "./chart-props";++// Thin wrapper so args infer at ChartProps. LineChartTimeSeries is typed as+// React.FC<ChartProps>, whose ComponentProps don't flow cleanly through+// preview.meta (story args resolve to `never`); a plain (props: ChartProps)+// component pins them. (Same escape hatch as data-table.stories.tsx.)+const LineChartTimeSeriesDemo = (props: ChartProps) => (+ <LineChartTimeSeries {...props} />+);++/**+ * Deterministic fake-ish time series β no Math.random so stories are stable.+ * `base`/`amp` shape each series; values stay non-negative like real metrics.+ */+const buildSeries = (+ series: { name: string; base: number; amp: number }[],+ days = 14,+): DataPoint[] => {+ const points: DataPoint[] = [];+ for (let day = 0; day < days; day++) {+ const label = `6/${day + 1}`;+ series.forEach(({ name, base, amp }, seed) => {+ const wave = 0.5 + 0.5 * Math.sin((day + seed * 1.7) / 2.3);+ const jitter = ((seed * 37 + day * 13) % 17) / 17;+ points.push({+ time_dimension: label,+ dimension: name,+ metric: Math.round(base + amp * wave + amp * 0.25 * jitter),+ });+ });+ }+ return points;+};++// Non-additive latencies (ms) β summing these is nonsense; avg/median/last read well.+const latencyData = buildSeries([+ { name: "gpt-4o", base: 800, amp: 600 },+ { name: "claude-3-5-sonnet", base: 1200, amp: 900 },+ { name: "gpt-4o-mini", base: 300, amp: 250 },+ { name: "<synthetic>", base: 1500, amp: 1100 },+]);++// Additive token counts β "sum" reconciles with a headline total.+const tokenData = buildSeries([+ { name: "gpt-4o", base: 40_000, amp: 30_000 },+ { name: "claude-3-5-sonnet", base: 25_000, amp: 18_000 },+ { name: "gpt-4o-mini", base: 90_000, amp: 60_000 },+]);++// Overloaded: many models at once (the Model-latencies failure case).+const manySeriesData = buildSeries(+ Array.from({ length: 12 }, (_, i) => ({+ name: `model-${String.fromCharCode(97 + i)}`,+ base: 200 + i * 90,+ amp: 150 + i * 60,+ })),+);++const msFormatter: MetricFormatterFunction = (value, options) =>+ formatMetric(value, { ...options, unit: "millisecond" });++const meta = preview.meta({+ component: LineChartTimeSeriesDemo,+ args: {+ data: latencyData,+ legendPosition: "above",+ metricFormatter: msFormatter,+ },+ // Host in a card-sized box so ResponsiveContainer has room (the widget shape).+ decorators: [+ (Story) => (+ <div className="bg-background h-[320px] w-[640px] rounded-md border p-3">+ <Story />+ </div>+ ),+ ],+});++// ββ Legend summary βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// Additive metrics (token counts) carry a `sum` value in the legend; non-additive+// metrics (latency, scores) show the bare series name β a sum is meaningless and+// an unlabeled non-sum number reads ambiguously. (LFE-10549)++export const LegendNoneOnLatency = meta.story({+ args: { data: latencyData, legendSummary: "none" },+});++export const LegendSumOnAdditive = meta.story({+ args: { data: tokenData, legendSummary: "sum", metricFormatter: undefined },+});++// ββ Overload handling (decide the de-clutter approach here) βββββββββββββββββββ+// All three use the same 12-series overloaded dataset.++export const OverloadAllSeriesHighlight = meta.story({+ args: {+ data: manySeriesData,+ legendSummary: "none",+ legendInteraction: "highlight",+ },+});++export const OverloadToggleVisibility = meta.story({+ args: {+ data: manySeriesData,+ legendSummary: "none",+ legendInteraction: "toggle",+ },+});++export const OverloadTopFive = meta.story({+ args: {+ data: manySeriesData,+ legendSummary: "none",+ legendInteraction: "toggle",+ maxVisibleSeries: 5,+ },+});diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsxindex 3ea8de09f3..796e37f506 100644--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx@@ -1,10 +1,12 @@-import React, { useMemo, useState } from "react";+import React, { useMemo, useRef, useState } from "react";import {ChartActiveReferenceLine,ChartContainer,ChartTooltip,ChartTooltipContent,+ ChartTooltipPortal,} from "@/src/components/ui/chart";+import { NearestSeriesProbe } from "@/src/features/widgets/chart-library/NearestSeriesProbe";import {CartesianGrid,Label,@@ -21,12 +23,19 @@ import {} from "@/src/features/widgets/chart-library/chart-props";import {formatMetric,- getDimensionSummaries,getUniqueDimensions,groupDataByTimeDimension,toFullMetricString,} from "@/src/features/widgets/chart-library/utils";-import { cn } from "@/src/utils/tailwind";+import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";+import { prepareTimeAxis } from "@/src/features/widgets/chart-library/prepareTimeAxis";+import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepareVisibleSeries";+import {+ seriesColor,+ SeriesOverflowNote,+ TimeSeriesLegend,+ useSeriesLegend,+} from "@/src/features/widgets/chart-library/TimeSeriesLegend";/** computeMetricExtent returns the [min, max] of all numeric metric values across the data, for sizing the eq/neq band. */const computeMetricExtent = (@@ -180,76 +189,109 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({metricFormatter = (value, options) => formatMetric(value, options),legendPosition = "none",legendSummary = "none",- showDataPointDots = true,+ legendInteraction = "highlight",+ maxVisibleSeries,+ syncId,+ // Lines draw clean by default β a dot per sample is chart-junk on anything+ // but a handful of points. The hovered point still gets a dot (activeDot),+ // so the value is readable on hover without littering the line. (LFE-10549, V7)+ showDataPointDots = false,thresholds,}) => {const metricExtent = useMemo(() => computeMetricExtent(data), [data]);- const [highlightedDimension, setHighlightedDimension] = useState<- string | null- >(null);const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);- const dimensions = useMemo(() => getUniqueDimensions(data), [data]);- const dimensionSummaries = useMemo(- () => (legendSummary === "none" ? null : getDimensionSummaries(data)),- [data, legendSummary],+ const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);+ // Cap how many series we draw (data -> preparer seam): a high-cardinality+ // breakdown of hundreds of series is both unreadable and slow to hover. (LFE-10549)+ const series = useMemo(+ () => prepareVisibleSeries(data, allDimensions),+ [data, allDimensions],+ );+ const dimensions = series.visible;+ const { ref: containerRef, maxTicks } = useChartTickBudget();+ const chartBoxRef = useRef<HTMLDivElement>(null);+ const timeAxis = useMemo(+ () =>+ prepareTimeAxis(+ groupedData.map((d) => d.time_dimension),+ maxTicks,+ ),+ [groupedData, maxTicks],+ );++ const {+ legendItems,+ onLegendClick,+ isRendered,+ isDimmed,+ isHighlightActive,+ } = useSeriesLegend({+ data,+ dimensions,+ legendSummary,+ legendInteraction,+ maxVisibleSeries,+ });++ const renderedDimensions = dimensions.filter(isRendered);++ // Hover proximity: the line the cursor is vertically nearest to is emphasized+ // and the rest dimmed; cleared when the cursor isn't on a line (then everything+ // renders normally). Disabled while a series is click-focused, and gated on+ // self-hover so a synced sibling chart doesn't react to a cursor over another.+ const [selfHovered, setSelfHovered] = useState(false);+ const [nearestDimensions, setNearestDimensions] = useState<string[]>([]);+ const nearestSet = useMemo(+ () => new Set(nearestDimensions),+ [nearestDimensions],);+ const proximityActive = !isHighlightActive && nearestSet.size > 0;const tooltipFormatter = (value: number) =>toFullMetricString(metricFormatter(value, { style: "compact" }));- const handleLegendClick = (dimension: string) => {- setHighlightedDimension((prev) => (prev === dimension ? null : dimension));- };-return (- <div className="flex size-full min-w-0 flex-col">- {legendPosition === "above" && dimensions.length > 0 && (- <div className="min-w-0 shrink-0 overflow-x-auto pb-3">- <div className="flex w-max min-w-full flex-nowrap justify-end gap-4">- {dimensions.map((dimension, index) => {- const isHighlighted =- highlightedDimension === null ||- highlightedDimension === dimension;- const isMuted = highlightedDimension !== null && !isHighlighted;- // A `0` summary is a real value and must be shown; only a `null`- // summary (series with no data) is omitted. (LFE-10498)- const summary = dimensionSummaries?.get(dimension) ?? null;- return (- <button- key={dimension}- type="button"- onClick={() => handleLegendClick(dimension)}- className={cn(- "flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap transition-opacity",- "cursor-pointer hover:opacity-80",- isMuted && "opacity-40",- )}- aria-pressed={isHighlighted}- aria-label={- isHighlighted ? `Show only ${dimension}` : "Show all series"- }- >- <div- className="h-2 w-2 shrink-0 rounded-[2px]"- style={{- backgroundColor: `hsl(var(--chart-${(index % 8) + 1}))`,- }}- />- <span className="text-muted-foreground">{dimension}</span>- {summary !== null && (- <span className="text-foreground font-medium">- {tooltipFormatter(summary)}- </span>- )}- </button>- );- })}- </div>- </div>+ <div+ ref={containerRef}+ className="flex size-full min-w-0 flex-col"+ // onMouseMove (not just onMouseEnter) so the tooltip un-gates even when the+ // cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)+ onMouseEnter={() => setSelfHovered(true)}+ onMouseMove={() => setSelfHovered(true)}+ onMouseLeave={() => setSelfHovered(false)}+ // Keyboard parity: recharts' accessibilityLayer lets Tab/arrow users move+ // the crosshair, but that fires no mouse event β un-gate the tooltip on+ // focus too, and re-gate only when focus leaves the chart. (LFE-10549)+ onFocus={() => setSelfHovered(true)}+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null))+ setSelfHovered(false);+ }}+ >+ {legendPosition === "above" && (+ <TimeSeriesLegend+ items={legendItems}+ interaction={legendInteraction}+ onItemClick={onLegendClick}+ formatSummary={tooltipFormatter}+ />)}- <ChartContainer config={config} className="min-h-0 flex-1">- <LineChart accessibilityLayer={accessibilityLayer} data={groupedData}>+ <SeriesOverflowNote+ visibleCount={dimensions.length}+ totalCount={series.total}+ />+ <ChartContainer+ ref={chartBoxRef}+ config={config}+ className="min-h-0 flex-1"+ >+ <LineChart+ accessibilityLayer={accessibilityLayer}+ data={groupedData}+ syncId={syncId}+ syncMethod="value"+ ><CartesianGrid stroke="hsl(var(--chart-grid))" vertical={false} /><XAxisdataKey="time_dimension"@@ -257,8 +299,8 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({fontSize={12}tickLine={false}axisLine={false}- interval="preserveStartEnd"- minTickGap={24}+ interval={timeAxis.interval}+ tickFormatter={timeAxis.formatTick}/><YAxistype="number"@@ -271,24 +313,23 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({tickFormatter={(value) => tooltipFormatter(Number(value))}/>{dimensions.map((dimension, index) => {- const isMuted =- highlightedDimension !== null &&- highlightedDimension !== dimension;+ if (!isRendered(dimension)) return null;+ const nearest = proximityActive && nearestSet.has(dimension);+ const muted = isDimmed(dimension) || (proximityActive && !nearest);return (<Linekey={dimension}type="monotone"dataKey={dimension}- strokeWidth={2.5}- dot={showDataPointDots && !isMuted ? { r: 4 } : false}- activeDot={- showDataPointDots && !isMuted- ? { r: 5, strokeWidth: 0 }- : false- }- stroke={`hsl(var(--chart-${(index % 8) + 1}))`}- strokeOpacity={isMuted ? 0.2 : 1}+ strokeWidth={nearest ? 3.5 : 2.5}+ dot={showDataPointDots && !muted ? { r: 4 } : false}+ // The hover marker is independent of the static-dot setting: even+ // a dotless line reveals the point under the cursor.+ activeDot={muted ? false : { r: 5, strokeWidth: 0 }}+ stroke={seriesColor(index)}+ strokeOpacity={muted ? 0.2 : 1}connectNulls+ isAnimationActive={false}/>);})}@@ -301,17 +342,37 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({))}<ChartActiveReferenceLine /><ChartTooltip- contentStyle={{ backgroundColor: "hsl(var(--background))" }}- content={({ active, payload, label }) => (- <ChartTooltipContent- active={active}- payload={payload}- label={label}- indicator="line"- valueFormatter={tooltipFormatter}- sortPayloadByValue="desc"- />- )}+ content={({ active, payload, label, coordinate }) =>+ // Synced sibling charts share the crosshair (above) but the+ // tooltip belongs only to the chart under the cursor; it portals+ // into the overlay layer so the chart frame never clips it. (LFE-10549)+ selfHovered ? (+ <ChartTooltipPortal+ active={active}+ coordinate={coordinate}+ anchorRef={chartBoxRef}+ >+ <ChartTooltipContent+ active={active}+ payload={payload}+ label={label}+ indicator="line"+ labelFormatter={(value) => timeAxis.formatTooltip(value)}+ valueFormatter={tooltipFormatter}+ sortPayloadByValue="desc"+ highlightedKeys={proximityActive ? nearestSet : undefined}+ />+ </ChartTooltipPortal>+ ) : null+ }+ />+ <NearestSeriesProbe+ // Only the lines actually drawn are candidates β otherwise a hidden+ // (toggled-off) series whose data still sits in groupedData could be+ // picked as "nearest" and mute every visible line. (LFE-10549)+ dimensions={renderedDimensions}+ enabled={selfHovered && !isHighlightActive}+ onNearestChange={setNearestDimensions}/></LineChart></ChartContainer>diff --git a/web/src/features/widgets/chart-library/NearestSeriesProbe.tsx b/web/src/features/widgets/chart-library/NearestSeriesProbe.tsxnew file mode 100644index 0000000000..356f0c29b8--- /dev/null+++ b/web/src/features/widgets/chart-library/NearestSeriesProbe.tsx@@ -0,0 +1,102 @@+import { useEffect, useMemo, useRef } from "react";+import {+ useActiveTooltipCoordinate,+ useActiveTooltipDataPoints,+ useIsTooltipActive,+ useYAxisScale,+} from "recharts";++/** Two lines count as overlapping (both highlight) within this many pixels. */+const COLOCATED_PX = 1;++/**+ * Detects the single series line the cursor is vertically nearest to at the+ * hovered x and reports it upward so the chart can emphasize it. Renders+ * nothing β it only reads recharts' active-hover state via hooks, so it MUST be+ * a child of the chart (LineChart/AreaChart). (LFE-10549)+ *+ * Reports the nearest line only when the cursor is within `thresholdPx` of it+ * (otherwise nothing β the chart renders normally). A second line is reported+ * only when it sits within {@link COLOCATED_PX} of the nearest one, i.e. they+ * overlap at that pixel. Gate with `enabled` so a synced sibling chart (whose+ * crosshair tracks via syncId) doesn't react to a cursor that isn't over it.+ */+export function NearestSeriesProbe({+ dimensions,+ thresholdPx = 8,+ enabled = true,+ onNearestChange,+}: {+ dimensions: string[];+ thresholdPx?: number;+ enabled?: boolean;+ onNearestChange: (nearest: string[]) => void;+}) {+ const isActive = useIsTooltipActive();+ const coordinate = useActiveTooltipCoordinate();+ const yScale = useYAxisScale();+ const activePoints = useActiveTooltipDataPoints<Record<string, unknown>>();++ const nearest = useMemo(() => {+ const cursorY = coordinate?.y;+ const row = activePoints?.[0];+ if (+ !enabled ||+ !isActive ||+ typeof cursorY !== "number" ||+ !yScale ||+ !row+ ) {+ return [] as string[];+ }++ const positions: { dimension: string; pixelY: number }[] = [];+ for (const dimension of dimensions) {+ const value = row[dimension];+ if (typeof value !== "number" || !Number.isFinite(value)) continue;+ const pixelY = yScale(value);+ if (typeof pixelY !== "number") continue;+ positions.push({ dimension, pixelY });+ }+ if (positions.length === 0) return [];++ let closest = positions[0];+ for (const position of positions) {+ if (+ Math.abs(position.pixelY - cursorY) < Math.abs(closest.pixelY - cursorY)+ ) {+ closest = position;+ }+ }+ // Only highlight when the cursor is essentially on a line.+ if (Math.abs(closest.pixelY - cursorY) > thresholdPx) return [];+ // The nearest line, plus any line overlapping it at this pixel row.+ return positions+ .filter(+ (position) =>+ Math.abs(position.pixelY - closest.pixelY) <= COLOCATED_PX,+ )+ .map((position) => position.dimension);+ }, [+ enabled,+ isActive,+ coordinate,+ yScale,+ activePoints,+ dimensions,+ thresholdPx,+ ]);++ // Report only when the set actually changes (the cursor moving within a line's+ // band shouldn't churn parent state). JSON.stringify (not join) so two distinct+ // dimension lists can't collide on a shared separator.+ const key = JSON.stringify(nearest);+ const lastKey = useRef<string | null>(null);+ useEffect(() => {+ if (lastKey.current === key) return;+ lastKey.current = key;+ onNearestChange(nearest);+ }, [key, nearest, onNearestChange]);++ return null;+}diff --git a/web/src/features/widgets/chart-library/PieChart.tsx b/web/src/features/widgets/chart-library/PieChart.tsxindex b70dfe2830..e9e1b24e4f 100644--- a/web/src/features/widgets/chart-library/PieChart.tsx+++ b/web/src/features/widgets/chart-library/PieChart.tsx@@ -97,6 +97,7 @@ export const PieChart: React.FC<ChartProps> = ({paddingAngle={2}strokeWidth={5}shape={renderSector}+ isAnimationActive={false}>{/* Label in the center of the donut */}{data.length > 0 && (diff --git a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsxnew file mode 100644index 0000000000..5cf1305629--- /dev/null+++ b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx@@ -0,0 +1,226 @@+import React, { useEffect, useMemo, useRef, useState } from "react";+import {+ type DataPoint,+ type LegendInteraction,+ type LegendSummaryMode,+} from "@/src/features/widgets/chart-library/chart-props";+import { getDimensionSummaries } from "@/src/features/widgets/chart-library/utils";+import { cn } from "@/src/utils/tailwind";++/** The 8-slot chart palette, cycled by series index (matches the series fills). */+export const seriesColor = (index: number): string =>+ `hsl(var(--chart-${(index % 8) + 1}))`;++export type LegendItem = {+ dimension: string;+ /** Position in the dimension list β pins the swatch color to the series fill. */+ colorIndex: number;+ color: string;+ /** Per-series summary under the active mode, or `null` when there's nothing to show. */+ summary: number | null;+ /** Greyed in the legend: muted (highlight mode) or hidden (toggle mode). */+ dimmed: boolean;+ /** Highlight mode only: this is the actively-focused series (clicking it clears focus). */+ focused: boolean;+};++/**+ * Owns the per-series legend state for a multi-series time chart: the displayed+ * summary, the focus-vs-toggle interaction, and the optional top-N default that+ * tames overloaded charts. Returns presentation-ready legend items plus the two+ * predicates the chart needs β whether to draw a series, and whether to mute it.+ *+ * Shared by the line/area/bar time-series charts so they stay consistent.+ */+export function useSeriesLegend({+ data,+ dimensions,+ legendSummary = "none",+ legendInteraction = "highlight",+ maxVisibleSeries,+}: {+ data: DataPoint[];+ dimensions: string[];+ legendSummary?: LegendSummaryMode;+ legendInteraction?: LegendInteraction;+ maxVisibleSeries?: number;+}): {+ legendItems: LegendItem[];+ onLegendClick: (dimension: string) => void;+ isRendered: (dimension: string) => boolean;+ isDimmed: (dimension: string) => boolean;+ /** True when a series is click-focused (highlight mode) β gates hover effects. */+ isHighlightActive: boolean;+} {+ const summaries = useMemo(+ () => (legendSummary === "none" ? null : getDimensionSummaries(data)),+ [data, legendSummary],+ );++ // Seed the top-N visible set by additive magnitude (chart metrics are+ // non-negative, so a plain sum ranks "biggest series" well enough).+ const initialHidden = useMemo(() => {+ if (legendInteraction !== "toggle" || maxVisibleSeries === undefined) {+ return new Set<string>();+ }+ const magnitude = getDimensionSummaries(data);+ const keep = new Set(+ [...dimensions]+ .sort(+ (a, b) =>+ (magnitude.get(b) ?? -Infinity) - (magnitude.get(a) ?? -Infinity),+ )+ .slice(0, Math.max(0, maxVisibleSeries)),+ );+ return new Set(dimensions.filter((dimension) => !keep.has(dimension)));+ }, [data, dimensions, legendInteraction, maxVisibleSeries]);++ const [highlighted, setHighlighted] = useState<string | null>(null);+ const [hidden, setHidden] = useState<Set<string>>(initialHidden);++ // Re-seed when the series SET or overload config changes (e.g. data reloads).+ // Sort before stringifying so the key is order-insensitive: when the top-N+ // preparer reorders an unchanged set (two near-equal series swap rank on a+ // refresh), we must NOT wipe the user's highlight/hide selections.+ const seedKey = `${legendInteraction}|${maxVisibleSeries ?? ""}|${JSON.stringify([...dimensions].sort())}`;+ const prevSeedKey = useRef(seedKey);+ useEffect(() => {+ if (prevSeedKey.current === seedKey) return;+ prevSeedKey.current = seedKey;+ setHighlighted(null);+ setHidden(initialHidden);+ }, [seedKey, initialHidden]);++ const onLegendClick = (dimension: string) => {+ if (legendInteraction === "toggle") {+ setHidden((prev) => {+ const next = new Set(prev);+ if (next.has(dimension)) next.delete(dimension);+ else next.add(dimension);+ return next;+ });+ } else {+ setHighlighted((prev) => (prev === dimension ? null : dimension));+ }+ };++ const isRendered = (dimension: string) =>+ legendInteraction === "toggle" ? !hidden.has(dimension) : true;++ const isDimmed = (dimension: string) =>+ legendInteraction === "toggle"+ ? hidden.has(dimension)+ : highlighted !== null && highlighted !== dimension;++ const legendItems: LegendItem[] = dimensions.map((dimension, index) => ({+ dimension,+ colorIndex: index,+ color: seriesColor(index),+ summary: summaries?.get(dimension) ?? null,+ dimmed: isDimmed(dimension),+ focused: legendInteraction !== "toggle" && highlighted === dimension,+ }));++ const isHighlightActive =+ legendInteraction !== "toggle" && highlighted !== null;++ return {+ legendItems,+ onLegendClick,+ isRendered,+ isDimmed,+ isHighlightActive,+ };+}++/**+ * Honest "we didn't draw everything" caption for charts whose breakdown+ * overflowed the render cap (see {@link prepareVisibleSeries}). Rendered even+ * when the legend is hidden so a capped chart never silently looks complete.+ * (LFE-10549)+ */+export function SeriesOverflowNote({+ visibleCount,+ totalCount,+}: {+ visibleCount: number;+ totalCount: number;+}) {+ if (totalCount <= visibleCount) return null;+ return (+ <div className="text-muted-foreground shrink-0 pb-1 text-right text-xs">+ Showing top {visibleCount} of {totalCount} series+ </div>+ );+}++/**+ * Presentational legend row for the multi-series time charts. State and click+ * semantics come from {@link useSeriesLegend}; this only renders.+ */+export function TimeSeriesLegend({+ items,+ interaction,+ onItemClick,+ formatSummary,+}: {+ items: LegendItem[];+ interaction: LegendInteraction;+ onItemClick: (dimension: string) => void;+ formatSummary: (value: number) => string;+}) {+ if (items.length === 0) return null;++ return (+ // Wrap onto multiple rows so every series stays visible, but cap the+ // legend's height and scroll inside it β a chart with hundreds of series+ // must never let the legend crowd the plot out entirely. (LFE-10549)+ <div className="[max-height:8rem] min-w-0 shrink-0 overflow-y-auto pb-3">+ <div className="flex flex-wrap justify-end gap-x-4 gap-y-1">+ {items.map((item) => {+ // Labels must describe the NEXT action, not the current state.+ // - toggle: click flips visibility β "Show"/"Hide".+ // - highlight: clicking the focused series clears focus ("Show all+ // series"); clicking any other focuses it ("Show only X"). (Getting+ // this from `dimmed` alone inverts it once a series is focused.)+ const ariaLabel =+ interaction === "toggle"+ ? item.dimmed+ ? `Show ${item.dimension}`+ : `Hide ${item.dimension}`+ : item.focused+ ? "Show all series"+ : `Show only ${item.dimension}`;+ // aria-pressed reflects state: visible (toggle) / focused (highlight).+ const ariaPressed =+ interaction === "toggle" ? !item.dimmed : item.focused;+ return (+ <button+ key={item.dimension}+ type="button"+ onClick={() => onItemClick(item.dimension)}+ className={cn(+ "flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap transition-opacity",+ "cursor-pointer hover:opacity-80",+ item.dimmed && "opacity-40",+ )}+ aria-pressed={ariaPressed}+ aria-label={ariaLabel}+ >+ <div+ className="h-2 w-2 shrink-0 rounded-[2px]"+ style={{ backgroundColor: item.color }}+ />+ <span className="text-muted-foreground">{item.dimension}</span>+ {item.summary !== null && (+ <span className="text-foreground font-medium">+ {formatSummary(item.summary)}+ </span>+ )}+ </button>+ );+ })}+ </div>+ </div>+ );+}diff --git a/web/src/features/widgets/chart-library/VerticalBarChart.tsx b/web/src/features/widgets/chart-library/VerticalBarChart.tsxindex 88e020cf15..36dc8d27b7 100644--- a/web/src/features/widgets/chart-library/VerticalBarChart.tsx+++ b/web/src/features/widgets/chart-library/VerticalBarChart.tsx@@ -62,6 +62,7 @@ export const VerticalBarChart: React.FC<ChartProps> = ({radius={[4, 4, 0, 0]}className="fill-(--color-metric)"fillOpacity={subtleFill ? 0.3 : 1}+ isAnimationActive={false}/><ChartTooltipcursor={false}diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsxindex 3c2fcfd687..73d6671fa0 100644--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx@@ -1,9 +1,10 @@-import React, { useMemo } from "react";+import React, { useMemo, useRef, useState } from "react";import {ChartActiveReferenceLine,ChartContainer,ChartTooltip,ChartTooltipContent,+ ChartTooltipPortal,} from "@/src/components/ui/chart";import { Bar, BarChart, XAxis, YAxis } from "recharts";import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";@@ -13,6 +14,15 @@ import {groupDataByTimeDimension,toFullMetricString,} from "@/src/features/widgets/chart-library/utils";+import { useChartTickBudget } from "@/src/features/widgets/chart-library/useChartTickBudget";+import { prepareTimeAxis } from "@/src/features/widgets/chart-library/prepareTimeAxis";+import { prepareVisibleSeries } from "@/src/features/widgets/chart-library/prepareVisibleSeries";+import {+ seriesColor,+ SeriesOverflowNote,+ TimeSeriesLegend,+ useSeriesLegend,+} from "@/src/features/widgets/chart-library/TimeSeriesLegend";/*** VerticalBarChartTimeSeries component@@ -32,63 +42,149 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({},accessibilityLayer = true,metricFormatter = (value, options) => formatMetric(value, options),+ legendPosition = "none",+ legendSummary = "none",+ legendInteraction = "highlight",+ maxVisibleSeries,+ syncId,subtleFill = false,}) => {+ const [selfHovered, setSelfHovered] = useState(false);const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);- const dimensions = useMemo(() => getUniqueDimensions(data), [data]);+ const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);+ // Cap how many series we draw (data -> preparer seam): a high-cardinality+ // breakdown of hundreds of series is both unreadable and slow to hover. (LFE-10549)+ const series = useMemo(+ () => prepareVisibleSeries(data, allDimensions),+ [data, allDimensions],+ );+ const dimensions = series.visible;+ const { ref: containerRef, maxTicks } = useChartTickBudget();+ const chartBoxRef = useRef<HTMLDivElement>(null);+ const timeAxis = useMemo(+ () =>+ prepareTimeAxis(+ groupedData.map((d) => d.time_dimension),+ maxTicks,+ ),+ [groupedData, maxTicks],+ );++ const { legendItems, onLegendClick, isRendered, isDimmed } = useSeriesLegend({+ data,+ dimensions,+ legendSummary,+ legendInteraction,+ maxVisibleSeries,+ });+const formatValue = (value: number) =>toFullMetricString(metricFormatter(value, { style: "compact" }));+ const renderedDimensions = dimensions.filter(isRendered);+return (- <ChartContainer- config={config}- className="[&_.recharts-bar-rectangle:hover]:opacity-30 dark:[&_.recharts-bar-rectangle:hover]:opacity-100 dark:[&_.recharts-bar-rectangle:hover]:brightness-[3]"+ <div+ ref={containerRef}+ className="flex h-full w-full min-w-0 flex-col"+ // onMouseMove (not just onMouseEnter) so the tooltip un-gates even when the+ // cursor is already over the chart at mount/refresh (enter never fires). (LFE-10549)+ onMouseEnter={() => setSelfHovered(true)}+ onMouseMove={() => setSelfHovered(true)}+ onMouseLeave={() => setSelfHovered(false)}+ // Keyboard parity: recharts' accessibilityLayer lets Tab/arrow users move+ // the crosshair, but that fires no mouse event β un-gate the tooltip on+ // focus too, and re-gate only when focus leaves the chart. (LFE-10549)+ onFocus={() => setSelfHovered(true)}+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null))+ setSelfHovered(false);+ }}>- <BarChart accessibilityLayer={accessibilityLayer} data={groupedData}>- <XAxis- dataKey="time_dimension"- stroke="hsl(var(--chart-grid))"- fontSize={12}- tickLine={false}- axisLine={false}- interval="preserveStartEnd"- minTickGap={24}- />- <YAxis- type="number"- stroke="hsl(var(--chart-grid))"- fontSize={12}- tickLine={false}- axisLine={false}- niceTicks="auto"- tickFormatter={(value) => formatValue(Number(value))}+ {legendPosition === "above" && (+ <TimeSeriesLegend+ items={legendItems}+ interaction={legendInteraction}+ onItemClick={onLegendClick}+ formatSummary={formatValue}/>- {dimensions.map((dimension, index) => (- <Bar- key={dimension}- dataKey={dimension}- stroke={`hsl(var(--chart-${(index % 8) + 1}))`}- fill={`hsl(var(--chart-${(index % 8) + 1}))`}- fillOpacity={subtleFill ? 0.3 : 1}- stackId={dimensions.length > 1 ? "stack" : undefined}+ )}+ <SeriesOverflowNote+ visibleCount={dimensions.length}+ totalCount={series.total}+ />+ <ChartContainer+ ref={chartBoxRef}+ config={config}+ className="min-h-0 flex-1 [&_.recharts-bar-rectangle:hover]:opacity-30 dark:[&_.recharts-bar-rectangle:hover]:opacity-100 dark:[&_.recharts-bar-rectangle:hover]:brightness-[3]"+ >+ <BarChart+ accessibilityLayer={accessibilityLayer}+ data={groupedData}+ syncId={syncId}+ syncMethod="value"+ >+ <XAxis+ dataKey="time_dimension"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ interval={timeAxis.interval}+ tickFormatter={timeAxis.formatTick}/>- ))}- <ChartActiveReferenceLine />- <ChartTooltip- cursor={false}- contentStyle={{ backgroundColor: "hsl(var(--background))" }}- content={({ active, payload, label }) => (- <ChartTooltipContent- active={active}- payload={payload}- label={label}- valueFormatter={formatValue}- sortPayloadByValue="desc"- />- )}- />- </BarChart>- </ChartContainer>+ <YAxis+ type="number"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ niceTicks="auto"+ tickFormatter={(value) => formatValue(Number(value))}+ />+ {dimensions.map((dimension, index) => {+ if (!isRendered(dimension)) return null;+ const muted = isDimmed(dimension);+ return (+ <Bar+ key={dimension}+ dataKey={dimension}+ stroke={seriesColor(index)}+ strokeOpacity={muted ? 0.2 : 1}+ fill={seriesColor(index)}+ fillOpacity={muted ? 0.2 : subtleFill ? 0.3 : 1}+ stackId={renderedDimensions.length > 1 ? "stack" : undefined}+ isAnimationActive={false}+ />+ );+ })}+ <ChartActiveReferenceLine />+ <ChartTooltip+ cursor={false}+ content={({ active, payload, label, coordinate }) =>+ // Synced siblings show only the crosshair; the tooltip is the+ // hovered chart's, portaled out of the chart frame. (LFE-10549)+ selfHovered ? (+ <ChartTooltipPortal+ active={active}+ coordinate={coordinate}+ anchorRef={chartBoxRef}+ >+ <ChartTooltipContent+ active={active}+ payload={payload}+ label={label}+ labelFormatter={(value) => timeAxis.formatTooltip(value)}+ valueFormatter={formatValue}+ sortPayloadByValue="desc"+ />+ </ChartTooltipPortal>+ ) : null+ }+ />+ </BarChart>+ </ChartContainer>+ </div>);};diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.tsindex 3acaf5f57d..394e722c38 100644--- a/web/src/features/widgets/chart-library/chart-props.ts+++ b/web/src/features/widgets/chart-library/chart-props.ts@@ -15,16 +15,27 @@ export type LegendPosition = "above" | "none";* with the card's headline number.* - `"none"`: no per-series summary (default).*- * Only additive metrics get a summary. A summary is deliberately *not* offered- * for non-additive metrics (latency percentiles, average scores): a cross-bucket- * sum is meaningless for them, and a correct average can't be computed here- * because the upstream pipeline pads missing buckets with real `0`s (it would- * deflate the mean). Such charts opt out via the `"none"` default. The mode is- * chosen per call-site because additivity is a property of the metric's- * aggregation, decided upstream of the chart. (LFE-10498)+ * Only additive metrics get a legend value. A summary is deliberately *not*+ * offered for non-additive metrics (latency percentiles, scores): a cross-bucket+ * sum is meaningless for them, a correct average can't be computed here because+ * the upstream pipeline pads missing buckets with real `0`s (it would deflate the+ * mean), and an unlabeled non-sum number reads ambiguously. Such charts show the+ * bare series name (the `"none"` default). The mode is chosen per call-site+ * because additivity is a property of the metric's aggregation, decided upstream+ * of the chart. (LFE-10498, LFE-10549)*/export type LegendSummaryMode = "sum" | "none";+/**+ * How clicking a legend entry behaves on a multi-series time chart:+ * - `"highlight"` (default): clicking a series focuses it and mutes the rest;+ * clicking again clears. All series stay rendered. (Historical behavior.)+ * - `"toggle"`: clicking a series shows/hides it; hidden series are dropped from+ * the plot and greyed in the legend. Pairs with `maxVisibleSeries` to tame+ * overloaded charts by hiding the long tail by default. (LFE-10549)+ */+export type LegendInteraction = "highlight" | "toggle";+export interface FormattedMetric {negative?: boolean;prefix?: string;@@ -72,6 +83,20 @@ export interface ChartProps {metricFormatter?: MetricFormatterFunction;legendPosition?: LegendPosition;legendSummary?: LegendSummaryMode;+ /** How a legend click behaves (focus-vs-toggle). Defaults to `"highlight"`. */+ legendInteraction?: LegendInteraction;+ /**+ * Cap the number of series drawn by default (top-N by magnitude); the rest+ * start hidden but remain toggleable from the legend. Only meaningful with+ * `legendInteraction="toggle"`. Undefined = draw every series. (LFE-10549)+ */+ maxVisibleSeries?: number;+ /**+ * Shared sync group: charts on the same dashboard timeline that pass the same+ * `syncId` show a synced hover crosshair + tooltip β hovering one moves the+ * vertical time marker on all of them. (LFE-10549)+ */+ syncId?: string;showValueLabels?: boolean;showDataPointDots?: boolean;subtleFill?: boolean;diff --git a/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.ts b/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.tsnew file mode 100644index 0000000000..a0b855d5d5--- /dev/null+++ b/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.ts@@ -0,0 +1,143 @@+import {+ prepareTimeAxis,+ parseChartTimestamp,+} from "@/src/features/widgets/chart-library/prepareTimeAxis";++const HOUR = 3_600_000;+const DAY = 24 * HOUR;+const iso = (ms: number) => new Date(ms).toISOString();+const MONTH_DAY = /[A-Z][a-z]{2}\s\d/; // e.g. "Jun 28"++describe("prepareTimeAxis", () => {+ it("intraday span β time-only ticks (no dates)", () => {+ const start = Date.UTC(2026, 5, 28, 0);+ const values = Array.from({ length: 24 }, (_, h) => iso(start + h * HOUR));+ const axis = prepareTimeAxis(values, 6);++ expect(axis.mode).toBe("time");+ const label = axis.formatTick(values[5]);+ expect(/\d/.test(label)).toBe(true);+ expect(MONTH_DAY.test(label)).toBe(false); // never a date on a time-scale tick+ });++ it("span >24h uses date mode (no hour-only ticks repeating across midnight)", () => {+ // 36 hourly buckets β 35h span β must NOT be time mode (would duplicate hours).+ const start = Date.UTC(2026, 5, 28, 0);+ const values = Array.from({ length: 36 }, (_, h) => iso(start + h * HOUR));+ const axis = prepareTimeAxis(values, 6);+ expect(axis.mode).toBe("date");+ });++ it("a single day (β€24h) stays time mode", () => {+ const start = Date.UTC(2026, 5, 28, 0);+ const values = Array.from({ length: 24 }, (_, h) => iso(start + h * HOUR));+ expect(prepareTimeAxis(values, 6).mode).toBe("time");+ });++ it("date ticks add the year only when the range crosses a year boundary", () => {+ const sameYear = Array.from({ length: 14 }, (_, d) =>+ iso(Date.UTC(2026, 5, 1) + d * DAY),+ );+ expect(+ /\d{4}/.test(prepareTimeAxis(sameYear, 6).formatTick(sameYear[0])),+ ).toBe(false);++ // Dec 26 β Jan 8 across the 2025/2026 boundary.+ const crossYear = Array.from({ length: 14 }, (_, d) =>+ iso(Date.UTC(2025, 11, 26) + d * DAY),+ );+ const axis = prepareTimeAxis(crossYear, 6);+ expect(axis.mode).toBe("date");+ expect(/2025|2026/.test(axis.formatTick(crossYear[0]))).toBe(true);+ });++ it("multi-day span β date ticks aligned to whole days (uniform gaps)", () => {+ // hourly buckets across 5 days β 120 points+ const start = Date.UTC(2026, 5, 1, 0);+ const values = Array.from({ length: 24 * 5 }, (_, i) =>+ iso(start + i * HOUR),+ );+ const axis = prepareTimeAxis(values, 6);++ expect(axis.mode).toBe("date");+ // bucketsPerDay = 24 β shown ticks land a whole number of days apart+ expect((axis.interval + 1) % 24).toBe(0);+ expect(MONTH_DAY.test(axis.formatTick(values[0]))).toBe(true);+ });++ it("daily buckets over a couple of weeks β date mode, evenly thinned", () => {+ const start = Date.UTC(2026, 5, 1, 0);+ const values = Array.from({ length: 14 }, (_, d) => iso(start + d * DAY));+ const axis = prepareTimeAxis(values, 5);++ expect(axis.mode).toBe("date");+ expect(axis.interval).toBeGreaterThanOrEqual(1); // 14 days, β€5 ticks β skip some+ });++ it("very long span β month labels", () => {+ const start = Date.UTC(2026, 0, 1, 0);+ const values = Array.from({ length: 200 }, (_, d) => iso(start + d * DAY));+ const axis = prepareTimeAxis(values, 6);++ expect(axis.mode).toBe("month");+ expect(/[A-Z][a-z]{2}\s\d{4}/.test(axis.formatTick(values[0]))).toBe(true);+ });++ it("tooltip always carries the year", () => {+ const values = [+ iso(Date.UTC(2026, 5, 28, 23)),+ iso(Date.UTC(2026, 5, 29, 0)),+ ];+ const axis = prepareTimeAxis(values, 6);+ expect(/2026/.test(axis.formatTooltip(values[0]))).toBe(true);+ });++ it("tooltip keeps the time for sub-day buckets in date mode (distinguishes hours)", () => {+ // hourly buckets across 7 days β date mode, but each bucket is an hour+ const start = Date.UTC(2026, 5, 1, 0);+ const values = Array.from({ length: 24 * 7 }, (_, i) =>+ iso(start + i * HOUR),+ );+ const axis = prepareTimeAxis(values, 6);+ expect(axis.mode).toBe("date");+ const oneAm = axis.formatTooltip(iso(Date.UTC(2026, 5, 2, 1)));+ const elevenPm = axis.formatTooltip(iso(Date.UTC(2026, 5, 2, 23)));+ expect(oneAm).not.toBe(elevenPm); // 1 AM vs 11 PM must differ+ expect(/\b(AM|PM)\b/.test(oneAm)).toBe(true);+ });++ it("daily buckets get a time-free tooltip (no spurious 12:00 AM)", () => {+ const start = Date.UTC(2026, 5, 1, 0);+ const values = Array.from({ length: 14 }, (_, d) => iso(start + d * DAY));+ const axis = prepareTimeAxis(values, 6);+ expect(/\b(AM|PM)\b/.test(axis.formatTooltip(values[0]))).toBe(false);+ });++ it("non-temporal labels (compare-view run names) pass through verbatim", () => {+ // Bare integers and arbitrary strings are run names, not timestamps.+ const values = ["1", "47", "20241230", "baseline-run"];+ const axis = prepareTimeAxis(values, 6);+ expect(axis.mode).toBe("category");+ expect(axis.formatTick("20241230")).toBe("20241230");+ expect(axis.formatTick("baseline-run")).toBe("baseline-run");+ expect(axis.formatTooltip("1")).toBe("1");+ });++ it("does not coerce bare numeric strings into epoch dates", () => {+ expect(parseChartTimestamp("1")).toBeNull();+ expect(parseChartTimestamp("20241230")).toBeNull();+ expect(parseChartTimestamp("2026-06-28")?.getTime()).toBe(+ Date.UTC(2026, 5, 28),+ );+ });++ it("parses a no-timezone ClickHouse datetime as UTC (not local)", () => {+ expect(parseChartTimestamp("2026-06-28 23:00:00")?.getTime()).toBe(+ Date.UTC(2026, 5, 28, 23, 0, 0),+ );+ expect(parseChartTimestamp("2026-06-28T23:00:00.000Z")?.getTime()).toBe(+ Date.UTC(2026, 5, 28, 23, 0, 0),+ );+ expect(parseChartTimestamp("not a date")).toBeNull();+ });+});diff --git a/web/src/features/widgets/chart-library/prepareTimeAxis.ts b/web/src/features/widgets/chart-library/prepareTimeAxis.tsnew file mode 100644index 0000000000..cbc7d40a63--- /dev/null+++ b/web/src/features/widgets/chart-library/prepareTimeAxis.ts@@ -0,0 +1,209 @@+/**+ * PREPARER LAYER β time axis.+ *+ * One source of truth for the time x-axis: from the raw bucket values it decides+ * the *scale-appropriate* label format AND the tick placement, and hands the+ * visualiser ready-to-use formatters + a tick interval. The visualiser renders+ * them and decides nothing. Data β preparer β visualiser, one way. (LFE-10549)+ *+ * Scale rule (one unit per scale β never "date, time" on every tick):+ * - intraday span β show TIME only ("2 PM", "2:30 PM")+ * - multi-day span β show DATES, day-aligned ("Jun 28", "Jul 2", β¦) at an+ * even number-of-days step so the gaps are identical+ * - very long span β show MONTHS ("Jun 2026")+ * The exact date+time always lives in the tooltip, so nothing is lost.+ */++import { getEvenTickInterval } from "@/src/features/widgets/chart-library/utils";++const MINUTE = 60_000;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;+/**+ * At/below this span we're "zoomed into a day" β time-only ticks. Capped at a+ * single day so a wider span never shows hour-only labels that silently repeat+ * across a midnight boundary (e.g. "12 AM" at both ends of a 36h range).+ */+const TIME_SCALE_MAX = DAY;+/** Above this total span we switch from day labels to month labels. */+const MONTH_SCALE_MIN = 180 * DAY;++type AxisMode = "time" | "date" | "month" | "category";++/**+ * Parse a raw bucket value into a Date, but ONLY when it actually looks like a+ * timestamp: an epoch-ms number, an ISO string, or a "YYYY-MM-DD[ T]HH:MM:SS"+ * ClickHouse datetime (optionally a bare "YYYY-MM-DD"). Values without an+ * explicit timezone are treated as UTC, because the buckets come back+ * UTC-aligned β parsing them as local is what produced wrong dates.+ *+ * Deliberately conservative for strings: a categorical x-axis (e.g. the+ * dataset-compare view) feeds arbitrary labels through `time_dimension` β+ * including bare integers like "1", "47", or "20241230" (run names). Those must+ * render as-is, so we never coerce a bare number into an epoch date, and never+ * fall back to `new Date(<arbitrary string>)`. Mirrors the historical+ * `looksLikeIso` guard. (LFE-10549)+ */+export function parseChartTimestamp(raw: unknown): Date | null {+ if (raw == null) return null;+ if (typeof raw === "number") {+ const d = new Date(raw);+ return Number.isNaN(d.getTime()) ? null : d;+ }+ if (typeof raw !== "string") return null;+ const s = raw.trim();+ if (s === "") return null;++ const match = s.match(+ /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/,+ );+ if (match) {+ const [, y, mo, d, h, mi, se, tz] = match;+ if (tz) {+ const parsed = new Date(s.replace(" ", "T"));+ return Number.isNaN(parsed.getTime()) ? null : parsed;+ }+ // No timezone β interpret as UTC (the buckets are UTC-aligned).+ return new Date(Date.UTC(+y, +mo - 1, +d, +h, +mi, se ? +se : 0));+ }++ // Bare calendar date (no time component) β UTC midnight.+ const dateOnly = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);+ if (dateOnly) {+ const [, y, mo, d] = dateOnly;+ return new Date(Date.UTC(+y, +mo - 1, +d));+ }++ // Anything else is not a timestamp (a categorical label) β leave it to the+ // caller to render verbatim.+ return null;+}++/** Median spacing between sorted buckets β the inferred bucket size in ms. */+function inferBucketMs(timestamps: number[]): number {+ if (timestamps.length < 2) return 0;+ const sorted = [...timestamps].sort((a, b) => a - b);+ const diffs: number[] = [];+ for (let i = 1; i < sorted.length; i++) {+ const diff = sorted[i] - sorted[i - 1];+ if (diff > 0) diffs.push(diff);+ }+ if (diffs.length === 0) return 0;+ diffs.sort((a, b) => a - b);+ return diffs[Math.floor(diffs.length / 2)];+}++export type TimeAxis = {+ /** recharts numeric x-axis `interval` (ticks skipped between shown ticks). */+ interval: number;+ /** Scale-appropriate label for a shown tick. */+ formatTick: (raw: unknown) => string;+ /** Fuller label for the tooltip (always date + year, time when intraday). */+ formatTooltip: (raw: unknown) => string;+ mode: AxisMode;+};++/**+ * Decide the time-axis format + tick spacing for a set of raw bucket values.+ * `maxTicks` is how many labels fit the chart's measured width.+ */+export function prepareTimeAxis(rawValues: unknown[], maxTicks = 6): TimeAxis {+ const timestamps: number[] = [];+ for (const value of rawValues) {+ const date = parseChartTimestamp(value);+ if (date) timestamps.push(date.getTime());+ }++ const target = Math.max(2, maxTicks);++ // Non-temporal x-axis (e.g. dataset-compare run names): the labels aren't+ // timestamps, so we don't invent dates β render them verbatim and only thin+ // by index. We treat the axis as time only when most values actually parse.+ const temporal =+ timestamps.length > 0 && timestamps.length >= rawValues.length / 2;+ if (!temporal) {+ const passthrough = (raw: unknown): string =>+ raw == null ? "" : typeof raw === "string" ? raw : String(raw);+ return {+ interval: getEvenTickInterval(rawValues.length, target),+ formatTick: passthrough,+ formatTooltip: passthrough,+ mode: "category",+ };+ }++ const count = timestamps.length;+ const bucketMs = inferBucketMs(timestamps);+ const minTs = Math.min(...timestamps);+ const maxTs = Math.max(...timestamps);+ const span = count >= 2 ? maxTs - minTs : 0;+ // Date ticks normally omit the year (one unit per scale), but show it when the+ // range straddles a year boundary so "Dec 29 β Jan 5" stays unambiguous.+ // Use LOCAL year to match the tick formatter (toLocaleDateString renders in+ // local time), so a range that crosses Jan 1 locally still shows the year.+ const crossesYear =+ new Date(minTs).getFullYear() !== new Date(maxTs).getFullYear();++ const mode: AxisMode =+ span > 0 && span <= TIME_SCALE_MAX+ ? "time"+ : span >= MONTH_SCALE_MIN+ ? "month"+ : "date";++ let interval: number;+ if (mode === "time" || mode === "month") {+ // Evenly spaced by bucket index.+ interval = getEvenTickInterval(count, target);+ } else {+ // Date mode: align ticks to a whole number of days so each shown tick is a+ // distinct day at the same time-of-day β identical gaps, no repeated dates.+ const bucketsPerDay =+ bucketMs > 0 ? Math.max(1, Math.round(DAY / bucketMs)) : 1;+ const dayCount = Math.max(1, Math.round(count / bucketsPerDay));+ const dayStep = Math.max(1, Math.ceil(dayCount / target));+ interval = bucketsPerDay * dayStep - 1;+ }++ const subHour = bucketMs > 0 && bucketMs < HOUR;+ const subDay = bucketMs > 0 && bucketMs < DAY;++ const formatTick = (raw: unknown): string => {+ const date = parseChartTimestamp(raw);+ if (!date) return typeof raw === "string" ? raw : "";+ if (mode === "time") {+ return date.toLocaleTimeString("en-US", {+ hour: "numeric",+ ...(subHour ? { minute: "2-digit" } : {}),+ });+ }+ if (mode === "month") {+ return date.toLocaleDateString("en-US", {+ month: "short",+ year: "numeric",+ });+ }+ return date.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ ...(crossesYear ? { year: "numeric" } : {}),+ });+ };++ // The tooltip identifies one exact bucket, so it always carries the date ++ // year and adds the time whenever buckets are sub-day β otherwise every+ // hourly bucket within a day (e.g. a 7-day range trunc'd to the hour) would+ // show an identical "Jun 28, 2026" and you couldn't tell 1 AM from 11 PM.+ const formatTooltip = (raw: unknown): string => {+ const date = parseChartTimestamp(raw);+ if (!date) return typeof raw === "string" ? raw : "";+ return date.toLocaleString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ ...(subDay ? { hour: "numeric", minute: "2-digit" } : {}),+ });+ };++ return { interval, formatTick, formatTooltip, mode };+}diff --git a/web/src/features/widgets/chart-library/prepareVisibleSeries.clienttest.ts b/web/src/features/widgets/chart-library/prepareVisibleSeries.clienttest.tsnew file mode 100644index 0000000000..be083a2d33--- /dev/null+++ b/web/src/features/widgets/chart-library/prepareVisibleSeries.clienttest.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_MAX_RENDERED_SERIES,+ prepareVisibleSeries,+} from "@/src/features/widgets/chart-library/prepareVisibleSeries";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";++/** Builds one bucket per value for a dimension, so its summary == sum(values). */+const series = (dimension: string, values: number[]): DataPoint[] =>+ values.map((metric, i) => ({+ time_dimension: `2026-01-0${i + 1}T00:00:00Z`,+ dimension,+ metric,+ }));++describe("prepareVisibleSeries", () => {+ it("returns every series untouched (and in original order) below the cap", () => {+ const dimensions = ["b", "a", "c"];+ const data = [+ ...series("b", [1]),+ ...series("a", [100]),+ ...series("c", [10]),+ ];+ const result = prepareVisibleSeries(data, dimensions, 25);+ expect(result).toEqual({ visible: ["b", "a", "c"], total: 3, hidden: 0 });+ });++ it("keeps the highest-magnitude series and reports the dropped count", () => {+ const dimensions = ["small", "big", "medium"];+ const data = [+ ...series("small", [1, 1]),+ ...series("big", [50, 50]),+ ...series("medium", [10, 10]),+ ];+ const result = prepareVisibleSeries(data, dimensions, 2);+ expect(result.visible).toEqual(["big", "medium"]);+ expect(result.total).toBe(3);+ expect(result.hidden).toBe(1);+ });++ it("breaks ties by name for a deterministic selection", () => {+ const dimensions = ["delta", "alpha", "charlie", "bravo"];+ const data = [+ ...series("delta", [5]),+ ...series("alpha", [5]),+ ...series("charlie", [5]),+ ...series("bravo", [5]),+ ];+ const result = prepareVisibleSeries(data, dimensions, 2);+ // All equal magnitude -> alphabetical.+ expect(result.visible).toEqual(["alpha", "bravo"]);+ });++ it("ranks series with no finite data last", () => {+ const dimensions = ["empty", "tiny", "huge"];+ const data = [+ // 'empty' has only non-finite metrics -> null summary -> ranked last.+ {+ time_dimension: "2026-01-01T00:00:00Z",+ dimension: "empty",+ metric: NaN,+ },+ ...series("tiny", [1]),+ ...series("huge", [999]),+ ];+ const result = prepareVisibleSeries(data, dimensions, 2);+ expect(result.visible).toEqual(["huge", "tiny"]);+ expect(result.hidden).toBe(1);+ });++ it("treats a real 0-sum series as data (kept over a no-data series)", () => {+ const dimensions = ["zero", "nodata"];+ const data = [+ ...series("zero", [0, 0]),+ {+ time_dimension: "2026-01-01T00:00:00Z",+ dimension: "nodata",+ metric: NaN,+ },+ ];+ const result = prepareVisibleSeries(data, dimensions, 1);+ expect(result.visible).toEqual(["zero"]);+ });++ it("defaults to the shared render cap", () => {+ const dimensions = Array.from(+ { length: DEFAULT_MAX_RENDERED_SERIES + 30 },+ (_, i) => `series-${i}`,+ );+ const data = dimensions.flatMap((d, i) => series(d, [i]));+ const result = prepareVisibleSeries(data, dimensions);+ expect(result.visible).toHaveLength(DEFAULT_MAX_RENDERED_SERIES);+ expect(result.hidden).toBe(30);+ expect(result.total).toBe(DEFAULT_MAX_RENDERED_SERIES + 30);+ });+});diff --git a/web/src/features/widgets/chart-library/prepareVisibleSeries.ts b/web/src/features/widgets/chart-library/prepareVisibleSeries.tsnew file mode 100644index 0000000000..b93c536f88--- /dev/null+++ b/web/src/features/widgets/chart-library/prepareVisibleSeries.ts@@ -0,0 +1,63 @@+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { getDimensionSummaries } from "@/src/features/widgets/chart-library/utils";++/**+ * Hard ceiling on how many series a multi-series time chart draws. High-+ * cardinality breakdowns (group-by id / name / user) routinely produce+ * hundreds of series; drawing them all is both unreadable (a legend/tooltip of+ * hundreds of one-off entries) and pathologically slow β recharts re-resolves+ * per-graphical-item state on every hover, so cost grows ~quadratically with+ * series count and a few hundred series make hovering janky. Bounding the drawn+ * set keeps every chart fast and legible regardless of the data thrown at it.+ * (LFE-10549)+ */+export const DEFAULT_MAX_RENDERED_SERIES = 25;++export type PreparedSeries = {+ /**+ * The series to draw, highest-magnitude first when the data overflowed the+ * cap (so the biggest contributors win the cap and the stable palette slots).+ * Returned in the caller's original order when nothing was dropped, so normal+ * charts keep their existing color assignment.+ */+ visible: string[];+ /** Distinct series present in the data. */+ total: number;+ /** Series not drawn (`total - visible.length`); `0` when nothing was capped. */+ hidden: number;+};++/**+ * Preparer (data -> visualiser seam): decides WHICH series a chart draws when+ * the breakdown is too wide to show them all. Ranks series by additive+ * magnitude (sum of finite metric values; this also tracks "most prominent" for+ * non-additive metrics well enough to pick the headline series) and keeps the+ * top `maxSeries`. Series with no finite value rank last. Ties break by name so+ * the selection is deterministic across reloads.+ *+ * Pure and side-effect free: presentation components consume the result, they+ * don't re-decide it. See ARCHITECTURE.md.+ */+export function prepareVisibleSeries(+ data: DataPoint[],+ dimensions: string[],+ maxSeries: number = DEFAULT_MAX_RENDERED_SERIES,+): PreparedSeries {+ const total = dimensions.length;+ if (total <= maxSeries) {+ return { visible: dimensions, total, hidden: 0 };+ }++ const summaries = getDimensionSummaries(data);+ const magnitude = (dimension: string): number =>+ summaries.get(dimension) ?? -Infinity;++ const ranked = [...dimensions].sort((a, b) => {+ const diff = magnitude(b) - magnitude(a);+ if (diff !== 0 && !Number.isNaN(diff)) return diff;+ return a < b ? -1 : a > b ? 1 : 0;+ });++ const visible = ranked.slice(0, maxSeries);+ return { visible, total, hidden: total - visible.length };+}diff --git a/web/src/features/widgets/chart-library/useChartTickBudget.ts b/web/src/features/widgets/chart-library/useChartTickBudget.tsnew file mode 100644index 0000000000..0e75672e00--- /dev/null+++ b/web/src/features/widgets/chart-library/useChartTickBudget.ts@@ -0,0 +1,33 @@+import { useEffect, useRef, useState } from "react";++// Approximate horizontal room one x-axis label needs (incl. a gap). Labels are+// now single-unit ("2 PM" / "Jun 28" / "Jun 2026"), so ~64px is comfortable.+const APPROX_LABEL_PX = 64;+const AXIS_GUTTER_PX = 56;++/**+ * Measures the chart's width and returns how many x-axis ticks comfortably fit+ * (`maxTicks`). The preparer (`prepareTimeAxis`) turns that budget into the+ * actual tick interval + labels β this hook only measures. (LFE-10549)+ */+export function useChartTickBudget() {+ const ref = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(0);++ useEffect(() => {+ const element = ref.current;+ if (!element) return;+ const observer = new ResizeObserver((entries) => {+ setWidth(entries[0]?.contentRect.width ?? 0);+ });+ observer.observe(element);+ return () => observer.disconnect();+ }, []);++ const maxTicks =+ width > 0+ ? Math.max(2, Math.floor((width - AXIS_GUTTER_PX) / APPROX_LABEL_PX))+ : 6;++ return { ref, maxTicks };+}diff --git a/web/src/features/widgets/chart-library/utils.clienttest.ts b/web/src/features/widgets/chart-library/utils.clienttest.tsindex 36e8131d9c..d20ecde9e7 100644--- a/web/src/features/widgets/chart-library/utils.clienttest.ts+++ b/web/src/features/widgets/chart-library/utils.clienttest.ts@@ -1,6 +1,7 @@import {formatMetric,getDimensionSummaries,+ getEvenTickInterval,} from "@/src/features/widgets/chart-library/utils";import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";@@ -259,3 +260,23 @@ describe("getDimensionSummaries", () => {expect(summaries.get("histo")).toBeNull();});});++describe("getEvenTickInterval", () => {+ it("shows every tick when the point count fits the target", () => {+ expect(getEvenTickInterval(7)).toBe(0);+ expect(getEvenTickInterval(8)).toBe(0);+ expect(getEvenTickInterval(0)).toBe(0);+ });++ it("skips ticks evenly past the target so gaps stay uniform", () => {+ // 14 daily points -> show every 2nd (6/1, 6/3, β¦ β no width-dependent drop).+ expect(getEvenTickInterval(14)).toBe(1);+ expect(getEvenTickInterval(9)).toBe(1);+ expect(getEvenTickInterval(30)).toBe(3);+ });++ it("honors a custom max tick target", () => {+ expect(getEvenTickInterval(12, 6)).toBe(1);+ expect(getEvenTickInterval(6, 6)).toBe(0);+ });+});diff --git a/web/src/features/widgets/chart-library/utils.ts b/web/src/features/widgets/chart-library/utils.tsindex db68a8927f..a2a676dfc1 100644--- a/web/src/features/widgets/chart-library/utils.ts+++ b/web/src/features/widgets/chart-library/utils.ts@@ -112,6 +112,19 @@ export const isTimeSeriesChart = (export const formatAxisLabel = (label: string): string =>label.length > 13 ? label.slice(0, 13).concat("β¦") : label;+/**+ * Picks a recharts numeric x-axis `interval` (= ticks skipped between two shown+ * ticks) that yields UNIFORM gaps targeting ~`maxTicks` labels. We use this+ * instead of `interval="preserveStartEnd"` + `minTickGap`, whose width-dependent+ * collision dropping skips ticks unevenly (e.g. 6/9, 6/11, 6/13 vanish while+ * 6/1β6/8 stay), making tick density vary by chart width. (LFE-10549)+ */+export const getEvenTickInterval = (+ pointCount: number,+ maxTicks = 8,+): number =>+ pointCount <= maxTicks ? 0 : Math.ceil(pointCount / maxTicks) - 1;+/*** Maps chart types to their human-readable display names.*/diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex c708919881..394080c58b 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -319,6 +319,44 @@ export function DashboardWidget({});}, [metricsVersion, widget.data]);+ // Memoize the Chart's config/chartConfig objects so the scheduler's page+ // re-renders don't hand Chart fresh literals every tick (transformedData is+ // already memoized) β letting Chart's React.memo bail. (LFE-10549)+ const chartConfigForRender = useMemo(() => {+ const data = widget.data;+ if (!data) return undefined;+ return {+ ...data.chartConfig,+ // For PIVOT_TABLE, enhance chartConfig with dimensions and metric field names+ ...(data.chartType === "PIVOT_TABLE" && {+ dimensions: data.dimensions.map((dim) => dim.field),+ metrics: data.metrics.map(+ (metric) => `${metric.agg}_${metric.measure}`,+ ),+ units: data.metrics.map((metric) =>+ getResultUnit(data.view, metric.measure, metric.agg, metricsVersion),+ ),+ defaultSort,+ }),+ ...(data.chartType !== "PIVOT_TABLE" && {+ unit: getResultUnit(+ data.view,+ data.metrics[0]?.measure ?? "",+ data.metrics[0]?.agg,+ metricsVersion,+ ),+ }),+ };+ }, [widget.data, metricsVersion, defaultSort]);++ const chartMetricConfig = useMemo(+ () =>+ chartPresentation+ ? { metric: { label: chartPresentation.label } }+ : undefined,+ [chartPresentation],+ );+const handleEdit = () => {router.push(`/project/${projectId}/widgets/${placement.widgetId}?dashboardId=${dashboardId}`,@@ -449,15 +487,10 @@ export function DashboardWidget({<ChartchartType={widget.data.chartType}data={transformedData}- config={- chartPresentation- ? {- metric: {- label: chartPresentation.label,- },- }- : undefined- }+ // Sync the hover crosshair across all time-series widgets on this+ // dashboard (non-time-series chart types ignore it). (LFE-10549)+ syncId={dashboardId}+ config={chartMetricConfig}rowLimit={widget.data.chartConfig.type === "LINE_TIME_SERIES" ||widget.data.chartConfig.type === "BAR_TIME_SERIES" ||@@ -465,33 +498,7 @@ export function DashboardWidget({? 100: (widget.data.chartConfig.row_limit ?? 100)}- chartConfig={{- ...widget.data.chartConfig,- // For PIVOT_TABLE, enhance chartConfig with dimensions and metric field names- ...(widget.data.chartType === "PIVOT_TABLE" && {- dimensions: widget.data.dimensions.map((dim) => dim.field),- metrics: widget.data.metrics.map(- (metric) => `${metric.agg}_${metric.measure}`,- ),- units: widget.data.metrics.map((metric) =>- getResultUnit(- widget.data.view,- metric.measure,- metric.agg,- metricsVersion,- ),- ),- defaultSort,- }),- ...(widget.data.chartType !== "PIVOT_TABLE" && {- unit: getResultUnit(- widget.data.view,- widget.data.metrics[0]?.measure ?? "",- widget.data.metrics[0]?.agg,- metricsVersion,- ),- }),- }}+ chartConfig={chartConfigForRender}sortState={widget.data.chartType === "PIVOT_TABLE" ? sortState : undefined}diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex 00e5f63abc..546d301521 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -54,6 +54,10 @@ const HOME_DASHBOARD_CARD_IDS = {scoreAnalytics: "home:score-analytics",} as const;+// Shared across the home time-series charts so hovering one moves the time+// crosshair on all of them (they share one time range + granularity). (LFE-10549)+const HOME_DASHBOARD_SYNC_ID = "home-dashboard-timeseries";+export default function Dashboard() {const router = useRouter();const projectId = router.query.projectId as string;@@ -283,6 +287,7 @@ export default function Dashboard() {isLoading={environmentOptionsState.isPending}metricsVersion={metricsVersion}schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.tracesTimeSeries}`}+ syncId={HOME_DASHBOARD_SYNC_ID}/><ModelUsageChartclassName="col-span-1 min-h-24 xl:col-span-3"@@ -295,6 +300,7 @@ export default function Dashboard() {isLoading={environmentOptionsState.isPending}metricsVersion={metricsVersion}schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.modelUsage}`}+ syncId={HOME_DASHBOARD_SYNC_ID}/><UserChartclassName="col-span-1 xl:col-span-3"@@ -316,6 +322,7 @@ export default function Dashboard() {isLoading={environmentOptionsState.isPending}metricsVersion={metricsVersion}schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.chartScores}`}+ syncId={HOME_DASHBOARD_SYNC_ID}/><LatencyTablesprojectId={projectId}@@ -336,6 +343,7 @@ export default function Dashboard() {isLoading={environmentOptionsState.isPending}metricsVersion={metricsVersion}schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.generationLatency}`}+ syncId={HOME_DASHBOARD_SYNC_ID}/><ScoreAnalyticsclassName="col-span-1 flex-auto justify-between lg:col-span-full"@@ -347,6 +355,7 @@ export default function Dashboard() {isLoading={environmentOptionsState.isPending}metricsVersion={metricsVersion}schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.scoreAnalytics}`}+ syncId={HOME_DASHBOARD_SYNC_ID}/></div>)}