πͺ’ 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(charts): in-view charts for the v4 events table ("any view is a chart") (#15187)
Nikita Kabardind416ee807abb
diff --git a/web/.storybook/main.ts b/web/.storybook/main.tsindex ece4fdc5cc..a6d9709c42 100644--- a/web/.storybook/main.ts+++ b/web/.storybook/main.ts@@ -58,6 +58,18 @@ const config: StorybookConfig = {replacement: replacement as string,}));viteConfig.resolve.alias = [+ // The package also exposes a few named subpath exports (e.g.+ // `@langfuse/shared/query`, imported transitively via the chart-library's+ // PivotTable β widgets/utils). Those aren't under `src/`, so the two rules+ // below miss them and they fall through to the CJS dist bundle, whose+ // re-exported names (e.g. `getViewDeclaration`) Vite's lexer can't resolve+ // β the same failure the bare-specifier rule fixes. Map the source-safe+ // subpaths to source too. (`query/index.ts` only re-exports client-safe+ // dataModel/types/validateQuery.)+ {+ find: /^@langfuse\/shared\/query$/,+ replacement: `${sharedSrc}/features/query`,+ },{find: /^\.prisma\/client\/index-browser$/,replacement: prismaBrowserStub,diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex eb20c3dde4..29ac0fe2f7 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -116,11 +116,19 @@ export interface QueryFilter {interface DataTableControlsProps {queryFilter: QueryFilter;filterWithAI?: boolean;+ /**+ * Given a filter column, the reason an active filter on it is NOT applied on+ * the current surface (e.g. the chart view can't filter on it), or null. When+ * it returns a reason, that active facet renders deactivated (dimmed + the+ * reason on hover); Clearing still works. Undefined leaves every filter live.+ */+ deactivatedColumnReason?: (column: string) => string | null;}export function DataTableControls({queryFilter,filterWithAI,+ deactivatedColumnReason,}: DataTableControlsProps) {const { isLangfuseCloud } = useLangfuseCloudRegion();const { setOpen } = useDataTableControls();@@ -257,6 +265,13 @@ export function DataTableControls({onValueChange={queryFilter.onExpandedChange}>{queryFilter.filters.map((filter) => {+ // "Not applied on this surface" (e.g. the chart can't filter on+ // this column). Only an ACTIVE filter deactivates β an empty facet+ // stays usable. Overrides isDisabled/disabledReason below so the+ // facet dims + explains on hover while Clear still works.+ const deactivatedReason = filter.isActive+ ? (deactivatedColumnReason?.(filter.column) ?? null)+ : null;if (filter.type === "categorical") {return (<CategoricalFacet@@ -281,8 +296,8 @@ export function DataTableControls({textFilters={filter.textFilters}onTextFilterAdd={filter.onTextFilterAdd}onTextFilterRemove={filter.onTextFilterRemove}- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}@@ -304,8 +319,8 @@ export function DataTableControls({unit={filter.unit}isActive={filter.isActive}onReset={filter.onReset}- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}@@ -324,8 +339,8 @@ export function DataTableControls({onChange={filter.onChange}isActive={filter.isActive}onReset={filter.onReset}- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}@@ -347,8 +362,8 @@ export function DataTableControls({isActive={filter.isActive}onReset={filter.onReset}keyPlaceholder="Name"- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}@@ -369,8 +384,8 @@ export function DataTableControls({isActive={filter.isActive}onReset={filter.onReset}keyPlaceholder="Name"- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}@@ -391,8 +406,8 @@ export function DataTableControls({isActive={filter.isActive}onReset={filter.onReset}keyPlaceholder="Name"- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}@@ -412,8 +427,8 @@ export function DataTableControls({onChange={filter.onChange}isActive={filter.isActive}onReset={filter.onReset}- isDisabled={filter.isDisabled}- disabledReason={filter.disabledReason}+ isDisabled={filter.isDisabled || deactivatedReason !== null}+ disabledReason={deactivatedReason ?? filter.disabledReason}/>);}diff --git a/web/src/features/chart-view-prototype/ChartViewPrototype.stories.tsx b/web/src/features/chart-view-prototype/ChartViewPrototype.stories.tsxnew file mode 100644index 0000000000..0ffdd42d36--- /dev/null+++ b/web/src/features/chart-view-prototype/ChartViewPrototype.stories.tsx@@ -0,0 +1,154 @@+import preview from "../../../.storybook/preview";+import { ChartViewPrototype } from "./components/ChartViewPrototype";+import { SCENARIOS } from "./lib/fixtures";+import { type ChartViewConfig } from "./types";++/**+ * "Any view is a chart" β the v4 events/traces view, flipped from table to a+ * configurable chart in place. These stories ARE the design: built on mock+ * fixtures (no backend), reusing the production `chart-library`, comparing two+ * UX takes on where the chart config lives.+ *+ * β’ Take A β Inline bar: config in a compact, always-on strip above the canvas.+ * β’ Take B β Side panel: a maximized canvas with config docked in a panel.+ *+ * Both share the same toggle, the same pure aggregator, and the same mocked+ * "Ask AI β chart" affordance β they differ only in how the config is presented.+ */+const meta = preview.meta({+ component: ChartViewPrototype,+ args: {+ events: SCENARIOS.default,+ affordance: "inline",+ initialMode: "chart",+ },+ argTypes: {+ affordance: {+ control: "inline-radio",+ options: ["inline", "panel"],+ },+ initialMode: {+ control: "inline-radio",+ options: ["table", "chart"],+ },+ },+ decorators: [+ // A definite-height frame so the (h-full) prototype and its charts size+ // correctly in the Storybook canvas.+ (Story) => (+ <div className="mx-auto h-[680px] w-full max-w-6xl p-4">+ <Story />+ </div>+ ),+ ],+});++const PRESETS = {+ latencyP95: {+ metric: "latency",+ aggregation: "p95",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ timeGranularity: "hour",+ },+ costByModel: {+ metric: "totalCost",+ aggregation: "sum",+ breakdown: "model",+ chartType: "HORIZONTAL_BAR",+ timeGranularity: "hour",+ },+ eventsByLevel: {+ metric: "count",+ aggregation: "count",+ breakdown: "level",+ chartType: "PIE",+ timeGranularity: "hour",+ },+} satisfies Record<string, ChartViewConfig>;++/** Take A β the inline explorer bar. The flagship; the default config is+ * count-of-events broken down by model over time. */+export const TakeA_InlineBar = meta.story({+ args: { events: SCENARIOS.default, affordance: "inline" },+});++/** Take B β the same experience with config docked in a collapsible panel and+ * a maximized chart canvas. */+export const TakeB_SidePanel = meta.story({+ args: { events: SCENARIOS.default, affordance: "panel" },+});++/** The starting point: the familiar events table. Flip the toggle (top right)+ * to chart. */+export const TableView = meta.story({+ args: { events: SCENARIOS.default, initialMode: "table" },+});++/** Ask AI β chart. Type an ask (or tap a suggestion) and the chart+ * reconfigures. Try "errors over time by level" against this error-spike+ * dataset. */+export const AskAI = meta.story({+ args: {+ events: SCENARIOS.errorSpike,+ affordance: "inline",+ initialConfig: PRESETS.eventsByLevel,+ },+});++export const LatencyP95ByModel = meta.story({+ args: {+ events: SCENARIOS.default,+ affordance: "inline",+ initialConfig: PRESETS.latencyP95,+ },+});++export const CostByModelRanked = meta.story({+ args: {+ events: SCENARIOS.default,+ affordance: "panel",+ initialConfig: PRESETS.costByModel,+ },+});++export const EventsByLevelPie = meta.story({+ args: {+ events: SCENARIOS.default,+ affordance: "inline",+ initialConfig: PRESETS.eventsByLevel,+ },+});++/** No data β the empty state inside the chart canvas. */+export const EmptyState = meta.story({+ args: { events: SCENARIOS.empty },+});++/** Both takes stacked for a direct side-by-side comparison. */+export const Comparison = meta.story({+ render: () => (+ <div className="flex h-full flex-col gap-8 overflow-y-auto">+ <div className="flex shrink-0 flex-col gap-2">+ <h3 className="text-sm font-semibold">Take A β Inline explorer bar</h3>+ <p className="text-muted-foreground text-xs">+ Config in an always-on strip above the canvas. Dense, fast, feels like+ a live extension of the table.+ </p>+ <div className="h-[460px]">+ <ChartViewPrototype events={SCENARIOS.default} affordance="inline" />+ </div>+ </div>+ <div className="flex shrink-0 flex-col gap-2">+ <h3 className="text-sm font-semibold">Take B β Docked side panel</h3>+ <p className="text-muted-foreground text-xs">+ Maximized canvas with config in a collapsible panel. Cleaner, more+ guided, more room for the chart.+ </p>+ <div className="h-[460px]">+ <ChartViewPrototype events={SCENARIOS.default} affordance="panel" />+ </div>+ </div>+ </div>+ ),+});diff --git a/web/src/features/chart-view-prototype/README.md b/web/src/features/chart-view-prototype/README.mdnew file mode 100644index 0000000000..bdd828b56d--- /dev/null+++ b/web/src/features/chart-view-prototype/README.md@@ -0,0 +1,49 @@+# chart-view-prototype++**Status: throwaway design prototype (EXP-CHART-PROTOTYPE, phase 0).** Storybook-only,+mock-data-only. This folder exists so we can _design by building_ the "any view is a+chart" experience for the v4 events/traces view before wiring it to real data. Nothing+here is imported by the app yet.++## The experience++In the v4 events view, flip **table β chart** and configure the visualization in place+(**metric Γ aggregation Γ breakdown Γ chart-type**), with an **Ask AI** affordance that+emits that config from natural language. We ship **two UX takes** for the config+affordance and let Nikita pick the direction:++- **Take A β inline bar:** config in a compact, always-on strip above the canvas.+- **Take B β side panel:** a maximized canvas with config in a collapsible dock.++Run the stories: `pnpm --filter web run storybook` β **Charts / Chart View Prototype**.++## Owner map++| File | Owns |+| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `types.ts` | The config spec (`ChartViewConfig`) + the mock event row (`PrototypeEvent`). |+| `vocab.ts` | Metric / dimension / aggregation / chart-type vocabulary (a faithful subset of the real widget vocabulary), value extractors, and config coercion. Pure, no React. |+| `lib/aggregate.ts` | **The data layer.** Pure `aggregateEvents(events, config) β DataPoint[]` β mirrors the shape the future v4 aggregate endpoint must return. |+| `lib/fixtures.ts` | Deterministic (seeded) mock event generator + named scenarios. |+| `components/ChartViewPrototype.tsx` | Root: owns the `mode` + `config` state, renders one of the two takes. Everything below is view-only. |+| `components/ChartCanvas.tsx` | `React.memo` chart render boundary (derives data, renders `chart-library`). |+| `components/ConfigControls.tsx` | The shared, view-only pickers (metric/agg/breakdown/granularity/chart-type). |+| `components/MockEventsTable.tsx` | Representative "table" side of the toggle. |+| `components/ViewModeToggle.tsx` | The tableβchart toggle. |+| `ChartViewPrototype.stories.tsx` | The stories (the actual deliverable). |++## Architecture notes (follows `frontend-large-feature-architecture`)++- **Pure derivation:** all data transformation lives in `lib/aggregate.ts`; components+ are view-only and just render derived data. Same events + config β same chart.+- **One-way data flow:** the root owns `mode` + `config`; children receive values ++ stable `onChange` callbacks (memoized), nothing reaches back up except via those.+- **Render boundaries:** `ChartCanvas` and the pickers are `React.memo`'d so a single+ config change doesn't re-aggregate or re-render unrelated UI.++## Wiring path (later phases β not in this folder yet)++1. **Phase 1:** replace `lib/aggregate.ts`'s client function with a tRPC `events.aggregate`+ call returning the same `DataPoint[]`; move `mode` + `config` into URL state+ (reversible toggle); mount inside `features/events/components/EventsTable.tsx`, gated+ to the v4 read path.diff --git a/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsx b/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsxnew file mode 100644index 0000000000..6eb38141c4--- /dev/null+++ b/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsx@@ -0,0 +1,197 @@+import React, { useCallback, useMemo, useState } from "react";+import { SlidersHorizontal } from "lucide-react";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import { Button } from "@/src/components/ui/button";+import { Separator } from "@/src/components/ui/separator";+// Shared, production chart-view components β the harness renders the exact same+// UI as the real EventsChartView, fed with mock-aggregated data.+import {+ AggregationSelect,+ BreakdownSelect,+ ChartTypePicker,+ GranularitySelect,+ MetricSelect,+} from "@/src/features/chart-view/components/ConfigControls";+import { ChartCanvas } from "@/src/features/chart-view/components/ChartCanvas";+import { ChartViewPanel } from "@/src/features/chart-view/components/ChartViewPanel";+import { ViewModeToggle } from "@/src/features/chart-view/components/ViewModeToggle";+import {+ coerceConfig,+ DEFAULT_CONFIG,+ describeConfig,+ isTimeSeriesChartType,+} from "@/src/features/chart-view/vocab";+import {+ type AggregationFn,+ type ChartViewConfig,+ type DimensionKey,+ type MetricKey,+ type PrototypeEvent,+ type TimeGranularity,+ type ViewMode,+} from "../types";+import { aggregateEvents } from "../lib/aggregate";+import { MockEventsTable } from "./MockEventsTable";++export type ChartViewAffordance = "inline" | "panel";++export interface ChartViewPrototypeProps {+ events: PrototypeEvent[];+ /** Which of the two config affordances to render. */+ affordance?: ChartViewAffordance;+ initialMode?: ViewMode;+ initialConfig?: Partial<ChartViewConfig>;+}++/**+ * Storybook design harness for "any view is a chart". Owns the tableβchart+ * `mode` and the `config` (production uses URL state instead), derives chart+ * data from mock events via the pure aggregator, and renders one of the two UX+ * takes. Take B β the docked panel Nikita picked β is the shared, production+ * `ChartViewPanel`; Take A (inline bar) is kept here as the design record.+ */+export function ChartViewPrototype({+ events,+ affordance = "inline",+ initialMode = "chart",+ initialConfig,+}: ChartViewPrototypeProps) {+ const [mode, setMode] = useState<ViewMode>(initialMode);+ const [config, setConfig] = useState<ChartViewConfig>(() =>+ coerceConfig({ ...DEFAULT_CONFIG, ...initialConfig }),+ );++ const patchConfig = useCallback(+ (patch: Partial<ChartViewConfig>) =>+ setConfig((prev) => coerceConfig({ ...prev, ...patch })),+ [],+ );++ const data = useMemo(() => aggregateEvents(events, config), [events, config]);+ const isTimeSeries = isTimeSeriesChartType(config.chartType);++ return (+ <div className="bg-background flex h-full flex-col overflow-hidden rounded-lg border">+ <div className="flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">+ <div className="text-muted-foreground flex items-center gap-2 text-xs">+ <Button variant="outline" size="sm" disabled className="h-7 gap-1.5">+ <SlidersHorizontal className="h-3.5 w-3.5" />+ Filters+ </Button>+ <span>{events.length.toLocaleString()} events Β· last 24h</span>+ </div>+ <ViewModeToggle mode={mode} onModeChange={setMode} />+ </div>++ {mode === "table" ? (+ <MockEventsTable events={events} />+ ) : affordance === "inline" ? (+ <InlineTake+ data={data}+ config={config}+ isTimeSeries={isTimeSeries}+ patchConfig={patchConfig}+ />+ ) : (+ <ChartViewPanel+ config={config}+ onConfigChange={patchConfig}+ data={data}+ granularitySlot={+ <GranularitySelect+ value={config.timeGranularity}+ onChange={(timeGranularity) => patchConfig({ timeGranularity })}+ disabled={!isTimeSeries}+ />+ }+ />+ )}+ </div>+ );+}++function InlineField({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div className="flex items-center gap-1.5">+ <span className="text-muted-foreground text-xs">{label}</span>+ {children}+ </div>+ );+}++/** Take A β everything in a compact, always-visible bar above the canvas. */+function InlineTake({+ data,+ config,+ isTimeSeries,+ patchConfig,+}: {+ data: ReturnType<typeof aggregateEvents>;+ config: ChartViewConfig;+ isTimeSeries: boolean;+ patchConfig: (patch: Partial<ChartViewConfig>) => void;+}) {+ const onMetric = useCallback(+ (metric: MetricKey) => patchConfig({ metric }),+ [patchConfig],+ );+ const onAggregation = useCallback(+ (aggregation: AggregationFn) => patchConfig({ aggregation }),+ [patchConfig],+ );+ const onBreakdown = useCallback(+ (breakdown: DimensionKey) => patchConfig({ breakdown }),+ [patchConfig],+ );+ const onChartType = useCallback(+ (chartType: DashboardWidgetChartType) => patchConfig({ chartType }),+ [patchConfig],+ );+ const onGranularity = useCallback(+ (timeGranularity: TimeGranularity) => patchConfig({ timeGranularity }),+ [patchConfig],+ );++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-b px-3 py-2">+ <ChartTypePicker value={config.chartType} onChange={onChartType} />+ <Separator orientation="vertical" className="h-5" />+ <InlineField label="Metric">+ <MetricSelect value={config.metric} onChange={onMetric} />+ </InlineField>+ <InlineField label="Aggregation">+ <AggregationSelect+ metric={config.metric}+ value={config.aggregation}+ onChange={onAggregation}+ />+ </InlineField>+ <InlineField label="by">+ <BreakdownSelect value={config.breakdown} onChange={onBreakdown} />+ </InlineField>+ <InlineField label="every">+ <GranularitySelect+ value={config.timeGranularity}+ onChange={onGranularity}+ disabled={!isTimeSeries}+ />+ </InlineField>+ </div>+ <div className="flex min-h-0 min-w-0 flex-1 flex-col gap-1 p-3">+ <div className="text-foreground text-sm font-medium">+ {describeConfig(config)}+ </div>+ <div className="min-h-0 flex-1">+ <ChartCanvas data={data} config={config} />+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/features/chart-view-prototype/components/MockEventsTable.tsx b/web/src/features/chart-view-prototype/components/MockEventsTable.tsxnew file mode 100644index 0000000000..cb1151f10b--- /dev/null+++ b/web/src/features/chart-view-prototype/components/MockEventsTable.tsx@@ -0,0 +1,109 @@+import React from "react";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/src/components/ui/table";+import { Badge } from "@/src/components/ui/badge";+import { cn } from "@/src/utils/tailwind";+import { type ObservationLevel, type PrototypeEvent } from "../types";++const VISIBLE_ROWS = 14;++const LEVEL_CLASS: Record<ObservationLevel, string> = {+ ERROR: "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300",+ WARNING: "bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",+ DEFAULT: "bg-muted text-muted-foreground",+ DEBUG: "bg-muted text-muted-foreground",+};++const formatLatency = (ms: number): string =>+ ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;++const formatCost = (usd: number): string =>+ usd === 0 ? "β" : `$${usd < 0.01 ? usd.toFixed(5) : usd.toFixed(4)}`;++const formatTime = (iso: string): string =>+ new Date(iso).toLocaleTimeString("en-US", {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ });++/**+ * A representative stand-in for the v4 events table β the "table" side of the+ * toggle. Deliberately a lightweight, view-only table (not the full virtualized+ * `DataTable`) so the prototype stays self-contained; it exists to make the+ * toggle feel honest, not to re-implement the real table.+ */+export const MockEventsTable = React.memo(function MockEventsTable({+ events,+}: {+ events: PrototypeEvent[];+}) {+ const rows = events.slice(0, VISIBLE_ROWS);++ return (+ <div className="flex h-full flex-col overflow-hidden">+ <div className="min-h-0 flex-1 overflow-auto">+ <Table>+ <TableHeader className="bg-background sticky top-0 z-10">+ <TableRow>+ <TableHead className="h-8">Type</TableHead>+ <TableHead className="h-8">Name</TableHead>+ <TableHead className="h-8">Model</TableHead>+ <TableHead className="h-8">Level</TableHead>+ <TableHead className="h-8 text-right">Latency</TableHead>+ <TableHead className="h-8 text-right">Cost</TableHead>+ <TableHead className="h-8 text-right">Tokens</TableHead>+ <TableHead className="h-8 text-right">Time</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((e) => (+ <TableRow key={e.id} className="text-xs">+ <TableCell className="py-1.5">+ <Badge variant="outline" className="font-mono text-[10px]">+ {e.type}+ </Badge>+ </TableCell>+ <TableCell className="py-1.5 font-medium">{e.name}</TableCell>+ <TableCell className="text-muted-foreground py-1.5 font-mono">+ {e.model ?? "β"}+ </TableCell>+ <TableCell className="py-1.5">+ <Badge+ className={cn(+ "border-transparent text-[10px]",+ LEVEL_CLASS[e.level],+ )}+ >+ {e.level}+ </Badge>+ </TableCell>+ <TableCell className="py-1.5 text-right font-mono">+ {formatLatency(e.latencyMs)}+ </TableCell>+ <TableCell className="py-1.5 text-right font-mono">+ {formatCost(e.totalCost)}+ </TableCell>+ <TableCell className="py-1.5 text-right font-mono">+ {e.totalTokens.toLocaleString()}+ </TableCell>+ <TableCell className="text-muted-foreground py-1.5 text-right font-mono">+ {formatTime(e.startTime)}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ <div className="text-muted-foreground border-t px-3 py-1.5 text-xs">+ Showing {rows.length} of {events.length.toLocaleString()} events+ </div>+ </div>+ );+});diff --git a/web/src/features/chart-view-prototype/lib/aggregate.clienttest.ts b/web/src/features/chart-view-prototype/lib/aggregate.clienttest.tsnew file mode 100644index 0000000000..47d4585997--- /dev/null+++ b/web/src/features/chart-view-prototype/lib/aggregate.clienttest.ts@@ -0,0 +1,154 @@+import { aggregateEvents, floorToGranularity } from "./aggregate";+import { type PrototypeEvent } from "../types";+import { DEFAULT_CONFIG } from "../vocab";++const evt = (overrides: Partial<PrototypeEvent>): PrototypeEvent => ({+ id: "evt",+ startTime: "2026-06-25T10:15:30.000Z",+ type: "GENERATION",+ name: "generate-answer",+ model: "gpt-4o",+ level: "DEFAULT",+ environment: "production",+ latencyMs: 1000,+ totalCost: 0.01,+ totalTokens: 500,+ ...overrides,+});++describe("aggregateEvents", () => {+ it("returns no data points for an empty event set", () => {+ expect(aggregateEvents([], DEFAULT_CONFIG)).toEqual([]);+ });++ it("counts rows per time bucket and breakdown series", () => {+ const events = [+ evt({ startTime: "2026-06-25T10:05:00.000Z", model: "gpt-4o" }),+ evt({ startTime: "2026-06-25T10:45:00.000Z", model: "gpt-4o" }),+ evt({ startTime: "2026-06-25T11:10:00.000Z", model: "claude-opus-4" }),+ ];+ const data = aggregateEvents(events, {+ ...DEFAULT_CONFIG,+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ timeGranularity: "hour",+ });+ // gpt-4o has 2 events in the 10:00 bucket, claude-opus-4 has 1 at 11:00.+ expect(data).toEqual([+ {+ time_dimension: "2026-06-25T10:00:00.000Z",+ dimension: "gpt-4o",+ metric: 2,+ },+ {+ time_dimension: "2026-06-25T11:00:00.000Z",+ dimension: "claude-opus-4",+ metric: 1,+ },+ ]);+ });++ it("emits time buckets in chronological order regardless of input order", () => {+ const events = [+ evt({ startTime: "2026-06-25T12:00:00.000Z" }),+ evt({ startTime: "2026-06-25T09:00:00.000Z" }),+ evt({ startTime: "2026-06-25T10:00:00.000Z" }),+ ];+ const data = aggregateEvents(events, {+ ...DEFAULT_CONFIG,+ breakdown: "none",+ timeGranularity: "hour",+ });+ expect(data.map((d) => d.time_dimension)).toEqual([+ "2026-06-25T09:00:00.000Z",+ "2026-06-25T10:00:00.000Z",+ "2026-06-25T12:00:00.000Z",+ ]);+ });++ it("averages a numeric metric within a group", () => {+ const events = [+ evt({ latencyMs: 100 }),+ evt({ latencyMs: 300 }),+ evt({ latencyMs: 200 }),+ ];+ const [point] = aggregateEvents(events, {+ ...DEFAULT_CONFIG,+ metric: "latency",+ aggregation: "avg",+ breakdown: "none",+ chartType: "NUMBER",+ });+ expect(point.metric).toBe(200);+ });++ it("computes interpolated percentiles", () => {+ const events = Array.from({ length: 100 }, (_, i) =>+ evt({ latencyMs: i + 1 }),+ ); // 1..100+ const [p95] = aggregateEvents(events, {+ ...DEFAULT_CONFIG,+ metric: "latency",+ aggregation: "p95",+ breakdown: "none",+ chartType: "NUMBER",+ });+ // linear interpolation over [1..100]: rank = 0.95 * 99 = 94.05 -> ~95.05+ expect(p95.metric as number).toBeCloseTo(95.05, 2);+ });++ it("ranks categorical results descending by metric", () => {+ const events = [+ evt({ model: "gpt-4o" }),+ evt({ model: "claude-opus-4" }),+ evt({ model: "claude-opus-4" }),+ evt({ model: "claude-opus-4" }),+ evt({ model: "gpt-4o" }),+ ];+ const data = aggregateEvents(events, {+ ...DEFAULT_CONFIG,+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "HORIZONTAL_BAR",+ });+ expect(data).toEqual([+ { time_dimension: undefined, dimension: "claude-opus-4", metric: 3 },+ { time_dimension: undefined, dimension: "gpt-4o", metric: 2 },+ ]);+ });++ it("produces a single aggregate for a big number", () => {+ const events = [evt({}), evt({}), evt({})];+ const data = aggregateEvents(events, {+ ...DEFAULT_CONFIG,+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "NUMBER",+ });+ expect(data).toEqual([+ { time_dimension: undefined, dimension: undefined, metric: 3 },+ ]);+ });+});++describe("floorToGranularity", () => {+ it("floors to the hour", () => {+ expect(floorToGranularity("2026-06-25T10:45:12.345Z", "hour")).toBe(+ "2026-06-25T10:00:00.000Z",+ );+ });+ it("floors to the day", () => {+ expect(floorToGranularity("2026-06-25T10:45:12.345Z", "day")).toBe(+ "2026-06-25T00:00:00.000Z",+ );+ });+ it("floors to the minute", () => {+ expect(floorToGranularity("2026-06-25T10:45:12.345Z", "minute")).toBe(+ "2026-06-25T10:45:00.000Z",+ );+ });+});diff --git a/web/src/features/chart-view-prototype/lib/aggregate.ts b/web/src/features/chart-view-prototype/lib/aggregate.tsnew file mode 100644index 0000000000..5acbf20f01--- /dev/null+++ b/web/src/features/chart-view-prototype/lib/aggregate.ts@@ -0,0 +1,169 @@+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import {+ type AggregationFn,+ type ChartViewConfig,+ type PrototypeEvent,+ type TimeGranularity,+} from "../types";+import {+ DIMENSION_EXTRACTORS,+ getMetric,+ isTimeSeriesChartType,+ METRIC_EXTRACTORS,+} from "../vocab";++/**+ * The harness's mock data layer: turns raw mock events into `chart-library`+ * `DataPoint[]` for a config, client-side and PURE. It mirrors the shape the+ * production `dashboard.executeQuery` returns for the observations view, so the+ * Storybook stories exercise the exact same view components as the real+ * `EventsChartView` β only the data source differs.+ */+export function aggregateEvents(+ events: PrototypeEvent[],+ config: ChartViewConfig,+): DataPoint[] {+ if (events.length === 0) return [];++ const metric = getMetric(config.metric);+ const extractor = METRIC_EXTRACTORS[config.metric];+ const dimExtractor = DIMENSION_EXTRACTORS[config.breakdown];+ const seriesOf = (e: PrototypeEvent): string =>+ dimExtractor ? dimExtractor(e) : metric.label;++ if (config.chartType === "NUMBER") {+ return [+ {+ time_dimension: undefined,+ dimension: undefined,+ metric: aggregate(events, extractor, config.aggregation),+ },+ ];+ }++ if (isTimeSeriesChartType(config.chartType)) {+ return aggregateTimeSeries(events, config, extractor, seriesOf);+ }++ return aggregateCategorical(events, config, extractor, seriesOf);+}++type Extractor = ((e: PrototypeEvent) => number) | null;++/** Time-series: bucket by time, then per series, in chronological order. */+function aggregateTimeSeries(+ events: PrototypeEvent[],+ config: ChartViewConfig,+ extractor: Extractor,+ seriesOf: (e: PrototypeEvent) => string,+): DataPoint[] {+ const buckets = new Map<string, Map<string, PrototypeEvent[]>>();+ for (const e of events) {+ const bucket = floorToGranularity(e.startTime, config.timeGranularity);+ const series = seriesOf(e);+ let perSeries = buckets.get(bucket);+ if (!perSeries) {+ perSeries = new Map();+ buckets.set(bucket, perSeries);+ }+ const list = perSeries.get(series);+ if (list) list.push(e);+ else perSeries.set(series, [e]);+ }++ const points: DataPoint[] = [];+ for (const bucket of [...buckets.keys()].sort()) {+ const perSeries = buckets.get(bucket)!;+ for (const [series, group] of perSeries) {+ points.push({+ time_dimension: bucket,+ dimension: series,+ metric: aggregate(group, extractor, config.aggregation),+ });+ }+ }+ return points;+}++/** Categorical (ranked bars, pie): one aggregate per breakdown value, ranked. */+function aggregateCategorical(+ events: PrototypeEvent[],+ config: ChartViewConfig,+ extractor: Extractor,+ seriesOf: (e: PrototypeEvent) => string,+): DataPoint[] {+ const groups = new Map<string, PrototypeEvent[]>();+ for (const e of events) {+ const key = seriesOf(e);+ const list = groups.get(key);+ if (list) list.push(e);+ else groups.set(key, [e]);+ }++ return [...groups.entries()]+ .map(([key, group]) => ({+ time_dimension: undefined,+ dimension: key,+ metric: aggregate(group, extractor, config.aggregation),+ }))+ .sort((a, b) => (b.metric as number) - (a.metric as number));+}++/** Aggregate one group of events into a single number. */+function aggregate(+ events: PrototypeEvent[],+ extractor: Extractor,+ agg: AggregationFn,+): number {+ if (agg === "count" || extractor === null) {+ return events.length;+ }+ const values = events.map(extractor).filter((v) => Number.isFinite(v));+ if (values.length === 0) return 0;++ switch (agg) {+ case "sum":+ return values.reduce((acc, v) => acc + v, 0);+ case "avg":+ return values.reduce((acc, v) => acc + v, 0) / values.length;+ case "min":+ return Math.min(...values);+ case "max":+ return Math.max(...values);+ case "p50":+ return percentile(values, 50);+ case "p95":+ return percentile(values, 95);+ case "p99":+ return percentile(values, 99);+ default:+ return values.length;+ }+}++/** Linear-interpolated percentile over an unsorted numeric array. */+function percentile(values: number[], p: number): number {+ const sorted = [...values].sort((a, b) => a - b);+ if (sorted.length === 1) return sorted[0];+ const rank = (p / 100) * (sorted.length - 1);+ const lo = Math.floor(rank);+ const hi = Math.ceil(rank);+ if (lo === hi) return sorted[lo];+ const weight = rank - lo;+ return sorted[lo] * (1 - weight) + sorted[hi] * weight;+}++/** Floors an ISO timestamp to the start of its minute/hour/day bucket (UTC). */+export function floorToGranularity(+ iso: string,+ granularity: TimeGranularity,+): string {+ const d = new Date(iso);+ d.setUTCMilliseconds(0);+ d.setUTCSeconds(0);+ if (granularity === "minute") return d.toISOString();+ d.setUTCMinutes(0);+ if (granularity === "hour") return d.toISOString();+ d.setUTCHours(0);+ return d.toISOString();+}diff --git a/web/src/features/chart-view-prototype/lib/fixtures.ts b/web/src/features/chart-view-prototype/lib/fixtures.tsnew file mode 100644index 0000000000..bb8d63fe6c--- /dev/null+++ b/web/src/features/chart-view-prototype/lib/fixtures.ts@@ -0,0 +1,188 @@+import {+ type ObservationKind,+ type ObservationLevel,+ type PrototypeEvent,+} from "../types";++/**+ * Deterministic mock event generator for the chart prototype. Seeded so stories+ * and the aggregator tests are stable across runs (no `Math.random`, no+ * wall-clock) β the window is anchored to a fixed instant. The shapes loosely+ * imitate a real trace stream: a handful of models/operations, mostly+ * `DEFAULT`-level generations with a thin tail of warnings/errors, costs that+ * track token counts, and latency that varies by model.+ */++// mulberry32 β tiny, fast, deterministic PRNG.+function makeRng(seed: number): () => number {+ let s = seed >>> 0;+ return () => {+ s |= 0;+ s = (s + 0x6d2b79f5) | 0;+ let t = Math.imul(s ^ (s >>> 15), 1 | s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++interface ModelSpec {+ name: string;+ weight: number;+ baseLatency: number;+ latencySpread: number;+ costPerToken: number;+}++const MODELS: ModelSpec[] = [+ {+ name: "gpt-4o",+ weight: 5,+ baseLatency: 900,+ latencySpread: 1400,+ costPerToken: 7.5e-6,+ },+ {+ name: "gpt-4o-mini",+ weight: 8,+ baseLatency: 450,+ latencySpread: 700,+ costPerToken: 9e-7,+ },+ {+ name: "claude-opus-4",+ weight: 3,+ baseLatency: 1500,+ latencySpread: 2200,+ costPerToken: 1.5e-5,+ },+ {+ name: "claude-haiku-4",+ weight: 6,+ baseLatency: 350,+ latencySpread: 500,+ costPerToken: 5e-7,+ },+ {+ name: "gemini-2.5-pro",+ weight: 4,+ baseLatency: 1100,+ latencySpread: 1600,+ costPerToken: 5e-6,+ },+];++const OPERATIONS = [+ "generate-answer",+ "summarize",+ "classify-intent",+ "embed-docs",+ "rerank-results",+];++const ENVIRONMENTS: Array<{ name: string; weight: number }> = [+ { name: "production", weight: 7 },+ { name: "staging", weight: 2 },+ { name: "development", weight: 1 },+];++/** Window anchor β fixed so generation is fully deterministic. */+const WINDOW_END = Date.parse("2026-06-25T18:00:00.000Z");+const HOUR = 60 * 60 * 1000;++function weightedPick<T extends { weight: number }>(+ rng: () => number,+ items: T[],+): T {+ const total = items.reduce((acc, i) => acc + i.weight, 0);+ let roll = rng() * total;+ for (const item of items) {+ roll -= item.weight;+ if (roll <= 0) return item;+ }+ return items[items.length - 1];+}++function pick<T>(rng: () => number, items: readonly T[]): T {+ return items[Math.floor(rng() * items.length)];+}++export interface GenerateOptions {+ seed?: number;+ count?: number;+ windowHours?: number;+ /** Fraction of events forced to ERROR, clustered in a recent sub-window. */+ errorSpike?: boolean;+}++export function generateEvents(+ options: GenerateOptions = {},+): PrototypeEvent[] {+ const {+ seed = 42,+ count = 640,+ windowHours = 24,+ errorSpike = false,+ } = options;+ const rng = makeRng(seed);+ const windowStart = WINDOW_END - windowHours * HOUR;+ const spikeStart = WINDOW_END - 4 * HOUR;++ const events: PrototypeEvent[] = [];+ for (let i = 0; i < count; i++) {+ const ts = windowStart + rng() * (WINDOW_END - windowStart);+ const model = weightedPick(rng, MODELS);+ const type: ObservationKind =+ rng() < 0.8 ? "GENERATION" : rng() < 0.6 ? "SPAN" : "EVENT";++ // Mostly clean, thin tail of warnings/errors; error spike concentrates+ // errors in the last few hours so "errors over time" reads as a real bump.+ let level: ObservationLevel = "DEFAULT";+ const levelRoll = rng();+ if (errorSpike && ts >= spikeStart && rng() < 0.45) {+ level = "ERROR";+ } else if (levelRoll > 0.97) {+ level = "ERROR";+ } else if (levelRoll > 0.9) {+ level = "WARNING";+ } else if (levelRoll < 0.04) {+ level = "DEBUG";+ }++ const isGeneration = type === "GENERATION";+ const totalTokens = isGeneration+ ? Math.round(120 + rng() * 3200)+ : Math.round(rng() * 40);+ const latencyMs = Math.round(+ model.baseLatency ++ rng() * model.latencySpread * (isGeneration ? 1 : 0.2),+ );+ const totalCost = isGeneration+ ? Number((totalTokens * model.costPerToken).toFixed(6))+ : 0;++ events.push({+ id: `evt_${seed}_${i}`,+ startTime: new Date(ts).toISOString(),+ type,+ name: pick(rng, OPERATIONS),+ model: isGeneration ? model.name : null,+ level,+ environment: weightedPick(rng, ENVIRONMENTS).name,+ latencyMs,+ totalCost,+ totalTokens,+ });+ }++ return events.sort((a, b) => a.startTime.localeCompare(b.startTime));+}++/** Named datasets the stories switch between. */+export const SCENARIOS = {+ default: generateEvents(),+ errorSpike: generateEvents({ seed: 7, errorSpike: true }),+ sparse: generateEvents({ seed: 3, count: 28, windowHours: 6 }),+ empty: [] as PrototypeEvent[],+} satisfies Record<string, PrototypeEvent[]>;++export type ScenarioKey = keyof typeof SCENARIOS;diff --git a/web/src/features/chart-view-prototype/types.ts b/web/src/features/chart-view-prototype/types.tsnew file mode 100644index 0000000000..3f51e880b6--- /dev/null+++ b/web/src/features/chart-view-prototype/types.ts@@ -0,0 +1,36 @@+// The chart-view config + vocabulary now live in the production feature+// (`features/chart-view`). This prototype is its Storybook design harness, so it+// re-exports those shared types and only adds the mock event row.+export type {+ ChartViewConfig,+ MetricKey,+ DimensionKey,+ AggregationFn,+ TimeGranularity,+ ViewMode,+} from "@/src/features/chart-view/types";++export type ObservationLevel = "DEBUG" | "DEFAULT" | "WARNING" | "ERROR";+export type ObservationKind = "GENERATION" | "SPAN" | "EVENT";++/**+ * A single mock v4 "event" (observation) row β the harness stand-in for one row+ * of the v4 events read path. The mock aggregator (`lib/aggregate.ts`) turns+ * arrays of these into chart data client-side, the way the production view's+ * server query does. Field names mirror the observations view declaration.+ */+export interface PrototypeEvent {+ id: string;+ /** ISO-8601 timestamp. */+ startTime: string;+ type: ObservationKind;+ name: string;+ /** `providedModelName`; null for non-generation events. */+ model: string | null;+ level: ObservationLevel;+ environment: string;+ latencyMs: number;+ /** USD. */+ totalCost: number;+ totalTokens: number;+}diff --git a/web/src/features/chart-view-prototype/vocab.ts b/web/src/features/chart-view-prototype/vocab.tsnew file mode 100644index 0000000000..337adb8bcc--- /dev/null+++ b/web/src/features/chart-view-prototype/vocab.ts@@ -0,0 +1,38 @@+// Re-export the production chart-view vocabulary (labels, query mappings,+// coerceConfig, describeConfig, chart types, β¦) so the harness and its tests+// use the exact same source of truth as the real view.+export * from "@/src/features/chart-view/vocab";++import {+ type DimensionKey,+ type MetricKey,+ type PrototypeEvent,+} from "./types";++/**+ * Mock-only value extractors that pull the metric/dimension value out of a+ * {@link PrototypeEvent}. Production reads these from ClickHouse via the+ * observations view; the harness extracts them client-side. `null` metric =+ * the row count (the `count` measure); `null` dimension = "no breakdown".+ */+export const METRIC_EXTRACTORS: Record<+ MetricKey,+ ((e: PrototypeEvent) => number) | null+> = {+ count: null,+ latency: (e) => e.latencyMs,+ totalCost: (e) => e.totalCost,+ totalTokens: (e) => e.totalTokens,+};++export const DIMENSION_EXTRACTORS: Record<+ DimensionKey,+ ((e: PrototypeEvent) => string) | null+> = {+ none: null,+ model: (e) => e.model ?? "unknown",+ name: (e) => e.name,+ level: (e) => e.level,+ type: (e) => e.type,+ environment: (e) => e.environment,+};diff --git a/web/src/features/chart-view/EventsChartView.tsx b/web/src/features/chart-view/EventsChartView.tsxnew file mode 100644index 0000000000..3085264c30--- /dev/null+++ b/web/src/features/chart-view/EventsChartView.tsx@@ -0,0 +1,81 @@+import React, { useMemo } from "react";+import { type FilterState } from "@langfuse/shared";+import { api } from "@/src/utils/api";+import { type ChartViewConfig } from "./types";+import { buildChartQuery, rowsToDataPoints } from "./lib/buildChartQuery";+import { toChartFilters } from "./lib/chartFilterCompatibility";+import { ChartViewPanel } from "./components/ChartViewPanel";+import { AddToDashboardButton } from "./components/AddToDashboardButton";++/**+ * Production chart view for the v4 events table. Builds the observations+ * aggregate query from the same filters + time window the table is showing,+ * runs it through the existing `dashboard.executeQuery` (the v2 / events read+ * path), and renders the Take-B panel. The query is the only difference from+ * the Storybook harness β everything below `ChartViewPanel` is shared, view-only.+ */+export function EventsChartView({+ projectId,+ filterState,+ fromTimestamp,+ toTimestamp,+ config,+ onConfigChange,+}: {+ projectId: string;+ filterState: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;+ config: ChartViewConfig;+ onConfigChange: (patch: Partial<ChartViewConfig>) => void;+}) {+ const filters = useMemo(() => toChartFilters(filterState), [filterState]);++ const query = useMemo(+ () => buildChartQuery({ config, filters, fromTimestamp, toTimestamp }),+ [config, filters, fromTimestamp, toTimestamp],+ );++ // A degenerate window (from === to, or from > to from independent time picks)+ // can't be charted; the query is disabled, which react-query keeps at+ // isPending forever β so surface a hint instead of an endless spinner.+ const validRange = fromTimestamp < toTimestamp;++ const queryResult = api.dashboard.executeQuery.useQuery(+ { projectId, query, version: "v2" },+ {+ enabled: validRange,+ meta: { silentHttpCodes: [422] },+ trpc: { context: { skipBatch: true } },+ },+ );++ const data = useMemo(+ () => (queryResult.data ? rowsToDataPoints(queryResult.data, config) : []),+ [queryResult.data, config],+ );++ const error = !validRange+ ? "Pick a wider time range to chart."+ : queryResult.isError+ ? (queryResult.error?.message ??+ "Couldn't build a chart for the current view.")+ : null;++ return (+ <ChartViewPanel+ config={config}+ onConfigChange={onConfigChange}+ data={data}+ isLoading={validRange && queryResult.isPending && !queryResult.isError}+ error={error}+ chartActions={+ <AddToDashboardButton+ projectId={projectId}+ config={config}+ filters={filters}+ />+ }+ />+ );+}diff --git a/web/src/features/chart-view/components/AddToDashboardButton.tsx b/web/src/features/chart-view/components/AddToDashboardButton.tsxnew file mode 100644index 0000000000..850ec2a0ec--- /dev/null+++ b/web/src/features/chart-view/components/AddToDashboardButton.tsx@@ -0,0 +1,81 @@+import React, { useCallback, useState } from "react";+import { useRouter } from "next/router";+import { LayoutDashboard } from "lucide-react";+import { type FilterState } from "@langfuse/shared";+import { Button } from "@/src/components/ui/button";+import { api } from "@/src/utils/api";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { SelectDashboardDialog } from "@/src/features/dashboard/components/SelectDashboardDialog";+import { type ChartViewConfig } from "../types";+import { chartConfigToWidgetInput } from "../lib/chartConfigToWidget";++/**+ * "Add to dashboard" β turns the in-view chart into a real dashboard widget by+ * REUSING the existing add-widget machinery, not duplicating it: map the chart+ * config to the `dashboardWidgets.create` input, pick a dashboard via the+ * existing `SelectDashboardDialog`, then hand off to the dashboard's own+ * `?addWidgetId=β¦` placement flow (same as the widget builder's save path).+ * Gated on `dashboards:CUD`, matching the server scope, so it never dead-ends.+ */+export const AddToDashboardButton = React.memo(function AddToDashboardButton({+ projectId,+ config,+ filters,+}: {+ projectId: string;+ config: ChartViewConfig;+ filters: FilterState;+}) {+ const router = useRouter();+ const [open, setOpen] = useState(false);+ const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });+ const createWidget = api.dashboardWidgets.create.useMutation();++ const onSelectDashboard = useCallback(+ (dashboardId: string) => {+ createWidget.mutate(+ { projectId, ...chartConfigToWidgetInput({ config, filters }) },+ {+ onSuccess: async (data) => {+ setOpen(false);+ // Hand off to the dashboard's existing placement flow β it reads+ // addWidgetId, fetches the widget, and drops it on the grid.+ await router.push(+ `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${data.widget.id}`,+ );+ },+ // Surface failures instead of leaving the dialog open with no feedback;+ // keep it open so the user can retry or pick another dashboard.+ onError: (error) =>+ showErrorToast("Failed to add chart to dashboard", error.message),+ },+ );+ },+ [createWidget, projectId, config, filters, router],+ );++ if (!hasAccess) return null;++ return (+ <>+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5"+ onClick={() => setOpen(true)}+ disabled={createWidget.isPending}+ >+ <LayoutDashboard className="h-3.5 w-3.5" />+ Add to dashboard+ </Button>+ <SelectDashboardDialog+ open={open}+ onOpenChange={setOpen}+ projectId={projectId}+ onSelectDashboard={onSelectDashboard}+ onSkip={() => setOpen(false)}+ />+ </>+ );+});diff --git a/web/src/features/chart-view/components/ChartCanvas.tsx b/web/src/features/chart-view/components/ChartCanvas.tsxnew file mode 100644index 0000000000..64c3ff7668--- /dev/null+++ b/web/src/features/chart-view/components/ChartCanvas.tsx@@ -0,0 +1,82 @@+import React, { useMemo } from "react";+import { BarChart3 } from "lucide-react";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { getWidgetMissingBucketValue } from "@/src/features/widgets/utils";+import { type ChartConfig } from "@/src/components/ui/chart";+import { type ChartViewConfig } from "../types";+import { getMetric, isTimeSeriesChartType } from "../vocab";++const RANKED_ROW_LIMIT = 20;++/**+ * Builds the `chart-library` `ChartConfig` (series labels + the `metric` key the+ * bar/pie primitives colour through `--color-metric`) from the rendered series.+ */+function buildChartConfig(data: DataPoint[], metricLabel: string): ChartConfig {+ const config: ChartConfig = {};+ // Per-series labels first, so a breakdown value that is literally "metric"+ // (e.g. an observation/model named "metric") keeps its own label.+ for (const point of data) {+ if (point.dimension && config[point.dimension] === undefined) {+ config[point.dimension] = { label: point.dimension };+ }+ }+ // Reserved key the bar/pie primitives colour through `--color-metric`; only+ // add it if no real series already claimed the "metric" key above.+ if (config.metric === undefined) config.metric = { label: metricLabel };+ return config;+}++/**+ * View-only chart renderer: takes already-aggregated `DataPoint[]` (from the+ * server query, or the mock aggregator in Storybook) plus the config, and hands+ * them to the shared `chart-library`. Memoized so a parent re-render or an+ * unrelated config change doesn't re-render the chart.+ */+export const ChartCanvas = React.memo(function ChartCanvas({+ data,+ config,+ emptyMessage = "No events match the current filters.",+}: {+ data: DataPoint[];+ config: ChartViewConfig;+ emptyMessage?: string;+}) {+ const metric = getMetric(config.metric);+ const chartConfig = useMemo(+ () => buildChartConfig(data, metric.label),+ [data, metric.label],+ );++ if (data.length === 0) {+ return (+ <div className="text-muted-foreground flex h-full flex-col items-center justify-center gap-2 p-8 text-center">+ <BarChart3 className="h-10 w-10 opacity-40" />+ <p className="text-sm">{emptyMessage}</p>+ </div>+ );+ }++ // Show the series legend only for a multi-series time chart. The shared+ // chart-library renders the legend below the plot now (LFE-10576), so "below"+ // is the value that used to be "above" here.+ const isTimeSeries = isTimeSeriesChartType(config.chartType);+ const legendPosition =+ isTimeSeries && config.breakdown !== "none" ? "below" : "none";++ return (+ <Chart+ chartType={config.chartType}+ data={data}+ rowLimit={RANKED_ROW_LIMIT}+ chartConfig={{ type: config.chartType, unit: metric.unit }}+ config={chartConfig}+ legendPosition={legendPosition}+ // Match dashboard widgets: additive metrics (count/sum) fill an empty+ // bucket with a 0 (continuous line), non-additive ones leave a gap β so a+ // chart renders the same here as once saved to a dashboard.+ missingValue={getWidgetMissingBucketValue(config.aggregation)}+ />+ );+});diff --git a/web/src/features/chart-view/components/ChartViewPanel.tsx b/web/src/features/chart-view/components/ChartViewPanel.tsxnew file mode 100644index 0000000000..85075c7654--- /dev/null+++ b/web/src/features/chart-view/components/ChartViewPanel.tsx@@ -0,0 +1,165 @@+import React, { useCallback, useState } from "react";+import { AlertCircle, ChevronLeft, ChevronRight, Loader2 } from "lucide-react";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { Button } from "@/src/components/ui/button";+import {+ type AggregationFn,+ type ChartViewConfig,+ type DimensionKey,+ type MetricKey,+} from "../types";+import { describeConfig } from "../vocab";+import { ChartCanvas } from "./ChartCanvas";+import {+ AggregationSelect,+ BreakdownSelect,+ ChartTypePicker,+ MetricSelect,+} from "./ConfigControls";++/**+ * The "Take B" chart-view layout (the direction Nikita picked): a maximized+ * chart canvas with the visualization config docked in a collapsible right-hand+ * panel. View-only β `data` and the loading/error state are supplied by the+ * caller (the server query in production, the mock aggregator in Storybook).+ * Optional `granularitySlot` lets a caller add a granularity control without+ * forking the layout.+ */+export const ChartViewPanel = React.memo(function ChartViewPanel({+ config,+ onConfigChange,+ data,+ isLoading = false,+ error = null,+ emptyMessage,+ granularitySlot,+ chartActions,+}: {+ config: ChartViewConfig;+ onConfigChange: (patch: Partial<ChartViewConfig>) => void;+ data: DataPoint[];+ isLoading?: boolean;+ error?: string | null;+ emptyMessage?: string;+ granularitySlot?: React.ReactNode;+ /** Right-aligned actions next to the chart subtitle (e.g. "Add to dashboard"). */+ chartActions?: React.ReactNode;+}) {+ const [open, setOpen] = useState(true);++ const onMetric = useCallback(+ (metric: MetricKey) => onConfigChange({ metric }),+ [onConfigChange],+ );+ const onAggregation = useCallback(+ (aggregation: AggregationFn) => onConfigChange({ aggregation }),+ [onConfigChange],+ );+ const onBreakdown = useCallback(+ (breakdown: DimensionKey) => onConfigChange({ breakdown }),+ [onConfigChange],+ );+ const onChartType = useCallback(+ (chartType: DashboardWidgetChartType) => onConfigChange({ chartType }),+ [onConfigChange],+ );++ return (+ <div className="flex min-h-0 flex-1">+ {/* Canvas */}+ <div className="flex min-h-0 min-w-0 flex-1 flex-col gap-1 p-3">+ <div className="flex items-center justify-between gap-2">+ <div className="text-foreground text-sm font-medium">+ {describeConfig(config)}+ </div>+ {chartActions}+ </div>+ <div className="min-h-0 flex-1">+ {error ? (+ <div className="text-muted-foreground flex h-full flex-col items-center justify-center gap-2 p-8 text-center">+ <AlertCircle className="h-10 w-10 opacity-40" />+ <p className="max-w-md text-sm">{error}</p>+ </div>+ ) : isLoading ? (+ <div className="text-muted-foreground flex h-full items-center justify-center">+ <Loader2 className="h-6 w-6 animate-spin" />+ </div>+ ) : (+ <ChartCanvas+ data={data}+ config={config}+ emptyMessage={emptyMessage}+ />+ )}+ </div>+ </div>++ {/* Config panel */}+ {open ? (+ <div className="flex w-72 shrink-0 flex-col gap-3 overflow-y-auto border-l p-3">+ <div className="flex items-center justify-between">+ <span className="text-sm font-semibold">Visualize</span>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Collapse panel"+ onClick={() => setOpen(false)}+ >+ <ChevronRight className="h-4 w-4" />+ </Button>+ </div>+ <PanelField label="Chart type">+ <ChartTypePicker+ value={config.chartType}+ onChange={onChartType}+ showLabels+ />+ </PanelField>+ <PanelField label="Metric">+ <MetricSelect value={config.metric} onChange={onMetric} />+ </PanelField>+ <PanelField label="Aggregation">+ <AggregationSelect+ metric={config.metric}+ value={config.aggregation}+ onChange={onAggregation}+ />+ </PanelField>+ <PanelField label="Breakdown">+ <BreakdownSelect value={config.breakdown} onChange={onBreakdown} />+ </PanelField>+ {granularitySlot ? (+ <PanelField label="Granularity">{granularitySlot}</PanelField>+ ) : null}+ </div>+ ) : (+ <div className="flex shrink-0 flex-col items-center border-l p-1.5">+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Expand panel"+ onClick={() => setOpen(true)}+ >+ <ChevronLeft className="h-4 w-4" />+ </Button>+ </div>+ )}+ </div>+ );+});++function PanelField({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div className="flex flex-col gap-1.5">+ <span className="text-muted-foreground text-xs font-medium">{label}</span>+ {children}+ </div>+ );+}diff --git a/web/src/features/chart-view/components/ConfigControls.tsx b/web/src/features/chart-view/components/ConfigControls.tsxnew file mode 100644index 0000000000..b038fbedb8--- /dev/null+++ b/web/src/features/chart-view/components/ConfigControls.tsx@@ -0,0 +1,193 @@+import React from "react";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { cn } from "@/src/utils/tailwind";+import {+ type AggregationFn,+ type DimensionKey,+ type MetricKey,+ type TimeGranularity,+} from "../types";+import {+ AGGREGATION_LABELS,+ CHART_TYPES,+ DIMENSIONS,+ getMetric,+ GRANULARITIES,+ METRICS,+} from "../vocab";++/**+ * View-only config pickers shared by the production chart view and the+ * Storybook harness. Each is a thin controlled wrapper over a primitive β+ * `value` in, `onChange` out, no feature logic.+ */++const TRIGGER_CLASS = "h-7 w-auto gap-1 text-xs";++export const MetricSelect = React.memo(function MetricSelect({+ value,+ onChange,+}: {+ value: MetricKey;+ onChange: (value: MetricKey) => void;+}) {+ return (+ <Select value={value} onValueChange={(v) => onChange(v as MetricKey)}>+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Metric">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {METRICS.map((m) => (+ <SelectItem key={m.key} value={m.key}>+ {m.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+});++export const AggregationSelect = React.memo(function AggregationSelect({+ metric,+ value,+ onChange,+}: {+ metric: MetricKey;+ value: AggregationFn;+ onChange: (value: AggregationFn) => void;+}) {+ const options = getMetric(metric).aggregations;+ return (+ <Select+ value={value}+ onValueChange={(v) => onChange(v as AggregationFn)}+ disabled={options.length <= 1}+ >+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Aggregation">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((agg) => (+ <SelectItem key={agg} value={agg}>+ {AGGREGATION_LABELS[agg]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+});++export const BreakdownSelect = React.memo(function BreakdownSelect({+ value,+ onChange,+}: {+ value: DimensionKey;+ onChange: (value: DimensionKey) => void;+}) {+ return (+ <Select value={value} onValueChange={(v) => onChange(v as DimensionKey)}>+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Breakdown dimension">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {DIMENSIONS.map((d) => (+ <SelectItem key={d.key} value={d.key}>+ {d.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+});++export const GranularitySelect = React.memo(function GranularitySelect({+ value,+ onChange,+ disabled,+}: {+ value: TimeGranularity;+ onChange: (value: TimeGranularity) => void;+ disabled?: boolean;+}) {+ return (+ <Select+ value={value}+ onValueChange={(v) => onChange(v as TimeGranularity)}+ disabled={disabled}+ >+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Time granularity">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {GRANULARITIES.map((g) => (+ <SelectItem key={g} value={g}>+ {g}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+});++export const ChartTypePicker = React.memo(function ChartTypePicker({+ value,+ onChange,+ showLabels = false,+}: {+ value: DashboardWidgetChartType;+ onChange: (value: DashboardWidgetChartType) => void;+ showLabels?: boolean;+}) {+ return (+ <ToggleGroup+ type="single"+ value={value}+ onValueChange={(v) => {+ if (v) onChange(v as DashboardWidgetChartType);+ }}+ variant="outline"+ className={cn(showLabels ? "grid grid-cols-3 gap-1" : "gap-0.5")}+ >+ {CHART_TYPES.map((ct) => {+ const Icon = ct.icon;+ const item = (+ <ToggleGroupItem+ key={ct.value}+ value={ct.value}+ size={showLabels ? "default" : "xs"}+ aria-label={ct.label}+ className={cn(+ showLabels+ ? "flex h-auto flex-col gap-1 py-2 text-[11px]"+ : "h-7 w-7 p-0",+ )}+ >+ <Icon className={showLabels ? "h-4 w-4" : "h-3.5 w-3.5"} />+ {showLabels ? <span>{ct.label}</span> : null}+ </ToggleGroupItem>+ );++ if (showLabels) return item;+ return (+ <Tooltip key={ct.value}>+ <TooltipTrigger asChild>{item}</TooltipTrigger>+ <TooltipContent>{ct.label}</TooltipContent>+ </Tooltip>+ );+ })}+ </ToggleGroup>+ );+});diff --git a/web/src/features/chart-view/components/ViewModeToggle.tsx b/web/src/features/chart-view/components/ViewModeToggle.tsxnew file mode 100644index 0000000000..7e1a245fff--- /dev/null+++ b/web/src/features/chart-view/components/ViewModeToggle.tsx@@ -0,0 +1,48 @@+import React from "react";+import { BarChart3, Table } from "lucide-react";+import { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";+import { type ViewMode } from "../types";++/**+ * The toolbar affordance that flips the v4 events view between table and chart.+ * "Any view is a chart". View-only.+ */+export const ViewModeToggle = React.memo(function ViewModeToggle({+ mode,+ onModeChange,+}: {+ mode: ViewMode;+ onModeChange: (mode: ViewMode) => void;+}) {+ return (+ <ToggleGroup+ type="single"+ value={mode}+ onValueChange={(v) => {+ if (v) onModeChange(v as ViewMode);+ }}+ variant="outline"+ // Match the h-8 height of the sibling toolbar controls (preset chips, My+ // Views, Columns). The view-mode switch is conceptually separate from the+ // filter presets to its left, so give it a margin bump off that cluster.+ className="ml-1 gap-0"+ >+ <ToggleGroupItem+ value="table"+ aria-label="Table view"+ className="h-8 gap-1.5 rounded-r-none px-2.5 text-xs"+ >+ <Table className="h-3.5 w-3.5" />+ Table+ </ToggleGroupItem>+ <ToggleGroupItem+ value="chart"+ aria-label="Chart view"+ className="h-8 gap-1.5 rounded-l-none border-l-0 px-2.5 text-xs"+ >+ <BarChart3 className="h-3.5 w-3.5" />+ Chart+ </ToggleGroupItem>+ </ToggleGroup>+ );+});diff --git a/web/src/features/chart-view/lib/buildChartQuery.clienttest.ts b/web/src/features/chart-view/lib/buildChartQuery.clienttest.tsnew file mode 100644index 0000000000..f265ea3086--- /dev/null+++ b/web/src/features/chart-view/lib/buildChartQuery.clienttest.ts@@ -0,0 +1,217 @@+import {+ buildChartQuery,+ metricField,+ rowsToDataPoints,+} from "./buildChartQuery";+import { DEFAULT_CONFIG } from "../vocab";+import { type ChartViewConfig } from "../types";++const FROM = new Date("2026-06-25T00:00:00.000Z");+const TO = new Date("2026-06-26T00:00:00.000Z");++const build = (config: Partial<ChartViewConfig>) =>+ buildChartQuery({+ config: { ...DEFAULT_CONFIG, ...config },+ filters: [],+ fromTimestamp: FROM,+ toTimestamp: TO,+ });++describe("buildChartQuery", () => {+ it("builds a time-series count-by-model query with auto granularity", () => {+ const q = build({+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ });+ expect(q.view).toBe("observations");+ expect(q.dimensions).toEqual([{ field: "providedModelName" }]);+ expect(q.metrics).toEqual([{ measure: "count", aggregation: "count" }]);+ expect(q.timeDimension).toEqual({ granularity: "auto" });+ expect(q.orderBy).toBeNull();+ expect(q.fromTimestamp).toBe("2026-06-25T00:00:00.000Z");+ });++ it("always uses auto granularity, ignoring config.timeGranularity", () => {+ // Production has no granularity control β the chart (and any widget it+ // becomes) always renders auto buckets, so a stale config value is ignored.+ const daily = build({+ chartType: "LINE_TIME_SERIES",+ timeGranularity: "day",+ });+ expect(daily.timeDimension).toEqual({ granularity: "auto" });+ });++ it("builds a categorical query with top-N ordering and a row limit", () => {+ const q = build({+ metric: "totalCost",+ aggregation: "sum",+ breakdown: "model",+ chartType: "HORIZONTAL_BAR",+ });+ expect(q.timeDimension).toBeNull();+ expect(q.dimensions).toEqual([{ field: "providedModelName" }]);+ expect(q.orderBy).toEqual([{ field: "sum_totalCost", direction: "desc" }]);+ expect(q.chartConfig).toEqual({ type: "HORIZONTAL_BAR", row_limit: 20 });+ });++ it("drops the breakdown and time dimension for a big number", () => {+ const q = build({+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "NUMBER",+ });+ expect(q.dimensions).toEqual([]);+ expect(q.timeDimension).toBeNull();+ expect(q.orderBy).toBeNull();+ });++ it("omits dimensions for a no-breakdown time series", () => {+ const q = build({ breakdown: "none", chartType: "AREA_TIME_SERIES" });+ expect(q.dimensions).toEqual([]);+ expect(q.timeDimension).toEqual({ granularity: "auto" });+ });++ it("names the metric column as aggregation_measure", () => {+ expect(+ metricField({ ...DEFAULT_CONFIG, metric: "latency", aggregation: "p95" }),+ ).toBe("p95_latency");+ expect(+ metricField({ ...DEFAULT_CONFIG, metric: "count", aggregation: "count" }),+ ).toBe("count_count");+ });+});++describe("rowsToDataPoints", () => {+ it("maps time-series breakdown rows", () => {+ const rows = [+ {+ time_dimension: "2026-06-25T10:00:00Z",+ providedModelName: "gpt-4o",+ count_count: 5,+ },+ {+ time_dimension: "2026-06-25T10:00:00Z",+ providedModelName: "claude-opus-4",+ count_count: 3,+ },+ ];+ expect(+ rowsToDataPoints(rows, {+ ...DEFAULT_CONFIG,+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ }),+ ).toEqual([+ {+ time_dimension: "2026-06-25T10:00:00Z",+ dimension: "gpt-4o",+ metric: 5,+ },+ {+ time_dimension: "2026-06-25T10:00:00Z",+ dimension: "claude-opus-4",+ metric: 3,+ },+ ]);+ });++ it("labels a no-breakdown series by the metric", () => {+ const rows = [{ time_dimension: "2026-06-25T10:00:00Z", count_count: 8 }];+ const [point] = rowsToDataPoints(rows, {+ ...DEFAULT_CONFIG,+ breakdown: "none",+ chartType: "LINE_TIME_SERIES",+ });+ expect(point.dimension).toBe("Count");+ expect(point.metric).toBe(8);+ });++ it("maps a categorical row and maps null/empty dimensions to n/a", () => {+ const config: ChartViewConfig = {+ ...DEFAULT_CONFIG,+ metric: "totalCost",+ aggregation: "sum",+ breakdown: "model",+ chartType: "HORIZONTAL_BAR",+ };+ const [nullPoint] = rowsToDataPoints(+ [{ providedModelName: null, sum_totalCost: 1.5 }],+ config,+ );+ expect(nullPoint.dimension).toBe("n/a");+ expect(nullPoint.metric).toBe(1.5);+ expect(nullPoint.time_dimension).toBeUndefined();++ const [emptyPoint] = rowsToDataPoints(+ [{ providedModelName: "", sum_totalCost: 2 }],+ config,+ );+ expect(emptyPoint.dimension).toBe("n/a");+ });++ it("produces a single dimensionless point for a big number", () => {+ const rows = [{ count_count: 42 }];+ expect(+ rowsToDataPoints(rows, {+ ...DEFAULT_CONFIG,+ chartType: "NUMBER",+ }),+ ).toEqual([+ { time_dimension: undefined, dimension: undefined, metric: 42 },+ ]);+ });++ it("preserves an explicit null as a gap on a time series (never coerces to 0)", () => {+ const config: ChartViewConfig = {+ ...DEFAULT_CONFIG,+ metric: "latency",+ aggregation: "p95",+ breakdown: "none",+ chartType: "LINE_TIME_SERIES",+ };+ const [point] = rowsToDataPoints(+ [{ time_dimension: "2026-06-25T10:00:00Z", p95_latency: null }],+ config,+ );+ expect(point.metric).toBeNull();+ });++ it("floors a missing value to 0 on a non-time-series chart", () => {+ const [point] = rowsToDataPoints([{ count_count: null }], {+ ...DEFAULT_CONFIG,+ chartType: "NUMBER",+ });+ expect(point.metric).toBe(0);+ });++ it("maps a gap-filled bucket on a breakdown time series to a marker, not an n/a series", () => {+ const config: ChartViewConfig = {+ ...DEFAULT_CONFIG,+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ };+ // count is additive β an empty bucket comes back as {dimension:null, 0}+ const [filler] = rowsToDataPoints(+ [{ time_dimension: "2026-06-25T10:00:00Z", providedModelName: null }],+ config,+ );+ expect(filler).toEqual({+ time_dimension: "2026-06-25T10:00:00Z",+ dimension: undefined,+ metric: null,+ });+ // a real breakdown value with an empty ("") cell still shows as n/a+ const [real] = rowsToDataPoints(+ [{ providedModelName: "gpt-4o", count_count: 5 }],+ config,+ );+ expect(real.dimension).toBe("gpt-4o");+ });+});diff --git a/web/src/features/chart-view/lib/buildChartQuery.ts b/web/src/features/chart-view/lib/buildChartQuery.tsnew file mode 100644index 0000000000..3a291bc5d9--- /dev/null+++ b/web/src/features/chart-view/lib/buildChartQuery.ts@@ -0,0 +1,133 @@+import { type FilterState, type QueryType } from "@langfuse/shared";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { getWidgetMissingBucketValue } from "@/src/features/widgets/utils";+import { type ChartViewConfig } from "../types";+import { getDimension, getMetric, isTimeSeriesChartType } from "../vocab";++/** Ranked/pie charts show a top-N slice. */+const CATEGORICAL_ROW_LIMIT = 20;++const VIEW = "observations" as const;++// Which sidebar/search filters the chart can honour (and the reasons it can't)+// live in `chartFilterCompatibility`. Callers narrow the FilterState with its+// `toChartFilters` before handing it here.++/** The executeQuery column name for a metric, e.g. `p95_latency`, `count_count`. */+export const metricField = (config: ChartViewConfig): string =>+ `${config.aggregation}_${getMetric(config.metric).measure}`;++/**+ * Builds the dashboard `QueryType` for a chart-view config over the v4+ * observations read path. Mirrors `WidgetForm`'s query construction: a time+ * series carries an auto-granularity `timeDimension`; a categorical chart drops+ * the time dimension and sorts top-N descending; a big number ignores the+ * breakdown entirely. `filters` and the time window come straight from the+ * events table so the chart always reflects what the table is showing.+ */+export function buildChartQuery({+ config,+ filters,+ fromTimestamp,+ toTimestamp,+}: {+ config: ChartViewConfig;+ filters: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;+}): QueryType {+ const metric = getMetric(config.metric);+ const dimension = getDimension(config.breakdown);+ const isTimeSeries = isTimeSeriesChartType(config.chartType);+ const isNumber = config.chartType === "NUMBER";++ // A big number is a single global aggregate β no breakdown, no time bucket.+ const dimensions =+ !isNumber && dimension.field ? [{ field: dimension.field }] : [];++ // Categorical breakdown (ranked bar / pie) β top-N descending by the metric.+ const isCategoricalBreakdown =+ !isTimeSeries && !isNumber && dimensions.length > 0;+ const field = metricField(config);++ return {+ view: VIEW,+ dimensions,+ metrics: [{ measure: metric.measure, aggregation: config.aggregation }],+ filters,+ // Auto-granularity, exactly like dashboard widgets (which have no+ // granularity control) β so a chart added to a dashboard renders the same+ // buckets there as here. See `chartConfigToWidgetInput`.+ timeDimension: isTimeSeries ? { granularity: "auto" } : null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: isCategoricalBreakdown+ ? [{ field, direction: "desc" as const }]+ : null,+ chartConfig: isCategoricalBreakdown+ ? { type: config.chartType, row_limit: CATEGORICAL_ROW_LIMIT }+ : { type: config.chartType },+ };+}++/** Stringify a raw dimension cell the way the widget charts do. */+const dimensionValue = (raw: unknown): string => {+ if (raw === null || raw === undefined || raw === "") return "n/a";+ if (typeof raw === "string") return raw;+ if (Array.isArray(raw)) return raw.join(", ");+ return String(raw);+};++/**+ * Turns `executeQuery` rows into chart-library `DataPoint[]` for a config β+ * the inverse of {@link buildChartQuery}. Pure; unit-tested. Time-series rows+ * carry `time_dimension`; a no-breakdown series is labelled by the metric so+ * the chart shows a single named line.+ */+export function rowsToDataPoints(+ rows: Array<Record<string, unknown>>,+ config: ChartViewConfig,+): DataPoint[] {+ const metric = getMetric(config.metric);+ const dimension = getDimension(config.breakdown);+ const field = metricField(config);+ const isNumber = config.chartType === "NUMBER";+ const isTimeSeries = isTimeSeriesChartType(config.chartType);+ const hasBreakdown = !isNumber && dimension.field !== null;++ return rows.map((row) => {+ const time_dimension = row["time_dimension"] as string | undefined;+ const value = row[field];++ // A gap-filled empty bucket on a BREAKDOWN time series arrives with no+ // dimension and a filler metric (null, or 0 for additive aggs). Keep it as a+ // pure bucket marker holding the axis slot β NOT a spurious "n/a" series.+ // Mirrors DashboardWidget's prep so the same rows render identically here and+ // on a dashboard (LFE-10694).+ if (isTimeSeries && hasBreakdown) {+ const rawDim = row[dimension.field as string];+ const isFiller =+ value == null ||+ (getWidgetMissingBucketValue(config.aggregation) === "zero" &&+ Number(value) === 0);+ if ((rawDim === null || rawDim === "") && isFiller) {+ return { time_dimension, dimension: undefined, metric: null };+ }+ }++ const dim = hasBreakdown+ ? dimensionValue(row[dimension.field as string])+ : isNumber+ ? undefined+ : metric.label;+ // Preserve an explicit null on a time series as a GAP β never coerce it to+ // 0 (the DataPoint contract, chart-props.ts: "null means measured nothing").+ // Categorical/number charts still floor a missing value.+ const metricValue = Array.isArray(value)+ ? value+ : isTimeSeries && value == null+ ? null+ : Number(value ?? 0);+ return { time_dimension, dimension: dim, metric: metricValue };+ });+}diff --git a/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.ts b/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.tsnew file mode 100644index 0000000000..131f41251e--- /dev/null+++ b/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.ts@@ -0,0 +1,64 @@+import { chartConfigToWidgetInput } from "./chartConfigToWidget";+import { DEFAULT_CONFIG } from "../vocab";+import { type ChartViewConfig } from "../types";++const map = (config: Partial<ChartViewConfig>) =>+ chartConfigToWidgetInput({+ config: { ...DEFAULT_CONFIG, ...config },+ filters: [],+ });++describe("chartConfigToWidgetInput", () => {+ it("maps a count-by-model line chart to an observations widget", () => {+ const w = map({+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ });+ expect(w.view).toBe("observations");+ expect(w.dimensions).toEqual([{ field: "providedModelName" }]);+ expect(w.metrics).toEqual([{ measure: "count", agg: "count" }]);+ expect(w.chartType).toBe("LINE_TIME_SERIES");+ expect(w.chartConfig).toEqual({ type: "LINE_TIME_SERIES" });+ expect(w.name).toBe("Count of events by model over time");+ // Always v2: the chart reads the v2 events path, so the widget must too.+ expect(w.minVersion).toBe(2);+ });++ it("maps a ranked cost-by-model chart with a row limit", () => {+ const w = map({+ metric: "totalCost",+ aggregation: "sum",+ breakdown: "model",+ chartType: "HORIZONTAL_BAR",+ });+ expect(w.metrics).toEqual([{ measure: "totalCost", agg: "sum" }]);+ expect(w.chartConfig).toEqual({ type: "HORIZONTAL_BAR", row_limit: 20 });+ expect(w.name).toBe("Sum cost by model");+ });++ it("drops the breakdown for a big number", () => {+ const w = map({+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "NUMBER",+ });+ expect(w.dimensions).toEqual([]);+ expect(w.chartConfig).toEqual({ type: "NUMBER" });+ });++ it("forwards the filters verbatim (the chart's safe subset)", () => {+ const filters = [+ {+ column: "type",+ type: "stringOptions" as const,+ operator: "any of" as const,+ value: ["GENERATION"],+ },+ ];+ const w = chartConfigToWidgetInput({ config: DEFAULT_CONFIG, filters });+ expect(w.filters).toEqual(filters);+ });+});diff --git a/web/src/features/chart-view/lib/chartConfigToWidget.ts b/web/src/features/chart-view/lib/chartConfigToWidget.tsnew file mode 100644index 0000000000..d9698b0f1c--- /dev/null+++ b/web/src/features/chart-view/lib/chartConfigToWidget.ts@@ -0,0 +1,76 @@+import { type FilterState } from "@langfuse/shared";+import { type RouterInputs } from "@/src/utils/api";+import { type ChartViewConfig } from "../types";+import {+ describeConfig,+ getDimension,+ getMetric,+ isTimeSeriesChartType,+} from "../vocab";++/** Ranked/pie widgets show a top-N slice β mirrors `buildChartQuery`. */+const CATEGORICAL_ROW_LIMIT = 20;++/** The `dashboardWidgets.create` input, minus the projectId the caller adds. */+export type ChartWidgetInput = Omit<+ RouterInputs["dashboardWidgets"]["create"],+ "projectId"+>;++/**+ * Maps a chart-view config (+ the filters the chart is showing) to the input of+ * the EXISTING `dashboardWidgets.create` mutation β the bridge that lets "Add to+ * dashboard" reuse the widget-creation flow instead of duplicating it. The+ * dimension/metric/chartConfig shaping mirrors `buildChartQuery`, so a chart+ * added this way is indistinguishable from a hand-built widget.+ *+ * The widget does not own a time range β the host dashboard supplies one β so+ * the chart's from/to are intentionally dropped here.+ */+export function chartConfigToWidgetInput({+ config,+ filters,+}: {+ config: ChartViewConfig;+ filters: FilterState;+}): ChartWidgetInput {+ const metric = getMetric(config.metric);+ const dimension = getDimension(config.breakdown);+ const isNumber = config.chartType === "NUMBER";++ const dimensions =+ !isNumber && dimension.field ? [{ field: dimension.field }] : [];+ const metrics = [{ measure: metric.measure, agg: config.aggregation }];++ const isCategoricalBreakdown =+ !isTimeSeriesChartType(config.chartType) &&+ !isNumber &&+ dimensions.length > 0;++ // The runtime shape is a valid ChartConfigSchema member; the cast just bridges+ // the broad chartType enum to the discriminated union TS can't narrow here.+ const chartConfig = (+ isCategoricalBreakdown+ ? { type: config.chartType, row_limit: CATEGORICAL_ROW_LIMIT }+ : { type: config.chartType }+ ) as ChartWidgetInput["chartConfig"];++ // Pin v2. The chart-view always queries the v2 events read path+ // (`EventsChartView` runs `dashboard.executeQuery` with version "v2"), so the+ // saved widget must read the same source β otherwise a non-beta viewer's+ // dashboard would fall back to the legacy observations table and show+ // different numbers than the chart the user just saved. "Save what I see."+ const minVersion = 2;++ return {+ name: describeConfig(config),+ description: "",+ view: "observations",+ dimensions,+ metrics,+ filters,+ chartType: config.chartType,+ chartConfig,+ minVersion,+ };+}diff --git a/web/src/features/chart-view/lib/chartFilterCompatibility.clienttest.ts b/web/src/features/chart-view/lib/chartFilterCompatibility.clienttest.tsnew file mode 100644index 0000000000..84e6bcf68b--- /dev/null+++ b/web/src/features/chart-view/lib/chartFilterCompatibility.clienttest.ts@@ -0,0 +1,133 @@+import {+ chartFilterExclusionReason,+ chartSearchFieldReason,+ classifyChartFilters,+ toChartFilters,+} from "./chartFilterCompatibility";+import { type FilterState } from "@langfuse/shared";++describe("chartFilterExclusionReason", () => {+ it("returns null for forwardable columns", () => {+ for (const col of [+ "environment",+ "type",+ "name",+ "level",+ "providedModelName",+ "userId",+ "sessionId",+ "traceName",+ "traceTags",+ "toolNames",+ "experimentId",+ ]) {+ expect(chartFilterExclusionReason(col)).toBeNull();+ }+ });++ it("groups measures, scores, comments, and metadata by reason", () => {+ expect(chartFilterExclusionReason("latency")).toMatch(/latency, cost/i);+ expect(chartFilterExclusionReason("totalCost")).toMatch(/latency, cost/i);+ expect(chartFilterExclusionReason("scores_avg")).toMatch(/scores/i);+ expect(chartFilterExclusionReason("trace_score_categories")).toMatch(+ /scores/i,+ );+ // promptVersion is a numeric field but the observations dimension is a+ // string β forwarding it errors the query, so it is NOT forwardable.+ expect(chartFilterExclusionReason("promptVersion")).not.toBeNull();+ expect(chartFilterExclusionReason("commentContent")).toMatch(/comments/i);+ expect(chartFilterExclusionReason("metadata")).toMatch(/metadata/i);+ });++ it("falls back to a generic reason for other unsupported columns", () => {+ const reason = chartFilterExclusionReason("isRootObservation");+ expect(reason).not.toBeNull();+ expect(reason).toMatch(/this field/i);+ });+});++describe("toChartFilters", () => {+ it("keeps forwardable filters, renames traceTags -> tags, drops the rest", () => {+ const filters: FilterState = [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["GENERATION"],+ },+ { column: "userId", type: "string", operator: "=", value: "u1" },+ {+ column: "traceTags",+ type: "arrayOptions",+ operator: "all of",+ value: ["prod"],+ },+ {+ column: "scores_avg",+ type: "numberObject",+ operator: ">",+ key: "accuracy",+ value: 0.5,+ },+ { column: "latency", type: "number", operator: ">", value: 2 },+ // a has:name presence check β dropped (null-type isn't applied to charts)+ { column: "name", type: "null", operator: "is not null", value: "" },+ ];+ const result = toChartFilters(filters);+ // scores + latency + the null-check dropped; traceTags -> tags+ expect(result.map((f) => f.column)).toEqual(["type", "userId", "tags"]);+ // the rename keeps the rest of the filter intact+ const tags = result.find((f) => f.column === "tags");+ expect(tags).toMatchObject({ operator: "all of", value: ["prod"] });+ });+});++describe("chartSearchFieldReason", () => {+ it("returns null for forwardable grammar fields (incl. aliases)", () => {+ expect(chartSearchFieldReason("level")).toBeNull();+ expect(chartSearchFieldReason("env")).toBeNull(); // alias -> environment+ expect(chartSearchFieldReason("user")).toBeNull(); // alias -> userId+ expect(chartSearchFieldReason("tags")).toBeNull(); // alias -> traceTags+ expect(chartSearchFieldReason("model")).toBeNull(); // -> providedModelName+ });++ it("classifies unsupported grammar fields by group", () => {+ expect(chartSearchFieldReason("latency")).toMatch(/latency, cost/i);+ expect(chartSearchFieldReason("cost")).toMatch(/latency, cost/i); // -> totalCost+ expect(chartSearchFieldReason("scores.accuracy")).toMatch(/scores/i);+ expect(chartSearchFieldReason("traceScores.helpfulness")).toMatch(+ /scores/i,+ );+ expect(chartSearchFieldReason("metadata.region")).toMatch(/metadata/i);+ // a search-bar startTime bound the chart can't honour+ expect(chartSearchFieldReason("startTime")).toMatch(/this field/i);+ });++ it("returns null for unknown fields", () => {+ expect(chartSearchFieldReason("nonsense")).toBeNull();+ });++ it("deactivates the has: presence pseudo-field (null-checks aren't charted)", () => {+ expect(chartSearchFieldReason("has")).toMatch(/is set/i);+ });+});++describe("classifyChartFilters", () => {+ it("splits forwarded filters from excluded ones with reasons", () => {+ const filters: FilterState = [+ { column: "environment", type: "string", operator: "=", value: "prod" },+ { column: "latency", type: "number", operator: ">", value: 1 },+ {+ column: "scores_avg",+ type: "numberObject",+ operator: ">",+ key: "acc",+ value: 0.5,+ },+ ];+ const { forwarded, excluded } = classifyChartFilters(filters);+ expect(forwarded.map((f) => f.column)).toEqual(["environment"]);+ expect([...excluded.keys()].sort()).toEqual(["latency", "scores_avg"]);+ expect(excluded.get("latency")).toMatch(/latency, cost/i);+ });+});diff --git a/web/src/features/chart-view/lib/chartFilterCompatibility.ts b/web/src/features/chart-view/lib/chartFilterCompatibility.tsnew file mode 100644index 0000000000..b0a284863c--- /dev/null+++ b/web/src/features/chart-view/lib/chartFilterCompatibility.ts@@ -0,0 +1,167 @@+import { type FilterState } from "@langfuse/shared";+import { resolveField } from "@/src/features/search-bar/lib/fields";++/**+ * Which of the events table's sidebar/search filters a chart can honour, and a+ * human reason for the ones it can't.+ *+ * The chart runs the observations aggregate query (`dashboard.executeQuery`,+ * v2 events read path β see `buildChartQuery`). That query accepts a subset of+ * the columns the events table exposes as filters: the dimensions the widget+ * builder also offers (LFE-10751). Everything else β measures, scores,+ * comments, metadata, and a few structural columns β has no dimension to filter+ * on, so it CANNOT be applied to the chart.+ *+ * Rather than hide the chart when an unsupported filter is present (the old+ * all-or-nothing gate), we forward what we can and mark the rest as "not+ * applied" in the sidebar + search bar, with the reason on hover. This module+ * is the single source of truth for that split β pure, unit-tested, shared by+ * the query builder (what to forward), the add-to-dashboard mapper (what the+ * saved widget carries), and both filter surfaces (what to deactivate).+ */++/**+ * Events-table filter columns whose values forward 1:1 onto an observations+ * query dimension. Keyed by the `column` string the events `FilterState` uses.+ * `traceTags` is the one whose query dimension name differs (`tags`) β see+ * {@link CHART_FILTER_COLUMN_RENAME}.+ */+export const FORWARDABLE_CHART_FILTER_COLUMNS: ReadonlySet<string> = new Set([+ "environment",+ "type",+ "name",+ "level",+ "providedModelName",+ "traceName",+ "userId",+ "sessionId",+ "version",+ "promptName",+ // NOTE: promptVersion is intentionally NOT forwardable. The search-bar+ // grammar registers it as a numeric field, so `promptVersion:>2` lowers to a+ // `number` filter β but the observations-view dimension is typed `string`,+ // which rejects numeric filters and errors the chart query. It shows as "not+ // applied" instead.+ "traceTags",+ "toolNames",+ "calledToolNames",+ "experimentName",+ "experimentDatasetId",+ "experimentId",+]);++/**+ * Events-table filter column -> observations-view dimension name, for the few+ * that differ. Applied to a forwarded filter's `column` so the query targets+ * the right dimension. Columns not listed forward under their own name.+ */+const CHART_FILTER_COLUMN_RENAME: Readonly<Record<string, string>> = {+ traceTags: "tags",+};++// Column groups that share one "why it's not applied" explanation. Kept as+// literal sets (not derived) so the reason a user sees is deliberate copy, not+// a leak of internal column ids.+const MEASURE_COLUMNS = new Set([+ "latency",+ "timeToFirstToken",+ "inputTokens",+ "outputTokens",+ "totalTokens",+ "inputCost",+ "outputCost",+ "totalCost",+]);++const SCORE_COLUMNS = new Set([+ "scores_avg",+ "score_categories",+ "score_booleans",+ "trace_scores_avg",+ "trace_score_categories",+ "trace_score_booleans",+]);++const COMMENT_COLUMNS = new Set(["commentCount", "commentContent"]);++/** Reason shown when full-text search is active β not a `FilterState` column. */+export const CHART_SEARCH_QUERY_REASON =+ "Charts can't apply text search at the moment β still narrows the table.";++/**+ * The reason a filter on `column` is NOT applied to the chart, or `null` if it+ * is forwarded. User-facing hover copy: plain "not at the moment" framing β+ * present-tense and polite, without claiming a hard impossibility (none of these+ * are) or promising a roadmap β plus the reassurance that the filter still works+ * on the table. No "dimension"/"measure" jargon.+ */+export function chartFilterExclusionReason(column: string): string | null {+ if (FORWARDABLE_CHART_FILTER_COLUMNS.has(column)) return null;+ if (MEASURE_COLUMNS.has(column))+ return "Charts can't filter by latency, cost, or tokens at the moment β still applies to the table.";+ if (SCORE_COLUMNS.has(column))+ return "Charts can't filter by scores at the moment β still applies to the table.";+ if (COMMENT_COLUMNS.has(column))+ return "Charts can't filter by comments at the moment β still applies to the table.";+ if (column === "metadata")+ return "Charts can't filter by metadata at the moment β still applies to the table.";+ return "Charts can't filter by this field at the moment β still applies to the table.";+}++/**+ * Narrows a `FilterState` to the subset the chart query can honour, renaming+ * the few columns whose observations-view dimension name differs. The inverse+ * of {@link chartFilterExclusionReason} on the forwarding side.+ */+export function toChartFilters(filterState: FilterState): FilterState {+ return filterState+ .filter(+ (f) =>+ // Presence checks (`has:`/`-has:`, a `null` filter) aren't applied by+ // the aggregate chart query β drop them so we never forward one and+ // 422; the search bar marks them "not applied" (chartSearchFieldReason).+ f.type !== "null" && FORWARDABLE_CHART_FILTER_COLUMNS.has(f.column),+ )+ .map((f) => {+ const renamed = CHART_FILTER_COLUMN_RENAME[f.column];+ return renamed ? { ...f, column: renamed } : f;+ });+}++/**+ * The reason a SEARCH-BAR field token is not applied to the chart, or `null` if+ * it is forwarded. Resolves a grammar field name (`level`, `user`, `latency`,+ * `scores.accuracy`, `metadata.region`) to its filter column via the bar's own+ * `resolveField`, so a token deactivates identically to its sidebar facet.+ */+export function chartSearchFieldReason(fieldName: string): string | null {+ const ref = resolveField(fieldName);+ if (!ref) return null;+ if (ref.type === "metadata") return chartFilterExclusionReason("metadata");+ if (ref.type === "scores")+ return chartFilterExclusionReason(+ ref.level === "trace" ? "trace_scores_avg" : "scores_avg",+ );+ // `has:`/`-has:` presence checks lower to a null-check filter, which the chart+ // doesn't apply (dropped by toChartFilters) β so the pill is deactivated too.+ if (ref.type === "pseudo")+ return "Charts can't filter by whether a field is set at the moment β still applies to the table.";+ return chartFilterExclusionReason(ref.field.id);+}++/**+ * Splits a `FilterState` into what the chart forwards and what it ignores, with+ * a per-column reason for the ignored ones. Both filter surfaces read the+ * `excluded` map (column -> reason) to deactivate the matching filter.+ */+export function classifyChartFilters(filterState: FilterState): {+ forwarded: FilterState;+ excluded: Map<string, string>;+} {+ const excluded = new Map<string, string>();+ for (const f of filterState) {+ const reason = chartFilterExclusionReason(f.column);+ if (reason) excluded.set(f.column, reason);+ }+ return { forwarded: toChartFilters(filterState), excluded };+}diff --git a/web/src/features/chart-view/lib/useChartViewState.ts b/web/src/features/chart-view/lib/useChartViewState.tsnew file mode 100644index 0000000000..baed9fd153--- /dev/null+++ b/web/src/features/chart-view/lib/useChartViewState.ts@@ -0,0 +1,87 @@+import { useCallback, useMemo } from "react";+import { StringParam, useQueryParams, withDefault } from "use-query-params";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import {+ type AggregationFn,+ type ChartViewConfig,+ type DimensionKey,+ type MetricKey,+ type ViewMode,+} from "../types";+import { coerceConfig, DEFAULT_CONFIG } from "../vocab";++/**+ * Returns `undefined` for a value equal to its default. Writing `undefined`+ * removes the param, so default values never land in the URL (read-side+ * `withDefault` only strips on read, not on write).+ */+const orUndefined = <T>(value: T, fallback: T): T | undefined =>+ value === fallback ? undefined : value;++/**+ * URL-driven, reversible state for the chart view: the tableβchart `viewMode`+ * and the visualization `config`. The URL is the single source of truth (the+ * search-bar pattern) β refresh, deep-link, and browser back all just work, and+ * the toggle is a clean revert. Only non-default fields are written to the URL+ * (see `orUndefined`), so the common case stays uncluttered. Everything+ * round-trips through `coerceConfig`, so a hand-edited URL can never yield an+ * invalid query.+ */+export function useChartViewState(): {+ viewMode: ViewMode;+ setViewMode: (mode: ViewMode) => void;+ config: ChartViewConfig;+ setConfig: (patch: Partial<ChartViewConfig>) => void;+} {+ const [params, setParams] = useQueryParams({+ // Namespaced ("eventsView", not bare "view") to avoid colliding with the+ // trace-peek panel's `view=timeline` param, which shares this router/URL.+ eventsView: withDefault(StringParam, "table"),+ chartMetric: withDefault(StringParam, DEFAULT_CONFIG.metric),+ chartAgg: withDefault(StringParam, DEFAULT_CONFIG.aggregation),+ chartBreakdown: withDefault(StringParam, DEFAULT_CONFIG.breakdown),+ chartType: withDefault(StringParam, DEFAULT_CONFIG.chartType),+ });++ const viewMode: ViewMode = params.eventsView === "chart" ? "chart" : "table";++ const config = useMemo<ChartViewConfig>(+ () =>+ coerceConfig({+ metric: params.chartMetric as MetricKey,+ aggregation: params.chartAgg as AggregationFn,+ breakdown: params.chartBreakdown as DimensionKey,+ chartType: params.chartType as DashboardWidgetChartType,+ // Granularity is not user-controllable in production β the chart (and+ // any widget it becomes) always renders auto buckets. Keep the default+ // so `coerceConfig` yields a complete config.+ timeGranularity: DEFAULT_CONFIG.timeGranularity,+ }),+ [+ params.chartMetric,+ params.chartAgg,+ params.chartBreakdown,+ params.chartType,+ ],+ );++ const setViewMode = useCallback(+ (mode: ViewMode) => setParams({ eventsView: orUndefined(mode, "table") }),+ [setParams],+ );++ const setConfig = useCallback(+ (patch: Partial<ChartViewConfig>) => {+ const next = coerceConfig({ ...config, ...patch });+ setParams({+ chartMetric: orUndefined(next.metric, DEFAULT_CONFIG.metric),+ chartAgg: orUndefined(next.aggregation, DEFAULT_CONFIG.aggregation),+ chartBreakdown: orUndefined(next.breakdown, DEFAULT_CONFIG.breakdown),+ chartType: orUndefined(next.chartType, DEFAULT_CONFIG.chartType),+ });+ },+ [config, setParams],+ );++ return { viewMode, setViewMode, config, setConfig };+}diff --git a/web/src/features/chart-view/metricAggregations.ts b/web/src/features/chart-view/metricAggregations.tsnew file mode 100644index 0000000000..162c05dee7--- /dev/null+++ b/web/src/features/chart-view/metricAggregations.ts@@ -0,0 +1,19 @@+import { type AggregationFn, type MetricKey } from "./types";++/**+ * Per-metric allowed aggregations β the single source of truth shared by the+ * vocab (UI pickers + `coerceConfig`) and the Ask-AI prompt. Keeping one map+ * means the LLM is never taught a `(metric, aggregation)` combination the chart+ * can't honour (which `coerceConfig` would otherwise silently demote). Pure+ * module: no React / `lucide`, so it is safe to import server-side.+ *+ * `count` is the row count and only ever uses `count`; the numeric metrics use+ * the subset that makes sense for their type (latency has no `sum`; cost/tokens+ * skip `min`/`p50`/`p99`).+ */+export const METRIC_AGGREGATIONS: Record<MetricKey, AggregationFn[]> = {+ count: ["count"],+ latency: ["avg", "p50", "p95", "p99", "max", "min"],+ totalCost: ["sum", "avg", "p95", "max"],+ totalTokens: ["sum", "avg", "p95", "max"],+};diff --git a/web/src/features/chart-view/types.ts b/web/src/features/chart-view/types.tsnew file mode 100644index 0000000000..85b94c2fac--- /dev/null+++ b/web/src/features/chart-view/types.ts@@ -0,0 +1,45 @@+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";++/**+ * The "chart view" feature β render the v4 events/observations data as a+ * configurable chart in place, instead of (or alongside) the table. The config+ * spec below is deliberately flat and enum-heavy: cheap to put in the URL, and+ * easy for an LLM to generate (phase 2's "Ask AI β chart"). Happy path only β+ * 1 metric Γ 1 dimension Γ 1 standard chart type.+ *+ * The Storybook design harness in `features/chart-view-prototype` renders these+ * same components against mock fixtures; the production wiring (`EventsChartView`)+ * renders them against the real v4 aggregate query.+ */++export type ViewMode = "table" | "chart";++export type MetricKey = "count" | "latency" | "totalCost" | "totalTokens";++export type DimensionKey =+ | "none"+ | "model"+ | "name"+ | "level"+ | "type"+ | "environment";++export type AggregationFn =+ | "count"+ | "sum"+ | "avg"+ | "min"+ | "max"+ | "p50"+ | "p95"+ | "p99";++export type TimeGranularity = "minute" | "hour" | "day";++export interface ChartViewConfig {+ metric: MetricKey;+ aggregation: AggregationFn;+ breakdown: DimensionKey;+ chartType: DashboardWidgetChartType;+ timeGranularity: TimeGranularity;+}diff --git a/web/src/features/chart-view/vocab.clienttest.ts b/web/src/features/chart-view/vocab.clienttest.tsnew file mode 100644index 0000000000..bbffd301f1--- /dev/null+++ b/web/src/features/chart-view/vocab.clienttest.ts@@ -0,0 +1,73 @@+import { coerceConfig, describeConfig, DEFAULT_CONFIG } from "./vocab";+import { type ChartViewConfig } from "./types";++describe("coerceConfig", () => {+ it("resets the aggregation when the metric does not support it", () => {+ const coerced = coerceConfig({+ ...DEFAULT_CONFIG,+ metric: "count",+ aggregation: "p95", // count only supports "count"+ });+ expect(coerced.aggregation).toBe("count");+ });++ it("keeps a valid aggregation untouched", () => {+ const coerced = coerceConfig({+ ...DEFAULT_CONFIG,+ metric: "latency",+ aggregation: "p99",+ });+ expect(coerced.aggregation).toBe("p99");+ });++ it("clamps unknown fields (untrusted URL params) to safe defaults", () => {+ const coerced = coerceConfig({+ metric: "bogus" as ChartViewConfig["metric"],+ aggregation: "nope" as ChartViewConfig["aggregation"],+ breakdown: "whoops" as ChartViewConfig["breakdown"],+ chartType: "FOO" as ChartViewConfig["chartType"],+ timeGranularity: "century" as ChartViewConfig["timeGranularity"],+ });+ expect(coerced.metric).toBe("count");+ expect(coerced.aggregation).toBe("count");+ expect(coerced.breakdown).toBe("none");+ expect(coerced.chartType).toBe("LINE_TIME_SERIES");+ expect(coerced.timeGranularity).toBe("hour");+ });+});++describe("describeConfig", () => {+ it("describes a count time series with a breakdown", () => {+ expect(+ describeConfig({+ ...DEFAULT_CONFIG,+ metric: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ }),+ ).toBe("Count of events by model over time");+ });++ it("includes the aggregation for numeric metrics", () => {+ expect(+ describeConfig({+ ...DEFAULT_CONFIG,+ metric: "latency",+ aggregation: "p95",+ breakdown: "model",+ chartType: "HORIZONTAL_BAR",+ }),+ ).toBe("p95 latency by model");+ });++ it("omits the breakdown for a big number (it shows a single total)", () => {+ expect(+ describeConfig({+ ...DEFAULT_CONFIG,+ metric: "count",+ breakdown: "model",+ chartType: "NUMBER",+ }),+ ).toBe("Count of events");+ });+});diff --git a/web/src/features/chart-view/vocab.ts b/web/src/features/chart-view/vocab.tsnew file mode 100644index 0000000000..eec794b75d--- /dev/null+++ b/web/src/features/chart-view/vocab.ts@@ -0,0 +1,211 @@+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import {+ AreaChart,+ BarChart3,+ BarChartHorizontal,+ Hash,+ LineChart,+ PieChart,+ type LucideIcon,+} from "lucide-react";+import {+ type AggregationFn,+ type ChartViewConfig,+ type DimensionKey,+ type MetricKey,+ type TimeGranularity,+} from "./types";+import { METRIC_AGGREGATIONS } from "./metricAggregations";++/**+ * The chart-view vocabulary: a trimmed, faithful subset of the real widget+ * vocabulary (`packages/shared/src/features/query/{dataModel,types}.ts`). Each+ * metric/dimension carries the real query identifier (`measure` / `field`) so+ * building the aggregate query is a straight mapping. Pure module β no React,+ * no mock-data coupling β shared by the production view and the Storybook+ * harness.+ */++export interface MetricDef {+ key: MetricKey;+ label: string;+ /** The observations-view measure name this metric aggregates over. */+ measure: string;+ /** Passed through to `formatMetric` so axes/tooltips render units. */+ unit?: "millisecond" | "USD";+ /** Aggregations that make sense for this metric. */+ aggregations: AggregationFn[];+}++export const METRICS: MetricDef[] = [+ {+ key: "count",+ label: "Count",+ measure: "count",+ aggregations: METRIC_AGGREGATIONS.count,+ },+ {+ key: "latency",+ label: "Latency",+ measure: "latency",+ unit: "millisecond",+ aggregations: METRIC_AGGREGATIONS.latency,+ },+ {+ key: "totalCost",+ label: "Cost",+ measure: "totalCost",+ unit: "USD",+ aggregations: METRIC_AGGREGATIONS.totalCost,+ },+ {+ key: "totalTokens",+ label: "Tokens",+ measure: "totalTokens",+ aggregations: METRIC_AGGREGATIONS.totalTokens,+ },+];++export interface DimensionDef {+ key: DimensionKey;+ label: string;+ /** The observations-view dimension field; `null` for "no breakdown". */+ field: string | null;+}++export const DIMENSIONS: DimensionDef[] = [+ { key: "none", label: "Total (no breakdown)", field: null },+ { key: "model", label: "Model", field: "providedModelName" },+ { key: "name", label: "Name", field: "name" },+ { key: "level", label: "Level", field: "level" },+ { key: "type", label: "Type", field: "type" },+ { key: "environment", label: "Environment", field: "environment" },+];++export const AGGREGATION_LABELS: Record<AggregationFn, string> = {+ count: "Count",+ sum: "Sum",+ avg: "Average",+ min: "Min",+ max: "Max",+ p50: "Median (p50)",+ p95: "p95",+ p99: "p99",+};++export interface ChartTypeOption {+ value: DashboardWidgetChartType;+ label: string;+ icon: LucideIcon;+ isTimeSeries: boolean;+}++/**+ * The chart types offered in-view: time series (line/area/bars), categorical+ * (ranked bars / pie), and a single big number. Pivot table and histogram are+ * intentionally left out β pivot overlaps the table side of the toggle, and the+ * happy path is 1 metric Γ 1 dimension.+ */+export const CHART_TYPES: ChartTypeOption[] = [+ {+ value: "LINE_TIME_SERIES",+ label: "Line",+ icon: LineChart,+ isTimeSeries: true,+ },+ {+ value: "AREA_TIME_SERIES",+ label: "Area",+ icon: AreaChart,+ isTimeSeries: true,+ },+ {+ value: "BAR_TIME_SERIES",+ label: "Bars",+ icon: BarChart3,+ isTimeSeries: true,+ },+ {+ value: "HORIZONTAL_BAR",+ label: "Ranked",+ icon: BarChartHorizontal,+ isTimeSeries: false,+ },+ { value: "PIE", label: "Pie", icon: PieChart, isTimeSeries: false },+ { value: "NUMBER", label: "Number", icon: Hash, isTimeSeries: false },+];++export const getMetric = (key: MetricKey): MetricDef =>+ METRICS.find((m) => m.key === key) ?? METRICS[0];++export const getDimension = (key: DimensionKey): DimensionDef =>+ DIMENSIONS.find((d) => d.key === key) ?? DIMENSIONS[0];++export const getChartType = (+ value: DashboardWidgetChartType,+): ChartTypeOption =>+ CHART_TYPES.find((c) => c.value === value) ?? CHART_TYPES[0];++export const isTimeSeriesChartType = (+ value: DashboardWidgetChartType,+): boolean => getChartType(value).isTimeSeries;++export const GRANULARITIES: TimeGranularity[] = ["minute", "hour", "day"];++/**+ * Coerces a config to a valid, internally-consistent spec. Clamps every field+ * to a known enum member (URL params are untrusted) and resets the aggregation+ * to one the metric supports when the metric changes. The view components and+ * the URL state both round-trip through this, so neither can produce an invalid+ * query.+ */+export const coerceConfig = (config: ChartViewConfig): ChartViewConfig => {+ const metric = getMetric(config.metric);+ const aggregation = metric.aggregations.includes(config.aggregation)+ ? config.aggregation+ : metric.aggregations[0];+ const breakdown = DIMENSIONS.some((d) => d.key === config.breakdown)+ ? config.breakdown+ : "none";+ const chartType = CHART_TYPES.some((c) => c.value === config.chartType)+ ? config.chartType+ : CHART_TYPES[0].value;+ const timeGranularity = GRANULARITIES.includes(config.timeGranularity)+ ? config.timeGranularity+ : "hour";+ return {+ metric: metric.key,+ aggregation,+ breakdown,+ chartType,+ timeGranularity,+ };+};++export const DEFAULT_CONFIG: ChartViewConfig = {+ metric: "count",+ aggregation: "count",+ breakdown: "model",+ chartType: "LINE_TIME_SERIES",+ timeGranularity: "hour",+};++/**+ * Human sentence describing a config β the chart subtitle, and the "here's what+ * I built" confirmation in the Ask-AI flow. Pure label lookup.+ */+export const describeConfig = (config: ChartViewConfig): string => {+ const metric = getMetric(config.metric);+ const metricPart =+ config.metric === "count"+ ? "Count of events"+ : `${AGGREGATION_LABELS[config.aggregation]} ${metric.label.toLowerCase()}`;+ // A big number is a single total β it ignores any breakdown, so don't claim+ // one in the subtitle.+ const byPart =+ config.breakdown === "none" || config.chartType === "NUMBER"+ ? ""+ : ` by ${getDimension(config.breakdown).label.toLowerCase()}`;+ const timePart = isTimeSeriesChartType(config.chartType) ? " over time" : "";+ return `${metricPart}${byPart}${timePart}`;+};diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex af9895e02e..cc5bbcf106 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -124,6 +124,14 @@ import {} from "@/src/features/search-bar/lib/observed-options";import { CategoryPresetChips } from "@/src/features/events/components/CategoryPresetChips";import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";+import { EventsChartView } from "@/src/features/chart-view/EventsChartView";+import { ViewModeToggle } from "@/src/features/chart-view/components/ViewModeToggle";+import { useChartViewState } from "@/src/features/chart-view/lib/useChartViewState";+import {+ chartFilterExclusionReason,+ chartSearchFieldReason,+ CHART_SEARCH_QUERY_REASON,+} from "@/src/features/chart-view/lib/chartFilterCompatibility";import { withMetadataPathOptions } from "@/src/features/search-bar/lib/metadata-paths";import { getEventsTableStatePolicy } from "@/src/features/events/lib/eventsTableStatePolicy";import {@@ -418,27 +426,43 @@ export default function ObservationsEventsTable({// never bumps.const [filterOptionsRefreshTick, setFilterOptionsRefreshTick] = useState(0);- // Auto-increment refresh tick to force date range recalculation- useEffect(() => {- if (!refreshInterval) return;- const id = setInterval(() => {- setRefreshTick((t) => t + 1);- }, refreshInterval);- return () => clearInterval(id);- }, [refreshInterval]);+ // Tick-safe refresh: table rows + counts + the chart query, WITHOUT+ // re-anchoring facet options (their values don't change tick-to-tick, so+ // re-fetching open high-cardinality facets every tick is wasteful). The auto+ // interval uses this. The chart runs dashboard.executeQuery; for absolute+ // time ranges its query key is stable across refreshes, so invalidate it too.+ const handleAutoRefresh = useCallback(() => {+ setRefreshTick((t) => t + 1);+ Promise.all([+ utils.events.all.invalidate(),+ utils.events.countAll.invalidate(),+ utils.dashboard.executeQuery.invalidate(),+ ]);+ }, [utils]);+ // Explicit refresh (manual button): everything the auto tick does, PLUS+ // re-anchoring the facet options β the one place their values are re-read.const handleRefresh = useCallback(() => {setRefreshTick((t) => t + 1);- // An explicit refresh re-anchors the facets too (and invalidate refetches- // whatever is already open); the auto interval above does not.setFilterOptionsRefreshTick((t) => t + 1);Promise.all([utils.events.all.invalidate(),utils.events.countAll.invalidate(),utils.events.filterOptions.invalidate(),+ utils.dashboard.executeQuery.invalidate(),]);}, [utils]);+ // Auto-refresh runs the tick-safe set (rows + chart), NOT the facet+ // re-anchor β otherwise every tick re-issues facet queries for open columns.+ useEffect(() => {+ if (!refreshInterval) return;+ const id = setInterval(() => {+ handleAutoRefresh();+ }, refreshInterval);+ return () => clearInterval(id);+ }, [refreshInterval, handleAutoRefresh]);+// Convert timeRange to absolute date range for compatibility// Include refreshTick to force recalculation on refreshconst tableDateRange = useMemo(() => {@@ -458,6 +482,28 @@ export default function ObservationsEventsTable({const filterOptionsDateRange =externalDateRange ?? filterOptionsTableDateRange;+ // Chart view ("any view is a chart"): URL-driven tableβchart toggle + config.+ // Only offered on the full (non-embedded) events surface, which is already+ // v4-only (the page mounts this table only for v4 users), so v1/legacy users+ // never see it. `chartEnabled` (computed below, once filterState exists) also+ // gates the chart off whenever the table's data can't be faithfully+ // reproduced by the aggregate query β free-text search, or any filter column+ // the query can't model β so the chart never silently disagrees with the+ // table.+ const {+ viewMode: chartViewMode,+ setViewMode: setChartViewMode,+ config: chartConfig,+ setConfig: setChartConfig,+ } = useChartViewState();+ const chartTimeWindow = useMemo(+ () => ({+ from: dateRange?.from ?? new Date(Date.now() - 24 * 60 * 60 * 1000),+ to: dateRange?.to ?? new Date(),+ }),+ [dateRange],+ );+const dateRangeFilter: FilterState = toStartTimeFilterState(dateRange);// Facet options are scoped only by the time window (the facet hook reads just@@ -708,6 +754,21 @@ export default function ObservationsEventsTable({? externalFilterState.concat(dateRangeFilter): combinedFilterState;+ // Offer the chart on the full (v4) surface β not embedded, not user/session+ // scoped. Unlike the old gate, an unsupported filter no longer HIDES the+ // chart: the chart forwards what it can and the sidebar + search bar mark the+ // rest as "not applied" (see chartFilterExclusions below).+ const chartEnabled = !hideControls && !userId && !sessionId;++ // The chart is actually on screen (not just enabled). Only then do we mark+ // the filters it can't honour as "not applied", so table mode stays untouched.+ // Both surfaces use the stateless per-column / per-field reason resolvers+ // (chartFilterExclusionReason / chartSearchFieldReason) β a filter deactivates+ // in the sidebar and its search-bar pill identically.+ const chartActive = chartEnabled && chartViewMode === "chart";+ // Free-text search is never applied to the chart (it has no aggregate form).+ const chartFreeTextIgnored = chartActive && Boolean(searchQuery);+// Use the custom hook for observations data fetchingconst {observations,@@ -734,6 +795,9 @@ export default function ObservationsEventsTable({selectAll,setSelectedRows,appRootFallbackEnabled: appRootDefault.isAutoManaged,+ // In chart mode the table is hidden and the chart runs its own aggregate+ // query β don't also run the expensive row + batched-I/O fetches.+ rowsEnabled: !chartActive,});useApplyAppRootFallback({@@ -1813,6 +1877,10 @@ export default function ObservationsEventsTable({commit={searchBarCommit}observed={observedOptions}erroredColumns={erroredColumns}+ fieldReason={chartActive ? chartSearchFieldReason : undefined}+ freeTextReason={+ chartFreeTextIgnored ? CHART_SEARCH_QUERY_REASON : undefined+ }onApplyFilters={searchBarApplyFilters}onRequestColumns={requestColumns}aiDataContext={aiDataContext}@@ -1864,14 +1932,14 @@ export default function ObservationsEventsTable({setRowHeight={setRowHeight}timeRange={showControlsInPageHeader ? undefined : timeRange}setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}- // Disabled, for now moved to filter sidebar- // TODO: remove this toggle once v4 looks good as is- // viewModeToggle={- // <EventsViewModeToggle- // viewMode={viewMode}- // onViewModeChange={setViewMode}- // />- // }+ viewModeToggle={+ chartEnabled ? (+ <ViewModeToggle+ mode={chartViewMode}+ onModeChange={setChartViewMode}+ />+ ) : undefined+ }refreshConfig={showControlsInPageHeader ? undefined : refreshConfig}@@ -1887,7 +1955,8 @@ export default function ObservationsEventsTable({tableName={BatchExportTableName.Events}key="batchExport"/>,- selectedObservationIds.length > 0 || selectAll ? (+ !chartActive &&+ (selectedObservationIds.length > 0 || selectAll) ? (<TableActionMenukey="observations-multi-select-actions"projectId={projectId}@@ -1909,19 +1978,27 @@ export default function ObservationsEventsTable({/>) : null,]}- multiSelect={{- selectAll,- setSelectAll,- selectedRowIds: selectedObservationIds,- setRowSelection: setSelectedRows,- totalCount,- // totalCount stays null until select-all triggers the lazy- // count query; hasNextPage lets the select-all banner show- // without an eager count over the events table.- hasNextPage: hasMore,- pageSize: paginationState.limit,- pageIndex: paginationState.page - 1,- }}+ // No row selection in chart mode β the table (and its select-all+ // banner) is hidden, so a stale selection must not keep the batch+ // menu (incl. Delete) operable. The selection is preserved and+ // reappears on switching back to Table.+ multiSelect={+ chartActive+ ? undefined+ : {+ selectAll,+ setSelectAll,+ selectedRowIds: selectedObservationIds,+ setRowSelection: setSelectedRows,+ totalCount,+ // totalCount stays null until select-all triggers the lazy+ // count query; hasNextPage lets the select-all banner show+ // without an eager count over the events table.+ hasNextPage: hasMore,+ pageSize: paginationState.limit,+ pageIndex: paginationState.page - 1,+ }+ }// In bar mode AI filtering lives in the search bar ("Ask AI"),// so the legacy wand is only offered when the bar is absent.filterWithAI={!searchBarMode}@@ -1973,109 +2050,125 @@ export default function ObservationsEventsTable({// In bar mode AI filtering lives in the search bar; only offer the// sidebar wand on non-bar surfaces (embedded scoped tables).filterWithAI={!searchBarMode}+ // In chart mode, dim active filters the chart can't apply (+ hover+ // reason). Stateless per-column resolver β matches the search bar.+ deactivatedColumnReason={+ chartActive ? chartFilterExclusionReason : undefined+ }/>)}<div className="flex flex-1 flex-col overflow-hidden">- <DataTable- key={`observations-table-${dataUpdatedAt}-${rows.length > 0 && rows[0]?.input ? "with-io" : "without-io"}`}- tableName="observations"- columns={columns}- peekView={peekConfig}- data={- observations.status === "loading" || isViewLoading- ? { isLoading: true, isError: false }- : observations.status === "error"- ? isSilencedError- ? {- isLoading: false,- isError: false,- data: [],- }+ {chartEnabled && chartViewMode === "chart" ? (+ <EventsChartView+ projectId={projectId}+ filterState={filterState}+ fromTimestamp={chartTimeWindow.from}+ toTimestamp={chartTimeWindow.to}+ config={chartConfig}+ onConfigChange={setChartConfig}+ />+ ) : (+ <DataTable+ key={`observations-table-${dataUpdatedAt}-${rows.length > 0 && rows[0]?.input ? "with-io" : "without-io"}`}+ tableName="observations"+ columns={columns}+ peekView={peekConfig}+ data={+ observations.status === "loading" || isViewLoading+ ? { isLoading: true, isError: false }+ : observations.status === "error"+ ? isSilencedError+ ? {+ isLoading: false,+ isError: false,+ data: [],+ }+ : {+ isLoading: false,+ isError: true,+ error: "",+ }: {isLoading: false,- isError: true,- error: "",+ isError: false,+ data: rows,}+ }+ noResultsMessage={+ isSilencedError ? (+ <span className="text-muted-foreground">+ {RESOURCE_LIMIT_ERROR_MESSAGE}+ </span>+ ) : undefined+ }+ pagination={+ limitRows+ ? undefined: {- isLoading: false,- isError: false,- data: rows,+ totalCount,+ hasNextPage: hasMore,+ hideTotalCount: true,+ canJumpPages: false,+ onChange: (updater) => {+ const newState =+ typeof updater === "function"+ ? updater({+ pageIndex: paginationState.page - 1,+ pageSize: paginationState.limit,+ })+ : updater;+ setPaginationState({+ page: newState.pageIndex + 1,+ limit: newState.pageSize,+ });+ },+ state: {+ pageIndex: paginationState.page - 1,+ pageSize: paginationState.limit,+ },}- }- noResultsMessage={- isSilencedError ? (- <span className="text-muted-foreground">- {RESOURCE_LIMIT_ERROR_MESSAGE}- </span>- ) : undefined- }- pagination={- limitRows- ? undefined- : {- totalCount,- hasNextPage: hasMore,- hideTotalCount: true,- canJumpPages: false,- onChange: (updater) => {- const newState =- typeof updater === "function"- ? updater({- pageIndex: paginationState.page - 1,- pageSize: paginationState.limit,- })- : updater;- setPaginationState({- page: newState.pageIndex + 1,- limit: newState.pageSize,- });- },- state: {- pageIndex: paginationState.page - 1,- pageSize: paginationState.limit,- },+ }+ rowSelection={selectedRows}+ highlightAllRows={selectAll}+ setRowSelection={setSelectedRows}+ setOrderBy={setOrderByState}+ orderBy={orderByState}+ columnOrder={columnOrder}+ onColumnOrderChange={setColumnOrder}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={setColumnVisibilityState}+ rowHeight={rowHeight}+ onRowClick={(row, event) => {+ // Handle Command/Ctrl+click to open observation in new tab+ if (event && (event.metaKey || event.ctrlKey)) {+ // Prevent the default peek behavior+ event.preventDefault();++ // Construct the observation URL directly to avoid race conditions+ const observationId = row.id;+ const traceId = row.traceId;+ const timestamp = row.timestamp;++ if (traceId) {+ const observationUrl = buildTraceDetailPath({+ projectId,+ traceId,+ observationId,+ timestamp,+ });++ window.open(+ getSafeRedirectPath(observationUrl),+ "_blank",+ "noopener,noreferrer",+ );}- }- rowSelection={selectedRows}- highlightAllRows={selectAll}- setRowSelection={setSelectedRows}- setOrderBy={setOrderByState}- orderBy={orderByState}- columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}- columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibilityState}- rowHeight={rowHeight}- onRowClick={(row, event) => {- // Handle Command/Ctrl+click to open observation in new tab- if (event && (event.metaKey || event.ctrlKey)) {- // Prevent the default peek behavior- event.preventDefault();-- // Construct the observation URL directly to avoid race conditions- const observationId = row.id;- const traceId = row.traceId;- const timestamp = row.timestamp;-- if (traceId) {- const observationUrl = buildTraceDetailPath({- projectId,- traceId,- observationId,- timestamp,- });-- window.open(- getSafeRedirectPath(observationUrl),- "_blank",- "noopener,noreferrer",- );}- }- // For normal clicks, let the data-table handle opening the peek view- }}- />+ // For normal clicks, let the data-table handle opening the peek view+ }}+ />+ )}</div></ResizableFilterLayout>{peekConfig && (diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.tsindex 0eb428e5d5..7127ee6a91 100644--- a/web/src/features/events/hooks/useEventsTableData.ts+++ b/web/src/features/events/hooks/useEventsTableData.ts@@ -37,6 +37,12 @@ type UseEventsTableDataParams = {selectAll: boolean;setSelectedRows: (rows: Record<string, boolean>) => void;appRootFallbackEnabled?: boolean;+ /**+ * Gate the row + batched-I/O queries. Defaults to true; the events table+ * passes `false` in chart mode so the (hidden) table's expensive row/IO+ * fetches don't run alongside the chart's aggregate query.+ */+ rowsEnabled?: boolean;};export function useEventsTableData({@@ -50,6 +56,7 @@ export function useEventsTableData({selectAll,setSelectedRows,appRootFallbackEnabled = false,+ rowsEnabled = true,}: UseEventsTableDataParams) {// Prepare query payloadsconst getCountPayload = useMemo(@@ -81,6 +88,7 @@ export function useEventsTableData({const silentHttpCodes = [422];const observations = api.events.all.useQuery(getAllPayload, {+ enabled: rowsEnabled,refetchOnWindowFocus: true,placeholderData: (prev) => prev,meta: {@@ -104,7 +112,9 @@ export function useEventsTableData({rootRowCount: observations.data?.observations.length ?? 0,});const appRootFallbackQuery = api.events.all.useQuery(fallbackPayload, {- enabled: shouldRunAppRootFallback,+ // Also gate on rowsEnabled (matches the primary + I/O queries): otherwise a+ // stale-cached fallback condition could fire a real row fetch in chart mode.+ enabled: rowsEnabled && shouldRunAppRootFallback,refetchOnWindowFocus: false,staleTime: Infinity,retry: false,@@ -158,7 +168,8 @@ export function useEventsTableData({// Fetch I/O dataconst ioDataQuery = api.events.batchIO.useQuery(batchIOPayload!, {...sendAsPostOption,- enabled: activeObservations.isSuccess && batchIOPayload !== null,+ enabled:+ rowsEnabled && activeObservations.isSuccess && batchIOPayload !== null,refetchOnWindowFocus: false,staleTime: 0,});diff --git a/web/src/features/search-bar/components/ComposerTokens.tsx b/web/src/features/search-bar/components/ComposerTokens.tsxindex 24abfbfa85..9a3e0295cc 100644--- a/web/src/features/search-bar/components/ComposerTokens.tsx+++ b/web/src/features/search-bar/components/ComposerTokens.tsx@@ -44,8 +44,12 @@ export const composerTokenVariants = cva("max-w-full", {invalid:"mr-1 inline rounded border border-dashed px-1.5 py-0.5 border-destructive/70 bg-destructive/10 text-destructive transition-colors hover:border-destructive",},+ // A filter that the current surface can't apply (e.g. the chart view can't+ // filter on this column). Dimmed + dashed so it reads as "shown but not+ // applied"; the reason is on hover (`title`).+ deactivated: { true: "opacity-50 line-through decoration-1", false: "" },},- defaultVariants: { kind: "freeText" },+ defaultVariants: { kind: "freeText", deactivated: false },});type TokenKind = "filter" | "freeText" | "operator" | "paren" | "invalid";@@ -107,10 +111,22 @@ export function ComposerTokens({draft,showDiagnostics,scoreTypes,+ fieldReason,+ freeTextReason,}: {draft: string;showDiagnostics: boolean;scoreTypes?: ScoreTypeContext;+ /**+ * Given a filter token's field name, the reason it is NOT applied on the+ * current surface, or `null` if it is. When it returns a reason the pill+ * renders deactivated (dimmed + struck) with the reason on hover. Undefined+ * (the default) leaves every filter active β nothing is deactivated.+ */+ fieldReason?: (field: string) => string | null;+ /** Reason a free-text token is not applied (e.g. charts ignore full-text+ * search), or null/undefined to leave it active. */+ freeTextReason?: string | null;}): React.ReactNode {const segments = deriveComposerSegments(draft, scoreTypes);const out: React.ReactNode[] = [];@@ -125,12 +141,24 @@ export function ComposerTokens({segment.kind === "invalid" && !showDiagnostics? "freeText": segment.kind;+ // "Not applied on this surface" β a filter column the chart can't honour,+ // or free text a chart ignores. Only filter/free-text tokens can deactivate+ // (operators/parens/invalid never do).+ const deactivatedReason =+ segment.kind === "filter"+ ? (fieldReason?.(segment.displayField) ?? null)+ : segment.kind === "freeText"+ ? (freeTextReason ?? null)+ : null;+ const deactivated = deactivatedReason !== null;// Invalid tokens get the styled per-token error tooltip (a positioned- // overlay in SearchComposer), not the native browser title. Free text is a- // full-text search β say so on hover so a standalone text chip explains- // itself instead of looking like a stray block.- const title =- segment.kind === "invalid"+ // overlay in SearchComposer), not the native browser title. A deactivated+ // token explains why it is ignored. Free text is a full-text search β say so+ // on hover so a standalone text chip explains itself instead of looking like+ // a stray block.+ const title = deactivated+ ? deactivatedReason+ : segment.kind === "invalid"? undefined: segment.kind === "freeText"? `Full-text search β matches results containing "${segment.raw}". Searches ids, names, input and output by default; use input: or output: to search one payload, or name:/id: to narrow.`@@ -140,9 +168,10 @@ export function ComposerTokens({key={segment.id}data-testid="search-bar-token"data-kind={visibleKind}+ data-deactivated={deactivated || undefined}data-segment-id={segment.id}title={title}- className={composerTokenVariants({ kind: visibleKind })}+ className={composerTokenVariants({ kind: visibleKind, deactivated })}>{segment.kind === "filter" ? (<FilterTokenBody segment={segment} />diff --git a/web/src/features/search-bar/components/ComposerWithPreview.tsx b/web/src/features/search-bar/components/ComposerWithPreview.tsxindex 0e8af1bf65..3ebac9d37e 100644--- a/web/src/features/search-bar/components/ComposerWithPreview.tsx+++ b/web/src/features/search-bar/components/ComposerWithPreview.tsx@@ -66,6 +66,8 @@ export function ComposerWithPreview(draft={previewText}showDiagnostics={false}scoreTypes={scoreTypes}+ fieldReason={props.fieldReason}+ freeTextReason={props.freeTextReason}/></div></div>diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsxindex 8d5416a5d2..f0e04837fe 100644--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx@@ -36,6 +36,8 @@ export function EventsSearchBarRow({commit,observed,erroredColumns,+ fieldReason,+ freeTextReason,onApplyFilters,onRequestColumns,aiDataContext,@@ -51,6 +53,12 @@ export function EventsSearchBarRow({* empty (per column) instead of pinning, matching the sidebar's settled-error* state, without blocking other columns. */erroredColumns?: ReadonlySet<string>;+ /** Given a filter token's field, the reason it is not applied on the current+ * surface (e.g. the chart view can't filter on it) β dims the pill + hover.+ * Undefined leaves all filters active. */+ fieldReason?: (field: string) => string | null;+ /** Reason free-text tokens are not applied on the current surface, or null. */+ freeTextReason?: string | null;/*** Applies AI-generated filters (apply-immediately); the bar re-derives them.* Preserves filters the grammar can't represent (no-silent-drop contract) β@@ -103,6 +111,8 @@ export function EventsSearchBarRow({projectId={projectId}observed={observed}erroredColumns={erroredColumns}+ fieldReason={fieldReason}+ freeTextReason={freeTextReason}onActivateAi={aiAvailable ? activateAi : undefined}onRequestColumns={onRequestColumns}/>diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsxindex 6215ef3fbe..eacc659db4 100644--- a/web/src/features/search-bar/components/SearchComposer.tsx+++ b/web/src/features/search-bar/components/SearchComposer.tsx@@ -293,6 +293,8 @@ export function SearchComposer({erroredColumns,onActivateAi,onRequestColumns,+ fieldReason,+ freeTextReason,}: {projectId: string;/** Observed facet values for value suggestions; undefined = loading. */@@ -309,6 +311,11 @@ export function SearchComposer({* loading is wired by the host table.*/onRequestColumns?: (columns: readonly string[]) => void;+ /** Given a filter token's field, the reason it is not applied on the current+ * surface (dims the pill + hover), or null. Undefined leaves all active. */+ fieldReason?: (field: string) => string | null;+ /** Reason free-text tokens are not applied on the current surface, or null. */+ freeTextReason?: string | null;}) {const storeApi = useSearchBarStoreApi();const commitToFilterState = useSearchBarCommit();@@ -1350,6 +1357,8 @@ export function SearchComposer({draft={draft}showDiagnostics={showTokenDiagnostics}scoreTypes={scoreTypes}+ fieldReason={fieldReason}+ freeTextReason={freeTextReason}/></div>{/* "Ask AI" affordance β a plain button, always available so filters can