πͺ’ 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
fix(widgets): derive minVersion from widget shape (#15655)
Valery Meleshkin1f47c8056ff5
diff --git a/packages/shared/src/server/services/DashboardService/DashboardService.ts b/packages/shared/src/server/services/DashboardService/DashboardService.tsindex 76c0b9809e..9b043891d1 100644--- a/packages/shared/src/server/services/DashboardService/DashboardService.ts+++ b/packages/shared/src/server/services/DashboardService/DashboardService.ts@@ -4,6 +4,8 @@ import {LangfuseNotFoundError,type OrderByState,} from "../../../";+import { InvalidRequestError } from "../../../errors";+import { env } from "../../../env";import {CreateWidgetInput,WidgetDomain,@@ -13,9 +15,77 @@ import {DashboardDomainSchema,WidgetDomainSchema,DashboardDefinitionSchema,+ dashboardWidgetViewToQueryView,} from "./types";import { z } from "zod";import { singleFilter } from "../../../";+import {+ getValidAggregationsForMeasureType,+ getViewDeclaration,+ requiresV2,+} from "../../../features/query";++type WidgetQueryShape = Parameters<typeof requiresV2>[0];++/**+ * `minVersion` is the lowest query-engine version that can represent a widget+ * definition. It is derived from the definition, never requested by a caller.+ * Same-view updates retain an already-persisted floor and promote it when the+ * updated definition requires v2.+ */+export const resolveDashboardWidgetMinVersion = (+ shape: WidgetQueryShape,+ persistedMinVersion?: number,+) => {+ const maxVersion = env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "legacy" ? 1 : 2;+ const requiredVersion = requiresV2(shape) ? 2 : 1;++ if (requiredVersion > maxVersion) {+ throw new InvalidRequestError(+ "This widget uses v2-only fields, but the current deployment only supports legacy widget queries",+ );+ }++ return Math.min(+ Math.max(persistedMinVersion ?? 1, requiredVersion),+ maxVersion,+ );+};++const toWidgetQueryShape = (input: CreateWidgetInput): WidgetQueryShape => ({+ view: dashboardWidgetViewToQueryView[input.view],+ dimensions: input.dimensions,+ measures: input.metrics,+ filters: input.filters,+});++const validateDashboardWidgetQuery = (+ input: CreateWidgetInput,+ minVersion: number,+) => {+ const view = dashboardWidgetViewToQueryView[input.view];+ const declaration = getViewDeclaration(view, minVersion >= 2 ? "v2" : "v1");++ for (const metric of input.metrics) {+ const measure = declaration.measures[metric.measure];+ if (!measure) continue;+ const validAggregations = getValidAggregationsForMeasureType(measure.type);+ if (!validAggregations.some((aggregation) => aggregation === metric.agg)) {+ throw new InvalidRequestError(+ `Aggregation "${metric.agg}" is not valid for measure "${metric.measure}" (type: ${measure.type}). Valid aggregations: ${validAggregations.join(", ")}`,+ );+ }+ }++ const hiddenDimensions = input.dimensions.filter(+ ({ field }) => declaration.dimensions[field]?.uiHidden,+ );+ if (hiddenDimensions.length > 0) {+ throw new InvalidRequestError(+ `Dimensions not available for widgets: ${hiddenDimensions.map(({ field }) => field).join(", ")}`,+ );+ }+};export class DashboardService {/**@@ -295,6 +365,10 @@ export class DashboardService {input: CreateWidgetInput,userId?: string,): Promise<WidgetDomain> {+ const minVersion = resolveDashboardWidgetMinVersion(+ toWidgetQueryShape(input),+ );+ validateDashboardWidgetQuery(input, minVersion);const newWidget = await prisma.dashboardWidget.create({data: {name: input.name,@@ -306,7 +380,7 @@ export class DashboardService {filters: input.filters,chartType: input.chartType,chartConfig: input.chartConfig,- minVersion: input.minVersion ?? 1,+ minVersion,createdBy: userId,updatedBy: userId,},@@ -351,6 +425,19 @@ export class DashboardService {input: CreateWidgetInput,userId?: string,): Promise<WidgetDomain> {+ const existingWidget = await prisma.dashboardWidget.findFirst({+ where: { id: widgetId, projectId },+ select: { minVersion: true, view: true },+ });+ const persistedMinVersion =+ existingWidget && existingWidget.view === input.view+ ? existingWidget.minVersion+ : undefined;+ const minVersion = resolveDashboardWidgetMinVersion(+ toWidgetQueryShape(input),+ persistedMinVersion,+ );+ validateDashboardWidgetQuery(input, minVersion);const updatedWidget = await prisma.dashboardWidget.update({where: {id: widgetId,@@ -365,9 +452,7 @@ export class DashboardService {filters: input.filters,chartType: input.chartType,chartConfig: input.chartConfig,- ...(input.minVersion !== undefined- ? { minVersion: input.minVersion }- : {}),+ minVersion,updatedBy: userId,},});@@ -445,7 +530,15 @@ export class DashboardService {`Source widget ${sourceWidgetId} not found`,);}-+ const sourceWidgetDomain = WidgetDomainSchema.parse({+ ...sourceWidget,+ owner: "LANGFUSE",+ });+ const minVersion = resolveDashboardWidgetMinVersion(+ toWidgetQueryShape(sourceWidgetDomain),+ sourceWidgetDomain.minVersion,+ );+ validateDashboardWidgetQuery(sourceWidgetDomain, minVersion);// Duplicate widget and update dashboard definition atomicallyreturn prisma.$transaction(async (tx) => {// 1. create duplicate in project scope@@ -459,7 +552,7 @@ export class DashboardService {filters: sourceWidget.filters ?? [],chartType: sourceWidget.chartType,chartConfig: sourceWidget.chartConfig ?? {},- minVersion: sourceWidget.minVersion,+ minVersion,projectId, // project ownedcreatedBy: userId,updatedBy: userId,diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.tsindex 4e14a07050..248781129a 100644--- a/packages/shared/src/server/services/DashboardService/types.ts+++ b/packages/shared/src/server/services/DashboardService/types.ts@@ -1,6 +1,25 @@import { DashboardWidgetChartType, DashboardWidgetViews } from "@prisma/client";import { z } from "zod";import { singleFilter } from "../../../";+import { type views } from "../../../features/query";++/** Maps the persisted Prisma enum to the query model's public view id. */+export const dashboardWidgetViewToQueryView = {+ [DashboardWidgetViews.TRACES]: "traces",+ [DashboardWidgetViews.OBSERVATIONS]: "observations",+ [DashboardWidgetViews.SCORES_NUMERIC]: "scores-numeric",+ [DashboardWidgetViews.SCORES_BOOLEAN]: "scores-boolean",+ [DashboardWidgetViews.SCORES_CATEGORICAL]: "scores-categorical",+} as const satisfies Record<DashboardWidgetViews, z.infer<typeof views>>;++/** Maps the query model's public view id to the persisted Prisma enum. */+export const queryViewToDashboardWidgetView = {+ traces: DashboardWidgetViews.TRACES,+ observations: DashboardWidgetViews.OBSERVATIONS,+ "scores-numeric": DashboardWidgetViews.SCORES_NUMERIC,+ "scores-boolean": DashboardWidgetViews.SCORES_BOOLEAN,+ "scores-categorical": DashboardWidgetViews.SCORES_CATEGORICAL,+} as const satisfies Record<z.infer<typeof views>, DashboardWidgetViews>;export const BaseTimeSeriesChartConfig = z.object({});export const BaseTotalValueChartConfig = z.object({@@ -142,6 +161,7 @@ export const WidgetDomainSchema = z.object({filters: z.array(singleFilter),chartType: z.enum(DashboardWidgetChartType),chartConfig: ChartConfigSchema,+ // Lowest query-engine version required by the persisted widget definition.minVersion: z.number().int().default(1),owner: OwnerEnum,});@@ -156,7 +176,6 @@ export const CreateWidgetInputSchema = z.object({filters: z.array(singleFilter),chartType: z.enum(DashboardWidgetChartType),chartConfig: ChartConfigSchema,- minVersion: z.number().int().optional(),});// Define the widget list responsediff --git a/web/src/__tests__/server/dashboard-widget-version.servertest.ts b/web/src/__tests__/server/dashboard-widget-version.servertest.tsindex f2599f9ab8..6f7f35c320 100644--- a/web/src/__tests__/server/dashboard-widget-version.servertest.ts+++ b/web/src/__tests__/server/dashboard-widget-version.servertest.ts@@ -3,6 +3,7 @@ import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import { DashboardService } from "@langfuse/shared/src/server";import { DashboardWidgetViews } from "@langfuse/shared/src/db";import { prisma } from "@langfuse/shared/src/db";+import { env as sharedEnv } from "@langfuse/shared/src/env";import {LANGFUSE_HOME_DASHBOARD_DEFINITION,LANGFUSE_HOME_DASHBOARD_ID,@@ -20,6 +21,7 @@ describe("dashboard widget minVersion", () => {let projectId: string;let orgId: string;let userId: string;+ const originalWriteMode = sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE;beforeAll(async () => {const org = await createOrgProjectAndApiKey();@@ -44,7 +46,11 @@ describe("dashboard widget minVersion", () => {});});- function makeCaller() {+ afterEach(() => {+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ function makeCaller(v4BetaEnabled = false) {const session: Session = {expires: "1",user: {@@ -83,6 +89,7 @@ describe("dashboard widget minVersion", () => {experimentsV4Enabled: false,searchBar: false,},+ v4BetaEnabled,admin: true,},environment: {} as any,@@ -172,6 +179,19 @@ describe("dashboard widget minVersion", () => {);});+ it("rejects v2 widget shapes at the tRPC boundary on a legacy deployment", async () => {+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";++ await expect(+ makeCaller().dashboardWidgets.create({+ ...baseWidgetInput,+ view: "observations",+ projectId,+ metrics: [{ measure: "traceId", agg: "uniq" }],+ }),+ ).rejects.toThrow(/v2-only fields/i);+ });+describe("observations release filter mapping", () => {it("keeps legacy observations Release filters on traceRelease for v1 compatibility", () => {expect(@@ -217,37 +237,41 @@ describe("dashboard widget minVersion", () => {// ββ Service layer tests βββββββββββββββββββββββββββββββββββββββββββββdescribe("DashboardService", () => {- it("should default minVersion to 1 when not provided", async () => {+ it("persists v1 shapes and rejects v2 creates and updates on legacy deployments", async () => {+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ const v2Input = {+ ...baseWidgetInput,+ metrics: [{ measure: "traceId", agg: "uniq" }],+ };++ await expect(+ DashboardService.createWidget(projectId, v2Input, userId),+ ).rejects.toThrow(/v2-only fields/i);+const widget = await DashboardService.createWidget(projectId,baseWidgetInput,userId,);-expect(widget.minVersion).toBe(1);++ await expect(+ DashboardService.updateWidget(projectId, widget.id, v2Input, userId),+ ).rejects.toThrow(/v2-only fields/i);});- it("should persist minVersion=2 when explicitly provided", async () => {+ it("derives v2, preserves it on dual writes, and heals it on legacy", async () => {const widget = await DashboardService.createWidget(projectId,- { ...baseWidgetInput, minVersion: 2 },+ {+ ...baseWidgetInput,+ metrics: [{ measure: "traceId", agg: "uniq" }],+ },userId,);expect(widget.minVersion).toBe(2);- const fetched = await DashboardService.getWidget(widget.id, projectId);- expect(fetched).not.toBeNull();- expect(fetched!.minVersion).toBe(2);- });-- it("should preserve minVersion when updating without specifying it", async () => {- const widget = await DashboardService.createWidget(- projectId,- { ...baseWidgetInput, minVersion: 2 },- userId,- );-const updated = await DashboardService.updateWidget(projectId,widget.id,@@ -255,25 +279,29 @@ describe("dashboard widget minVersion", () => {userId,);- expect(updated.minVersion).toBe(2);- expect(updated.name).toBe("Updated Widget");- });-- it("should allow changing minVersion on update", async () => {- const widget = await DashboardService.createWidget(- projectId,- { ...baseWidgetInput, minVersion: 1 },- userId,- );+ expect(updated).toMatchObject({+ minVersion: 2,+ name: "Updated Widget",+ });- const updated = await DashboardService.updateWidget(+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ const healed = await DashboardService.updateWidget(projectId,widget.id,- { ...baseWidgetInput, minVersion: 2 },+ baseWidgetInput,userId,);+ expect(healed.minVersion).toBe(1);+ });- expect(updated.minVersion).toBe(2);+ it("derives minVersion from the shape instead of v4 session state", async () => {+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ const result = await makeCaller(true).dashboardWidgets.create({+ ...baseWidgetInput,+ view: "observations",+ projectId,+ });+ expect(result.widget.minVersion).toBe(1);});it("should preserve minVersion when copying widget to project", async () => {@@ -553,7 +581,6 @@ describe("dashboard widget minVersion", () => {filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,});const fetched = await caller.dashboardWidgets.get({@@ -577,7 +604,6 @@ describe("dashboard widget minVersion", () => {filters: [],chartType: "HISTOGRAM",chartConfig: { type: "HISTOGRAM", bins: 10 },- minVersion: 2,}),).rejects.toThrow(/not valid for measure/);});@@ -594,7 +620,6 @@ describe("dashboard widget minVersion", () => {filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,});expect(result.success).toBe(true);@@ -612,7 +637,6 @@ describe("dashboard widget minVersion", () => {filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,});await expect(@@ -627,7 +651,6 @@ describe("dashboard widget minVersion", () => {filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,}),).rejects.toThrow(/not valid for measure/);});@@ -659,7 +682,7 @@ describe("dashboard widget minVersion", () => {["parentObservationId", true],["name", false],])(- "create with dimension '%s' on v2 observations β rejected=%s",+ "create with dimension '%s' on shape-required v2 observations β rejected=%s",async (field, shouldReject) => {const caller = makeCaller();const promise = caller.dashboardWidgets.create({@@ -668,11 +691,10 @@ describe("dashboard widget minVersion", () => {description: `${field} dimension on v2`,view: "observations",dimensions: [{ field }],- metrics: [{ measure: "count", agg: "count" }],+ metrics: [{ measure: "traceId", agg: "uniq" }],filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,});if (shouldReject) {@@ -691,11 +713,10 @@ describe("dashboard widget minVersion", () => {description: "will try hidden dim update",view: "observations",dimensions: [{ field: "name" }],- metrics: [{ measure: "count", agg: "count" }],+ metrics: [{ measure: "traceId", agg: "uniq" }],filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,});await expect(@@ -710,7 +731,6 @@ describe("dashboard widget minVersion", () => {filters: [],chartType: "NUMBER",chartConfig: { type: "NUMBER" },- minVersion: 2,}),).rejects.toThrow(/not available for widgets/);});diff --git a/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.ts b/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.tsindex d9fca39d3a..0c07662cb3 100644--- a/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.ts+++ b/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.ts@@ -1,22 +1,9 @@-// The public widget API stamps the internal `minVersion` that decides whether a-// widget queries the v1 tables or the v2 events_* tables. Only the deployment-// knows which of the two it can serve, so these cases pin the behavior on a-// deployment without a v4 write mode β the v3 default (LFE-14581).-const envMock = vi.hoisted(() => ({}) as Record<string, unknown>);--// Partial mock β real env underneath so the rest of the imported graph keeps-// working; envMock keeps its object identity so per-test mutations stay visible.-vi.mock("@/src/env.mjs", async (importOriginal) => {- const actual = (await importOriginal()) as { env: Record<string, unknown> };- Object.assign(envMock, actual.env);- return { env: envMock };-});-import {normalizePublicDashboardWidgetInput,validatePublicDashboardWidgetInput,} from "@/src/features/widgets/server/public-dashboard-widget-service";import { UnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";+import { env as sharedEnv } from "@langfuse/shared/src/env";const baseInput = {name: "API widget",@@ -28,51 +15,43 @@ const baseInput = {chartType: "BAR_TIME_SERIES" as const,};-describe("public dashboard widget minVersion", () => {+describe("public dashboard widget version validation", () => {+ const originalWriteMode = sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ const setWriteMode = (mode: "legacy" | "dual") => {+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = mode;+ };++ afterEach(() => {+ sharedEnv.LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });+describe("legacy write mode, where the events_* tables are empty", () => {beforeEach(() => {- envMock.LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ setWriteMode("legacy");});- it("stamps a v1-expressible widget as v1 so it can render", () => {+ it("accepts a v1-expressible widget so it can render", () => {const normalized = normalizePublicDashboardWidgetInput(baseInput);- expect(normalized.minVersion).toBe(1);expect(() =>validatePublicDashboardWidgetInput(normalized),).not.toThrow();});it("rejects a widget that genuinely needs v2 instead of persisting it unrenderable", () => {- const normalized = normalizePublicDashboardWidgetInput({- ...baseInput,- metrics: [{ measure: "traceId", agg: "uniq" as const }],- });-- expect(() => validatePublicDashboardWidgetInput(normalized)).toThrow(- /Measure "traceId" is not available for view "observations" in version "v1"/,- );- });-- it("caps a stored v2 widget back to v1 so a patch heals it", () => {- expect(normalizePublicDashboardWidgetInput(baseInput, 2).minVersion).toBe(- 1,- );+ expect(() =>+ validatePublicDashboardWidgetInput(+ normalizePublicDashboardWidgetInput({+ ...baseInput,+ metrics: [{ measure: "traceId", agg: "uniq" as const }],+ }),+ ),+ ).toThrow(/v2-only fields/i);});});- // dual writes the events_* tables, so v2 is servable there whatever the- // preview opt-in says β Monitors ships on exactly that test and its charts- // are v2-only. Capping here would break them.- it("keeps stamping v2 in dual write mode with the preview opt-in off", () => {- envMock.LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";- envMock.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "false";-- expect(normalizePublicDashboardWidgetInput(baseInput).minVersion).toBe(2);- });-it("only suggests dimensions that widget validation accepts", () => {- envMock.LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ setWriteMode("dual");const normalized = normalizePublicDashboardWidgetInput({...baseInput,dimensions: [{ field: "notAViewDimension" }],@@ -99,4 +78,27 @@ describe("public dashboard widget minVersion", () => {).not.toThrow();}});++ it("validates public widgets against the minimum version required by their shape", () => {+ setWriteMode("dual");++ expect(() =>+ validatePublicDashboardWidgetInput(+ normalizePublicDashboardWidgetInput({+ ...baseInput,+ // `id` is available to v1 widgets but uiHidden in v2.+ dimensions: [{ field: "id" }],+ }),+ ),+ ).not.toThrow();++ expect(() =>+ validatePublicDashboardWidgetInput(+ normalizePublicDashboardWidgetInput({+ ...baseInput,+ metrics: [{ measure: "traceId", agg: "uniq" as const }],+ }),+ ),+ ).not.toThrow();+ });});diff --git a/web/src/__tests__/server/unstable-dashboard-widgets-api.servertest.ts b/web/src/__tests__/server/unstable-dashboard-widgets-api.servertest.tsindex 44b0dd4572..a9b4cbb551 100644--- a/web/src/__tests__/server/unstable-dashboard-widgets-api.servertest.ts+++ b/web/src/__tests__/server/unstable-dashboard-widgets-api.servertest.ts@@ -36,7 +36,6 @@ const legacyTracesWidgetInput = {filters: [],chartType: "NUMBER" as const,chartConfig: { type: "NUMBER" as const },- minVersion: 1,};const expectUnstableError = (@@ -82,8 +81,8 @@ describe("/api/public/unstable/dashboard-widgets API", () => {projectId,name: "API widget",view: "OBSERVATIONS",- // widgets created via the public API are always v2 internally- minVersion: 2,+ // The submitted shape is fully expressible in v1.+ minVersion: 1,});await expect(@@ -209,6 +208,12 @@ describe("/api/public/unstable/dashboard-widgets API", () => {name: "Legacy v1 observations widget",view: DashboardWidgetViews.OBSERVATIONS,});+ await prisma.dashboardWidget.update({+ where: { id: v1Widget.id },+ // `id` is valid in v1 but uiHidden in v2, making a validation/persistence+ // version mismatch observable on the following name-only PATCH.+ data: { minVersion: 1, dimensions: [{ field: "id" }] },+ });await makeZodVerifiedAPICall(PatchUnstableDashboardWidgetResponse,@@ -221,19 +226,6 @@ describe("/api/public/unstable/dashboard-widgets API", () => {where: { id: v1Widget.id, projectId },});expect(afterRename.minVersion).toBe(1);-- const patchViewResponse = await makeZodVerifiedAPICall(- PatchUnstableDashboardWidgetResponse,- "PATCH",- `/api/public/unstable/dashboard-widgets/${v1Widget.id}`,- { view: "scores-numeric" },- auth,- );- expect(patchViewResponse.body.view).toBe("scores-numeric");- const afterViewChange = await prisma.dashboardWidget.findUniqueOrThrow({- where: { id: v1Widget.id, projectId },- });- expect(afterViewChange.minVersion).toBe(2);});it("rejects patching a widget into the legacy traces view", async () => {diff --git a/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.ts b/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.tsindex 131f41251e..327659dbd3 100644--- a/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.ts+++ b/web/src/features/chart-view/lib/chartConfigToWidget.clienttest.ts@@ -22,8 +22,6 @@ describe("chartConfigToWidgetInput", () => {expect(w.chartType).toBe("LINE_TIME_SERIES");expect(w.chartConfig).toEqual({ type: "LINE_TIME_SERIES" });expect(w.name).toBe("Count of events by model over time");- // Always v2: the chart reads the v2 events path, so the widget must too.- expect(w.minVersion).toBe(2);});it("maps a ranked cost-by-model chart with a row limit", () => {diff --git a/web/src/features/chart-view/lib/chartConfigToWidget.ts b/web/src/features/chart-view/lib/chartConfigToWidget.tsindex d9698b0f1c..5fc5497710 100644--- a/web/src/features/chart-view/lib/chartConfigToWidget.ts+++ b/web/src/features/chart-view/lib/chartConfigToWidget.ts@@ -55,13 +55,6 @@ export function chartConfigToWidgetInput({: { type: config.chartType }) as ChartWidgetInput["chartConfig"];- // Pin v2. The chart-view always queries the v2 events read path- // (`EventsChartView` runs `dashboard.executeQuery` with version "v2"), so the- // saved widget must read the same source β otherwise a non-beta viewer's- // dashboard would fall back to the legacy observations table and show- // different numbers than the chart the user just saved. "Save what I see."- const minVersion = 2;-return {name: describeConfig(config),description: "",@@ -71,6 +64,5 @@ export function chartConfigToWidgetInput({filters,chartType: config.chartType,chartConfig,- minVersion,};}diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsxindex 1b8f60bbe3..b2cadc40b3 100644--- a/web/src/features/widgets/components/WidgetForm.tsx+++ b/web/src/features/widgets/components/WidgetForm.tsx@@ -128,6 +128,7 @@ import {type SortField,type WidgetFormValues,type WidgetInitialValues,+ type WidgetSavePayload,} from "./widgetFormSchema";// Re-exported from the schema module so co-located tests keep importing it from@@ -246,27 +247,15 @@ export function WidgetForm({minVersion?: number;};projectId: string;- onSave: (widgetData: {- name: string;- description: string;- view: string;- dimensions: { field: string }[];- metrics: { measure: string; agg: string }[];- filters: any[];- chartType: DashboardWidgetChartType;- chartConfig: NonNullable<WidgetInitialValues["chartConfig"]>;- minVersion: number;- }) => void;+ onSave: (widgetData: WidgetSavePayload) => void;widgetId?: string;}) {const { isBetaEnabled } = useV4Beta();const importInputRef = useRef<HTMLInputElement>(null);- // 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.+ // The initial widget's persisted version is a local hint frozen at mount.+ // The resolver and live viewVersion additionally derive v2 from the current+ // form shape; the server derives the value that gets persisted.const baseMinVersion = deriveWidgetBaseMinVersion(initialValues);// The auto-suggestions change on every keystroke; a ref keeps the resolver@@ -288,10 +277,10 @@ export function WidgetForm({[],);// 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).+ // being validated β not from a render-written ref β so it is never render+ // stale after a version-flipping view or import. baseMinVersion and+ // isBetaEnabled are in the dep list so either promotion 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;@@ -312,6 +301,7 @@ export function WidgetForm({view: mapped.view,baseMinVersion,isBetaEnabled,+ shape: mapped,});return resolversByVersion[version](mapped as any, context, options);};@@ -341,6 +331,7 @@ export function WidgetForm({view: selectedView,baseMinVersion,isBetaEnabled,+ shape: values,});const suggestions = deriveWidgetSuggestions(values);const effectiveSort = deriveEffectiveSort(values);@@ -871,6 +862,7 @@ export function WidgetForm({view: newView,baseMinVersion,isBetaEnabled,+ shape: values,});const newViewDeclaration = viewDeclarations[newViewVersion][newView];@@ -985,9 +977,8 @@ export function WidgetForm({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.+ // The preview version for the imported widget is re-derived from the+ // snapshot's own version hint (not the mount's).const importViewVersion = resolveWidgetViewVersion({view: snapshot.selectedView,baseMinVersion: snapshot.widgetMinVersion,diff --git a/web/src/features/widgets/components/widgetFormAdapters.clienttest.ts b/web/src/features/widgets/components/widgetFormAdapters.clienttest.tsindex ee93e3257c..363365ebe7 100644--- a/web/src/features/widgets/components/widgetFormAdapters.clienttest.ts+++ b/web/src/features/widgets/components/widgetFormAdapters.clienttest.ts@@ -1,7 +1,7 @@import startCase from "lodash/startCase";import { type z } from "zod";-import { requiresV2, type metricAggregations } from "@langfuse/shared/query";+import { type metricAggregations } from "@langfuse/shared/query";import {mapWidgetUiTableFilterToView,normalizeStoredWidgetFiltersForEditor,@@ -194,14 +194,6 @@ function legacyReconstruct(iv: WidgetInitialValues): WidgetSavePayload {filters: normalizedUserFilters,chartType: iv.chartType,chartConfig,- minVersion: requiresV2({- view: iv.view,- dimensions: saveDimensions,- measures: saveMetrics.map((m) => ({ measure: m.measure })),- filters: normalizedUserFilters,- })- ? 2- : 1,};}@@ -358,7 +350,6 @@ describe("widget form adapters round-trip parity", () => {filters: [],chartType: "LINE_TIME_SERIES",chartConfig: { type: "LINE_TIME_SERIES" },- minVersion: 1,});});@@ -399,6 +390,23 @@ describe("widget form adapters round-trip parity", () => {});});+describe("widget form view version", () => {+ it("promotes a legacy widget when its current shape requires v2", () => {+ expect(+ resolveWidgetViewVersion({+ view: "observations",+ baseMinVersion: 1,+ isBetaEnabled: false,+ shape: {+ dimensions: [{ field: "experimentName" }],+ metrics: [{ measure: "count" }],+ filters: [],+ },+ }),+ ).toBe("v2");+ });+});+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 = {diff --git a/web/src/features/widgets/components/widgetFormSchema.ts b/web/src/features/widgets/components/widgetFormSchema.tsindex 025a1b6440..dbe437b8d5 100644--- a/web/src/features/widgets/components/widgetFormSchema.ts+++ b/web/src/features/widgets/components/widgetFormSchema.ts@@ -309,7 +309,7 @@ export type WidgetInitialValues = {minVersion?: number;};-/** The exact object shape passed to `onSave` β unchanged from the legacy form. */+/** The editor payload passed to `onSave`; persistence metadata is server-owned. */export type WidgetSavePayload = {name: string;description: string;@@ -319,18 +319,17 @@ export type WidgetSavePayload = {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)`.+ * The frozen local version hint for a widget. The server owns the persisted+ * version; the editor only uses the stored hint and current shape to select+ * the declaration it can show.*/export function deriveWidgetBaseMinVersion(initialValues: WidgetInitialValues,): number {- const initialWidgetRequiresV2 = requiresV2({+ return requiresV2({view: initialValues.view,dimensions:initialValues.dimensions ??@@ -341,22 +340,37 @@ export function deriveWidgetBaseMinVersion(measure: metric.measure,})) ?? [{ measure: initialValues.measure }],filters: initialValues.filters ?? [],- });- return initialWidgetRequiresV2 ? 2 : (initialValues.minVersion ?? 1);+ })+ ? 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.+ * Derives the effective view version (query-engine v1/v2) from the current view,+ * selected query shape, frozen initial hint, and beta flag. The persisted value+ * is a local hint only; shape-required v2 is always promoted.*/export function resolveWidgetViewVersion(params: {view: z.infer<typeof views>;baseMinVersion: number;isBetaEnabled: boolean;+ shape?: {+ dimensions: { field: string }[];+ metrics: { measure: string }[];+ filters?: FilterState;+ };}): ViewVersion {- return params.baseMinVersion >= 2 ||+ const shapeRequiresV2 = requiresV2({+ view: params.view,+ dimensions: params.shape?.dimensions ?? [],+ measures: params.shape?.metrics ?? [],+ filters: mapWidgetUiTableFilterToView(+ params.view,+ params.shape?.filters ?? [],+ ),+ });+ return shapeRequiresV2 ||+ params.baseMinVersion >= 2 ||(params.isBetaEnabled && params.view !== "traces")? "v2": "v1";@@ -616,8 +630,8 @@ export function toDefaultValues(* 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`.+ * view space and the per-type chartConfig is rebuilt. The server derives and+ * persists the query version from this shape when the widget is written.*/export function toSavePayload(values: WidgetFormValues,@@ -680,14 +694,6 @@ export function toSavePayload(filters: normalizedFilters,chartType,chartConfig,- minVersion: requiresV2({- view: values.view,- dimensions: saveDimensions,- measures: saveMetrics.map((m) => ({ measure: m.measure })),- filters: normalizedFilters,- })- ? 2- : 1,};}diff --git a/web/src/features/widgets/server/public-dashboard-widget-service.ts b/web/src/features/widgets/server/public-dashboard-widget-service.tsindex 729ad85be4..c740590041 100644--- a/web/src/features/widgets/server/public-dashboard-widget-service.ts+++ b/web/src/features/widgets/server/public-dashboard-widget-service.ts@@ -1,17 +1,16 @@import type { z } from "zod";-import {- DashboardWidgetChartType,- DashboardWidgetViews,-} from "@langfuse/shared/src/db";+import { DashboardWidgetChartType } from "@langfuse/shared/src/db";import {DashboardService,+ dashboardWidgetViewToQueryView,+ queryViewToDashboardWidgetView,+ resolveDashboardWidgetMinVersion,type WidgetDomain,} from "@langfuse/shared/src/server";import type { ApiAccessScope } from "@langfuse/shared/src/server";import {getValidAggregationsForMeasureType,getViewDeclaration,- type views,type ViewVersion,} from "@langfuse/shared/query";import { auditLog } from "@/src/features/audit-logs/auditLog";@@ -26,38 +25,17 @@ import {getWidgetImportFilterConfig,partitionStoredUiTableFiltersToView,} from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";-import { env } from "@/src/env.mjs";import {MAX_PIVOT_TABLE_DIMENSIONS,MAX_PIVOT_TABLE_METRICS,} from "@/src/features/widgets/utils/pivot-table-utils";// The widget shape used internally after input normalization: the public-// body with chartConfig fully resolved plus the internal minVersion.+// body with chartConfig and filters fully resolved.type NormalizedWidgetInput = Omit<z.infer<typeof PostUnstableDashboardWidgetResponse>,"id" | "createdAt" | "updatedAt"-> & { minVersion: number };--const viewMapping: Record<DashboardWidgetViewOutputType, DashboardWidgetViews> =- {- observations: DashboardWidgetViews.OBSERVATIONS,- "scores-numeric": DashboardWidgetViews.SCORES_NUMERIC,- "scores-boolean": DashboardWidgetViews.SCORES_BOOLEAN,- "scores-categorical": DashboardWidgetViews.SCORES_CATEGORICAL,- traces: DashboardWidgetViews.TRACES,- };--const reverseViewMapping: Record<- DashboardWidgetViews,- z.infer<typeof views>-> = {- [DashboardWidgetViews.TRACES]: "traces",- [DashboardWidgetViews.OBSERVATIONS]: "observations",- [DashboardWidgetViews.SCORES_NUMERIC]: "scores-numeric",- [DashboardWidgetViews.SCORES_BOOLEAN]: "scores-boolean",- [DashboardWidgetViews.SCORES_CATEGORICAL]: "scores-categorical",-};+>;const throwInvalidWidget = (params: {message: string;@@ -78,15 +56,27 @@ const throwInvalidWidget = (params: {});};-function getWidgetViewVersion(widget: { minVersion: number }): ViewVersion {- return widget.minVersion >= 2 ? "v2" : "v1";+function getWidgetViewVersion(+ widget: NormalizedWidgetInput,+ persistedMinVersion?: number,+): ViewVersion {+ return resolveDashboardWidgetMinVersion(+ {+ view: widget.view,+ dimensions: widget.dimensions,+ measures: widget.metrics,+ filters: widget.filters,+ },+ persistedMinVersion,+ ) >= 2+ ? "v2"+ : "v1";}function getPublicDashboardWidgetViewDeclaration(widget: NormalizedWidgetInput,+ viewVersion: ViewVersion,): ReturnType<typeof getViewDeclaration> {- const viewVersion = getWidgetViewVersion(widget);-try {return getViewDeclaration(widget.view, viewVersion);} catch (error) {@@ -103,28 +93,18 @@ type PublicDashboardWidgetInput = Omit<> & { view: DashboardWidgetViewOutputType };/**- * v2 widgets read the `events_*` tables, which the worker only writes in `dual`- * and `events_only` mode. Under `legacy` they stay empty β and on a v3- * deployment they do not exist at all β so a v2 query cannot succeed there.+ * Normalize a public widget against the query tables available in this+ * deployment. V2 widgets read the `events_*` tables, which the worker only+ * writes in `dual` and `events_only` mode; preview opt-in controls whether the+ * UI offers v4, not whether those tables contain data.*- * `LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN` is deliberately not consulted:- * it gates whether users are *offered* the v4 read path, not whether the data- * is there. The same write-mode-only test is what ships Monitors, whose charts- * are v2-only (`web/src/components/layouts/routes.tsx` β `show`).- */-function deploymentMinWidgetVersion(): number {- return env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "legacy" ? 1 : 2;-}--/**- * `requestedMinVersion` is capped to what the deployment can actually query, so- * the API never persists a widget that can never render (LFE-14581). Omit it to- * take the deployment's own default, as create does. The cap never promotes, so- * a legacy v1 widget stays v1 on a v4 deployment.+ * The shape-required version is checked against what the deployment can+ * actually query, so the API never accepts a widget that can never render+ * (LFE-14581). The DashboardService derives the persisted version when it+ * writes the normalized shape.*/export function normalizePublicDashboardWidgetInput(input: PublicDashboardWidgetInput,- requestedMinVersion?: number,): NormalizedWidgetInput {const { mappedFilters, unsupportedFilters } =partitionStoredUiTableFiltersToView(input.view, input.filters);@@ -173,27 +153,26 @@ export function normalizePublicDashboardWidgetInput(});}- const deploymentMinVersion = deploymentMinWidgetVersion();-+ const normalizedFilters = mappedFilters.map((filter) => ({+ ...filter,+ column: columnAliases[filter.column] ?? filter.column,+ }));return {...input,- filters: mappedFilters.map((filter) => ({- ...filter,- column: columnAliases[filter.column] ?? filter.column,- })),+ filters: normalizedFilters,chartConfig: chartConfig.data,- minVersion:- requestedMinVersion === undefined- ? deploymentMinVersion- : Math.min(requestedMinVersion, deploymentMinVersion),};}export function validatePublicDashboardWidgetInput(widget: NormalizedWidgetInput,+ persistedMinVersion?: number,): void {- const viewVersion = getWidgetViewVersion(widget);- const viewDeclaration = getPublicDashboardWidgetViewDeclaration(widget);+ const viewVersion = getWidgetViewVersion(widget, persistedMinVersion);+ const viewDeclaration = getPublicDashboardWidgetViewDeclaration(+ widget,+ viewVersion,+ );const widgetCompatibleDimensions = Object.entries(viewDeclaration.dimensions,).flatMap(([field, definition]) => (definition.uiHidden ? [] : [field]));@@ -280,7 +259,7 @@ export function toApiDashboardWidget(widget: WidgetDomain) {updatedAt: widget.updatedAt,name: widget.name,description: widget.description,- view: reverseViewMapping[widget.view],+ view: dashboardWidgetViewToQueryView[widget.view],dimensions: widget.dimensions,metrics: widget.metrics,filters: widget.filters,@@ -299,7 +278,7 @@ export async function createPublicDashboardWidget(params: {const widget = await DashboardService.createWidget(params.projectId, {...input,- view: viewMapping[input.view],+ view: queryViewToDashboardWidgetView[input.view],});await auditLog({@@ -373,33 +352,30 @@ export async function updatePublicDashboardWidget(params: {const chartTypeChanged =params.input.chartType !== undefined &¶ms.input.chartType !== currentPublic.chartType;- // Keep the stored minVersion (and thus v1/v2 query semantics) unless the- // caller explicitly changes the view; view changes take the deployment- // default like create. Either way normalize caps the result, so patching a- // widget that was stamped v2 on a deployment that cannot serve v2 heals it.- const mergedView = params.input.view ?? currentPublic.view;- const requestedMinVersion =- mergedView === currentPublic.view ? current.minVersion : undefined;- const input = normalizePublicDashboardWidgetInput(- {- ...currentPublic,- ...params.input,- // A chartType change without an explicit chartConfig resets the config- // to the new type; carrying the stale config type over would always- // fail validation.- chartConfig:- params.input.chartConfig ??- (chartTypeChanged- ? { type: params.input.chartType }- : currentPublic.chartConfig),- },- requestedMinVersion,- );- validatePublicDashboardWidgetInput(input);+ const input = normalizePublicDashboardWidgetInput({+ ...currentPublic,+ ...params.input,+ // A chartType change without an explicit chartConfig resets the config+ // to the new type; carrying the stale config type over would always+ // fail validation.+ chartConfig:+ params.input.chartConfig ??+ (chartTypeChanged+ ? { type: params.input.chartType }+ : currentPublic.chartConfig),+ });+ const persistedMinVersion =+ current.view === queryViewToDashboardWidgetView[input.view]+ ? current.minVersion+ : undefined;+ validatePublicDashboardWidgetInput(input, persistedMinVersion);const updated = await DashboardService.updateWidget(params.projectId,params.widgetId,- { ...input, view: viewMapping[input.view] },+ {+ ...input,+ view: queryViewToDashboardWidgetView[input.view],+ },);const result = toApiDashboardWidget(updated);await auditLog({diff --git a/web/src/features/widgets/utils/import-export-utils.clienttest.ts b/web/src/features/widgets/utils/import-export-utils.clienttest.tsindex 810324f3b0..4e196e1b6c 100644--- a/web/src/features/widgets/utils/import-export-utils.clienttest.ts+++ b/web/src/features/widgets/utils/import-export-utils.clienttest.ts@@ -2,6 +2,7 @@ import {buildWidgetExport,buildWidgetImportAllowedValues,importWidgetFile,+ parseImportedWidgetJson,parseAndNormalizeImportedWidget,parsePastedWidget,WIDGET_FILE_FORMAT_VERSION,@@ -152,6 +153,22 @@ describe("parseAndNormalizeImportedWidget", () => {expect(result.snapshot.widgetMinVersion).toBe(1);});+ it("validates a v2-required imported shape without rewriting its version hint", () => {+ const result = parseImportedWidgetJson({+ parsedJson: {+ ...baseWidget,+ view: "observations",+ dimensions: [{ field: "experimentName" }],+ chartType: "VERTICAL_BAR",+ chartConfig: { type: "VERTICAL_BAR" },+ filters: [],+ },+ isBetaEnabled: false,+ });++ expect(result.widget.minVersion).toBe(1);+ });+it("imports boolean score widgets with boolean filters intact", async () => {const result = await importWidgetFile({file: {diff --git a/web/src/features/widgets/utils/import-export-utils.ts b/web/src/features/widgets/utils/import-export-utils.tsindex e9d98bebf1..be3946bd88 100644--- a/web/src/features/widgets/utils/import-export-utils.ts+++ b/web/src/features/widgets/utils/import-export-utils.ts@@ -2,6 +2,7 @@ import { z } from "zod";import {getValidAggregationsForMeasureType,metricAggregations,+ requiresV2,viewDeclarations,views,type ViewVersion,@@ -458,7 +459,9 @@ function normalizeImportedWidgetVersion(widget: WidgetImport): WidgetImport {* Full import pipeline for one parsed widget JSON payload: schema parse,* filter normalization (value-level pruning only when option sets are* provided β clipboard/drop flows skip the option queries and pass none),- * traces-view version normalization, and view-declaration validation.+ * traces-view version normalization, and view-declaration validation. The+ * imported minVersion is a preview hint only; the write API derives the+ * persisted version from the submitted shape.* Throws on any payload that cannot become a valid widget.*/export function parseImportedWidgetJson(params: {@@ -480,10 +483,18 @@ export function parseImportedWidgetJson(params: {});const normalizedWidget = normalizeImportedWidgetVersion(importedWidget);- const importedMinVersion = normalizedWidget.minVersion ?? 1;+ const shapeRequiresV2 = requiresV2({+ view: normalizedWidget.view,+ dimensions: normalizedWidget.dimensions,+ measures: normalizedWidget.metrics.map((metric) => ({+ measure: metric.measure,+ })),+ filters: normalizedWidget.filters,+ });const importedViewVersion: ViewVersion =(params.isBetaEnabled && normalizedWidget.view !== "traces") ||- importedMinVersion >= 2+ shapeRequiresV2 ||+ (normalizedWidget.minVersion ?? 1) >= 2? "v2": "v1";@@ -582,6 +593,5 @@ export function toWidgetCreateFields(widget: WidgetExportSource) {filters: widget.filters,chartType: widget.chartType,chartConfig: widget.chartConfig,- minVersion: widget.minVersion,};}diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsxindex 1a365e016b..c6f443775e 100644--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx@@ -2,12 +2,11 @@ import { useRouter } from "next/router";import Page from "@/src/components/layouts/page";import { api } from "@/src/utils/api";import { WidgetForm } from "@/src/features/widgets/components/WidgetForm";+import { type WidgetSavePayload } from "@/src/features/widgets/components/widgetFormSchema";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";-import { type DashboardWidgetChartType } from "@langfuse/shared";import { type metricAggregations, type views } from "@langfuse/shared/query";import { type z } from "zod";-import { type WidgetChartConfig } from "@/src/features/widgets/utils";export default function EditWidget() {const router = useRouter();@@ -55,17 +54,7 @@ export default function EditWidget() {});// Handle update widget- const handleUpdateWidget = (widgetFormData: {- name: string;- description: string;- view: string;- dimensions: { field: string }[];- metrics: { measure: string; agg: string }[];- filters: any[];- chartType: DashboardWidgetChartType;- chartConfig: WidgetChartConfig;- minVersion: number;- }) => {+ const handleUpdateWidget = (widgetFormData: WidgetSavePayload) => {if (!widgetId) return;updateWidgetMutation.mutate({@@ -82,7 +71,6 @@ export default function EditWidget() {filters: widgetFormData.filters,chartType: widgetFormData.chartType,chartConfig: widgetFormData.chartConfig,- minVersion: widgetFormData.minVersion,});};diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsxindex ac3e0f4902..fbdcac3e11 100644--- a/web/src/pages/project/[projectId]/widgets/new.tsx+++ b/web/src/pages/project/[projectId]/widgets/new.tsx@@ -1,10 +1,10 @@import { useRouter } from "next/router";import Page from "@/src/components/layouts/page";import { api } from "@/src/utils/api";-import { type WidgetChartConfig, WidgetForm } from "@/src/features/widgets";+import { WidgetForm } from "@/src/features/widgets";+import { type WidgetSavePayload } from "@/src/features/widgets/components/widgetFormSchema";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { showErrorToast } from "@/src/features/notifications/showErrorToast";-import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";import { type metricAggregations, type views } from "@langfuse/shared/query";import { type z } from "zod";import { SelectDashboardDialog } from "@/src/features/dashboard/components/SelectDashboardDialog";@@ -41,17 +41,7 @@ export default function NewWidget() {},});- const handleSaveWidget = (widgetData: {- name: string;- description: string;- view: string;- dimensions: { field: string }[];- metrics: { measure: string; agg: string }[];- filters: any[];- chartType: DashboardWidgetChartType;- chartConfig: WidgetChartConfig;- minVersion: number;- }) => {+ const handleSaveWidget = (widgetData: WidgetSavePayload) => {if (!widgetData.name.trim()) {showErrorToast("Error", "Widget name is required");return;@@ -71,7 +61,6 @@ export default function NewWidget() {filters: widgetData.filters,chartType: widgetData.chartType,chartConfig: widgetData.chartConfig,- minVersion: widgetData.minVersion,});};diff --git a/web/src/server/api/routers/dashboardWidgets.ts b/web/src/server/api/routers/dashboardWidgets.tsindex 1f8dba470a..a08522e2b5 100644--- a/web/src/server/api/routers/dashboardWidgets.ts+++ b/web/src/server/api/routers/dashboardWidgets.ts@@ -5,22 +5,16 @@ import {} from "@/src/server/api/trpc";import { orderBy, singleFilter, optionalPaginationZod } from "@langfuse/shared";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import {- DashboardWidgetChartType,- DashboardWidgetViews,-} from "@langfuse/shared/src/db";+import { DashboardWidgetChartType } from "@langfuse/shared/src/db";import {DashboardService,DimensionSchema,MetricSchema,ChartConfigSchema,+ dashboardWidgetViewToQueryView,+ queryViewToDashboardWidgetView,} from "@langfuse/shared/src/server";-import {- getValidAggregationsForMeasureType,- getViewDeclaration,- views,- type ViewVersion,-} from "@langfuse/shared/query";+import { views } from "@langfuse/shared/query";import { TRPCError } from "@trpc/server";import { LangfuseConflictError } from "@langfuse/shared";@@ -34,7 +28,6 @@ const CreateDashboardWidgetInput = z.object({filters: z.array(singleFilter),chartType: z.enum(DashboardWidgetChartType),chartConfig: ChartConfigSchema,- minVersion: z.number().int().optional(),});// Define update widget input schema (without projectId)@@ -49,7 +42,6 @@ const UpdateDashboardWidgetInput = z.object({filters: z.array(singleFilter),chartType: z.enum(DashboardWidgetChartType),chartConfig: ChartConfigSchema,- minVersion: z.number().int().optional(),});// Define the widget list input schema@@ -65,72 +57,6 @@ const GetDashboardWidgetInput = z.object({widgetId: z.string(),});-const viewMapping: Record<string, DashboardWidgetViews> = {- traces: DashboardWidgetViews.TRACES,- observations: DashboardWidgetViews.OBSERVATIONS,- "scores-numeric": DashboardWidgetViews.SCORES_NUMERIC,- "scores-boolean": DashboardWidgetViews.SCORES_BOOLEAN,- "scores-categorical": DashboardWidgetViews.SCORES_CATEGORICAL,-};--// Reverse mapping for client-side use-const reverseViewMapping: Record<- DashboardWidgetViews,- z.infer<typeof views>-> = {- [DashboardWidgetViews.TRACES]: "traces",- [DashboardWidgetViews.OBSERVATIONS]: "observations",- [DashboardWidgetViews.SCORES_NUMERIC]: "scores-numeric",- [DashboardWidgetViews.SCORES_BOOLEAN]: "scores-boolean",- [DashboardWidgetViews.SCORES_CATEGORICAL]: "scores-categorical",-};--function validateMetricAggregations(params: {- view: string;- metrics: Array<{ measure: string; agg: string }>;- minVersion?: number;-}): void {- const version: ViewVersion = (params.minVersion ?? 1) >= 2 ? "v2" : "v1";- const viewDecl = getViewDeclaration(- params.view as z.infer<typeof views>,- version,- );-- for (const metric of params.metrics) {- const measureDef = viewDecl.measures[metric.measure];- if (!measureDef) continue; // measure existence is validated elsewhere- const validAggs = getValidAggregationsForMeasureType(measureDef.type);- if (!validAggs.some((a) => a === metric.agg)) {- throw new TRPCError({- code: "BAD_REQUEST",- message: `Aggregation "${metric.agg}" is not valid for measure "${metric.measure}" (type: ${measureDef.type}). Valid aggregations: ${validAggs.join(", ")}`,- });- }- }-}--function validateUiHiddenDimensions(params: {- view: string;- dimensions: Array<{ field: string }>;- minVersion?: number;-}): void {- const version: ViewVersion = (params.minVersion ?? 1) >= 2 ? "v2" : "v1";- const viewDecl = getViewDeclaration(- params.view as z.infer<typeof views>,- version,- );-- const hiddenDims = params.dimensions.filter(- (dim) => viewDecl.dimensions[dim.field]?.uiHidden,- );- if (hiddenDims.length > 0) {- throw new TRPCError({- code: "BAD_REQUEST",- message: `Dimensions not available for widgets: ${hiddenDims.map((d) => d.field).join(", ")}`,- });- }-}-export const dashboardWidgetRouter = createTRPCRouter({create: protectedProjectProcedure.input(CreateDashboardWidgetInput)@@ -141,25 +67,12 @@ export const dashboardWidgetRouter = createTRPCRouter({scope: "dashboards:CUD",});- validateMetricAggregations({- view: input.view,- metrics: input.metrics,- minVersion: input.minVersion,- });-- validateUiHiddenDimensions({- view: input.view,- dimensions: input.dimensions,- minVersion: input.minVersion,- });-// Create the widget using the DashboardServiceconst widget = await DashboardService.createWidget(input.projectId,{...input,- view: viewMapping[input.view],- minVersion: input.minVersion ?? 1,+ view: queryViewToDashboardWidgetView[input.view],},ctx.session.user?.id,);@@ -212,7 +125,7 @@ export const dashboardWidgetRouter = createTRPCRouter({return {...widget,- view: reverseViewMapping[widget.view],+ view: dashboardWidgetViewToQueryView[widget.view],metrics: widget.metrics,owner: widget.owner,};@@ -227,18 +140,6 @@ export const dashboardWidgetRouter = createTRPCRouter({scope: "dashboards:CUD",});- validateMetricAggregations({- view: input.view,- metrics: input.metrics,- minVersion: input.minVersion,- });-- validateUiHiddenDimensions({- view: input.view,- dimensions: input.dimensions,- minVersion: input.minVersion,- });-// Update the widget using the DashboardServiceconst widget = await DashboardService.updateWidget(input.projectId,@@ -246,13 +147,12 @@ export const dashboardWidgetRouter = createTRPCRouter({{name: input.name,description: input.description,- view: viewMapping[input.view],+ view: queryViewToDashboardWidgetView[input.view],dimensions: input.dimensions,metrics: input.metrics,filters: input.filters,chartType: input.chartType,chartConfig: input.chartConfig,- minVersion: input.minVersion,},ctx.session.user?.id,);