πͺ’ 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
refactor(widgets): move WidgetForm to react-hook-form and fix histogram silent-revert (LFE-10699) (#15403)
Nikita Kabardinca2e5456f978
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsxindex afd54fb7e4..1b8f60bbe3 100644--- a/web/src/features/widgets/components/WidgetForm.tsx+++ b/web/src/features/widgets/components/WidgetForm.tsx@@ -13,7 +13,6 @@ import {getResultUnit,getValidAggregationsForMeasureType,isV2BreakdownChart,- requiresV2,validateQuery,viewDeclarations,views,@@ -24,10 +23,17 @@ import {} from "@langfuse/shared/query";import {mapWidgetUiTableFilterToView,- normalizeStoredWidgetFiltersForEditor,partitionWidgetUiTableFiltersToView,} from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";-import React, { useState, useMemo, useEffect, useRef } from "react";+import React, { useMemo, useRef } from "react";+import {+ useController,+ useForm,+ useWatch,+ type Control,+ type Resolver,+} from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";import {Select,SelectContent,@@ -88,13 +94,9 @@ import {PopoverClose,} from "@/src/components/ui/popover";import {- buildWidgetName,- buildWidgetDescription,formatMetricName,getWidgetMetricPresentation,getWidgetMissingBucketValue,- sanitizePivotTableDefaultSort,- type WidgetChartConfig,} from "@/src/features/widgets/utils";import {MAX_PIVOT_TABLE_DIMENSIONS,@@ -110,17 +112,35 @@ import {getWidgetFilterColumns,} from "./widgetFilterColumns";import { WIDGET_FILTER_PRESETS } from "@/src/features/widgets/constants/widgetFilterPresets";+import {+ applyChartTypeChange,+ deriveEffectiveSort,+ deriveSaveReason,+ deriveWidgetBaseMinVersion,+ deriveWidgetSuggestions,+ effectiveWidgetName,+ makeWidgetFormSchema,+ normalizeWidgetFormValues,+ resolveWidgetViewVersion,+ toDefaultValues,+ toSavePayload,+ widgetChartTypeSupportsBreakdown,+ type SortField,+ type WidgetFormValues,+ type WidgetInitialValues,+} from "./widgetFormSchema";++// Re-exported from the schema module so co-located tests keep importing it from+// this file; it now backs the shared normalizeWidgetFormValues healing.+export { resolveAggregationAndChartType } from "./widgetFormSchema";type ChartType = {group: "time-series" | "total-value";name: string;value: DashboardWidgetChartType;icon: React.ElementType;- supportsBreakdown: boolean;};-type ChartConfig = WidgetChartConfig;-const getDateRangeFilter = (column: "timestamp" | "startTime",dateRange?: { from: Date; to: Date },@@ -132,62 +152,57 @@ const getDateRangeFilter = (]: undefined;+// chartTypes drives the chart-type SelectGroup rendering (group/name/value/+// icon). Whether a type supports a breakdown dimension is derived on demand via+// widgetChartTypeSupportsBreakdown(chartType) at each gate, not stored here.const chartTypes: ChartType[] = [{group: "total-value",name: "Big Number",value: "NUMBER",icon: Hash,- supportsBreakdown: false,},{group: "time-series",name: "Line Chart",value: "LINE_TIME_SERIES",icon: LineChart,- supportsBreakdown: true,},{group: "time-series",name: "Vertical Bar Chart",value: "BAR_TIME_SERIES",icon: BarChart,- supportsBreakdown: true,},{group: "total-value",name: "Horizontal Bar Chart",value: "HORIZONTAL_BAR",icon: BarChartHorizontal,- supportsBreakdown: true,},{group: "total-value",name: "Vertical Bar Chart",value: "VERTICAL_BAR",icon: BarChart,- supportsBreakdown: true,},{group: "total-value",name: "Histogram",value: "HISTOGRAM",icon: BarChart3,- supportsBreakdown: false,},{group: "total-value",name: "Pie Chart",value: "PIE",icon: PieChart,- supportsBreakdown: true,},{group: "total-value",name: "Pivot Table",value: "PIVOT_TABLE",icon: Table,- supportsBreakdown: true,},];@@ -199,87 +214,15 @@ const observationTypeOptions = ObservationTypeDomain.options.map((value) => ({}));/**- * Pure function that resolves the correct aggregation and chart type given the- * current selections and valid aggregation list. Returns null when no change is- * needed.- *- * All constraints are resolved in a single pass so the output is a fixed point- * (running the function again on its own output always returns null). This- * prevents infinite React state-update loops when constraints conflict β e.g.- * HISTOGRAM requires "histogram" aggregation but "count" measure forces "count".- */-export function resolveAggregationAndChartType(params: {- chartType: string;- measure: string;- currentAgg: string;- validAggs: z.infer<typeof metricAggregations>[];-}): {- aggregation?: z.infer<typeof metricAggregations>;- chartType?: string;-} | null {- const { chartType, measure, currentAgg, validAggs } = params;- const supportsHistogram = validAggs.includes("histogram");-- let targetChart = chartType;- let targetAgg = currentAgg as z.infer<typeof metricAggregations>;-- // HISTOGRAM chart needs a histogram-compatible measure- if (targetChart === "HISTOGRAM") {- if (!supportsHistogram) {- targetChart = "NUMBER";- } else {- targetAgg = "histogram";- }- }-- // Non-HISTOGRAM chart can't keep histogram aggregation- if (targetChart !== "HISTOGRAM" && targetAgg === "histogram") {- targetAgg =- measure === "count"- ? "count"- : ((validAggs[0] ?? "sum") as z.infer<typeof metricAggregations>);- }-- // "count" measure only supports "count" aggregation. If this conflicts with- // the chart type (e.g. HISTOGRAM requires "histogram"), bail the chart type- // rather than creating an unresolvable conflict.- if (measure === "count" && targetAgg !== "count") {- if (targetChart === "HISTOGRAM") {- targetChart = "NUMBER";- }- targetAgg = "count";- }-- // Current aggregation not valid for the measure type- if (!validAggs.includes(targetAgg)) {- targetAgg = (validAggs[0] ?? "count") as z.infer<typeof metricAggregations>;- }-- // Only return if something changed- const result: {- aggregation?: z.infer<typeof metricAggregations>;- chartType?: string;- } = {};- if (targetChart !== chartType) result.chartType = targetChart;- if (targetAgg !== currentAgg) result.aggregation = targetAgg;-- return Object.keys(result).length > 0 ? result : null;-}--/**- * Interface for representing a selected metric combination- * Combines measure and aggregation into a single selectable entity+ * A small read-only context passed DOWN to field subcomponents. It lets a field+ * render meta (descriptions/units) and gate options without any child ever+ * calling `watch` β the controller owns the single `useWatch`.*/-interface SelectedMetric {- /** Unique identifier for this metric combination */- id: string;- /** The measure field name (e.g., "count", "latency") */- measure: string;- /** The aggregation method (e.g., "sum", "avg", "count") */- aggregation: z.infer<typeof metricAggregations>;- /** Display label for the metric */- label: string;-}+type WidgetFieldContext = {+ view: z.infer<typeof views>;+ viewVersion: ViewVersion;+ chartType: DashboardWidgetChartType;+};export function WidgetForm({initialValues,@@ -296,7 +239,7 @@ export function WidgetForm({dimension: string;filters?: FilterState;chartType: DashboardWidgetChartType;- chartConfig?: ChartConfig;+ chartConfig?: WidgetInitialValues["chartConfig"];// Support for complete widget data (editing mode)metrics?: { measure: string; agg: string }[];dimensions?: { field: string }[];@@ -311,183 +254,163 @@ export function WidgetForm({metrics: { measure: string; agg: string }[];filters: any[];chartType: DashboardWidgetChartType;- chartConfig: ChartConfig;+ chartConfig: NonNullable<WidgetInitialValues["chartConfig"]>;minVersion: number;}) => void;widgetId?: string;}) {const { isBetaEnabled } = useV4Beta();-- // State for form fields- const [widgetName, setWidgetName] = useState<string>(initialValues.name);- const [widgetDescription, setWidgetDescription] = useState<string>(- initialValues.description,- );-- // Determine if this is an existing widget (editing mode)- const isExistingWidget = Boolean(widgetId);-- // Disables further auto-updates once the user edits name or description- const [autoLocked, setAutoLocked] = useState<boolean>(isExistingWidget);const importInputRef = useRef<HTMLInputElement>(null);- const [selectedView, setSelectedView] = useState<z.infer<typeof views>>(- initialValues.view,+ // The widget's frozen, view-shape-derived base minVersion. It is a pure+ // function of `initialValues`, so it is mount-stable; the edit page remounts+ // via `key={widgetId}` while the create page does NOT remount on a beta+ // toggle (viewVersion re-derives reactively from isBetaEnabled + view). No+ // widgetMinVersion state, no sync effect.+ const baseMinVersion = deriveWidgetBaseMinVersion(initialValues);++ // The auto-suggestions change on every keystroke; a ref keeps the resolver+ // closure from being rebuilt on each one (the filled name/description do not+ // affect validity β name/description are nullable with no min).+ const suggestionsRef = useRef<{ name: string; description: string }>({+ name: "",+ description: "",+ });++ // Precompute both version schemas/resolvers once. A blank name/description is+ // filled with the live suggestion and the filters are mapped into view space+ // before zod (mirrors MonitorForm).+ const resolversByVersion = useMemo(+ () => ({+ v1: zodResolver(makeWidgetFormSchema("v1") as any),+ v2: zodResolver(makeWidgetFormSchema("v2") as any),+ }),+ [],);+ // The schema version is derived INSIDE the resolver from the (mapped) view+ // being validated β not from a render-written ref β so it is never a render+ // stale after a version-flipping view change. baseMinVersion is mount-stable+ // and isBetaEnabled is read live; both are in the dep list so a beta toggle+ // rebuilds the closure (react-hook-form re-reads control._options each render).+ const resolver = useMemo<Resolver<WidgetFormValues>>(() => {+ return (values, context, options) => {+ const v = values as WidgetFormValues;+ const suggestions = suggestionsRef.current;+ const mapped = {+ ...v,+ name: effectiveWidgetName(v.name, suggestions.name),+ description: effectiveWidgetName(+ v.description,+ suggestions.description,+ ),+ // mapWidgetUiTableFilterToView MUST stay idempotent: the form holds+ // editor-space filters, and both this validation path and toSavePayload+ // map them to view space independently.+ filters: mapWidgetUiTableFilterToView(v.view, v.filters ?? []),+ };+ const version = resolveWidgetViewVersion({+ view: mapped.view,+ baseMinVersion,+ isBetaEnabled,+ });+ return resolversByVersion[version](mapped as any, context, options);+ };+ }, [resolversByVersion, baseMinVersion, isBetaEnabled]);- // Form definitions follow beta toggle, or v2 if widget already requires it.- // Traces view is excluded from beta-v2 because it has no v2-only fields.- const initialWidgetRequiresV2 = requiresV2({+ // The initial view version, derived from initialValues alone (view is known+ // before the form mounts) so the seed can normalize against the right view+ // declaration.+ const initialViewVersion = resolveWidgetViewVersion({view: initialValues.view,- dimensions:- initialValues.dimensions ??- (initialValues.dimension && initialValues.dimension !== "none"- ? [{ field: initialValues.dimension }]- : []),- measures: initialValues.metrics?.map((metric) => ({- measure: metric.measure,- })) ?? [{ measure: initialValues.measure }],- filters: initialValues.filters ?? [],+ baseMinVersion,+ isBetaEnabled,});- const [widgetMinVersion, setWidgetMinVersion] = useState<number>(- initialWidgetRequiresV2 ? 2 : (initialValues.minVersion ?? 1),- );- const viewVersion: ViewVersion =- initialWidgetRequiresV2 ||- widgetMinVersion >= 2 ||- (isBetaEnabled && selectedView !== "traces")- ? "v2"- : "v1";- const availableViewOptions = viewVersion === "v2" ? viewsV2 : views;- // For regular charts: single metric selection- const [selectedMeasure, setSelectedMeasure] = useState<string>(- initialValues.measure,- );- const [selectedAggregation, setSelectedAggregation] = useState<- z.infer<typeof metricAggregations>- >(initialValues.aggregation);-- // For pivot tables: multiple metrics selection- const [selectedMetrics, setSelectedMetrics] = useState<SelectedMetric[]>(- initialValues.chartType === "PIVOT_TABLE" && initialValues.metrics?.length- ? // Initialize from complete metrics data (editing mode)- initialValues.metrics.map((metric) => ({- id: `${metric.agg}_${metric.measure}`,- measure: metric.measure,- aggregation: metric.agg as z.infer<typeof metricAggregations>,- label: `${startCase(metric.agg)} ${startCase(metric.measure)}`,- }))- : // Default to single metric (new widget)- [- {- id: `${initialValues.aggregation}_${initialValues.measure}`,- measure: initialValues.measure,- aggregation: initialValues.aggregation,- label: `${startCase(initialValues.aggregation)} ${startCase(initialValues.measure)}`,- },- ],- );+ const form = useForm<WidgetFormValues>({+ resolver,+ defaultValues: toDefaultValues(initialValues, initialViewVersion),+ mode: "onChange",+ });- const [selectedDimension, setSelectedDimension] = useState<string>(- initialValues.dimension,- );+ // THE single useWatch. Everything below is derived from `values` once.+ const values = useWatch({ control: form.control }) as WidgetFormValues;- const selectedViewRef = useRef(selectedView);- selectedViewRef.current = selectedView;-- // Pivot table dimensions state (for PIVOT_TABLE chart type)- const [pivotDimensions, setPivotDimensions] = useState<string[]>(- initialValues.chartType === "PIVOT_TABLE" &&- initialValues.dimensions?.length- ? // Initialize from complete dimensions data (editing mode)- initialValues.dimensions.map((dim) => dim.field)- : // Default to empty array (new widget)- [],- );+ const selectedView = values.view;+ const chartType = values.chart.type;+ const viewVersion = resolveWidgetViewVersion({+ view: selectedView,+ baseMinVersion,+ isBetaEnabled,+ });+ const suggestions = deriveWidgetSuggestions(values);+ const effectiveSort = deriveEffectiveSort(values);- const [selectedChartType, setSelectedChartType] = useState<string>(- initialValues.chartType,- );- const initialDefaultSort =- initialValues.chartType === "PIVOT_TABLE"- ? sanitizePivotTableDefaultSort(initialValues.chartConfig?.defaultSort, {- dimensions: initialValues.dimensions ?? [],- metrics:- initialValues.metrics ??- (initialValues.measure && initialValues.aggregation- ? [- {- measure: initialValues.measure,- agg: initialValues.aggregation,- },- ]- : []),- })- : undefined;- const [rowLimit, setRowLimit] = useState<number>(- initialValues.chartConfig?.row_limit ?? 100,- );- const [histogramBins, setHistogramBins] = useState<number>(- initialValues.chartConfig?.bins ?? 10,- );+ suggestionsRef.current = suggestions;- // Default sort configuration for pivot tables- const [defaultSortColumn, setDefaultSortColumn] = useState<string>(- initialDefaultSort?.column ?? "none",- );- const [defaultSortOrder, setDefaultSortOrder] = useState<"ASC" | "DESC">(- initialDefaultSort?.order ?? "DESC",+ const availableViewOptions = viewVersion === "v2" ? viewsV2 : views;++ // Valid aggregations for a given measure on the current (view, version).+ const getValidAggregationsForMeasure = (+ measure: string,+ ): z.infer<typeof metricAggregations>[] => {+ const measureType =+ viewDeclarations[viewVersion][selectedView]?.measures?.[measure]?.type;+ return getValidAggregationsForMeasureType(measureType);+ };+ const validAggregationsForMeasure = getValidAggregationsForMeasure(+ values.metrics[0]?.measure ?? "count",);+ const measureSupportsHistogram =+ validAggregationsForMeasure.includes("histogram") &&+ (values.metrics[0]?.measure ?? "count") !== "count";++ const ctx: WidgetFieldContext = {+ view: selectedView,+ viewVersion,+ chartType,+ };- // Filter state. The picker here is a transient PREVIEW control β the widget- // does not own a time range (the host dashboard supplies one at render time),- // so it must not write the user's shared cross-view default.+ // superRefine messages, surfaced inline under the relevant control and next+ // to the disabled Save button (replaces the legacy save-time error toasts).+ const formErrors = form.formState.errors as Record<string, any>;+ const chartTypeError: string | undefined = formErrors.chart?.type?.message;+ const metricsError: string | undefined =+ formErrors.metrics?.message ??+ formErrors.metrics?.[0]?.measure?.message ??+ formErrors.metrics?.[0]?.aggregation?.message;+ const dimensionsError: string | undefined = formErrors.dimensions?.message;++ // Preview time range. The picker here is a transient PREVIEW control β the+ // widget does not own a time range, so it must not write the user's shared+ // cross-view default. Kept as LOCAL state (not RHF).const { timeRange, setTimeRange } = useDashboardDateRange({defaultRelativeAggregation: "last7Days",persistAsDefault: false,});-- // Convert timeRange to absolute date range for compatibility- const dateRange = useMemo(() => {- return toAbsoluteTimeRange(timeRange) ?? undefined;- }, [timeRange]);-- // Convert timeRange to legacy format for DatePickerWithRange compatibility+ const dateRange = useMemo(+ () => toAbsoluteTimeRange(timeRange) ?? undefined,+ [timeRange],+ );const selectedOption = useMemo(() => {- if ("range" in timeRange) {- return timeRange.range;- }+ if ("range" in timeRange) return timeRange.range;return "custom" as const;}, [timeRange]);-const setDateRangeAndOption = (option: DashboardDateRangeOptions,range?: { from: Date; to: Date },) => {if (option === "custom") {- if (range) {- setTimeRange({- from: range.from,- to: range.to,- });- }+ if (range) setTimeRange({ from: range.from, to: range.to });} else {setTimeRange({ range: option });}};- const [userFilterState, setUserFilterState] = useState<FilterState>(- () =>- normalizeStoredWidgetFiltersForEditor(- initialValues.view,- initialValues.filters ?? [],- ).editorFilters,- );+const unsupportedFilters = useMemo(() =>- partitionWidgetUiTableFiltersToView(selectedView, userFilterState)+ partitionWidgetUiTableFiltersToView(selectedView, values.filters).unsupportedFilters,- [selectedView, userFilterState],+ [selectedView, values.filters],);const unsupportedFilterColumns = useMemo(() =>@@ -497,179 +420,18 @@ export function WidgetForm({[unsupportedFilters],);const normalizedUserFilters = useMemo(- () => mapWidgetUiTableFilterToView(selectedView, userFilterState),- [selectedView, userFilterState],- );-- // When beta is toggled on while "traces" is selected (and not editing an- // existing widget), auto-switch to "observations" and reset dependent fields.- // selectedView is read via ref to avoid re-triggering on view changes.- useEffect(() => {- if (- isBetaEnabled &&- selectedViewRef.current === "traces" &&- !isExistingWidget- ) {- setSelectedView("observations");- setSelectedMeasure("count");- setSelectedAggregation("count");- setSelectedDimension("none");- setPivotDimensions([]);- setSelectedMetrics([- {- id: "count_count",- measure: "count",- aggregation: "count" as z.infer<typeof metricAggregations>,- label: "Count Count",- },- ]);- setUserFilterState([]);- }- }, [isBetaEnabled, isExistingWidget]);-- // Static sort state for pivot table preview (non-interactive)- const previewSortState = useMemo(- () =>- selectedChartType === "PIVOT_TABLE" &&- defaultSortColumn &&- defaultSortColumn !== "none"- ? { column: defaultSortColumn, order: defaultSortOrder }- : null,- [selectedChartType, defaultSortColumn, defaultSortOrder],+ () => mapWidgetUiTableFilterToView(selectedView, values.filters),+ [selectedView, values.filters],);- useEffect(() => {- if (selectedChartType !== "PIVOT_TABLE") return;-- // Old widgets can carry persisted default sort keys for metrics or- // dimensions that are no longer part of the pivot query. Clear those stale- // sort columns so preview/save do not send invalid orderBy fields.- const sanitizedDefaultSort = sanitizePivotTableDefaultSort(- defaultSortColumn !== "none"- ? { column: defaultSortColumn, order: defaultSortOrder }- : undefined,- {- dimensions: pivotDimensions- .filter((field) => field && field !== "none")- .map((field) => ({ field })),- metrics: selectedMetrics- .filter((metric) => metric.measure && metric.measure !== "")- .map((metric) => ({- measure: metric.measure,- agg: metric.aggregation,- })),- },- );-- if (defaultSortColumn !== "none" && !sanitizedDefaultSort) {- setDefaultSortColumn("none");- setDefaultSortOrder("DESC");- }- }, [- defaultSortColumn,- defaultSortOrder,- pivotDimensions,- selectedMetrics,- selectedChartType,- setDefaultSortColumn,- setDefaultSortOrder,- ]);-- // Helper function to update pivot table dimensions- const updatePivotDimension = (index: number, value: string) => {- const newDimensions = [...pivotDimensions];- if (value && value !== "none") {- // Set the dimension at the specified index- newDimensions[index] = value;- } else {- // Clear this dimension and all subsequent ones- newDimensions.splice(index);- }- setPivotDimensions(newDimensions);- };-- // Helper function for updating pivot table metrics- const updatePivotMetric = (- index: number,- measure: string,- aggregation?: z.infer<typeof metricAggregations>,- ) => {- const newMetrics = [...selectedMetrics];-- if (measure && measure !== "none") {- let finalAggregation: z.infer<typeof metricAggregations>;-- if (measure === "count") {- finalAggregation = "count";- } else {- // Get available aggregations for this measure at this index- const availableAggregations = getAvailableAggregations(index, measure);-- if (aggregation && availableAggregations.includes(aggregation)) {- // Use provided aggregation if it's available- finalAggregation = aggregation as z.infer<typeof metricAggregations>;- } else {- // Use the first available aggregation as default- finalAggregation =- availableAggregations.length > 0- ? availableAggregations[0]- : ("sum" as z.infer<typeof metricAggregations>);- }- }-- const newMetric: SelectedMetric = {- id: `${finalAggregation}_${measure}`,- measure: measure,- aggregation: finalAggregation as z.infer<typeof metricAggregations>,- label: `${startCase(finalAggregation)} ${startCase(measure)}`,- };-- // Set the metric at the specified index- newMetrics[index] = newMetric;- } else {- // Clear this metric and all subsequent ones- newMetrics.splice(index);- }-- setSelectedMetrics(newMetrics);- };-- // Add a new empty metric slot- const addNewMetricSlot = () => {- if (selectedMetrics.length < MAX_PIVOT_TABLE_METRICS) {- const newMetrics = [...selectedMetrics];- newMetrics.push({- id: `temp_${selectedMetrics.length}`,- measure: "",- aggregation: "sum" as z.infer<typeof metricAggregations>,- label: "",- });- setSelectedMetrics(newMetrics);- }- };-- // Remove a metric slot and roll up subsequent ones- const removeMetricSlot = (index: number) => {- if (index > 0) {- // Can't remove the first metric (it's required)- const newMetrics = [...selectedMetrics];- newMetrics.splice(index, 1); // Remove only the metric at this index- setSelectedMetrics(newMetrics);- }- };-- // v1: Use traces/generations filter options (old normalized tables)+ // v1: traces/generations filter options (old normalized tables)const traceFilterOptions = api.traces.filterOptions.useQuery({projectId,timestampFilter: getDateRangeFilter("timestamp", dateRange),},{- trpc: {- context: {- skipBatch: true,- },- },+ trpc: { context: { skipBatch: true } },refetchOnMount: false,refetchOnWindowFocus: false,refetchOnReconnect: false,@@ -677,7 +439,6 @@ export function WidgetForm({enabled: viewVersion === "v1",},);-const generationsFilterOptions = api.generations.filterOptions.useQuery({projectId,@@ -685,11 +446,7 @@ export function WidgetForm({observationType: "ALL",},{- trpc: {- context: {- skipBatch: true,- },- },+ trpc: { context: { skipBatch: true } },refetchOnMount: false,refetchOnWindowFocus: false,refetchOnReconnect: false,@@ -697,18 +454,13 @@ export function WidgetForm({enabled: viewVersion === "v1",},);-const eventsFilterOptions = api.events.filterOptions.useQuery({projectId,startTimeFilter: getDateRangeFilter("startTime", dateRange),},{- trpc: {- context: {- skipBatch: true,- },- },+ trpc: { context: { skipBatch: true } },refetchOnMount: false,refetchOnWindowFocus: false,refetchOnReconnect: false,@@ -716,8 +468,6 @@ export function WidgetForm({enabled: viewVersion === "v2",},);-- // v1: Use project environment filter options (queries from Postgres)const environmentFilterOptions =api.projects.environmentFilterOptions.useQuery({@@ -725,11 +475,7 @@ export function WidgetForm({fromTimestamp: dateRange?.from,},{- trpc: {- context: {- skipBatch: true,- },- },+ trpc: { context: { skipBatch: true } },refetchOnMount: false,refetchOnWindowFocus: false,refetchOnReconnect: false,@@ -737,11 +483,8 @@ export function WidgetForm({enabled: viewVersion === "v1",},);-const datasets = api.datasets.allDatasetMeta.useQuery(- {- projectId,- },+ { projectId },{ enabled: viewVersion === "v2" },);@@ -776,7 +519,6 @@ export function WidgetForm({viewVersion === "v2"? eventsFilterOptions.data?.calledToolNames || []: generationsFilterOptions.data?.calledToolNames || [];- // Experiment options only available in v2 (from events table)const experimentNameOptions =viewVersion === "v2" ? eventsFilterOptions.data?.experimentName || [] : [];const experimentDatasetIdSet = new Set(@@ -785,27 +527,9 @@ export function WidgetForm({const experimentDatasetIdOptions =datasets.data?.filter((d) => experimentDatasetIdSet.has(d.id))- .map((d) => ({- value: d.id,- displayValue: d.name,- })) ?? [];+ .map((d) => ({ value: d.id, displayValue: d.name })) ?? [];- const filterColumns = getWidgetFilterColumns({- selectedView,- viewVersion,- environmentOptions,- nameOptions,- observationNameOptions,- tagsOptions,- modelOptions,- toolNamesOptions,- calledToolNamesOptions,- observationLevelOptions,- experimentNameOptions,- experimentDatasetOptions: experimentDatasetIdOptions,- observationTypeOptions,- });- const columnsWithCustomSelect = getWidgetColumnsWithCustomSelect({+ const filterColumnsParams = {selectedView,viewVersion,environmentOptions,@@ -819,232 +543,119 @@ export function WidgetForm({experimentNameOptions,experimentDatasetOptions: experimentDatasetIdOptions,observationTypeOptions,- });+ };+ const filterColumns = getWidgetFilterColumns(filterColumnsParams);+ const columnsWithCustomSelect =+ getWidgetColumnsWithCustomSelect(filterColumnsParams);- // Helper to get valid filter column identifiers for a given viewconst getValidFilterColumnIds = (view: z.infer<typeof views>,+ version: ViewVersion,): Set<string> => {const columns = getWidgetFilterColumns({+ ...filterColumnsParams,selectedView: view,- viewVersion,- environmentOptions,- nameOptions,- observationNameOptions,- tagsOptions,- modelOptions,- toolNamesOptions,- calledToolNamesOptions,- observationLevelOptions,- observationTypeOptions,- experimentNameOptions,- experimentDatasetOptions: experimentDatasetIdOptions,+ viewVersion: version,});- // Include both column id and name since filters may use eitherreturn new Set(columns.flatMap((col) => [col.id, col.name]));};- // When chart type does not support breakdown, wipe the breakdown dimension- useEffect(() => {- if (- chartTypes.find((c) => c.value === selectedChartType)- ?.supportsBreakdown === false &&- selectedDimension !== "none"- ) {- setSelectedDimension("none");- }- }, [selectedChartType, selectedDimension]);-- // Reset pivot dimensions when switching away from PIVOT_TABLE- useEffect(() => {- if (selectedChartType !== "PIVOT_TABLE" && pivotDimensions.length > 0) {- setPivotDimensions([]);- }- }, [selectedChartType, pivotDimensions.length]);-- // Reset multiple metrics when switching away from PIVOT_TABLE- useEffect(() => {- if (selectedChartType !== "PIVOT_TABLE" && selectedMetrics.length > 1) {- // Keep only the first metric for non-pivot charts- setSelectedMetrics(selectedMetrics.slice(0, 1));- }- }, [selectedChartType, selectedMetrics]);-- // Resolve valid aggregations for the currently selected measure- const validAggregationsForMeasure = useMemo(() => {- const measureType =- viewDeclarations[viewVersion][selectedView]?.measures?.[selectedMeasure]- ?.type;- return getValidAggregationsForMeasureType(measureType);- }, [viewVersion, selectedView, selectedMeasure]);-- const measureSupportsHistogram =- validAggregationsForMeasure.includes("histogram") &&- selectedMeasure !== "count";-- // Sync aggregation and chart type when selections change- useEffect(() => {- const resolved = resolveAggregationAndChartType({- chartType: selectedChartType,- measure: selectedMeasure,- currentAgg: selectedAggregation,- validAggs: validAggregationsForMeasure,- });- if (!resolved) return;- if (resolved.chartType) setSelectedChartType(resolved.chartType);- if (resolved.aggregation) {- setSelectedAggregation(resolved.aggregation);- }- }, [- selectedMeasure,- selectedAggregation,- selectedChartType,- validAggregationsForMeasure,- ]);-- // Get available metrics for the selected view- const availableMetrics = useMemo(() => {- const viewDeclaration = viewDeclarations[viewVersion][selectedView];-- // For pivot tables, only show measures that still have available aggregations- if (selectedChartType === "PIVOT_TABLE") {- return Object.entries(viewDeclaration.measures)- .filter(([measureKey]) => {- // For count, there's only one aggregation option- if (measureKey === "count") {- return !selectedMetrics.some((m) => m.measure === "count");- }-- // For other measures, check if there are any aggregations left- const selectedAggregationsForMeasure = selectedMetrics- .filter((m) => m.measure === measureKey)- .map((m) => m.aggregation);-- const measureType = viewDeclaration.measures[measureKey]?.type;- const validAggs = getValidAggregationsForMeasureType(measureType);- const availableAggregationsForMeasure = validAggs.filter(- (agg) =>- agg !== "histogram" &&- !selectedAggregationsForMeasure.includes(agg),- );-- return availableAggregationsForMeasure.length > 0;- })- .map(([key]) => ({- value: key,- label: startCase(key),- }))- .sort((a, b) =>- a.label.localeCompare(b.label, "en", { sensitivity: "base" }),- );- }-- // For regular charts, show all metrics- return Object.entries(viewDeclaration.measures)- .map(([key]) => ({- value: key,- label: startCase(key),- }))+ // Available measures for the single (non-pivot) metric picker.+ const singleChartMetrics = useMemo(() => {+ const measures = viewDeclarations[viewVersion][selectedView].measures;+ return Object.entries(measures)+ .map(([key]) => ({ value: key, label: startCase(key) })).sort((a, b) =>a.label.localeCompare(b.label, "en", { sensitivity: "base" }),);- }, [selectedView, selectedChartType, selectedMetrics, viewVersion]);+ }, [selectedView, viewVersion]);- // Get available aggregations for a specific metric index in pivot tables- const getAvailableAggregations = (+ // Available aggregations for a specific pivot metric index (excludes the+ // aggregation/measure pairs already used by other pivot metrics).+ const getAvailablePivotAggregations = (metricIndex: number,measureKey: string,): z.infer<typeof metricAggregations>[] => {const measureType =viewDeclarations[viewVersion][selectedView]?.measures?.[measureKey]?.type;- const validAggs = getValidAggregationsForMeasureType(measureType);- if (selectedChartType === "PIVOT_TABLE" && measureKey) {+ // Pivot metrics never use the histogram aggregation (superRefine invariant+ // 2 rejects it outside a histogram chart), so keep it out of the options.+ const validAggs = getValidAggregationsForMeasureType(measureType).filter(+ (agg) => agg !== "histogram",+ );+ if (measureKey) {return validAggs.filter((agg) =>- !selectedMetrics.some(+ !values.metrics.some((m, idx) =>idx !== metricIndex &&m.measure === measureKey &&m.aggregation === agg,),- ) as z.infer<typeof metricAggregations>[];+ );}- return validAggs as z.infer<typeof metricAggregations>[];+ return validAggs;};- // Get available metrics for a specific metric index in pivot tables- const getAvailableMetrics = (metricIndex: number) => {- if (selectedChartType === "PIVOT_TABLE") {- const viewDeclaration = viewDeclarations[viewVersion][selectedView];- return Object.entries(viewDeclaration.measures)- .filter(([measureKey]) => {- // For count, there's only one aggregation option- if (measureKey === "count") {- return !selectedMetrics.some(- (m, idx) => idx !== metricIndex && m.measure === "count",- );- }-- // For other measures, check if there are any aggregations left- const selectedAggregationsForMeasure = selectedMetrics- .filter((m, idx) => idx !== metricIndex && m.measure === measureKey)- .map((m) => m.aggregation);-- const measureType = viewDeclaration.measures[measureKey]?.type;- const validAggs = getValidAggregationsForMeasureType(measureType);- const availableAggregationsForMeasure = validAggs.filter(- (agg) =>- agg !== "histogram" &&- !selectedAggregationsForMeasure.includes(agg),+ // Available measures for a specific pivot metric index.+ const getAvailablePivotMetrics = (metricIndex: number) => {+ const viewDeclaration = viewDeclarations[viewVersion][selectedView];+ return Object.entries(viewDeclaration.measures)+ .filter(([measureKey]) => {+ if (measureKey === "count") {+ return !values.metrics.some(+ (m, idx) => idx !== metricIndex && m.measure === "count",);-- return availableAggregationsForMeasure.length > 0;- })- .map(([key]) => ({- value: key,- label: startCase(key),- }))- .sort((a, b) =>- a.label.localeCompare(b.label, "en", { sensitivity: "base" }),+ }+ const selectedAggregationsForMeasure = values.metrics+ .filter((m, idx) => idx !== metricIndex && m.measure === measureKey)+ .map((m) => m.aggregation);+ const measureType = viewDeclaration.measures[measureKey]?.type;+ const validAggs = getValidAggregationsForMeasureType(measureType);+ const availableAggregationsForMeasure = validAggs.filter(+ (agg) =>+ agg !== "histogram" &&+ !selectedAggregationsForMeasure.includes(agg),);- }- return availableMetrics;+ return availableAggregationsForMeasure.length > 0;+ })+ .map(([key]) => ({ value: key, label: startCase(key) }))+ .sort((a, b) =>+ a.label.localeCompare(b.label, "en", { sensitivity: "base" }),+ );};- // Get available dimensions for the selected viewconst availableDimensions = useMemo(() => {const viewDeclaration = viewDeclarations[viewVersion][selectedView];return Object.entries(viewDeclaration.dimensions).filter(([_, dim]) => !dim.uiHidden)- .map(([key]) => ({- value: key,- label: startCase(key),- }))+ .map(([key]) => ({ value: key, label: startCase(key) })).sort((a, b) =>a.label.localeCompare(b.label, "en", { sensitivity: "base" }),);}, [selectedView, viewVersion]);- // Create a dynamic query based on the selected view+ const previewSortState = effectiveSort ?? null;+ const pivotDimensionFields = values.dimensions.map((d) => d.field);++ // Preview query. Depends ONLY on the fields that affect it β not+ // name/description.const query = useMemo<QueryType>(() => {- // Calculate fromTimestamp and toTimestamp from dateRangeconst fromTimestamp = dateRange? dateRange.from- : new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000); // Default to last 7 days+ : new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000);const toTimestamp = dateRange ? dateRange.to : new Date();- // Determine dimensions based on chart typeconst queryDimensions =- selectedChartType === "PIVOT_TABLE"- ? pivotDimensions.map((field) => ({ field }))- : selectedDimension !== "none"- ? [{ field: selectedDimension }]+ chartType === "PIVOT_TABLE"+ ? values.dimensions.map((d) => ({ field: d.field }))+ : values.dimensions.length > 0+ ? [{ field: values.dimensions[0].field }]: [];- // Determine metrics based on chart typeconst queryMetrics =- selectedChartType === "PIVOT_TABLE"- ? selectedMetrics+ chartType === "PIVOT_TABLE"+ ? values.metrics.filter((metric) => metric.measure && metric.measure !== "").map((metric) => ({measure: metric.measure,@@ -1052,40 +663,35 @@ export function WidgetForm({})): [{- measure: selectedMeasure,- aggregation: selectedAggregation,+ measure: values.metrics[0]?.measure ?? "count",+ aggregation: values.metrics[0]?.aggregation ?? "count",},];- // For v2 non-timeseries breakdown charts, auto-sort desc by metric for top-Nconst needsTopN = isV2BreakdownChart({version: viewVersion,- hasDimension: selectedDimension !== "none",- isTimeSeries: isTimeSeriesChart(- selectedChartType as DashboardWidgetChartType,- ),- chartType: selectedChartType,+ hasDimension: queryDimensions.length > 0,+ isTimeSeries: isTimeSeriesChart(chartType),+ chartType,});const orderBy = buildWidgetOrderBy({- chartType: selectedChartType,+ chartType,sortState: previewSortState,needsTopN,firstMetric: {- aggregation: selectedAggregation,- measure: selectedMeasure,+ aggregation: values.metrics[0]?.aggregation ?? "count",+ measure: values.metrics[0]?.measure ?? "count",},});- // Only query-engine fields (type, bins, row_limit) β rendering fields- // (dimensions, defaultSort) go via handleSaveWidget / Chart componentlet chartConfig: QueryType["chartConfig"];- if (selectedChartType === "HISTOGRAM") {- chartConfig = { type: selectedChartType, bins: histogramBins };- } else if (selectedChartType === "PIVOT_TABLE" || needsTopN) {- chartConfig = { type: selectedChartType, row_limit: rowLimit };+ if (chartType === "HISTOGRAM") {+ chartConfig = { type: chartType, bins: values.chart.bins };+ } else if (chartType === "PIVOT_TABLE" || needsTopN) {+ chartConfig = { type: chartType, row_limit: values.chart.rowLimit };} else {- chartConfig = { type: selectedChartType };+ chartConfig = { type: chartType };}return {@@ -1093,9 +699,7 @@ export function WidgetForm({dimensions: queryDimensions,metrics: queryMetrics,filters: [...normalizedUserFilters],- timeDimension: isTimeSeriesChart(- selectedChartType as DashboardWidgetChartType,- )+ timeDimension: isTimeSeriesChart(chartType)? { granularity: "auto" }: null,fromTimestamp: fromTimestamp.toISOString(),@@ -1105,15 +709,12 @@ export function WidgetForm({};}, [selectedView,- selectedDimension,- selectedAggregation,- selectedMeasure,- selectedMetrics,+ values.metrics,+ values.dimensions,+ chartType,+ values.chart.bins,+ values.chart.rowLimit,dateRange,- selectedChartType,- histogramBins,- pivotDimensions,- rowLimit,previewSortState,viewVersion,normalizedUserFilters,@@ -1128,7 +729,6 @@ export function WidgetForm({"Remove them or switch to a compatible view before saving this widget.",};}-return validateQuery(query, viewVersion);}, [query, unsupportedFilterColumns, unsupportedFilters.length, viewVersion]);@@ -1139,14 +739,8 @@ export function WidgetForm({version: viewVersion,},{- trpc: {- context: {- skipBatch: true,- },- },- meta: {- silentHttpCodes: [422],- },+ trpc: { context: { skipBatch: true } },+ meta: { silentHttpCodes: [422] },enabled: queryValidation.valid,},);@@ -1161,39 +755,30 @@ export function WidgetForm({useBackendProgress: false,});- // Transform the query results to a consistent format for charts+ const selectedMeasure = values.metrics[0]?.measure ?? "count";+ const selectedAggregation = values.metrics[0]?.aggregation ?? "count";+ const selectedDimension = values.dimensions[0]?.field ?? "none";+const transformedData: DataPoint[] = useMemo(() =>queryResult.data?.map((item: any) => {- if (selectedChartType === "PIVOT_TABLE") {- // For pivot tables, preserve all raw data fields- // The PivotTable component will extract the appropriate metric fields+ if (chartType === "PIVOT_TABLE") {return {dimension:- pivotDimensions.length > 0 ? pivotDimensions[0] : "dimension", // Fallback for compatibility- metric: 0, // Placeholder - not used for pivot tables+ values.dimensions.length > 0+ ? values.dimensions[0].field+ : "dimension",+ metric: 0,time_dimension: item["time_dimension"],- // Include all original query fields for pivot table processing...item,};}- // Regular chart processingconst metricField = `${selectedAggregation}_${selectedMeasure}`;const metric = item[metricField];const dimensionField = selectedDimension;const dimensionValue = item[dimensionField];- const isTimeSeries = isTimeSeriesChart(- selectedChartType as DashboardWidgetChartType,- );+ const isTimeSeries = isTimeSeriesChart(chartType);- // A gap-filled empty bucket arrives as a row with no dimension and the- // metric column's type default: NULL for nullable aggregations- // (avg/percentiles), 0 for non-nullable ones (count/uniq/sum). Keep it- // as a pure bucket marker (holds the spot on the time axis) instead of- // inventing an "n/a" series. The 0 form is only treated as filler for- // additive metrics, where the marker is lossless (prepareDenseSeries- // re-derives the honest 0 for any series that exists); a real- // dimension-less avg/percentile 0 stays a visible data point. (LFE-10694)const isFillerMetricValue =metric == null ||(getWidgetMissingBucketValue(selectedAggregation) === "zero" &&@@ -1216,7 +801,6 @@ export function WidgetForm({dimensionValue !== undefined && dimensionField !== "none"? (() => {const val = dimensionValue;- // Empty first: "" is a string, so the order matters. (LFE-10694)if (val === null || val === undefined || val === "")return "n/a";if (typeof val === "string") return val;@@ -1226,9 +810,7 @@ export function WidgetForm({: formatMetricName(metricField),metric: Array.isArray(metric)? metric- : // On a time series a missing value stays null β the chart renders- // it by the metric's missing-bucket semantics instead of a fake 0.- isTimeSeries && metric == null+ : isTimeSeries && metric == null? null: Number(metric || 0),time_dimension: item["time_dimension"],@@ -1239,20 +821,125 @@ export function WidgetForm({selectedAggregation,selectedDimension,selectedMeasure,- selectedChartType,- pivotDimensions,+ chartType,+ values.dimensions,],);+ const chartPresentation = useMemo(() => {+ if (chartType === "PIVOT_TABLE") return undefined;+ return getWidgetMetricPresentation({+ metric: { measure: selectedMeasure, agg: selectedAggregation },+ view: selectedView,+ version: viewVersion,+ });+ }, [+ selectedAggregation,+ chartType,+ selectedMeasure,+ selectedView,+ viewVersion,+ ]);++ // ---------------------------------------------------------------------------+ // Cross-slice cascades β the ONLY writers of sibling fields. Each builds the+ // candidate next state, HEALS it through the shared normalizeWidgetFormValues+ // (resolve aggregation/chart type + drop unsupported dimensions), and commits+ // the changed slices. This is the same healing the legacy resolve/breakdown+ // effects did, run in the initiating event handler β so no view change,+ // chart-type change, or measure change can leave the form invalid, and there+ // is no effect.+ // ---------------------------------------------------------------------------++ // Applies a healed candidate to the changed slices; the final write validates.+ const commitHealed = (+ candidate: WidgetFormValues,+ opts: { view?: boolean; filters?: boolean } = {},+ ) => {+ form.setValue("metrics", candidate.metrics);+ form.setValue("dimensions", candidate.dimensions);+ if (opts.filters) form.setValue("filters", candidate.filters);+ if (opts.view) form.setValue("view", candidate.view);+ form.setValue("chart.type", candidate.chart.type, { shouldValidate: true });+ };++ // View change (ports resetChartFieldsForView + setSelectedView + the mount+ // resolve/breakdown-wipe healing so the post-view-change state is valid).+ const onViewChange = (newView: z.infer<typeof views>) => {+ if (newView === selectedView) return;+ const newViewVersion = resolveWidgetViewVersion({+ view: newView,+ baseMinVersion,+ isBetaEnabled,+ });+ const newViewDeclaration = viewDeclarations[newViewVersion][newView];++ let metrics: WidgetFormValues["metrics"];+ let dimensions: WidgetFormValues["dimensions"];+ if (chartType === "PIVOT_TABLE") {+ const validMetrics = values.metrics.filter(+ (metric) => metric.measure in newViewDeclaration.measures,+ );+ metrics =+ validMetrics.length > 0+ ? validMetrics+ : [{ measure: "count", aggregation: "count" }];+ dimensions = values.dimensions.filter(+ (dimension) => dimension.field in newViewDeclaration.dimensions,+ );+ } else {+ metrics = [{ measure: "count", aggregation: "count" }];+ dimensions = [];+ }++ const validColumns = getValidFilterColumnIds(newView, newViewVersion);+ const filters = values.filters.filter((filter) =>+ validColumns.has(filter.column),+ );++ const candidate = normalizeWidgetFormValues(+ { ...values, view: newView, metrics, dimensions, filters },+ newViewVersion,+ );+ commitHealed(candidate, { view: true, filters: true });+ };++ // Chart-type change (ports breakdown-wipe / pivot-dims-reset / trim-metrics+ // PLUS the histogram resolution β the histogram silent-revert fix). Crossing+ // the pivot boundary resets dimensions so a breakdown dim and pivot row dims+ // never cross-contaminate (see applyChartTypeChange).+ const onChartTypeChange = (newType: DashboardWidgetChartType) => {+ commitHealed(applyChartTypeChange(values, newType, viewVersion));+ };++ // Single (non-pivot) measure change β heals the aggregation + chart type in+ // the same action (the histogram fix, in the initiating event handler).+ const onMeasureChange = (newMeasure: string) => {+ const nextMetrics = values.metrics.map((m, i) =>+ i === 0 ? { ...m, measure: newMeasure } : m,+ );+ const candidate = normalizeWidgetFormValues(+ { ...values, metrics: nextMetrics },+ viewVersion,+ );+ commitHealed(candidate);+ };++ const applyPreset = (+ preset: (typeof WIDGET_FILTER_PRESETS)[keyof typeof WIDGET_FILTER_PRESETS],+ ) => {+ if (preset.view !== selectedView) {+ onViewChange(preset.view);+ }+ form.setValue("filters", [...preset.filters], { shouldValidate: true });+ };+const handleImportWidget = async (event: React.ChangeEvent<HTMLInputElement>,) => {const file = event.target.files?.[0];event.target.value = "";-- if (!file) {- return;- }+ if (!file) return;const showMalformedImportToast = () =>showErrorToast(@@ -1296,22 +983,61 @@ export function WidgetForm({isBetaEnabled,});- setAutoLocked(true);- setWidgetMinVersion(result.snapshot.widgetMinVersion);- setWidgetName(result.snapshot.widgetName);- setWidgetDescription(result.snapshot.widgetDescription);- setSelectedView(result.snapshot.selectedView);- setSelectedChartType(result.snapshot.selectedChartType);- setSelectedMeasure(result.snapshot.selectedMeasure);- setSelectedAggregation(result.snapshot.selectedAggregation);- setSelectedMetrics(result.snapshot.selectedMetrics);- setSelectedDimension(result.snapshot.selectedDimension);- setPivotDimensions(result.snapshot.pivotDimensions);- setUserFilterState(result.snapshot.userFilterState);- setRowLimit(result.snapshot.rowLimit);- setHistogramBins(result.snapshot.histogramBins);- setDefaultSortColumn(result.snapshot.defaultSortColumn);- setDefaultSortOrder(result.snapshot.defaultSortOrder);+ const snapshot = result.snapshot;+ const importIsPivot = snapshot.selectedChartType === "PIVOT_TABLE";+ // The preview version for the imported widget, re-derived from the+ // snapshot's own minVersion (not the mount's) so a v2-requiring import+ // normalizes against the right view declaration.+ const importViewVersion = resolveWidgetViewVersion({+ view: snapshot.selectedView,+ baseMinVersion: snapshot.widgetMinVersion,+ isBetaEnabled,+ });+ // Explicit user-event reset (allowed β not an effect). The imported name+ // is a non-empty override, so it sticks and does not auto-update. The+ // snapshot's filters are already in editor space, so they are seeded+ // directly (no re-normalization); the chart/aggregation/dimension shape+ // is healed via normalizeWidgetFormValues so a malformed import mounts+ // valid β the same healing the legacy import path's mount effects did.+ form.reset(+ normalizeWidgetFormValues(+ {+ name: snapshot.widgetName || null,+ description: snapshot.widgetDescription || null,+ view: snapshot.selectedView,+ filters: snapshot.userFilterState,+ metrics: importIsPivot+ ? snapshot.selectedMetrics.map((m) => ({+ measure: m.measure,+ aggregation: m.aggregation,+ }))+ : [+ {+ measure: snapshot.selectedMeasure,+ aggregation: snapshot.selectedAggregation,+ },+ ],+ dimensions: importIsPivot+ ? snapshot.pivotDimensions.map((field) => ({ field }))+ : snapshot.selectedDimension !== "none"+ ? [{ field: snapshot.selectedDimension }]+ : [],+ chart: {+ type: snapshot.selectedChartType,+ bins: snapshot.histogramBins,+ rowLimit: snapshot.rowLimit,+ sort:+ snapshot.defaultSortColumn !== "none"+ ? {+ column: snapshot.defaultSortColumn,+ order: snapshot.defaultSortOrder,+ }+ : null,+ },+ },+ importViewVersion,+ ),+ );showSuccessToast({title: "Widget uploaded successfully",@@ -1330,231 +1056,39 @@ export function WidgetForm({}};- const chartPresentation = useMemo(() => {- if (selectedChartType === "PIVOT_TABLE") {- return undefined;+ const onSubmit = form.handleSubmit((submitted) => {+ if (!queryValidation.valid) {+ showErrorToast("Invalid query", queryValidation.reason);+ return;}+ const s = deriveWidgetSuggestions(submitted);+ onSave(+ toSavePayload(submitted, {+ suggestedName: s.name,+ suggestedDescription: s.description,+ effectiveSort: deriveEffectiveSort(submitted),+ }) as Parameters<typeof onSave>[0],+ );+ });- return getWidgetMetricPresentation({- metric: { measure: selectedMeasure, agg: selectedAggregation },- view: selectedView,- version: viewVersion,- });- }, [- selectedAggregation,- selectedChartType,- selectedMeasure,- selectedView,- viewVersion,- ]);-- // Resets chart fields and pivot table state when switching views- const resetChartFieldsForView = (newView: z.infer<typeof views>) => {- const newViewDeclaration = viewDeclarations[viewVersion][newView];-- // Reset regular chart fields- setSelectedMeasure("count");- setSelectedAggregation("count");- setSelectedDimension("none");-- // Handle pivot table cleanup- if (selectedChartType === "PIVOT_TABLE") {- const validMetrics = selectedMetrics.filter(- (metric) => metric.measure in newViewDeclaration.measures,- );- if (validMetrics.length === 0) {- validMetrics.push({- id: "count_count",- measure: "count",- aggregation: "count" as z.infer<typeof metricAggregations>,- label: "Count Count",- });- }- setSelectedMetrics(validMetrics);-- const validDimensions = pivotDimensions.filter(- (dimension) => dimension in newViewDeclaration.dimensions,- );- setPivotDimensions(validDimensions);- }-- // Remove filters that are not valid for the new view- const validColumns = getValidFilterColumnIds(newView);- setUserFilterState((prev) =>- prev.filter((filter) => validColumns.has(filter.column)),- );- };-- const handleSaveWidget = () => {- if (!queryValidation.valid) {- showErrorToast("Invalid query", queryValidation.reason);- return;- }-- if (!widgetName.trim()) {- showErrorToast("Error", "Widget name is required");- return;- }-- // Validate pivot table requirements- const validMetrics = selectedMetrics.filter(- (m) => m.measure && m.measure !== "",- );- if (selectedChartType === "PIVOT_TABLE" && validMetrics.length === 0) {- showErrorToast(- "Error",- "At least one metric is required for pivot tables",- );- return;- }-- const saveDimensions =- selectedChartType === "PIVOT_TABLE"- ? pivotDimensions.map((field) => ({ field }))- : selectedDimension !== "none"- ? [{ field: selectedDimension }]- : [];- const saveMetrics =- selectedChartType === "PIVOT_TABLE"- ? validMetrics.map((metric) => ({- measure: metric.measure,- agg: metric.aggregation,- }))- : [- {- measure: selectedMeasure,- agg: selectedAggregation,- },- ];-- onSave({- name: widgetName,- description: widgetDescription,- view: selectedView,- dimensions: saveDimensions,- metrics: saveMetrics,- filters: normalizedUserFilters,- chartType: selectedChartType as DashboardWidgetChartType,- chartConfig: isTimeSeriesChart(- selectedChartType as DashboardWidgetChartType,- )- ? { type: selectedChartType as DashboardWidgetChartType }- : selectedChartType === "HISTOGRAM"- ? {- type: selectedChartType as DashboardWidgetChartType,- bins: histogramBins,- }- : selectedChartType === "PIVOT_TABLE"- ? {- type: selectedChartType as DashboardWidgetChartType,- row_limit: rowLimit,- defaultSort:- defaultSortColumn && defaultSortColumn !== "none"- ? {- column: defaultSortColumn,- order: defaultSortOrder,- }- : undefined,- }- : {- type: selectedChartType as DashboardWidgetChartType,- row_limit: rowLimit,- },- minVersion: requiresV2({- view: selectedView,- dimensions: saveDimensions,- measures: saveMetrics.map((m) => ({ measure: m.measure })),- filters: normalizedUserFilters,- })- ? 2- : 1,- });- };-- // Update widget name when selection changes, unless locked- useEffect(() => {- if (autoLocked) return;-- // For pivot tables, combine all dimensions, otherwise use regular dimension- const dimensionForNaming =- selectedChartType === "PIVOT_TABLE" && pivotDimensions.length > 0- ? pivotDimensions.map(startCase).join(" and ")- : selectedDimension;-- // For pivot tables, extract actual metric names for the new formatting- const isPivotTable = selectedChartType === "PIVOT_TABLE";-- const validMetricsForNaming = selectedMetrics.filter(- (m) => m.measure && m.measure !== "",- );- const metricNames =- isPivotTable && validMetricsForNaming.length > 0- ? validMetricsForNaming.map((m) => m.id) // Use the ID which is "${aggregation}_${measure}"- : undefined;-- const suggested = buildWidgetName({- aggregation: isPivotTable ? "count" : selectedAggregation,- measure: isPivotTable ? "count" : selectedMeasure,- dimension: dimensionForNaming,- view: selectedView,- metrics: metricNames,- isMultiMetric: isPivotTable && validMetricsForNaming.length > 0,- });-- setWidgetName(suggested);- }, [- autoLocked,- selectedAggregation,- selectedMeasure,- selectedMetrics,- selectedDimension,- selectedView,- selectedChartType,- pivotDimensions,- ]);-- // Update widget description when selection or filters change, unless locked- useEffect(() => {- if (autoLocked) return;-- // For pivot tables, combine all dimensions, otherwise use regular dimension- const dimensionForDescription =- selectedChartType === "PIVOT_TABLE" && pivotDimensions.length > 0- ? pivotDimensions.map(startCase).join(" and ")- : selectedDimension;+ const displayName = effectiveWidgetName(values.name, suggestions.name);+ const displayDescription = effectiveWidgetName(+ values.description,+ suggestions.description,+ );- // For pivot tables, extract actual metric names for the new formatting- const isPivotTable = selectedChartType === "PIVOT_TABLE";- const validMetricsForDescription = selectedMetrics.filter(- (m) => m.measure && m.measure !== "",- );- const metricNames =- isPivotTable && validMetricsForDescription.length > 0- ? validMetricsForDescription.map((m) => m.id) // Use the ID which is "${aggregation}_${measure}"- : undefined;-- const suggested = buildWidgetDescription({- aggregation: isPivotTable ? "count" : selectedAggregation,- measure: isPivotTable ? "count" : selectedMeasure,- dimension: dimensionForDescription,- view: selectedView,- filters: userFilterState,- metrics: metricNames,- isMultiMetric: isPivotTable && validMetricsForDescription.length > 0,- });+ const metricsForSort = values.metrics+ .filter((metric) => metric.measure && metric.measure !== "")+ .map((metric) => ({ id: `${metric.aggregation}_${metric.measure}` }));- setWidgetDescription(suggested);- }, [- autoLocked,- selectedAggregation,- selectedMeasure,- selectedMetrics,- selectedDimension,- selectedView,- userFilterState,- selectedChartType,- pivotDimensions,- ]);+ // Save is gated on schema validity + query validity; surface WHY it is+ // disabled instead of a silent greyed-out button (replaces the legacy toasts).+ // deriveSaveReason falls back to the FIRST message anywhere in the error tree+ // so even a path without an inline marker still explains the disabled button.+ const saveDisabled = !form.formState.isValid || !queryValidation.valid;+ const saveDisabledReason = !queryValidation.valid+ ? queryValidation.reason+ : deriveSaveReason(formErrors);return (<div className="flex h-full gap-4">@@ -1624,13 +1158,7 @@ export function WidgetForm({<ButtonclassName="w-full justify-start"variant="ghost"- onClick={() => {- if (preset.view !== selectedView) {- resetChartFieldsForView(preset.view);- setSelectedView(preset.view);- }- setUserFilterState([...preset.filters]);- }}+ onClick={() => applyPreset(preset)}><preset.icon className="mr-2 h-4 w-4" />{preset.label}@@ -1643,451 +1171,78 @@ export function WidgetForm({)}</div>- {/* View Selection */}- <div className="space-y-2">- <Label htmlFor="view-select">View</Label>- <Select- value={selectedView}- onValueChange={(value) => {- const newView = value as z.infer<typeof views>;- if (newView !== selectedView) {- resetChartFieldsForView(newView);- }- setSelectedView(newView);- }}- >- <SelectTrigger id="view-select">- <SelectValue placeholder="Select a view" />- </SelectTrigger>- <SelectContent>- {availableViewOptions.options.map((view) => (- <WidgetPropertySelectItem- key={view}- value={view}- label={startCase(view)}- description={- viewDeclarations[viewVersion][view].description- }- />- ))}- </SelectContent>- </Select>- </div>+ <ViewSelect+ control={form.control}+ ctx={ctx}+ availableViewOptions={availableViewOptions}+ onViewChange={onViewChange}+ />{/* Metrics Selection */}<div className="space-y-2"><Label htmlFor="metrics-select">- {selectedChartType === "PIVOT_TABLE" ? "Metrics" : "Metric"}+ {chartType === "PIVOT_TABLE" ? "Metrics" : "Metric"}</Label>-- {/* For pivot tables: multiple metrics selection */}- {selectedChartType === "PIVOT_TABLE" ? (- <div className="space-y-3">- {/* Metric selection dropdowns */}- {Array.from(- { length: Math.max(1, selectedMetrics.length) },- (_, index) => {- const isEnabled =- index === 0 ||- (selectedMetrics[index - 1] &&- selectedMetrics[index - 1].measure);- const currentMetric = selectedMetrics[index];- const currentMeasure = currentMetric?.measure || "";- const currentAggregation =- currentMetric?.aggregation || "sum";-- const metricsForIndex = getAvailableMetrics(index);- const aggregationsForIndex = getAvailableAggregations(- index,- currentMeasure,- );-- const canEdit = metricsForIndex.length > 0;-- return (- <div key={index} className="space-y-2">- <div className="flex items-center justify-between">- <Label htmlFor={`pivot-metric-${index}`}>- Metric {index + 1}{" "}- {index === 0 ? "(Required)" : "(Optional)"}- </Label>- {index > 0 && (- <Button- type="button"- variant="ghost"- size="sm"- onClick={() => removeMetricSlot(index)}- className="text-muted-foreground hover:text-destructive h-6 w-6 p-0"- >- <X className="h-4 w-4" />- </Button>- )}- </div>- <div className="flex items-center gap-2">- <div className="flex-1">- <Select- value={currentMeasure}- onValueChange={(value) =>- updatePivotMetric(- index,- value,- // Don't pass current aggregation when measure changes- // Let the function determine the best default- undefined,- )- }- disabled={!isEnabled || !canEdit}- >- <SelectTrigger id={`pivot-metric-${index}`}>- <SelectValue- placeholder={- !isEnabled- ? "Select previous metric first"- : !canEdit- ? "No more measures available"- : "Select measure"- }- />- </SelectTrigger>- <SelectContent>- {metricsForIndex.map((metric) => {- const meta =- viewDeclarations[viewVersion][- selectedView- ]?.measures?.[metric.value];- return (- <WidgetPropertySelectItem- key={metric.value}- value={metric.value}- label={metric.label}- description={meta?.description}- unit={meta?.unit}- type={meta?.type}- />- );- })}- </SelectContent>- </Select>- </div>-- {currentMeasure && currentMeasure !== "count" && (- <div className="flex-1">- <Select- value={currentAggregation}- onValueChange={(value) =>- updatePivotMetric(- index,- currentMeasure,- value as z.infer<- typeof metricAggregations- >,- )- }- >- <SelectTrigger>- <SelectValue placeholder="Select aggregation" />- </SelectTrigger>- <SelectContent>- {aggregationsForIndex.map(- (aggregation) => (- <SelectItem- key={aggregation}- value={aggregation}- >- {startCase(aggregation)}- </SelectItem>- ),- )}- </SelectContent>- </Select>- </div>- )}- </div>- </div>- );- },- )}-- {/* Add new metric button */}- {selectedMetrics.length < MAX_PIVOT_TABLE_METRICS &&- getAvailableMetrics(selectedMetrics.length).length >- 0 && (- <Button- type="button"- variant="outline"- size="sm"- onClick={addNewMetricSlot}- className="w-full"- >- <Plus className="mr-1 h-3 w-3" />- Add Metric {selectedMetrics.length + 1}- </Button>- )}- </div>+ {chartType === "PIVOT_TABLE" ? (+ <PivotMetricsField+ control={form.control}+ ctx={ctx}+ error={metricsError}+ getAvailablePivotMetrics={getAvailablePivotMetrics}+ getAvailablePivotAggregations={+ getAvailablePivotAggregations+ }+ />) : (- /* For regular charts: single metric selection */- <div className="space-y-2">- <Select- value={selectedMeasure}- onValueChange={(value) => setSelectedMeasure(value)}- >- <SelectTrigger id="metrics-select">- <SelectValue placeholder="Select metrics" />- </SelectTrigger>- <SelectContent>- {availableMetrics.map((metric) => {- const meta =- viewDeclarations[viewVersion][selectedView]- ?.measures?.[metric.value];- return (- <WidgetPropertySelectItem- key={metric.value}- value={metric.value}- label={metric.label}- description={meta?.description}- unit={meta?.unit}- type={meta?.type}- />- );- })}- </SelectContent>- </Select>- {selectedMeasure !== "count" && (- <div className="space-y-1">- <Select- value={selectedAggregation}- disabled={selectedChartType === "HISTOGRAM"} // Disable when histogram chart type is selected- onValueChange={(value) =>- setSelectedAggregation(- value as z.infer<typeof metricAggregations>,- )- }- >- <SelectTrigger id="aggregation-select">- <SelectValue placeholder="Select Aggregation" />- </SelectTrigger>- <SelectContent>- {validAggregationsForMeasure.map((aggregation) => (- <SelectItem key={aggregation} value={aggregation}>- {startCase(aggregation)}- </SelectItem>- ))}- </SelectContent>- </Select>- {selectedChartType === "HISTOGRAM" && (- <p className="text-muted-foreground text-xs">- Aggregation is automatically set to- "histogram" for histogram charts- </p>- )}- </div>- )}- </div>+ <SingleMetricField+ control={form.control}+ ctx={ctx}+ error={metricsError}+ measure={selectedMeasure}+ onMeasureChange={onMeasureChange}+ availableMetrics={singleChartMetrics}+ validAggregationsForMeasure={validAggregationsForMeasure}+ />)}</div>- {/* Filters Section */}- <div className="space-y-2">- <Label>Filters</Label>- <div className="space-y-2">- {unsupportedFilters.length > 0 && (- <Alert- variant="default"- className="border-yellow-500/50 bg-yellow-50 dark:bg-yellow-950/20"- >- <AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-500" />- <AlertTitle className="text-yellow-800 dark:text-yellow-400">- Unsupported legacy filters- </AlertTitle>- <AlertDescription className="text-yellow-700 dark:text-yellow-500">- {`This widget still contains filter columns that are not supported for ${startCase(selectedView)}: ${unsupportedFilterColumns}. Remove them or switch to a compatible view before saving.`}- </AlertDescription>- </Alert>- )}- <InlineFilterBuilder- columns={filterColumns}- filterState={userFilterState}- onChange={setUserFilterState}- columnsWithCustomSelect={columnsWithCustomSelect}- />- </div>- </div>+ <FiltersField+ control={form.control}+ filterColumns={filterColumns}+ columnsWithCustomSelect={columnsWithCustomSelect}+ unsupportedFilters={unsupportedFilters}+ unsupportedFilterColumns={unsupportedFilterColumns}+ selectedView={selectedView}+ />{/* Dimension Selection - Regular charts (Breakdown) */}- {chartTypes.find((c) => c.value === selectedChartType)- ?.supportsBreakdown &&- selectedChartType !== "PIVOT_TABLE" && (- <div className="space-y-2">- <Label htmlFor="dimension-select">- Breakdown Dimension (Optional)- </Label>- <Select- value={selectedDimension}- onValueChange={setSelectedDimension}- >- <SelectTrigger id="dimension-select">- <SelectValue placeholder="Select a dimension" />- </SelectTrigger>- <SelectContent>- <SelectItem value="none">None</SelectItem>- {availableDimensions.map((dimension) => {- const meta =- viewDeclarations[viewVersion][selectedView]- ?.dimensions?.[dimension.value];- return (- <WidgetPropertySelectItem- key={dimension.value}- value={dimension.value}- label={dimension.label}- description={meta?.description}- unit={meta?.unit}- type={meta?.type}- />- );- })}- </SelectContent>- </Select>- </div>+ {widgetChartTypeSupportsBreakdown(chartType) &&+ chartType !== "PIVOT_TABLE" && (+ <BreakdownSelect+ control={form.control}+ ctx={ctx}+ error={dimensionsError}+ availableDimensions={availableDimensions}+ />)}{/* Pivot Table Dimension Selection */}- {selectedChartType === "PIVOT_TABLE" && (- <div className="space-y-4">- <div>- <h4 className="mb-2 text-sm font-bold">Row Dimensions</h4>- <p className="text-muted-foreground mb-3 text-xs">- Configure up to {MAX_PIVOT_TABLE_DIMENSIONS} dimensions- for pivot table rows. Each dimension creates groupings- with subtotals.- </p>- </div>-- {Array.from(- { length: MAX_PIVOT_TABLE_DIMENSIONS },- (_, index) => {- const isEnabled =- index === 0 || pivotDimensions[index - 1]; // Enable if first or previous is selected- const selectedDimensions = pivotDimensions.slice(- 0,- index,- ); // Exclude current and later dimensions- const currentValue = pivotDimensions[index] || "";-- return (- <div key={index} className="space-y-2">- <Label htmlFor={`pivot-dimension-${index}`}>- Dimension {index + 1} (Optional)- </Label>- <Select- value={currentValue}- onValueChange={(value) =>- updatePivotDimension(index, value)- }- disabled={!isEnabled}- >- <SelectTrigger id={`pivot-dimension-${index}`}>- <SelectValue- placeholder={- isEnabled- ? "Select a dimension"- : "Select previous dimension first"- }- />- </SelectTrigger>- <SelectContent>- {index >= 0 && (- <SelectItem value="none">None</SelectItem>- )}- {availableDimensions- .filter(- (d) => !selectedDimensions.includes(d.value),- )- .map((dimension) => {- const meta =- viewDeclarations[viewVersion][selectedView]- ?.dimensions?.[dimension.value];- return (- <WidgetPropertySelectItem- key={dimension.value}- value={dimension.value}- label={dimension.label}- description={meta?.description}- unit={meta?.unit}- type={meta?.type}- />- );- })}- </SelectContent>- </Select>- </div>- );- },- )}- </div>+ {chartType === "PIVOT_TABLE" && (+ <PivotDimensionsField+ control={form.control}+ ctx={ctx}+ error={dimensionsError}+ availableDimensions={availableDimensions}+ />)}{/* Pivot Table Default Sort Configuration */}- {selectedChartType === "PIVOT_TABLE" && (- <div className="space-y-4">- <div>- <h4 className="mb-2 text-sm font-bold">- Default Sort Configuration- </h4>- <p className="text-muted-foreground mb-3 text-xs">- Configure the default sort order for the pivot table. This- will be applied when the widget is first loaded.- </p>- </div>-- <div className="grid grid-cols-2 gap-4">- <div className="space-y-2">- <Label htmlFor="default-sort-column">Sort Column</Label>- <Select- value={defaultSortColumn}- onValueChange={setDefaultSortColumn}- >- <SelectTrigger id="default-sort-column">- <SelectValue placeholder="Select a column to sort by" />- </SelectTrigger>- <SelectContent>- <SelectItem value="none">No default sort</SelectItem>- {/* Show available metrics as sort options */}- {selectedMetrics- .filter(- (metric) =>- metric.measure && metric.measure !== "",- )- .map((metric) => (- <SelectItem key={metric.id} value={metric.id}>- {formatMetricName(metric.id)}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div className="space-y-2">- <Label htmlFor="default-sort-order">Sort Order</Label>- <Select- value={defaultSortOrder}- onValueChange={(value: "ASC" | "DESC") =>- setDefaultSortOrder(value)- }- disabled={- !defaultSortColumn || defaultSortColumn === "none"- }- >- <SelectTrigger id="default-sort-order">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="ASC">Ascending (A-Z)</SelectItem>- <SelectItem value="DESC">Descending (Z-A)</SelectItem>- </SelectContent>- </Select>- </div>- </div>- </div>+ {chartType === "PIVOT_TABLE" && (+ <PivotSortField+ control={form.control}+ effectiveSort={effectiveSort}+ metricsForSort={metricsForSort}+ />)}</div>@@ -2095,85 +1250,18 @@ export function WidgetForm({<div className="mt-6 space-y-4"><h3 className="text-lg font-bold">Visualization</h3>- {/* Widget Name */}- <div className="space-y-2">- <Label htmlFor="widget-name">Name</Label>- <Input- id="widget-name"- value={widgetName}- onChange={(e) => {- if (!autoLocked) setAutoLocked(true);- setWidgetName(e.target.value);- }}- placeholder="Enter widget name"- />- </div>-- {/* Widget Description */}- <div className="space-y-2">- <Label htmlFor="widget-description">Description</Label>- <Input- id="widget-description"- value={widgetDescription}- onChange={(e) => {- if (!autoLocked) setAutoLocked(true);- setWidgetDescription(e.target.value);- }}- placeholder="Enter widget description"- />- </div>+ <NameField control={form.control} suggestion={suggestions.name} />+ <DescriptionField+ control={form.control}+ suggestion={suggestions.description}+ />- {/* Chart Type Selection */}- <div className="space-y-2">- <Label htmlFor="chart-type-select">Chart Type</Label>- <Select- value={selectedChartType}- onValueChange={setSelectedChartType}- >- <SelectTrigger id="chart-type-select">- <SelectValue placeholder="Select a chart type" />- </SelectTrigger>- <SelectContent>- <SelectGroup>- <SelectLabel>Time Series</SelectLabel>- {chartTypes- .filter((item) => item.group === "time-series")- .map((chart) => (- <SelectItem key={chart.value} value={chart.value}>- <div className="flex items-center">- {React.createElement(chart.icon, {- className: "mr-2 w-4",- })}- <span>{chart.name}</span>- </div>- </SelectItem>- ))}- </SelectGroup>- <SelectGroup>- <SelectLabel>Total Value</SelectLabel>- {chartTypes- .filter((item) => item.group === "total-value")- .map((chart) => (- <SelectItem- key={chart.value}- value={chart.value}- disabled={- chart.value === "HISTOGRAM" &&- !measureSupportsHistogram- }- >- <div className="flex items-center">- {React.createElement(chart.icon, {- className: "mr-2 w-4",- })}- <span>{chart.name}</span>- </div>- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </div>+ <ChartTypeSelect+ value={chartType}+ onChartTypeChange={onChartTypeChange}+ measureSupportsHistogram={measureSupportsHistogram}+ error={chartTypeError}+ /><div className="space-y-2"><Label htmlFor="date-select">Date Range</Label>@@ -2193,57 +1281,28 @@ export function WidgetForm({/></div>- {/* Histogram Bins Selection - Only shown for HISTOGRAM chart type */}- {selectedChartType === "HISTOGRAM" && (- <div className="space-y-2">- <Label htmlFor="histogram-bins">Number of Bins (1-100)</Label>- <Input- id="histogram-bins"- type="number"- min={1}- max={100}- value={histogramBins}- onChange={(e) => {- const value = parseInt(e.target.value);- if (!isNaN(value) && value >= 1 && value <= 100) {- setHistogramBins(value);- }- }}- placeholder="Enter number of bins (1-100)"- />- </div>+ {chartType === "HISTOGRAM" && (+ <HistogramBinsField control={form.control} />)}- {/* Row Limit Selection - Only shown for non-time series charts that support breakdown */}- {chartTypes.find((c) => c.value === selectedChartType)- ?.supportsBreakdown &&- !isTimeSeriesChart(- selectedChartType as DashboardWidgetChartType,- ) && (- <div className="space-y-2">- <Label htmlFor="row-limit">- Breakdown Row Limit (0-1000)- </Label>- <Input- id="row-limit"- type="number"- min={0}- max={1000}- value={rowLimit}- onChange={(e) => {- const value = parseInt(e.target.value);- if (!isNaN(value) && value >= 0 && value <= 1000) {- setRowLimit(value);- }- }}- placeholder="Enter breakdown row limit (0-1000)"- />- </div>+ {widgetChartTypeSupportsBreakdown(chartType) &&+ !isTimeSeriesChart(chartType) && (+ <RowLimitField control={form.control} />)}</div></CardContent>- <CardFooter className="mt-auto">- <Button className="w-full" size="lg" onClick={handleSaveWidget}>+ <CardFooter className="mt-auto flex-col items-stretch gap-2">+ {saveDisabled && saveDisabledReason && (+ <p role="alert" className="text-destructive text-xs">+ {saveDisabledReason}+ </p>+ )}+ <Button+ className="w-full"+ size="lg"+ onClick={onSubmit}+ disabled={saveDisabled}+ >Save Widget</Button></CardFooter>@@ -2253,11 +1312,11 @@ export function WidgetForm({<div className="w-2/3"><Card className="flex aspect-video flex-col"><CardHeader>- <CardTitle className="truncate" title={widgetName}>- {widgetName}+ <CardTitle className="truncate" title={displayName}>+ {displayName}</CardTitle>- <CardDescription className="truncate" title={widgetDescription}>- {widgetDescription}+ <CardDescription className="truncate" title={displayDescription}>+ {displayDescription}</CardDescription></CardHeader>{!queryValidation.valid ? (@@ -2274,26 +1333,25 @@ export function WidgetForm({<div className="flex min-h-0 flex-1 flex-col"><div className="relative min-h-0 flex-1"><Chart- chartType={selectedChartType as DashboardWidgetChartType}+ chartType={chartType}data={transformedData}config={chartPresentation- ? {- metric: {- label: chartPresentation.label,- },- }+ ? { metric: { label: chartPresentation.label } }: undefined}- rowLimit={rowLimit}+ rowLimit={values.chart.rowLimit}chartConfig={- selectedChartType === "PIVOT_TABLE"+ chartType === "PIVOT_TABLE"? {- type: selectedChartType as DashboardWidgetChartType,- dimensions: pivotDimensions,- row_limit: rowLimit,- metrics: selectedMetrics.map((metric) => metric.id), // Pass metric field names- units: selectedMetrics.map((metric) =>+ type: chartType,+ dimensions: pivotDimensionFields,+ row_limit: values.chart.rowLimit,+ metrics: values.metrics.map(+ (metric) =>+ `${metric.aggregation}_${metric.measure}`,+ ),+ units: values.metrics.map((metric) =>getResultUnit(selectedView,metric.measure,@@ -2301,18 +1359,12 @@ export function WidgetForm({viewVersion,),),- defaultSort:- defaultSortColumn && defaultSortColumn !== "none"- ? {- column: defaultSortColumn,- order: defaultSortOrder,- }- : undefined,+ defaultSort: effectiveSort ?? undefined,}- : selectedChartType === "HISTOGRAM"+ : chartType === "HISTOGRAM"? {- type: selectedChartType as DashboardWidgetChartType,- bins: histogramBins,+ type: chartType,+ bins: values.chart.bins,unit: getResultUnit(selectedView,selectedMeasure,@@ -2321,8 +1373,8 @@ export function WidgetForm({),}: {- type: selectedChartType as DashboardWidgetChartType,- row_limit: rowLimit,+ type: chartType,+ row_limit: values.chart.rowLimit,unit: getResultUnit(selectedView,selectedMeasure,@@ -2332,9 +1384,7 @@ export function WidgetForm({}}sortState={- selectedChartType === "PIVOT_TABLE"- ? previewSortState- : undefined+ chartType === "PIVOT_TABLE" ? previewSortState : undefined}onSortChange={undefined}isLoading={queryResult.isPending}@@ -2377,3 +1427,786 @@ export function WidgetForm({</div>);}++// -----------------------------------------------------------------------------+// Field subcomponents. Each binds exactly ONE nested field via a single+// useController and receives the read-only ctx as props. Cross-slice cascades+// are invoked through the parent-owned handlers (onViewChange, onChartTypeChange,+// onMeasureChange); no child pokes a sibling field or calls `watch`.+// -----------------------------------------------------------------------------++function ViewSelect({+ control,+ ctx,+ availableViewOptions,+ onViewChange,+}: {+ control: Control<WidgetFormValues>;+ ctx: WidgetFieldContext;+ availableViewOptions: typeof views | typeof viewsV2;+ onViewChange: (view: z.infer<typeof views>) => void;+}) {+ const { field } = useController({ control, name: "view" });+ return (+ <div className="space-y-2">+ <Label htmlFor="view-select">View</Label>+ <Select+ value={field.value}+ onValueChange={(value) => onViewChange(value as z.infer<typeof views>)}+ >+ <SelectTrigger id="view-select">+ <SelectValue placeholder="Select a view" />+ </SelectTrigger>+ <SelectContent>+ {availableViewOptions.options.map((view) => (+ <WidgetPropertySelectItem+ key={view}+ value={view}+ label={startCase(view)}+ description={viewDeclarations[ctx.viewVersion][view].description}+ />+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}++function SingleMetricField({+ control,+ ctx,+ error,+ measure,+ onMeasureChange,+ availableMetrics,+ validAggregationsForMeasure,+}: {+ control: Control<WidgetFormValues>;+ ctx: WidgetFieldContext;+ error?: string;+ measure: string;+ onMeasureChange: (measure: string) => void;+ availableMetrics: { value: string; label: string }[];+ validAggregationsForMeasure: z.infer<typeof metricAggregations>[];+}) {+ // Owns metrics.0.aggregation; the measure is a cross-slice trigger handled by+ // the parent (onMeasureChange also resolves the chart type).+ const { field: aggField } = useController({+ control,+ name: "metrics.0.aggregation",+ });++ // THE HISTOGRAM FIX (a): the histogram aggregation is offered only on the+ // histogram chart (where it is forced and this Select is disabled). It is+ // never manually selectable on a non-histogram chart, so no silent revert.+ const aggregationOptions = validAggregationsForMeasure.filter(+ (agg) => agg !== "histogram" || ctx.chartType === "HISTOGRAM",+ );++ return (+ <div className="space-y-2">+ <Select value={measure} onValueChange={(value) => onMeasureChange(value)}>+ <SelectTrigger+ id="metrics-select"+ aria-invalid={error ? true : undefined}+ aria-describedby={error ? "single-metric-error" : undefined}+ >+ <SelectValue placeholder="Select metrics" />+ </SelectTrigger>+ <SelectContent>+ {availableMetrics.map((metric) => {+ const meta =+ viewDeclarations[ctx.viewVersion][ctx.view]?.measures?.[+ metric.value+ ];+ return (+ <WidgetPropertySelectItem+ key={metric.value}+ value={metric.value}+ label={metric.label}+ description={meta?.description}+ unit={meta?.unit}+ type={meta?.type}+ />+ );+ })}+ </SelectContent>+ </Select>+ {measure !== "count" && (+ <div className="space-y-1">+ <Select+ value={aggField.value}+ disabled={ctx.chartType === "HISTOGRAM"}+ onValueChange={(value) =>+ aggField.onChange(value as z.infer<typeof metricAggregations>)+ }+ >+ <SelectTrigger id="aggregation-select">+ <SelectValue placeholder="Select Aggregation" />+ </SelectTrigger>+ <SelectContent>+ {aggregationOptions.map((aggregation) => (+ <SelectItem key={aggregation} value={aggregation}>+ {startCase(aggregation)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {ctx.chartType === "HISTOGRAM" && (+ <p className="text-muted-foreground text-xs">+ Aggregation is automatically set to "histogram" for+ histogram charts+ </p>+ )}+ </div>+ )}+ {error && (+ <p id="single-metric-error" className="text-destructive text-xs">+ {error}+ </p>+ )}+ </div>+ );+}++function PivotMetricsField({+ control,+ ctx,+ error,+ getAvailablePivotMetrics,+ getAvailablePivotAggregations,+}: {+ control: Control<WidgetFormValues>;+ ctx: WidgetFieldContext;+ error?: string;+ getAvailablePivotMetrics: (+ index: number,+ ) => { value: string; label: string }[];+ getAvailablePivotAggregations: (+ index: number,+ measure: string,+ ) => z.infer<typeof metricAggregations>[];+}) {+ // Owns the entire `metrics` slice β one value in (field.value), one onChange+ // out (field.onChange with a fresh array).+ const { field } = useController({ control, name: "metrics" });+ const metrics = field.value;++ const updateMetric = (+ index: number,+ measure: string,+ aggregation?: z.infer<typeof metricAggregations>,+ ) => {+ const next = [...metrics];+ if (measure && measure !== "none") {+ let finalAggregation: z.infer<typeof metricAggregations>;+ if (measure === "count") {+ finalAggregation = "count";+ } else {+ const available = getAvailablePivotAggregations(index, measure);+ finalAggregation =+ aggregation && available.includes(aggregation)+ ? aggregation+ : (available[0] ?? "sum");+ }+ next[index] = { measure, aggregation: finalAggregation };+ } else {+ next.splice(index);+ }+ field.onChange(next);+ };++ const addSlot = () => {+ if (metrics.length < MAX_PIVOT_TABLE_METRICS) {+ field.onChange([...metrics, { measure: "", aggregation: "sum" }]);+ }+ };++ const removeSlot = (index: number) => {+ if (index > 0) {+ const next = [...metrics];+ next.splice(index, 1);+ field.onChange(next);+ }+ };++ return (+ <div className="space-y-3">+ {Array.from({ length: Math.max(1, metrics.length) }, (_, index) => {+ const isEnabled =+ index === 0 ||+ Boolean(metrics[index - 1] && metrics[index - 1].measure);+ const currentMetric = metrics[index];+ const currentMeasure = currentMetric?.measure || "";+ const currentAggregation = currentMetric?.aggregation || "sum";+ const metricsForIndex = getAvailablePivotMetrics(index);+ const aggregationsForIndex = getAvailablePivotAggregations(+ index,+ currentMeasure,+ );+ const canEdit = metricsForIndex.length > 0;++ return (+ <div key={index} className="space-y-2">+ <div className="flex items-center justify-between">+ <Label htmlFor={`pivot-metric-${index}`}>+ Metric {index + 1} {index === 0 ? "(Required)" : "(Optional)"}+ </Label>+ {index > 0 && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => removeSlot(index)}+ className="text-muted-foreground hover:text-destructive h-6 w-6 p-0"+ >+ <X className="h-4 w-4" />+ </Button>+ )}+ </div>+ <div className="flex items-center gap-2">+ <div className="flex-1">+ <Select+ value={currentMeasure}+ onValueChange={(value) =>+ updateMetric(index, value, undefined)+ }+ disabled={!isEnabled || !canEdit}+ >+ <SelectTrigger+ id={`pivot-metric-${index}`}+ aria-invalid={error && index === 0 ? true : undefined}+ aria-describedby={+ error && index === 0 ? "pivot-metrics-error" : undefined+ }+ >+ <SelectValue+ placeholder={+ !isEnabled+ ? "Select previous metric first"+ : !canEdit+ ? "No more measures available"+ : "Select measure"+ }+ />+ </SelectTrigger>+ <SelectContent>+ {metricsForIndex.map((metric) => {+ const meta =+ viewDeclarations[ctx.viewVersion][ctx.view]?.measures?.[+ metric.value+ ];+ return (+ <WidgetPropertySelectItem+ key={metric.value}+ value={metric.value}+ label={metric.label}+ description={meta?.description}+ unit={meta?.unit}+ type={meta?.type}+ />+ );+ })}+ </SelectContent>+ </Select>+ </div>++ {currentMeasure && currentMeasure !== "count" && (+ <div className="flex-1">+ <Select+ value={currentAggregation}+ onValueChange={(value) =>+ updateMetric(+ index,+ currentMeasure,+ value as z.infer<typeof metricAggregations>,+ )+ }+ >+ <SelectTrigger>+ <SelectValue placeholder="Select aggregation" />+ </SelectTrigger>+ <SelectContent>+ {aggregationsForIndex.map((aggregation) => (+ <SelectItem key={aggregation} value={aggregation}>+ {startCase(aggregation)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}+ </div>+ </div>+ );+ })}++ {metrics.length < MAX_PIVOT_TABLE_METRICS &&+ getAvailablePivotMetrics(metrics.length).length > 0 && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={addSlot}+ className="w-full"+ >+ <Plus className="mr-1 h-3 w-3" />+ Add Metric {metrics.length + 1}+ </Button>+ )}+ {error && (+ <p id="pivot-metrics-error" className="text-destructive text-xs">+ {error}+ </p>+ )}+ </div>+ );+}++function FiltersField({+ control,+ filterColumns,+ columnsWithCustomSelect,+ unsupportedFilters,+ unsupportedFilterColumns,+ selectedView,+}: {+ control: Control<WidgetFormValues>;+ filterColumns: ReturnType<typeof getWidgetFilterColumns>;+ columnsWithCustomSelect: ReturnType<typeof getWidgetColumnsWithCustomSelect>;+ unsupportedFilters: FilterState;+ unsupportedFilterColumns: string;+ selectedView: z.infer<typeof views>;+}) {+ const { field } = useController({ control, name: "filters" });+ return (+ <div className="space-y-2">+ <Label>Filters</Label>+ <div className="space-y-2">+ {unsupportedFilters.length > 0 && (+ <Alert+ variant="default"+ className="border-yellow-500/50 bg-yellow-50 dark:bg-yellow-950/20"+ >+ <AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-500" />+ <AlertTitle className="text-yellow-800 dark:text-yellow-400">+ Unsupported legacy filters+ </AlertTitle>+ <AlertDescription className="text-yellow-700 dark:text-yellow-500">+ {`This widget still contains filter columns that are not supported for ${startCase(selectedView)}: ${unsupportedFilterColumns}. Remove them or switch to a compatible view before saving.`}+ </AlertDescription>+ </Alert>+ )}+ <InlineFilterBuilder+ columns={filterColumns}+ filterState={field.value}+ onChange={(next: FilterState) => field.onChange(next)}+ columnsWithCustomSelect={columnsWithCustomSelect}+ />+ </div>+ </div>+ );+}++function BreakdownSelect({+ control,+ ctx,+ error,+ availableDimensions,+}: {+ control: Control<WidgetFormValues>;+ ctx: WidgetFieldContext;+ error?: string;+ availableDimensions: { value: string; label: string }[];+}) {+ // Owns the entire `dimensions` slice; a non-pivot chart carries at most one.+ const { field } = useController({ control, name: "dimensions" });+ const value = field.value[0]?.field ?? "none";+ return (+ <div className="space-y-2">+ <Label htmlFor="dimension-select">Breakdown Dimension (Optional)</Label>+ <Select+ value={value}+ onValueChange={(next) =>+ field.onChange(next === "none" ? [] : [{ field: next }])+ }+ >+ <SelectTrigger+ id="dimension-select"+ aria-invalid={error ? true : undefined}+ aria-describedby={error ? "breakdown-error" : undefined}+ >+ <SelectValue placeholder="Select a dimension" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">None</SelectItem>+ {availableDimensions.map((dimension) => {+ const meta =+ viewDeclarations[ctx.viewVersion][ctx.view]?.dimensions?.[+ dimension.value+ ];+ return (+ <WidgetPropertySelectItem+ key={dimension.value}+ value={dimension.value}+ label={dimension.label}+ description={meta?.description}+ unit={meta?.unit}+ type={meta?.type}+ />+ );+ })}+ </SelectContent>+ </Select>+ {error && (+ <p id="breakdown-error" className="text-destructive text-xs">+ {error}+ </p>+ )}+ </div>+ );+}++function PivotDimensionsField({+ control,+ ctx,+ error,+ availableDimensions,+}: {+ control: Control<WidgetFormValues>;+ ctx: WidgetFieldContext;+ error?: string;+ availableDimensions: { value: string; label: string }[];+}) {+ const { field } = useController({ control, name: "dimensions" });+ const pivotDimensions = field.value.map((d) => d.field);++ const updateDimension = (index: number, value: string) => {+ const next = [...pivotDimensions];+ if (value && value !== "none") {+ next[index] = value;+ } else {+ next.splice(index);+ }+ field.onChange(next.map((f) => ({ field: f })));+ };++ return (+ <div className="space-y-4">+ <div>+ <h4 className="mb-2 text-sm font-bold">Row Dimensions</h4>+ <p className="text-muted-foreground mb-3 text-xs">+ Configure up to {MAX_PIVOT_TABLE_DIMENSIONS} dimensions for pivot+ table rows. Each dimension creates groupings with subtotals.+ </p>+ </div>++ {Array.from({ length: MAX_PIVOT_TABLE_DIMENSIONS }, (_, index) => {+ const isEnabled = index === 0 || Boolean(pivotDimensions[index - 1]);+ const selectedDimensions = pivotDimensions.slice(0, index);+ const currentValue = pivotDimensions[index] || "";++ return (+ <div key={index} className="space-y-2">+ <Label htmlFor={`pivot-dimension-${index}`}>+ Dimension {index + 1} (Optional)+ </Label>+ <Select+ value={currentValue}+ onValueChange={(value) => updateDimension(index, value)}+ disabled={!isEnabled}+ >+ <SelectTrigger+ id={`pivot-dimension-${index}`}+ aria-invalid={error && index === 0 ? true : undefined}+ aria-describedby={+ error && index === 0 ? "pivot-dimensions-error" : undefined+ }+ >+ <SelectValue+ placeholder={+ isEnabled+ ? "Select a dimension"+ : "Select previous dimension first"+ }+ />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">None</SelectItem>+ {availableDimensions+ .filter((d) => !selectedDimensions.includes(d.value))+ .map((dimension) => {+ const meta =+ viewDeclarations[ctx.viewVersion][ctx.view]?.dimensions?.[+ dimension.value+ ];+ return (+ <WidgetPropertySelectItem+ key={dimension.value}+ value={dimension.value}+ label={dimension.label}+ description={meta?.description}+ unit={meta?.unit}+ type={meta?.type}+ />+ );+ })}+ </SelectContent>+ </Select>+ </div>+ );+ })}+ {error && (+ <p id="pivot-dimensions-error" className="text-destructive text-xs">+ {error}+ </p>+ )}+ </div>+ );+}++function PivotSortField({+ control,+ effectiveSort,+ metricsForSort,+}: {+ control: Control<WidgetFormValues>;+ effectiveSort: SortField | undefined;+ metricsForSort: { id: string }[];+}) {+ // Owns chart.sort; the DISPLAY value is always the sanitized effectiveSort so+ // a stale sort column shows as "no default sort" without any write-back.+ const { field } = useController({ control, name: "chart.sort" });+ const column = effectiveSort?.column ?? "none";+ const order = effectiveSort?.order ?? "DESC";++ return (+ <div className="space-y-4">+ <div>+ <h4 className="mb-2 text-sm font-bold">Default Sort Configuration</h4>+ <p className="text-muted-foreground mb-3 text-xs">+ Configure the default sort order for the pivot table. This will be+ applied when the widget is first loaded.+ </p>+ </div>++ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label htmlFor="default-sort-column">Sort Column</Label>+ <Select+ value={column}+ onValueChange={(next) =>+ field.onChange(next === "none" ? null : { column: next, order })+ }+ >+ <SelectTrigger id="default-sort-column">+ <SelectValue placeholder="Select a column to sort by" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">No default sort</SelectItem>+ {metricsForSort.map((metric) => (+ <SelectItem key={metric.id} value={metric.id}>+ {formatMetricName(metric.id)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-2">+ <Label htmlFor="default-sort-order">Sort Order</Label>+ <Select+ value={order}+ onValueChange={(value: "ASC" | "DESC") =>+ field.onChange({ column, order: value })+ }+ disabled={column === "none"}+ >+ <SelectTrigger id="default-sort-order">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="ASC">Ascending (A-Z)</SelectItem>+ <SelectItem value="DESC">Descending (Z-A)</SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>+ </div>+ );+}++/**+ * NameField / DescriptionField isolate the "override vs. live suggestion"+ * presentation. The field value is the user's override; a blank (null) override+ * shows the live-derived suggestion as the input's value (today's behaviour β+ * pre-filled, live-updating until the user edits, then it sticks). The whole+ * placeholder decision lives here, so switching to a grey-placeholder variant+ * later is a one-component change.+ */+function NameField({+ control,+ suggestion,+}: {+ control: Control<WidgetFormValues>;+ suggestion: string;+}) {+ const { field } = useController({ control, name: "name" });+ return (+ <div className="space-y-2">+ <Label htmlFor="widget-name">Name</Label>+ <Input+ id="widget-name"+ // A blank/whitespace-only override shows the live suggestion; typing+ // real content sticks; clearing reverts to tracking + saving the+ // suggestion. Uses the same trim-aware effective logic as the preview+ // title and toSavePayload, so input, preview, and saved value agree.+ value={effectiveWidgetName(field.value, suggestion)}+ onChange={(e) => field.onChange(e.target.value)}+ placeholder="Enter widget name"+ />+ </div>+ );+}++function DescriptionField({+ control,+ suggestion,+}: {+ control: Control<WidgetFormValues>;+ suggestion: string;+}) {+ const { field } = useController({ control, name: "description" });+ return (+ <div className="space-y-2">+ <Label htmlFor="widget-description">Description</Label>+ <Input+ id="widget-description"+ value={effectiveWidgetName(field.value, suggestion)}+ onChange={(e) => field.onChange(e.target.value)}+ placeholder="Enter widget description"+ />+ </div>+ );+}++function ChartTypeSelect({+ value,+ onChartTypeChange,+ measureSupportsHistogram,+ error,+}: {+ value: DashboardWidgetChartType;+ onChartTypeChange: (type: DashboardWidgetChartType) => void;+ measureSupportsHistogram: boolean;+ error?: string;+}) {+ return (+ <div className="space-y-2">+ <Label htmlFor="chart-type-select">Chart Type</Label>+ <Select+ value={value}+ onValueChange={(next) =>+ onChartTypeChange(next as DashboardWidgetChartType)+ }+ >+ <SelectTrigger+ id="chart-type-select"+ aria-invalid={error ? true : undefined}+ aria-describedby={error ? "chart-type-error" : undefined}+ >+ <SelectValue placeholder="Select a chart type" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Time Series</SelectLabel>+ {chartTypes+ .filter((item) => item.group === "time-series")+ .map((chart) => (+ <SelectItem key={chart.value} value={chart.value}>+ <div className="flex items-center">+ {React.createElement(chart.icon, { className: "mr-2 w-4" })}+ <span>{chart.name}</span>+ </div>+ </SelectItem>+ ))}+ </SelectGroup>+ <SelectGroup>+ <SelectLabel>Total Value</SelectLabel>+ {chartTypes+ .filter((item) => item.group === "total-value")+ .map((chart) => (+ <SelectItem+ key={chart.value}+ value={chart.value}+ disabled={+ chart.value === "HISTOGRAM" && !measureSupportsHistogram+ }+ >+ <div className="flex items-center">+ {React.createElement(chart.icon, { className: "mr-2 w-4" })}+ <span>{chart.name}</span>+ </div>+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ {error && (+ <p id="chart-type-error" className="text-destructive text-xs">+ {error}+ </p>+ )}+ </div>+ );+}++function HistogramBinsField({+ control,+}: {+ control: Control<WidgetFormValues>;+}) {+ const { field } = useController({ control, name: "chart.bins" });+ return (+ <div className="space-y-2">+ <Label htmlFor="histogram-bins">Number of Bins (1-100)</Label>+ <Input+ id="histogram-bins"+ type="number"+ min={1}+ max={100}+ value={field.value}+ onChange={(e) => {+ const value = parseInt(e.target.value);+ if (!isNaN(value) && value >= 1 && value <= 100) {+ field.onChange(value);+ }+ }}+ placeholder="Enter number of bins (1-100)"+ />+ </div>+ );+}++function RowLimitField({ control }: { control: Control<WidgetFormValues> }) {+ const { field } = useController({ control, name: "chart.rowLimit" });+ return (+ <div className="space-y-2">+ <Label htmlFor="row-limit">Breakdown Row Limit (0-1000)</Label>+ <Input+ id="row-limit"+ type="number"+ min={0}+ max={1000}+ value={field.value}+ onChange={(e) => {+ const value = parseInt(e.target.value);+ if (!isNaN(value) && value >= 0 && value <= 1000) {+ field.onChange(value);+ }+ }}+ placeholder="Enter breakdown row limit (0-1000)"+ />+ </div>+ );+}diff --git a/web/src/features/widgets/components/widgetFormAdapters.clienttest.ts b/web/src/features/widgets/components/widgetFormAdapters.clienttest.tsnew file mode 100644index 0000000000..ee93e3257c--- /dev/null+++ b/web/src/features/widgets/components/widgetFormAdapters.clienttest.ts@@ -0,0 +1,563 @@+import startCase from "lodash/startCase";+import { type z } from "zod";++import { requiresV2, type metricAggregations } from "@langfuse/shared/query";+import {+ mapWidgetUiTableFilterToView,+ normalizeStoredWidgetFiltersForEditor,+} from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";+import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";+import {+ buildWidgetDescription,+ buildWidgetName,+ sanitizePivotTableDefaultSort,+ type WidgetChartConfig,+} from "@/src/features/widgets/utils";++import {+ applyChartTypeChange,+ deriveEffectiveSort,+ deriveWidgetBaseMinVersion,+ deriveWidgetSuggestions,+ resolveWidgetViewVersion,+ toDefaultValues,+ toSavePayload,+ type WidgetFormValues,+ type WidgetInitialValues,+ type WidgetSavePayload,+} from "./widgetFormSchema";++/** The view version the app would seed with for a given widget (non-beta). */+const fixtureViewVersion = (iv: WidgetInitialValues) =>+ resolveWidgetViewVersion({+ view: iv.view,+ baseMinVersion: deriveWidgetBaseMinVersion(iv),+ isBetaEnabled: false,+ });++/**+ * An INDEPENDENT reconstruction of the legacy `handleSaveWidget` object builder+ * (WidgetForm.tsx :1430-1471), driven off the legacy single/pivot state seeding,+ * the auto-name/description effects, and the pivot default-sort sanitize effect.+ * It is deliberately written from the ORIGINAL component logic β not from the+ * new adapters β so that a shape-mapping bug in `toDefaultValues`/`toSavePayload`+ * is caught by the deep-equality assertion below.+ */+function legacyReconstruct(iv: WidgetInitialValues): WidgetSavePayload {+ const isPivot = iv.chartType === "PIVOT_TABLE";++ const selectedMeasure = iv.measure;+ const selectedAggregation = iv.aggregation;+ const selectedDimension = iv.dimension;++ const selectedMetrics =+ isPivot && iv.metrics?.length+ ? iv.metrics.map((m) => ({+ id: `${m.agg}_${m.measure}`,+ measure: m.measure,+ aggregation: m.agg as z.infer<typeof metricAggregations>,+ }))+ : [+ {+ id: `${iv.aggregation}_${iv.measure}`,+ measure: iv.measure,+ aggregation: iv.aggregation,+ },+ ];++ const pivotDimensions =+ isPivot && iv.dimensions?.length ? iv.dimensions.map((d) => d.field) : [];++ const initialDefaultSort = isPivot+ ? sanitizePivotTableDefaultSort(iv.chartConfig?.defaultSort, {+ dimensions: iv.dimensions ?? [],+ metrics:+ iv.metrics ??+ (iv.measure && iv.aggregation+ ? [{ measure: iv.measure, agg: iv.aggregation }]+ : []),+ })+ : undefined;++ let defaultSortColumn = initialDefaultSort?.column ?? "none";+ let defaultSortOrder: "ASC" | "DESC" = initialDefaultSort?.order ?? "DESC";++ const rowLimit = iv.chartConfig?.row_limit ?? 100;+ const histogramBins = iv.chartConfig?.bins ?? 10;++ const userFilterState = normalizeStoredWidgetFiltersForEditor(+ iv.view,+ iv.filters ?? [],+ ).editorFilters;++ // Legacy sort-sanitize effect (:541): drop a stale sort column.+ if (isPivot) {+ const sanitized = sanitizePivotTableDefaultSort(+ defaultSortColumn !== "none"+ ? { column: defaultSortColumn, order: defaultSortOrder }+ : undefined,+ {+ dimensions: pivotDimensions+ .filter((field) => field && field !== "none")+ .map((field) => ({ field })),+ metrics: selectedMetrics+ .filter((metric) => metric.measure && metric.measure !== "")+ .map((metric) => ({+ measure: metric.measure,+ agg: metric.aggregation,+ })),+ },+ );+ if (defaultSortColumn !== "none" && !sanitized) {+ defaultSortColumn = "none";+ defaultSortOrder = "DESC";+ }+ }++ // Legacy auto-name / auto-description (create: suggestion; edit: sticks).+ const validMetricsForNaming = selectedMetrics.filter(+ (m) => m.measure && m.measure !== "",+ );+ const dimensionForNaming =+ isPivot && pivotDimensions.length > 0+ ? pivotDimensions.map(startCase).join(" and ")+ : selectedDimension;+ const metricNames =+ isPivot && validMetricsForNaming.length > 0+ ? validMetricsForNaming.map((m) => m.id)+ : undefined;++ // buildWidgetName / buildWidgetDescription are shared with the adapter; the+ // structural arg construction above is what the parity check exercises.+ const suggestedName = buildWidgetName({+ aggregation: isPivot ? "count" : selectedAggregation,+ measure: isPivot ? "count" : selectedMeasure,+ dimension: dimensionForNaming,+ view: iv.view,+ metrics: metricNames,+ isMultiMetric: isPivot && validMetricsForNaming.length > 0,+ });+ const suggestedDescription = buildWidgetDescription({+ aggregation: isPivot ? "count" : selectedAggregation,+ measure: isPivot ? "count" : selectedMeasure,+ dimension: dimensionForNaming,+ view: iv.view,+ filters: userFilterState,+ metrics: metricNames,+ isMultiMetric: isPivot && validMetricsForNaming.length > 0,+ });++ const widgetName = iv.name && iv.name.length > 0 ? iv.name : suggestedName;+ const widgetDescription =+ iv.description && iv.description.length > 0+ ? iv.description+ : suggestedDescription;++ const validMetrics = selectedMetrics.filter(+ (m) => m.measure && m.measure !== "",+ );+ const saveDimensions = isPivot+ ? pivotDimensions.map((field) => ({ field }))+ : selectedDimension !== "none"+ ? [{ field: selectedDimension }]+ : [];+ const saveMetrics = isPivot+ ? validMetrics.map((m) => ({ measure: m.measure, agg: m.aggregation }))+ : [{ measure: selectedMeasure, agg: selectedAggregation }];++ const normalizedUserFilters = mapWidgetUiTableFilterToView(+ iv.view,+ userFilterState,+ );++ const chartConfig: WidgetChartConfig = isTimeSeriesChart(iv.chartType)+ ? { type: iv.chartType }+ : iv.chartType === "HISTOGRAM"+ ? { type: iv.chartType, bins: histogramBins }+ : iv.chartType === "PIVOT_TABLE"+ ? {+ type: iv.chartType,+ row_limit: rowLimit,+ defaultSort:+ defaultSortColumn && defaultSortColumn !== "none"+ ? { column: defaultSortColumn, order: defaultSortOrder }+ : undefined,+ }+ : { type: iv.chartType, row_limit: rowLimit };++ return {+ name: widgetName,+ description: widgetDescription,+ view: iv.view,+ dimensions: saveDimensions,+ metrics: saveMetrics,+ filters: normalizedUserFilters,+ chartType: iv.chartType,+ chartConfig,+ minVersion: requiresV2({+ view: iv.view,+ dimensions: saveDimensions,+ measures: saveMetrics.map((m) => ({ measure: m.measure })),+ filters: normalizedUserFilters,+ })+ ? 2+ : 1,+ };+}++/** Runs the new adapter path: initialValues β form values β save payload. */+function adapterSavePayload(iv: WidgetInitialValues): WidgetSavePayload {+ const values = toDefaultValues(iv, fixtureViewVersion(iv));+ const suggestions = deriveWidgetSuggestions(values);+ const effectiveSort = deriveEffectiveSort(values);+ return toSavePayload(values, {+ suggestedName: suggestions.name,+ suggestedDescription: suggestions.description,+ effectiveSort,+ });+}++const fixtures: Record<string, WidgetInitialValues> = {+ "regular line (create)": {+ name: "",+ description: "",+ view: "observations",+ measure: "latency",+ aggregation: "avg",+ dimension: "none",+ filters: [],+ chartType: "LINE_TIME_SERIES",+ chartConfig: { type: "LINE_TIME_SERIES" },+ },+ "breakdown bar with dimension": {+ name: "",+ description: "",+ view: "observations",+ measure: "totalCost",+ aggregation: "sum",+ dimension: "environment",+ filters: [],+ chartType: "VERTICAL_BAR",+ chartConfig: { type: "VERTICAL_BAR", row_limit: 25 },+ },+ "count measure big number": {+ name: "",+ description: "",+ view: "observations",+ measure: "count",+ aggregation: "count",+ dimension: "none",+ filters: [],+ chartType: "NUMBER",+ chartConfig: { type: "NUMBER" },+ },+ histogram: {+ name: "",+ description: "",+ view: "observations",+ measure: "latency",+ aggregation: "histogram",+ dimension: "none",+ filters: [],+ chartType: "HISTOGRAM",+ chartConfig: { type: "HISTOGRAM", bins: 25 },+ },+ "pivot with sort (edit-mode arrays)": {+ name: "My Pivot Widget",+ description: "A saved description",+ view: "observations",+ measure: "latency",+ aggregation: "avg",+ dimension: "environment",+ filters: [],+ chartType: "PIVOT_TABLE",+ metrics: [+ { measure: "latency", agg: "avg" },+ { measure: "count", agg: "count" },+ ],+ dimensions: [{ field: "environment" }, { field: "name" }],+ chartConfig: {+ type: "PIVOT_TABLE",+ row_limit: 50,+ defaultSort: { column: "avg_latency", order: "DESC" },+ },+ minVersion: 1,+ },+ "pivot with stale sort column dropped": {+ name: "Stale Sort Pivot",+ description: "desc",+ view: "observations",+ measure: "latency",+ aggregation: "avg",+ dimension: "environment",+ filters: [],+ chartType: "PIVOT_TABLE",+ metrics: [{ measure: "latency", agg: "avg" }],+ dimensions: [{ field: "environment" }],+ // sort references a metric that is no longer present -> must be dropped+ chartConfig: {+ type: "PIVOT_TABLE",+ row_limit: 100,+ defaultSort: { column: "sum_totalCost", order: "ASC" },+ },+ minVersion: 1,+ },+ "edit non-pivot single metric (arrays ignored)": {+ name: "Edited Widget",+ description: "Edited description",+ view: "observations",+ measure: "totalCost",+ aggregation: "sum",+ dimension: "environment",+ filters: [],+ chartType: "LINE_TIME_SERIES",+ metrics: [{ measure: "totalCost", agg: "sum" }],+ dimensions: [{ field: "environment" }],+ chartConfig: { type: "LINE_TIME_SERIES" },+ minVersion: 1,+ },+ // Exercises the filter double-transform path: stored view-space filters go+ // through normalizeStoredWidgetFiltersForEditor (on seed) and back through+ // mapWidgetUiTableFilterToView (on save). Parity holds because BOTH the+ // adapter and the legacy reconstruction apply the identical transforms.+ "line with a stored environment filter": {+ name: "",+ description: "",+ view: "observations",+ measure: "count",+ aggregation: "count",+ dimension: "none",+ filters: [+ {+ column: "environment",+ type: "stringOptions",+ operator: "any of",+ value: ["production"],+ },+ ],+ chartType: "LINE_TIME_SERIES",+ chartConfig: { type: "LINE_TIME_SERIES" },+ },+};++describe("widget form adapters round-trip parity", () => {+ it.each(Object.entries(fixtures))(+ "%s: toSavePayload(toDefaultValues(x)) matches the legacy save object",+ (_name, iv) => {+ expect(adapterSavePayload(iv)).toEqual(legacyReconstruct(iv));+ },+ );++ it("regular line create produces the exact legacy save shape", () => {+ expect(adapterSavePayload(fixtures["regular line (create)"])).toEqual({+ name: "Avg Latency (Observations)",+ description: "Shows the avg latency of Observations",+ view: "observations",+ dimensions: [],+ metrics: [{ measure: "latency", agg: "avg" }],+ filters: [],+ chartType: "LINE_TIME_SERIES",+ chartConfig: { type: "LINE_TIME_SERIES" },+ minVersion: 1,+ });+ });++ it("pivot save carries row_limit + sanitized defaultSort and drops stale sort", () => {+ const kept = adapterSavePayload(+ fixtures["pivot with sort (edit-mode arrays)"],+ );+ expect(kept.chartConfig).toEqual({+ type: "PIVOT_TABLE",+ row_limit: 50,+ defaultSort: { column: "avg_latency", order: "DESC" },+ });+ expect(kept.metrics).toEqual([+ { measure: "latency", agg: "avg" },+ { measure: "count", agg: "count" },+ ]);+ expect(kept.dimensions).toEqual([+ { field: "environment" },+ { field: "name" },+ ]);++ const dropped = adapterSavePayload(+ fixtures["pivot with stale sort column dropped"],+ );+ expect(dropped.chartConfig).toEqual({+ type: "PIVOT_TABLE",+ row_limit: 100,+ defaultSort: undefined,+ });+ });++ it("count + NUMBER save carries row_limit and count metric", () => {+ const payload = adapterSavePayload(fixtures["count measure big number"]);+ expect(payload.chartType).toBe("NUMBER");+ expect(payload.chartConfig).toEqual({ type: "NUMBER", row_limit: 100 });+ expect(payload.metrics).toEqual([{ measure: "count", agg: "count" }]);+ expect(payload.name).toBe("Count (Observations)");+ });+});++describe("toDefaultValues normalizes malformed stored/imported widgets", () => {+ it("heals a HISTOGRAM on the count measure to NUMBER (matches the old mount effect)", () => {+ const iv: WidgetInitialValues = {+ name: "Legacy Histogram",+ description: "d",+ view: "observations",+ measure: "count",+ aggregation: "histogram",+ dimension: "none",+ filters: [],+ chartType: "HISTOGRAM",+ chartConfig: { type: "HISTOGRAM", bins: 10 },+ minVersion: 1,+ };+ const values = toDefaultValues(iv, fixtureViewVersion(iv));+ expect(values.chart.type).toBe("NUMBER");+ expect(values.metrics).toEqual([+ { measure: "count", aggregation: "count" },+ ]);++ // And the save payload reflects the healed (valid) state.+ const payload = adapterSavePayload(iv);+ expect(payload.chartType).toBe("NUMBER");+ expect(payload.metrics).toEqual([{ measure: "count", agg: "count" }]);+ });++ it("heals a HISTOGRAM with a stored non-histogram aggregation to the histogram aggregation", () => {+ const iv: WidgetInitialValues = {+ name: "",+ description: "",+ view: "observations",+ measure: "latency",+ aggregation: "avg",+ dimension: "none",+ filters: [],+ chartType: "HISTOGRAM",+ chartConfig: { type: "HISTOGRAM", bins: 10 },+ };+ const values = toDefaultValues(iv, fixtureViewVersion(iv));+ expect(values.chart.type).toBe("HISTOGRAM");+ expect(values.metrics[0].aggregation).toBe("histogram");+ });++ it("drops a stored breakdown dimension on a NUMBER chart (matches the old breakdown-wipe effect)", () => {+ const iv: WidgetInitialValues = {+ name: "Big number with a stray dimension",+ description: "d",+ view: "observations",+ measure: "count",+ aggregation: "count",+ dimension: "environment",+ filters: [],+ chartType: "NUMBER",+ chartConfig: { type: "NUMBER" },+ minVersion: 1,+ };+ const values = toDefaultValues(iv, fixtureViewVersion(iv));+ expect(values.dimensions).toEqual([]);+ expect(adapterSavePayload(iv).dimensions).toEqual([]);+ });++ it("is a fixed point on a valid widget (normalizes to itself)", () => {+ const iv = fixtures["breakdown bar with dimension"];+ const once = toDefaultValues(iv, fixtureViewVersion(iv));+ expect(once.chart.type).toBe("VERTICAL_BAR");+ expect(once.dimensions).toEqual([{ field: "environment" }]);+ expect(once.metrics).toEqual([+ { measure: "totalCost", aggregation: "sum" },+ ]);+ });+});++describe("applyChartTypeChange dimension boundary", () => {+ const pivotWithDims: WidgetFormValues = {+ name: null,+ description: null,+ view: "observations",+ filters: [],+ metrics: [+ { measure: "latency", aggregation: "avg" },+ { measure: "count", aggregation: "count" },+ ],+ dimensions: [{ field: "environment" }, { field: "name" }],+ chart: {+ type: "PIVOT_TABLE",+ bins: 10,+ rowLimit: 100,+ sort: null,+ },+ };++ const barWithBreakdown: WidgetFormValues = {+ name: null,+ description: null,+ view: "observations",+ filters: [],+ metrics: [{ measure: "latency", aggregation: "avg" }],+ dimensions: [{ field: "environment" }],+ chart: { type: "VERTICAL_BAR", bins: 10, rowLimit: 100, sort: null },+ };++ it("pivot([environment, name]) -> vertical bar clears the breakdown to none", () => {+ const next = applyChartTypeChange(pivotWithDims, "VERTICAL_BAR", "v2");+ expect(next.chart.type).toBe("VERTICAL_BAR");+ expect(next.dimensions).toEqual([]);+ // non-pivot trims to a single metric+ expect(next.metrics).toEqual([{ measure: "latency", aggregation: "avg" }]);+ });++ it("vertical bar(breakdown=environment) -> pivot starts with empty row dimensions", () => {+ const next = applyChartTypeChange(barWithBreakdown, "PIVOT_TABLE", "v2");+ expect(next.chart.type).toBe("PIVOT_TABLE");+ expect(next.dimensions).toEqual([]);+ });++ it("vertical bar -> line keeps the breakdown dimension (within non-pivot)", () => {+ const next = applyChartTypeChange(+ barWithBreakdown,+ "LINE_TIME_SERIES",+ "v2",+ );+ expect(next.chart.type).toBe("LINE_TIME_SERIES");+ expect(next.dimensions).toEqual([{ field: "environment" }]);+ });+});++describe("save seam: editor-space filters map to view space (double-map)", () => {+ // The live path maps the SAME editor-space filters to view space twice, from+ // two independent seams: the resolver (validation) and toSavePayload (save).+ // The parity suite above bypasses the resolver, so exercise both mappings+ // here and assert they agree AND that the mapping is idempotent (a filter+ // already in view space maps to itself).+ const stored: WidgetInitialValues =+ fixtures["line with a stored environment filter"];++ it("resolver mapping and toSavePayload agree, and the mapping is idempotent", () => {+ const values = toDefaultValues(stored, fixtureViewVersion(stored));++ // Resolver seam: maps the form's editor-space filters to view space.+ const resolverMapped = mapWidgetUiTableFilterToView(+ values.view,+ values.filters,+ );++ // Save seam: toSavePayload maps the same editor-space filters independently.+ const suggestions = deriveWidgetSuggestions(values);+ const saved = toSavePayload(values, {+ suggestedName: suggestions.name,+ suggestedDescription: suggestions.description,+ effectiveSort: deriveEffectiveSort(values),+ });++ expect(saved.filters).toEqual(resolverMapped);+ expect(saved.filters.length).toBeGreaterThan(0);++ // Idempotency: mapping the already-mapped (view-space) filters again is a+ // no-op. This invariant is what lets the two seams double-map safely.+ expect(mapWidgetUiTableFilterToView(values.view, saved.filters)).toEqual(+ saved.filters,+ );+ });+});diff --git a/web/src/features/widgets/components/widgetFormSchema.clienttest.ts b/web/src/features/widgets/components/widgetFormSchema.clienttest.tsnew file mode 100644index 0000000000..abadbb9697--- /dev/null+++ b/web/src/features/widgets/components/widgetFormSchema.clienttest.ts@@ -0,0 +1,351 @@+import {+ deriveSaveReason,+ makeWidgetFormSchema,+ type WidgetFormValues,+} from "./widgetFormSchema";++/** A valid, minimal non-pivot line-chart widget on the observations view. */+const baseValues = (): WidgetFormValues => ({+ name: null,+ description: null,+ view: "observations",+ filters: [],+ metrics: [{ measure: "latency", aggregation: "avg" }],+ dimensions: [],+ chart: { type: "LINE_TIME_SERIES", bins: 10, rowLimit: 100, sort: null },+});++const parse = (values: WidgetFormValues, version: "v1" | "v2" = "v2") =>+ makeWidgetFormSchema(version).safeParse(values);++describe("makeWidgetFormSchema superRefine", () => {+ it("accepts a valid non-pivot line chart", () => {+ expect(parse(baseValues()).success).toBe(true);+ });++ it("accepts a valid histogram on a histogram-capable measure", () => {+ const result = parse({+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "histogram" }],+ chart: { type: "HISTOGRAM", bins: 20, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(true);+ });++ it("rejects HISTOGRAM on the count measure (not histogram-capable)", () => {+ const result = parse({+ ...baseValues(),+ metrics: [{ measure: "count", aggregation: "histogram" }],+ chart: { type: "HISTOGRAM", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("rejects HISTOGRAM when the aggregation is not histogram", () => {+ const result = parse({+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "avg" }],+ chart: { type: "HISTOGRAM", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("rejects the histogram aggregation on a non-histogram chart", () => {+ const result = parse({+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "histogram" }],+ chart: { type: "LINE_TIME_SERIES", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("rejects a breakdown dimension on a non-breakdown chart type", () => {+ const result = parse({+ ...baseValues(),+ dimensions: [{ field: "environment" }],+ chart: { type: "NUMBER", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("rejects more than one metric on a non-pivot chart", () => {+ const result = parse({+ ...baseValues(),+ metrics: [+ { measure: "latency", aggregation: "avg" },+ { measure: "totalCost", aggregation: "sum" },+ ],+ });+ expect(result.success).toBe(false);+ });++ it("rejects more than one dimension on a non-pivot breakdown chart", () => {+ const result = parse({+ ...baseValues(),+ dimensions: [{ field: "environment" }, { field: "name" }],+ chart: { type: "VERTICAL_BAR", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("accepts a pivot table with multiple metrics and dimensions", () => {+ const result = parse({+ ...baseValues(),+ metrics: [+ { measure: "latency", aggregation: "avg" },+ { measure: "count", aggregation: "count" },+ ],+ dimensions: [{ field: "environment" }, { field: "name" }],+ chart: {+ type: "PIVOT_TABLE",+ bins: 10,+ rowLimit: 50,+ sort: { column: "avg_latency", order: "DESC" },+ },+ });+ expect(result.success).toBe(true);+ });++ it("rejects a pivot table with an empty metrics array (zod .min(1))", () => {+ const result = parse({+ ...baseValues(),+ metrics: [],+ chart: { type: "PIVOT_TABLE", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("rejects a pivot table with more than the maximum metrics", () => {+ const result = parse({+ ...baseValues(),+ metrics: Array.from({ length: 11 }, () => ({+ measure: "latency",+ aggregation: "avg" as const,+ })),+ chart: { type: "PIVOT_TABLE", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("rejects a pivot table with more than the maximum dimensions", () => {+ const result = parse({+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "avg" }],+ dimensions: [+ { field: "environment" },+ { field: "name" },+ { field: "userId" },+ ],+ chart: { type: "PIVOT_TABLE", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });++ it("coerces string chart.bins / chart.rowLimit and enforces bounds", () => {+ const ok = parse({+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "histogram" }],+ chart: {+ type: "HISTOGRAM",+ bins: "25" as unknown as number,+ rowLimit: 100,+ sort: null,+ },+ });+ expect(ok.success).toBe(true);++ const tooManyBins = parse({+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "histogram" }],+ chart: { type: "HISTOGRAM", bins: 101, rowLimit: 100, sort: null },+ });+ expect(tooManyBins.success).toBe(false);+ });++ it("allows a pivot table with a trailing empty metric slot (>=1 non-empty)", () => {+ const result = parse({+ ...baseValues(),+ metrics: [+ { measure: "latency", aggregation: "avg" },+ { measure: "", aggregation: "sum" },+ ],+ chart: { type: "PIVOT_TABLE", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(true);+ });++ it("rejects a non-pivot chart with an empty measure", () => {+ const result = parse({+ ...baseValues(),+ metrics: [{ measure: "", aggregation: "count" }],+ chart: { type: "LINE_TIME_SERIES", bins: 10, rowLimit: 100, sort: null },+ });+ expect(result.success).toBe(false);+ });+});++describe("makeWidgetFormSchema superRefine issue paths", () => {+ // Guards against a silent path rename: each invariant must emit an issue at+ // the exact path the UI reads for its inline marker, with a real message.+ const issues = (values: WidgetFormValues) => {+ const result = parse(values);+ return result.success ? [] : result.error.issues;+ };+ const hasIssueAt = (values: WidgetFormValues, path: (string | number)[]) =>+ issues(values).some(+ (issue) =>+ JSON.stringify(issue.path) === JSON.stringify(path) &&+ typeof issue.message === "string" &&+ issue.message.length > 0,+ );++ it("HISTOGRAM on a non-histogram-capable measure -> issue at chart.type", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ metrics: [{ measure: "count", aggregation: "histogram" }],+ chart: { type: "HISTOGRAM", bins: 10, rowLimit: 100, sort: null },+ },+ ["chart", "type"],+ ),+ ).toBe(true);+ });++ it("HISTOGRAM with a non-histogram aggregation -> issue at metrics.0.aggregation", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "avg" }],+ chart: { type: "HISTOGRAM", bins: 10, rowLimit: 100, sort: null },+ },+ ["metrics", 0, "aggregation"],+ ),+ ).toBe(true);+ });++ it("histogram aggregation on a non-histogram chart -> issue at metrics.0.aggregation", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "histogram" }],+ },+ ["metrics", 0, "aggregation"],+ ),+ ).toBe(true);+ });++ it("breakdown dimension on a non-breakdown chart -> issue at dimensions", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ dimensions: [{ field: "environment" }],+ chart: { type: "NUMBER", bins: 10, rowLimit: 100, sort: null },+ },+ ["dimensions"],+ ),+ ).toBe(true);+ });++ it("non-pivot with two metrics -> issue at metrics", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ metrics: [+ { measure: "latency", aggregation: "avg" },+ { measure: "totalCost", aggregation: "sum" },+ ],+ },+ ["metrics"],+ ),+ ).toBe(true);+ });++ it("non-pivot with an empty measure -> issue at metrics.0.measure", () => {+ expect(+ hasIssueAt(+ { ...baseValues(), metrics: [{ measure: "", aggregation: "count" }] },+ ["metrics", 0, "measure"],+ ),+ ).toBe(true);+ });++ it("pivot with too many metrics -> issue at metrics", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ metrics: Array.from({ length: 11 }, () => ({+ measure: "latency",+ aggregation: "avg" as const,+ })),+ chart: { type: "PIVOT_TABLE", bins: 10, rowLimit: 100, sort: null },+ },+ ["metrics"],+ ),+ ).toBe(true);+ });++ it("pivot with too many dimensions -> issue at dimensions", () => {+ expect(+ hasIssueAt(+ {+ ...baseValues(),+ metrics: [{ measure: "latency", aggregation: "avg" }],+ dimensions: [+ { field: "environment" },+ { field: "name" },+ { field: "userId" },+ ],+ chart: { type: "PIVOT_TABLE", bins: 10, rowLimit: 100, sort: null },+ },+ ["dimensions"],+ ),+ ).toBe(true);+ });+});++describe("deriveSaveReason", () => {+ it("returns undefined when there are no errors", () => {+ expect(deriveSaveReason({})).toBeUndefined();+ });++ it("prefers metrics -> dimensions -> chart.type order", () => {+ expect(+ deriveSaveReason({+ metrics: { message: "metric problem" },+ dimensions: { message: "dimension problem" },+ chart: { type: { message: "chart problem" } },+ }),+ ).toBe("metric problem");+ expect(+ deriveSaveReason({+ dimensions: { message: "dimension problem" },+ chart: { type: { message: "chart problem" } },+ }),+ ).toBe("dimension problem");+ expect(+ deriveSaveReason({ chart: { type: { message: "chart problem" } } }),+ ).toBe("chart problem");+ });++ it("reads a nested metrics.0.aggregation message", () => {+ expect(+ deriveSaveReason({+ metrics: [{ aggregation: { message: "bad aggregation" } }],+ }),+ ).toBe("bad aggregation");+ });++ it("falls back to the first message anywhere for an unlisted path", () => {+ expect(+ deriveSaveReason({+ chart: { bins: { message: "bins out of range" } },+ }),+ ).toBe("bins out of range");+ });+});diff --git a/web/src/features/widgets/components/widgetFormSchema.ts b/web/src/features/widgets/components/widgetFormSchema.tsnew file mode 100644index 0000000000..025a1b6440--- /dev/null+++ b/web/src/features/widgets/components/widgetFormSchema.ts@@ -0,0 +1,730 @@+import { z } from "zod";+import startCase from "lodash/startCase";++import {+ DashboardWidgetChartType,+ singleFilter,+ type FilterState,+} from "@langfuse/shared";+import {+ getValidAggregationsForMeasureType,+ metricAggregations,+ requiresV2,+ viewDeclarations,+ views,+ type ViewVersion,+} from "@langfuse/shared/query";++import {+ mapWidgetUiTableFilterToView,+ normalizeStoredWidgetFiltersForEditor,+} from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";+import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";+import {+ buildWidgetDescription,+ buildWidgetName,+ sanitizePivotTableDefaultSort,+ type WidgetChartConfig,+} from "@/src/features/widgets/utils";+import {+ MAX_PIVOT_TABLE_DIMENSIONS,+ MAX_PIVOT_TABLE_METRICS,+} from "@/src/features/widgets/utils/pivot-table-utils";++/**+ * The set of widget chart types that accept a breakdown dimension. This mirrors+ * `chartTypes[].supportsBreakdown` in WidgetForm.tsx; WidgetForm imports+ * {@link widgetChartTypeSupportsBreakdown} so the two never drift. `NUMBER` and+ * `HISTOGRAM` are the two total-value charts that take no dimension.+ */+const BREAKDOWN_CAPABLE_CHART_TYPES = new Set<string>([+ "LINE_TIME_SERIES",+ "BAR_TIME_SERIES",+ "AREA_TIME_SERIES",+ "HORIZONTAL_BAR",+ "VERTICAL_BAR",+ "PIE",+ "PIVOT_TABLE",+]);++/** widgetChartTypeSupportsBreakdown is the single source of truth for whether a chart type takes a breakdown dimension. */+export function widgetChartTypeSupportsBreakdown(type: string): boolean {+ return BREAKDOWN_CAPABLE_CHART_TYPES.has(type);+}++/**+ * Pure function that resolves the correct aggregation and chart type given the+ * current selections and valid aggregation list. Returns null when no change is+ * needed.+ *+ * All constraints are resolved in a single pass so the output is a fixed point+ * (running the function again on its own output always returns null). This+ * prevents infinite React state-update loops when constraints conflict β e.g.+ * HISTOGRAM requires "histogram" aggregation but "count" measure forces "count".+ */+export function resolveAggregationAndChartType(params: {+ chartType: string;+ measure: string;+ currentAgg: string;+ validAggs: z.infer<typeof metricAggregations>[];+}): {+ aggregation?: z.infer<typeof metricAggregations>;+ chartType?: string;+} | null {+ const { chartType, measure, currentAgg, validAggs } = params;+ const supportsHistogram = validAggs.includes("histogram");++ let targetChart = chartType;+ let targetAgg = currentAgg as z.infer<typeof metricAggregations>;++ // HISTOGRAM chart needs a histogram-compatible measure+ if (targetChart === "HISTOGRAM") {+ if (!supportsHistogram) {+ targetChart = "NUMBER";+ } else {+ targetAgg = "histogram";+ }+ }++ // Non-HISTOGRAM chart can't keep histogram aggregation+ if (targetChart !== "HISTOGRAM" && targetAgg === "histogram") {+ targetAgg =+ measure === "count"+ ? "count"+ : ((validAggs[0] ?? "sum") as z.infer<typeof metricAggregations>);+ }++ // "count" measure only supports "count" aggregation. If this conflicts with+ // the chart type (e.g. HISTOGRAM requires "histogram"), bail the chart type+ // rather than creating an unresolvable conflict.+ if (measure === "count" && targetAgg !== "count") {+ if (targetChart === "HISTOGRAM") {+ targetChart = "NUMBER";+ }+ targetAgg = "count";+ }++ // Current aggregation not valid for the measure type+ if (!validAggs.includes(targetAgg)) {+ targetAgg = (validAggs[0] ?? "count") as z.infer<typeof metricAggregations>;+ }++ // Only return if something changed+ const result: {+ aggregation?: z.infer<typeof metricAggregations>;+ chartType?: string;+ } = {};+ if (targetChart !== chartType) result.chartType = targetChart;+ if (targetAgg !== currentAgg) result.aggregation = targetAgg;++ return Object.keys(result).length > 0 ? result : null;+}++/**+ * A single measure + aggregation pair, matching the save payload's `metrics[]`+ * element (minus the string `agg` alias). `measure` is intentionally NOT+ * `.min(1)`: a pivot table may carry a trailing empty "Add Metric" slot that the+ * user has not filled yet (matching the legacy form, which filtered empty slots+ * at save). The "at least one non-empty metric / no empty non-pivot metric"+ * rule lives in `superRefine`, and `toSavePayload` drops empty slots.+ */+const MetricFieldSchema = z.object({+ measure: z.string(),+ aggregation: metricAggregations,+});+type MetricField = z.infer<typeof MetricFieldSchema>;++/** A pivot-table default sort column + direction. `null` on the form means "no default sort". */+const SortFieldSchema = z.object({+ column: z.string().min(1),+ order: z.enum(["ASC", "DESC"]),+});+export type SortField = z.infer<typeof SortFieldSchema>;++/**+ * The unified, one-concept-one-field widget form schema. The dual+ * single-metric / pivot-metrics (and single-dimension / pivot-dimensions)+ * representation of the legacy form is collapsed into `metrics[]` and+ * `dimensions[]` arrays that already match the `onSave` payload shape.+ *+ * `chart` is a FLAT record (not a discriminated union): a union keyed on+ * `chart.type` would churn react-hook-form field arrays every time the chart+ * type changes. Instead the cross-field invariants live in `superRefine`.+ *+ * The factory is parameterised by `viewVersion` because the histogram+ * measure-capability check (invariant 1) reads the measure's type from the+ * version-specific view declaration.+ */+export function makeWidgetFormSchema(viewVersion: ViewVersion) {+ return z+ .object({+ // Blank (null) name/description means "use the live auto-suggestion";+ // see toSavePayload + NameField for the override-vs-suggestion model.+ name: z.string().nullable(),+ description: z.string().nullable(),+ view: views,+ filters: z.array(singleFilter),+ metrics: z.array(MetricFieldSchema).min(1),+ dimensions: z.array(z.object({ field: z.string() })),+ chart: z.object({+ type: z.enum(DashboardWidgetChartType),+ bins: z.coerce.number().int().min(1).max(100),+ rowLimit: z.coerce.number().int().min(0).max(1000),+ sort: SortFieldSchema.nullable(),+ }),+ })+ .superRefine((values, ctx) => {+ const isPivot = values.chart.type === "PIVOT_TABLE";+ const isHistogram = values.chart.type === "HISTOGRAM";+ const supportsBreakdown = widgetChartTypeSupportsBreakdown(+ values.chart.type,+ );++ // Invariant 3: a non-breakdown chart type cannot carry a dimension.+ if (!supportsBreakdown && values.dimensions.length > 0) {+ ctx.addIssue({+ code: "custom",+ path: ["dimensions"],+ message: "This chart type does not support a breakdown dimension.",+ });+ }++ // Invariant 4: pivot vs. non-pivot metric/dimension cardinality.+ if (isPivot) {+ const nonEmptyMetrics = values.metrics.filter(+ (m) => m.measure && m.measure !== "",+ );+ if (nonEmptyMetrics.length < 1) {+ ctx.addIssue({+ code: "custom",+ path: ["metrics"],+ message: "At least one metric is required for pivot tables.",+ });+ }+ if (values.metrics.length > MAX_PIVOT_TABLE_METRICS) {+ ctx.addIssue({+ code: "custom",+ path: ["metrics"],+ message: `A pivot table supports at most ${MAX_PIVOT_TABLE_METRICS} metrics.`,+ });+ }+ if (values.dimensions.length > MAX_PIVOT_TABLE_DIMENSIONS) {+ ctx.addIssue({+ code: "custom",+ path: ["dimensions"],+ message: `A pivot table supports at most ${MAX_PIVOT_TABLE_DIMENSIONS} dimensions.`,+ });+ }+ } else {+ if (values.metrics.length !== 1) {+ ctx.addIssue({+ code: "custom",+ path: ["metrics"],+ message: "This chart type requires exactly one metric.",+ });+ } else if (!values.metrics[0].measure) {+ ctx.addIssue({+ code: "custom",+ path: ["metrics", 0, "measure"],+ message: "Select a measure.",+ });+ }+ if (values.dimensions.length > 1) {+ ctx.addIssue({+ code: "custom",+ path: ["dimensions"],+ message:+ "This chart type supports at most one breakdown dimension.",+ });+ }+ }++ // Invariant 1: a HISTOGRAM needs a single, histogram-capable metric using+ // the histogram aggregation. This is the histogram-incompatible case as a+ // REAL validation error rather than a silent revert.+ if (isHistogram) {+ if (values.metrics.length !== 1) {+ ctx.addIssue({+ code: "custom",+ path: ["chart", "type"],+ message: "A histogram uses a single metric.",+ });+ } else {+ const metric = values.metrics[0];+ if (metric.aggregation !== "histogram") {+ ctx.addIssue({+ code: "custom",+ path: ["metrics", 0, "aggregation"],+ message: "A histogram requires the histogram aggregation.",+ });+ }+ const measureType =+ viewDeclarations[viewVersion][values.view]?.measures?.[+ metric.measure+ ]?.type;+ const histogramCapable =+ getValidAggregationsForMeasureType(measureType).includes(+ "histogram",+ ) && metric.measure !== "count";+ if (!histogramCapable) {+ ctx.addIssue({+ code: "custom",+ path: ["chart", "type"],+ message: "This measure cannot be shown as a histogram.",+ });+ }+ }+ } else if (values.metrics.some((m) => m.aggregation === "histogram")) {+ // Invariant 2: outside a histogram chart no metric may use the+ // histogram aggregation.+ ctx.addIssue({+ code: "custom",+ path: ["metrics", 0, "aggregation"],+ message:+ "The histogram aggregation is only valid for histogram charts.",+ });+ }+ });+}++type WidgetFormSchema = ReturnType<typeof makeWidgetFormSchema>;+export type WidgetFormValues = z.infer<WidgetFormSchema>;++/**+ * The shape WidgetForm receives as `initialValues` β the legacy prop contract,+ * kept verbatim so create/edit pages need no changes to what they pass.+ */+export type WidgetInitialValues = {+ name: string;+ description: string;+ view: z.infer<typeof views>;+ measure: string;+ aggregation: z.infer<typeof metricAggregations>;+ dimension: string;+ filters?: FilterState;+ chartType: WidgetFormValues["chart"]["type"];+ chartConfig?: WidgetChartConfig;+ metrics?: { measure: string; agg: string }[];+ dimensions?: { field: string }[];+ minVersion?: number;+};++/** The exact object shape passed to `onSave` β unchanged from the legacy form. */+export type WidgetSavePayload = {+ name: string;+ description: string;+ view: string;+ dimensions: { field: string }[];+ metrics: { measure: string; agg: string }[];+ filters: FilterState;+ chartType: WidgetFormValues["chart"]["type"];+ chartConfig: WidgetChartConfig;+ minVersion: number;+};++/**+ * The frozen, view-shape-derived base minVersion for a widget, computed from the+ * `initialValues` at mount. Mirrors the legacy `initialWidgetRequiresV2 ? 2 :+ * (initialValues.minVersion ?? 1)`.+ */+export function deriveWidgetBaseMinVersion(+ initialValues: WidgetInitialValues,+): number {+ const initialWidgetRequiresV2 = requiresV2({+ view: initialValues.view,+ dimensions:+ initialValues.dimensions ??+ (initialValues.dimension && initialValues.dimension !== "none"+ ? [{ field: initialValues.dimension }]+ : []),+ measures: initialValues.metrics?.map((metric) => ({+ measure: metric.measure,+ })) ?? [{ measure: initialValues.measure }],+ filters: initialValues.filters ?? [],+ });+ return initialWidgetRequiresV2 ? 2 : (initialValues.minVersion ?? 1);+}++/**+ * Derives the effective view version (query-engine v1/v2) from the current view+ * plus the frozen base minVersion and the beta flag. Mirrors the legacy+ * `initialWidgetRequiresV2 || widgetMinVersion >= 2 || (isBetaEnabled && view+ * !== "traces")`. Traces has no v2-only fields, so beta never promotes it.+ */+export function resolveWidgetViewVersion(params: {+ view: z.infer<typeof views>;+ baseMinVersion: number;+ isBetaEnabled: boolean;+}): ViewVersion {+ return params.baseMinVersion >= 2 ||+ (params.isBetaEnabled && params.view !== "traces")+ ? "v2"+ : "v1";+}++/** Sanitized pivot default sort for the current metric/dimension selection, or undefined when the stored sort no longer applies. */+export function deriveEffectiveSort(+ values: WidgetFormValues,+): SortField | undefined {+ if (values.chart.type !== "PIVOT_TABLE") return undefined;+ return sanitizePivotTableDefaultSort(values.chart.sort ?? undefined, {+ dimensions: values.dimensions.filter((d) => d.field && d.field !== "none"),+ metrics: values.metrics+ .filter((m) => m.measure && m.measure !== "")+ .map((m) => ({ measure: m.measure, agg: m.aggregation })),+ });+}++/**+ * Live auto-suggested name/description for the current selection. Ports the two+ * legacy auto-name/description effects (WidgetForm.tsx :1475 / :1517). The+ * description uses the UI-space editor filters (`values.filters`), matching the+ * legacy behaviour.+ */+export function deriveWidgetSuggestions(values: WidgetFormValues): {+ name: string;+ description: string;+} {+ const isPivot = values.chart.type === "PIVOT_TABLE";+ const validMetrics = values.metrics.filter(+ (m) => m.measure && m.measure !== "",+ );+ const metricNames =+ isPivot && validMetrics.length > 0+ ? validMetrics.map((m) => `${m.aggregation}_${m.measure}`)+ : undefined;+ const dimensionForNaming =+ isPivot && values.dimensions.length > 0+ ? values.dimensions.map((d) => startCase(d.field)).join(" and ")+ : (values.dimensions[0]?.field ?? "none");++ const aggregation = isPivot+ ? "count"+ : (values.metrics[0]?.aggregation ?? "count");+ const measure = isPivot ? "count" : (values.metrics[0]?.measure ?? "count");++ return {+ name: buildWidgetName({+ aggregation,+ measure,+ dimension: dimensionForNaming,+ view: values.view,+ metrics: metricNames,+ isMultiMetric: isPivot && validMetrics.length > 0,+ }),+ description: buildWidgetDescription({+ aggregation,+ measure,+ dimension: dimensionForNaming,+ view: values.view,+ filters: values.filters,+ metrics: metricNames,+ isMultiMetric: isPivot && validMetrics.length > 0,+ }),+ };+}++/** effectiveWidgetName resolves the override-vs-suggestion name used for save + query. A blank/whitespace override falls back to the live suggestion. */+export function effectiveWidgetName(+ override: string | null,+ suggested: string,+): string {+ return override && override.trim().length > 0 ? override : suggested;+}++/**+ * normalizeWidgetFormValues heals a candidate form state into a VALID one using+ * the same pure logic the legacy mount/measure/chart-type effects applied:+ *+ * - non-pivot charts keep a single metric and at most one dimension;+ * - the (chart type, leading aggregation) pair is resolved via+ * {@link resolveAggregationAndChartType} β e.g. a HISTOGRAM on a+ * non-histogram-capable measure falls back to NUMBER, a stranded histogram+ * aggregation resolves to a real one;+ * - a breakdown dimension the (possibly healed) chart type cannot carry is+ * dropped.+ *+ * `resolveAggregationAndChartType` is a fixed point, so a VALID widget+ * normalizes to itself (preserving save parity); an INVALID stored/imported+ * widget heals exactly as the old mount effects would have. This replaces those+ * effects at the seed/cascade seams so no invalid state can mount or arise from+ * a view change β with no `useEffect`.+ */+export function normalizeWidgetFormValues(+ values: WidgetFormValues,+ viewVersion: ViewVersion,+): WidgetFormValues {+ const isPivot = values.chart.type === "PIVOT_TABLE";+ let metrics = values.metrics;+ let dimensions = values.dimensions;++ if (!isPivot) {+ if (metrics.length > 1) metrics = metrics.slice(0, 1);+ if (dimensions.length > 1) dimensions = dimensions.slice(0, 1);+ }++ const measure = metrics[0]?.measure ?? "count";+ const currentAgg = metrics[0]?.aggregation ?? "count";+ const measureType =+ viewDeclarations[viewVersion][values.view]?.measures?.[measure]?.type;+ const resolved = resolveAggregationAndChartType({+ chartType: values.chart.type,+ measure,+ currentAgg,+ validAggs: getValidAggregationsForMeasureType(measureType),+ });++ let chartType = values.chart.type;+ if (resolved?.chartType) {+ chartType = resolved.chartType as WidgetFormValues["chart"]["type"];+ }+ if (resolved?.aggregation && metrics.length > 0) {+ const healedAgg = resolved.aggregation;+ metrics = metrics.map((m, i) =>+ i === 0 ? { ...m, aggregation: healedAgg } : m,+ );+ }++ if (!widgetChartTypeSupportsBreakdown(chartType)) {+ dimensions = [];+ }++ return {+ ...values,+ metrics,+ dimensions,+ chart: { ...values.chart, type: chartType },+ };+}++/**+ * applyChartTypeChange heals the form when the chart type changes.+ *+ * Crossing the pivot β non-pivot boundary RESETS `dimensions` to `[]`: the+ * single breakdown dimension (non-pivot) and the pivot row dimensions are+ * distinct concepts that the legacy form kept as separate state, so neither+ * carries across the boundary β a breakdown defaults to "none" when entering a+ * non-pivot chart, and a pivot starts with empty row dimensions. Switching+ * WITHIN the non-pivot breakdown charts (e.g. bar β line) keeps the breakdown+ * dimension. The result is then run through {@link normalizeWidgetFormValues}+ * for the aggregation/chart-type resolution and unsupported-dimension wipe.+ */+export function applyChartTypeChange(+ values: WidgetFormValues,+ newType: WidgetFormValues["chart"]["type"],+ viewVersion: ViewVersion,+): WidgetFormValues {+ const crossesPivotBoundary =+ (values.chart.type === "PIVOT_TABLE") !== (newType === "PIVOT_TABLE");+ return normalizeWidgetFormValues(+ {+ ...values,+ dimensions: crossesPivotBoundary ? [] : values.dimensions,+ chart: { ...values.chart, type: newType },+ },+ viewVersion,+ );+}++/**+ * toDefaultValues maps the legacy `initialValues` prop into the unified form+ * values, replacing the 17 legacy useState initializers (including+ * pivot-vs-single metric/dimension seeding and the pivot default-sort seed).+ * The seeded values are normalized ({@link normalizeWidgetFormValues}) so a+ * malformed stored/imported widget mounts VALID β reproducing the legacy+ * mount-time resolve + breakdown-wipe effects without an effect.+ */+export function toDefaultValues(+ initialValues: WidgetInitialValues,+ viewVersion: ViewVersion,+): WidgetFormValues {+ const isPivot = initialValues.chartType === "PIVOT_TABLE";++ const metrics: MetricField[] =+ isPivot && initialValues.metrics?.length+ ? initialValues.metrics.map((m) => ({+ measure: m.measure,+ aggregation: m.agg as z.infer<typeof metricAggregations>,+ }))+ : [+ {+ measure: initialValues.measure,+ aggregation: initialValues.aggregation,+ },+ ];++ const dimensions = isPivot+ ? initialValues.dimensions?.length+ ? initialValues.dimensions.map((d) => ({ field: d.field }))+ : []+ : initialValues.dimension && initialValues.dimension !== "none"+ ? [{ field: initialValues.dimension }]+ : [];++ const sort: SortField | null = isPivot+ ? (sanitizePivotTableDefaultSort(initialValues.chartConfig?.defaultSort, {+ dimensions: initialValues.dimensions ?? [],+ metrics:+ initialValues.metrics ??+ (initialValues.measure && initialValues.aggregation+ ? [+ {+ measure: initialValues.measure,+ agg: initialValues.aggregation,+ },+ ]+ : []),+ }) ?? null)+ : null;++ return normalizeWidgetFormValues(+ {+ // A blank initial name/description is "auto" (null β show the live+ // suggestion); a non-empty one is an explicit override that sticks. This+ // is how edit mode seeds the saved name so it does not auto-update.+ // Blank = auto is BY DESIGN (the "blank = auto" model): a widget saved+ // with an empty description renders and saves the live auto-suggestion,+ // so an emptied description regenerating on a later edit is intentional,+ // not a bug.+ name:+ initialValues.name && initialValues.name.length > 0+ ? initialValues.name+ : null,+ description:+ initialValues.description && initialValues.description.length > 0+ ? initialValues.description+ : null,+ view: initialValues.view,+ filters: normalizeStoredWidgetFiltersForEditor(+ initialValues.view,+ initialValues.filters ?? [],+ ).editorFilters,+ metrics,+ dimensions,+ chart: {+ type: initialValues.chartType,+ bins: initialValues.chartConfig?.bins ?? 10,+ rowLimit: initialValues.chartConfig?.row_limit ?? 100,+ sort,+ },+ },+ viewVersion,+ );+}++/**+ * toSavePayload folds the form values into the exact `onSave` object the legacy+ * `handleSaveWidget` produced (WidgetForm.tsx :1430-1471), byte for byte:+ * name/description fall back to the live suggestions, filters are mapped into+ * view space, the per-type chartConfig is rebuilt, and `minVersion` is derived+ * from the query shape via `requiresV2`.+ */+export function toSavePayload(+ values: WidgetFormValues,+ params: {+ suggestedName: string;+ suggestedDescription: string;+ effectiveSort: SortField | undefined;+ },+): WidgetSavePayload {+ const isPivot = values.chart.type === "PIVOT_TABLE";+ const validMetrics = values.metrics.filter(+ (m) => m.measure && m.measure !== "",+ );++ const saveDimensions = isPivot+ ? values.dimensions.map((d) => ({ field: d.field }))+ : values.dimensions.length > 0 && values.dimensions[0].field !== "none"+ ? [{ field: values.dimensions[0].field }]+ : [];++ const saveMetrics = isPivot+ ? validMetrics.map((m) => ({ measure: m.measure, agg: m.aggregation }))+ : [+ {+ measure: values.metrics[0].measure,+ agg: values.metrics[0].aggregation,+ },+ ];++ // The save seam of the editor->view filter mapping (the resolver is the+ // other). mapWidgetUiTableFilterToView MUST stay idempotent so the two seams+ // map the same editor-space filters to identical, stable view-space filters.+ const normalizedFilters = mapWidgetUiTableFilterToView(+ values.view,+ values.filters,+ );++ const chartType = values.chart.type;+ const chartConfig: WidgetChartConfig = isTimeSeriesChart(chartType)+ ? { type: chartType }+ : chartType === "HISTOGRAM"+ ? { type: chartType, bins: values.chart.bins }+ : chartType === "PIVOT_TABLE"+ ? {+ type: chartType,+ row_limit: values.chart.rowLimit,+ defaultSort: params.effectiveSort ?? undefined,+ }+ : { type: chartType, row_limit: values.chart.rowLimit };++ return {+ name: effectiveWidgetName(values.name, params.suggestedName),+ description: effectiveWidgetName(+ values.description,+ params.suggestedDescription,+ ),+ view: values.view,+ dimensions: saveDimensions,+ metrics: saveMetrics,+ filters: normalizedFilters,+ chartType,+ chartConfig,+ minVersion: requiresV2({+ view: values.view,+ dimensions: saveDimensions,+ measures: saveMetrics.map((m) => ({ measure: m.measure })),+ filters: normalizedFilters,+ })+ ? 2+ : 1,+ };+}++/** Recursively finds the first non-empty `message` string in a react-hook-form error tree. */+function firstFormErrorMessage(node: unknown): string | undefined {+ if (!node || typeof node !== "object") return undefined;+ const message = (node as { message?: unknown }).message;+ if (typeof message === "string" && message.length > 0) return message;+ for (const key of Object.keys(node as Record<string, unknown>)) {+ // `ref`/`type` are react-hook-form leaf metadata, not nested errors.+ if (key === "ref" || key === "type" || key === "message") continue;+ const found = firstFormErrorMessage((node as Record<string, unknown>)[key]);+ if (found) return found;+ }+ return undefined;+}++/**+ * deriveSaveReason picks the message to show next to a disabled Save button. It+ * prefers the metric β dimension β chart-type messages (the fields with inline+ * markers) for a stable, predictable order, then falls back to the FIRST+ * message anywhere in the error tree so even an otherwise-unsurfaced invalid+ * path explains why Save is disabled instead of leaving it silently greyed out.+ */+export function deriveSaveReason(+ errors: Record<string, any>,+): string | undefined {+ const chartTypeError: string | undefined = errors.chart?.type?.message;+ const metricsError: string | undefined =+ errors.metrics?.message ??+ errors.metrics?.[0]?.measure?.message ??+ errors.metrics?.[0]?.aggregation?.message;+ const dimensionsError: string | undefined = errors.dimensions?.message;+ return (+ metricsError ??+ dimensionsError ??+ chartTypeError ??+ firstFormErrorMessage(errors)+ );+}diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsxindex d881866212..1a365e016b 100644--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx@@ -98,6 +98,9 @@ export default function EditWidget() {>{!isWidgetLoading && widgetData ? (<WidgetForm+ // Remount when the edited widget changes so its loaded values seed+ // the form defaults once, rather than syncing via an effect.+ key={widgetId}projectId={projectId}widgetId={widgetId}onSave={handleUpdateWidget}diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsxindex bac75d70a6..ac3e0f4902 100644--- a/web/src/pages/project/[projectId]/widgets/new.tsx+++ b/web/src/pages/project/[projectId]/widgets/new.tsx@@ -89,6 +89,12 @@ export default function NewWidget() {}}><WidgetForm+ // No `key` on the beta flag: WidgetForm derives viewVersion (and its+ // available views/measures/filter columns) reactively from isBetaEnabled+ // + the selected view, so a live beta toggle re-derives them without a+ // remount β preserving the in-progress form. The only tradeoff is that+ // an untouched form's default view no longer auto-switches on toggle;+ // the initial mount still seeds the beta-aware default view below.projectId={projectId}onSave={handleSaveWidget}initialValues={{