Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(dashboards): import/export widget configs (#13011)

Caleb2645ba459cd9
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 62a3f4ee17..13dc240454 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -99,6 +99,11 @@ export * from "./utils/IORepresentation";
// analytics integrations (client-safe)
export * from "./features/analytics-integrations";
+export {
+ ChartConfigSchema,
+ DimensionSchema,
+ MetricSchema,
+} from "./server/services/DashboardService/types";
// query (dashboard / monitor data model)
export * from "./features/query/types";
diff --git a/web/src/__tests__/server/dashboard-widget-version.servertest.ts b/web/src/__tests__/server/dashboard-widget-version.servertest.ts
index 3e73ef78ef..57c09a4f84 100644
--- a/web/src/__tests__/server/dashboard-widget-version.servertest.ts
+++ b/web/src/__tests__/server/dashboard-widget-version.servertest.ts
@@ -336,6 +336,29 @@ describe("dashboard widget minVersion", () => {
// validateMetricAggregations guard that lives in the tRPC router.
describe("tRPC measure-aggregation validation", () => {
+ it("should return stored metrics from get without additional client-side parsing", async () => {
+ const caller = makeCaller();
+ const created = await caller.dashboardWidgets.create({
+ projectId,
+ name: "Get Widget",
+ description: "fetch metrics unchanged",
+ view: "observations",
+ dimensions: [],
+ metrics: [{ measure: "count", agg: "count" }],
+ filters: [],
+ chartType: "NUMBER",
+ chartConfig: { type: "NUMBER" },
+ minVersion: 2,
+ });
+
+ const fetched = await caller.dashboardWidgets.get({
+ projectId,
+ widgetId: created.widget.id,
+ });
+
+ expect(fetched.metrics).toEqual([{ measure: "count", agg: "count" }]);
+ });
+
it("should reject invalid aggregation on a string measure", async () => {
const caller = makeCaller();
await expect(
diff --git a/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts b/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts
index f5790fc68c..53c3add600 100644
--- a/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts
+++ b/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts
@@ -288,6 +288,25 @@ const buildFilterMappings = (
const currentWidgetFilterMappings = buildFilterMappings("current");
const legacyDashboardFilterMappings = buildFilterMappings("legacy");
+export const getWidgetImportFilterConfig = (
+ view: z.infer<typeof views>,
+): {
+ allowedColumns: Set<string>;
+ columnAliases: Record<string, string>;
+} => {
+ const allowedColumns = new Set(
+ currentWidgetFilterMappings[view].map((mapping) => mapping.viewName),
+ );
+
+ const columnAliases: Record<string, string> = {};
+
+ if (view === "observations") {
+ columnAliases.observationModelName = "providedModelName";
+ }
+
+ return { allowedColumns, columnAliases };
+};
+
const allWidgetFilterMappings = [
...Object.values(currentWidgetFilterMappings).flat(),
...Object.values(legacyDashboardFilterMappings).flat(),
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 0e0b807156..b88f1b7e0b 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -7,6 +7,7 @@ import {
CardFooter,
} from "@/src/components/ui/card";
import { api } from "@/src/utils/api";
+import { importWidgetFile } from "@/src/features/widgets/utils/import-export-utils";
import {
buildWidgetOrderBy,
getResultUnit,
@@ -58,6 +59,7 @@ import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props
import { Button } from "@/src/components/ui/button";
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import {
type FilterState,
ObservationLevelDomain,
@@ -75,6 +77,7 @@ import {
Plus,
X,
AlertCircle,
+ Upload,
Sparkles,
} from "lucide-react";
import {
@@ -313,6 +316,7 @@ export function WidgetForm({
// 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,
@@ -332,12 +336,15 @@ export function WidgetForm({
})) ?? [{ measure: initialValues.measure }],
filters: initialValues.filters ?? [],
});
+ const [widgetMinVersion, setWidgetMinVersion] = useState<number>(
+ initialWidgetRequiresV2 ? 2 : (initialValues.minVersion ?? 1),
+ );
const viewVersion: ViewVersion =
- initialWidgetRequiresV2 || (initialValues.minVersion ?? 1) >= 2
+ initialWidgetRequiresV2 ||
+ widgetMinVersion >= 2 ||
+ (isBetaEnabled && selectedView !== "traces")
? "v2"
- : isBetaEnabled && selectedView !== "traces"
- ? "v2"
- : "v1";
+ : "v1";
const availableViewOptions = viewVersion === "v2" ? viewsV2 : views;
// For regular charts: single metric selection
@@ -1175,6 +1182,92 @@ export function WidgetForm({
],
);
+ const handleImportWidget = async (
+ event: React.ChangeEvent<HTMLInputElement>,
+ ) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+
+ if (!file) {
+ return;
+ }
+
+ const showMalformedImportToast = () =>
+ showErrorToast(
+ "Malformed input",
+ "This operation can't be done due to the malformed input",
+ "WARNING",
+ );
+
+ try {
+ const result = await importWidgetFile({
+ file,
+ optionSets: {
+ environmentValues: environmentFilterOptions.data?.map(
+ (option) => option.environment,
+ ),
+ traceNames: traceFilterOptions.data
+ ? normalizeSingleValueOptions(traceFilterOptions.data.name).map(
+ (option) => option.value,
+ )
+ : undefined,
+ tags: traceFilterOptions.data
+ ? traceFilterOptions.data.tags.map((option) => option.value)
+ : undefined,
+ toolNames: generationsFilterOptions.data
+ ? generationsFilterOptions.data.toolNames.map(
+ (option) => option.value,
+ )
+ : undefined,
+ calledToolNames: generationsFilterOptions.data
+ ? generationsFilterOptions.data.calledToolNames.map(
+ (option) => option.value,
+ )
+ : undefined,
+ modelNames: generationsFilterOptions.data
+ ? generationsFilterOptions.data.model.map((option) => option.value)
+ : undefined,
+ observationLevels: observationLevelOptions.map(
+ (option) => option.value,
+ ),
+ },
+ 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);
+
+ showSuccessToast({
+ title: "Widget uploaded successfully",
+ description: "Widget configuration has been loaded.",
+ });
+
+ if (result.removedValues || result.removedFilters) {
+ showErrorToast(
+ "Widget filters were adjusted",
+ "Some imported filters or filter values were removed because they are not available in this project.",
+ "WARNING",
+ );
+ }
+ } catch {
+ showMalformedImportToast();
+ }
+ };
+
const chartPresentation = useMemo(() => {
if (selectedChartType === "PIVOT_TABLE") {
return undefined;
@@ -1407,7 +1500,28 @@ export function WidgetForm({
<div className="h-full w-1/3 min-w-[430px]">
<Card className="flex h-full flex-col">
<CardHeader>
- <CardTitle>Widget Configuration</CardTitle>
+ <div className="flex items-start justify-between gap-3">
+ <CardTitle>Widget Configuration</CardTitle>
+ {!widgetId && isBetaEnabled && (
+ <>
+ <input
+ ref={importInputRef}
+ type="file"
+ accept="application/json,.json"
+ className="hidden"
+ onChange={handleImportWidget}
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => importInputRef.current?.click()}
+ >
+ <Upload className="mr-2 h-4 w-4" />
+ Import
+ </Button>
+ </>
+ )}
+ </div>
<CardDescription>
Configure your widget by selecting data and visualization options
</CardDescription>
diff --git a/web/src/features/widgets/components/WidgetTable.tsx b/web/src/features/widgets/components/WidgetTable.tsx
index ef94f905b5..a27e999231 100644
--- a/web/src/features/widgets/components/WidgetTable.tsx
+++ b/web/src/features/widgets/components/WidgetTable.tsx
@@ -12,8 +12,10 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context
import startCase from "lodash/startCase";
import { Button } from "@/src/components/ui/button";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { Trash } from "lucide-react";
+import { Download, Trash } from "lucide-react";
import { useState } from "react";
+import { downloadWidgetJson } from "@/src/features/widgets/utils/import-export-utils";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import {
Popover,
PopoverContent,
@@ -24,6 +26,8 @@ import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { useRouter } from "next/router";
import { getChartTypeDisplayName } from "@/src/features/widgets/chart-library/utils";
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import { type metricAggregations } from "@langfuse/shared/query";
+import { type z } from "zod";
type WidgetTableRow = {
id: string;
@@ -93,7 +97,7 @@ export function DeleteWidget({
return;
}
- void mutDeleteWidget.mutateAsync({
+ void mutDeleteWidget.mutate({
projectId,
widgetId,
});
@@ -108,8 +112,62 @@ export function DeleteWidget({
);
}
+function ShareWidgetButton({ widgetId }: { widgetId: string }) {
+ const projectId = useProjectIdFromURL();
+ const utils = api.useUtils();
+ const [isDownloading, setIsDownloading] = useState(false);
+
+ return (
+ <Button
+ variant="ghost"
+ size="xs"
+ disabled={!projectId}
+ loading={isDownloading}
+ onClick={async () => {
+ if (!projectId) {
+ return;
+ }
+
+ setIsDownloading(true);
+
+ try {
+ const widget = await utils.dashboardWidgets.get.fetch({
+ projectId,
+ widgetId,
+ });
+
+ downloadWidgetJson({
+ name: widget.name,
+ description: widget.description,
+ view: widget.view,
+ dimensions: widget.dimensions,
+ metrics: widget.metrics.map((metric) => ({
+ measure: metric.measure,
+ agg: metric.agg as z.infer<typeof metricAggregations>,
+ })),
+ filters: widget.filters,
+ chartType: widget.chartType,
+ chartConfig: widget.chartConfig,
+ minVersion: widget.minVersion,
+ });
+ } catch (error) {
+ showErrorToast(
+ "Failed to download widget",
+ error instanceof Error ? error.message : "Unknown error",
+ );
+ } finally {
+ setIsDownloading(false);
+ }
+ }}
+ >
+ <Download className="h-4 w-4" />
+ </Button>
+ );
+}
+
export function DashboardWidgetTable() {
const projectId = useProjectIdFromURL();
+ const { isBetaEnabled } = useV4Beta();
const { setDetailPageList } = useDetailPageLists();
const router = useRouter();
@@ -218,7 +276,11 @@ export function DashboardWidgetTable() {
cell: (row) => {
const id = row.row.original.id;
return (
- <div onClick={(e) => e.stopPropagation()}>
+ <div
+ className="flex items-center gap-1"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {isBetaEnabled && <ShareWidgetButton widgetId={id} />}
<DeleteWidget widgetId={id} owner={row.row.original.owner} />
</div>
);
diff --git a/web/src/features/widgets/utils/import-export-utils.clienttest.ts b/web/src/features/widgets/utils/import-export-utils.clienttest.ts
new file mode 100644
index 0000000000..3bc8f73193
--- /dev/null
+++ b/web/src/features/widgets/utils/import-export-utils.clienttest.ts
@@ -0,0 +1,151 @@
+import {
+ buildWidgetImportAllowedValues,
+ importWidgetFile,
+ parseAndNormalizeImportedWidget,
+} from "./import-export-utils";
+
+describe("parseAndNormalizeImportedWidget", () => {
+ const baseWidget = {
+ name: "Imported widget",
+ description: "Round-trip export",
+ view: "traces" as const,
+ dimensions: [],
+ metrics: [{ measure: "count", agg: "count" as const }],
+ chartType: "NUMBER" as const,
+ chartConfig: { type: "NUMBER" as const },
+ minVersion: 1,
+ };
+
+ it("keeps recognized filter values", () => {
+ const result = parseAndNormalizeImportedWidget({
+ parsedJson: {
+ ...baseWidget,
+ filters: [
+ {
+ column: "environment",
+ operator: "any of",
+ value: ["prod"],
+ type: "stringOptions",
+ },
+ ],
+ },
+ allowedValuesByColumn: new Map([["environment", new Set(["prod"])]]),
+ });
+
+ expect(result.widget.filters).toEqual([
+ {
+ column: "environment",
+ operator: "any of",
+ value: ["prod"],
+ type: "stringOptions",
+ },
+ ]);
+ expect(result.removedValues).toBe(false);
+ expect(result.removedFilters).toBe(false);
+ });
+
+ it("keeps option filters when allowed values are still unavailable", () => {
+ const result = parseAndNormalizeImportedWidget({
+ parsedJson: {
+ ...baseWidget,
+ filters: [
+ {
+ column: "environment",
+ operator: "any of",
+ value: ["prod"],
+ type: "stringOptions",
+ },
+ ],
+ },
+ allowedValuesByColumn: buildWidgetImportAllowedValues(
+ {
+ observationLevels: [],
+ },
+ {
+ ...baseWidget,
+ filters: [],
+ },
+ ),
+ });
+
+ expect(result.widget.filters).toEqual([
+ {
+ column: "environment",
+ operator: "any of",
+ value: ["prod"],
+ type: "stringOptions",
+ },
+ ]);
+ expect(result.removedValues).toBe(false);
+ expect(result.removedFilters).toBe(false);
+ });
+
+ it("drops unavailable option values instead of rejecting the import", () => {
+ const result = parseAndNormalizeImportedWidget({
+ parsedJson: {
+ ...baseWidget,
+ filters: [
+ {
+ column: "environment",
+ operator: "any of",
+ value: ["prod"],
+ type: "stringOptions",
+ },
+ ],
+ },
+ allowedValuesByColumn: new Map([["environment", new Set()]]),
+ });
+
+ expect(result.widget.filters).toEqual([]);
+ expect(result.removedValues).toBe(true);
+ expect(result.removedFilters).toBe(false);
+ });
+
+ it("marks unsupported cross-view filters as removed", () => {
+ const result = parseAndNormalizeImportedWidget({
+ parsedJson: {
+ ...baseWidget,
+ filters: [
+ {
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ type: "stringOptions",
+ },
+ ],
+ },
+ allowedValuesByColumn: buildWidgetImportAllowedValues(
+ {
+ observationLevels: [],
+ },
+ {
+ ...baseWidget,
+ filters: [],
+ },
+ ),
+ });
+
+ expect(result.widget.filters).toEqual([]);
+ expect(result.removedFilters).toBe(true);
+ });
+
+ it("normalizes imported traces widgets with minVersion 2 back to v1", async () => {
+ const result = await importWidgetFile({
+ file: {
+ text: async () =>
+ JSON.stringify({
+ ...baseWidget,
+ filters: [],
+ minVersion: 2,
+ }),
+ } as File,
+ optionSets: {
+ observationLevels: [],
+ },
+ isBetaEnabled: true,
+ });
+
+ expect(result.snapshot.selectedView).toBe("traces");
+ expect(result.snapshot.widgetMinVersion).toBe(1);
+ });
+});
diff --git a/web/src/features/widgets/utils/import-export-utils.ts b/web/src/features/widgets/utils/import-export-utils.ts
new file mode 100644
index 0000000000..3afec12c45
--- /dev/null
+++ b/web/src/features/widgets/utils/import-export-utils.ts
@@ -0,0 +1,451 @@
+import { z } from "zod";
+import {
+ getValidAggregationsForMeasureType,
+ metricAggregations,
+ viewDeclarations,
+ views,
+ type ViewVersion,
+} from "@langfuse/shared/query";
+import {
+ getWidgetImportFilterConfig,
+ normalizeStoredWidgetFiltersForEditor,
+ partitionStoredUiTableFiltersToView,
+} from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";
+import startCase from "lodash/startCase";
+import {
+ ChartConfigSchema,
+ DashboardWidgetChartType,
+ DimensionSchema,
+ MetricSchema,
+ singleFilter,
+ type FilterState,
+} from "@langfuse/shared";
+import {
+ MAX_PIVOT_TABLE_DIMENSIONS,
+ MAX_PIVOT_TABLE_METRICS,
+} from "@/src/features/widgets/utils/pivot-table-utils";
+
+const dashboardWidgetChartTypeSchema = z.enum(DashboardWidgetChartType);
+const widgetMetricSchema = MetricSchema.extend({
+ agg: metricAggregations,
+});
+
+const widgetImportBaseSchema = z
+ .object({
+ name: z.string(),
+ description: z.string(),
+ view: views,
+ dimensions: z.array(DimensionSchema),
+ metrics: z.array(widgetMetricSchema),
+ filters: z.array(singleFilter),
+ chartType: dashboardWidgetChartTypeSchema,
+ chartConfig: ChartConfigSchema,
+ minVersion: z.number().int().optional(),
+ })
+ .loose();
+
+export const widgetImportSchema = widgetImportBaseSchema.superRefine(
+ (widget, ctx) => {
+ if (widget.chartConfig.type !== widget.chartType) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["chartConfig", "type"],
+ message: "chartConfig.type must match chartType",
+ });
+ }
+ },
+);
+
+type WidgetImport = z.infer<typeof widgetImportSchema>;
+
+export type WidgetImportOptionSets = {
+ environmentValues?: string[];
+ traceNames?: string[];
+ tags?: string[];
+ toolNames?: string[];
+ calledToolNames?: string[];
+ modelNames?: string[];
+ observationLevels: string[];
+};
+
+export type ImportedWidgetFormSnapshot = {
+ widgetMinVersion: number;
+ widgetName: string;
+ widgetDescription: string;
+ selectedView: WidgetImport["view"];
+ selectedChartType: WidgetImport["chartType"];
+ selectedMeasure: string;
+ selectedAggregation: z.infer<typeof metricAggregations>;
+ selectedMetrics: {
+ id: string;
+ measure: string;
+ aggregation: z.infer<typeof metricAggregations>;
+ label: string;
+ }[];
+ selectedDimension: string;
+ pivotDimensions: string[];
+ userFilterState: FilterState;
+ rowLimit: number;
+ histogramBins: number;
+ defaultSortColumn: string;
+ defaultSortOrder: "ASC" | "DESC";
+};
+
+export type ImportedWidgetResult = {
+ snapshot: ImportedWidgetFormSnapshot;
+ removedValues: boolean;
+ removedFilters: boolean;
+};
+
+export function buildWidgetImportAllowedValues(
+ options: WidgetImportOptionSets,
+ parsedJson: unknown,
+): Map<string, Set<string>> {
+ const allowedValuesByColumn = new Map<string, Set<string>>();
+
+ if (options.environmentValues) {
+ allowedValuesByColumn.set(
+ "environment",
+ new Set(options.environmentValues),
+ );
+ }
+
+ if (options.traceNames) {
+ const traceNameValues = new Set(options.traceNames);
+ allowedValuesByColumn.set("traceName", traceNameValues);
+ allowedValuesByColumn.set("name", traceNameValues);
+ }
+
+ if (options.tags) {
+ allowedValuesByColumn.set("tags", new Set(options.tags));
+ }
+
+ if (options.toolNames) {
+ allowedValuesByColumn.set("toolNames", new Set(options.toolNames));
+ }
+
+ if (
+ typeof parsedJson === "object" &&
+ parsedJson !== null &&
+ "view" in parsedJson &&
+ parsedJson.view === "observations"
+ ) {
+ if (options.calledToolNames) {
+ allowedValuesByColumn.set(
+ "calledToolNames",
+ new Set(options.calledToolNames),
+ );
+ }
+
+ if (options.modelNames) {
+ allowedValuesByColumn.set(
+ "providedModelName",
+ new Set(options.modelNames),
+ );
+ }
+
+ allowedValuesByColumn.set("level", new Set(options.observationLevels));
+ }
+
+ return allowedValuesByColumn;
+}
+
+export function downloadWidgetJson(
+ widget: Pick<
+ WidgetImport,
+ | "name"
+ | "description"
+ | "view"
+ | "dimensions"
+ | "metrics"
+ | "filters"
+ | "chartType"
+ | "chartConfig"
+ | "minVersion"
+ >,
+) {
+ const exportWidget = {
+ name: widget.name,
+ description: widget.description,
+ view: widget.view,
+ dimensions: widget.dimensions,
+ metrics: widget.metrics,
+ filters: widget.filters,
+ chartType: widget.chartType,
+ chartConfig: widget.chartConfig,
+ minVersion: widget.minVersion,
+ };
+
+ const blob = new Blob([JSON.stringify(exportWidget, null, 2)], {
+ type: "application/json",
+ });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = buildWidgetJsonFileName(widget.name);
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+export function buildWidgetJsonFileName(widgetName: string) {
+ const fileSafeName = widgetName
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+
+ return `${fileSafeName || "widget"}.json`;
+}
+
+export function normalizeImportedFilters(params: {
+ filters: FilterState;
+ view: z.infer<typeof views>;
+ allowedValuesByColumn: Map<string, Set<string>>;
+}): { filters: FilterState; removedValues: boolean; removedFilters: boolean } {
+ let removedValues = false;
+ let removedFilters = false;
+
+ const { mappedFilters: normalizedLegacyFilters, unsupportedFilters } =
+ partitionStoredUiTableFiltersToView(params.view, params.filters);
+
+ if (unsupportedFilters.length > 0) {
+ removedFilters = true;
+ }
+
+ const { allowedColumns, columnAliases } = getWidgetImportFilterConfig(
+ params.view,
+ );
+
+ const filters: FilterState = normalizedLegacyFilters.flatMap<
+ FilterState[number]
+ >((filter) => {
+ const normalizedColumn = columnAliases[filter.column] ?? filter.column;
+ if (!allowedColumns.has(normalizedColumn)) {
+ removedFilters = true;
+ return [];
+ }
+
+ const normalizedFilter = { ...filter, column: normalizedColumn };
+
+ if (
+ normalizedFilter.type !== "stringOptions" &&
+ normalizedFilter.type !== "arrayOptions" &&
+ normalizedFilter.type !== "categoryOptions"
+ ) {
+ return [normalizedFilter];
+ }
+
+ const allowedValues = params.allowedValuesByColumn.get(
+ normalizedFilter.column,
+ );
+ if (!allowedValues) {
+ return [normalizedFilter];
+ }
+
+ const nextValues = normalizedFilter.value.filter((value) =>
+ allowedValues.has(value),
+ );
+ if (nextValues.length === normalizedFilter.value.length) {
+ return [normalizedFilter];
+ }
+
+ removedValues = true;
+
+ if (nextValues.length === 0) {
+ return [];
+ }
+
+ return [{ ...normalizedFilter, value: nextValues }];
+ });
+
+ return { filters, removedValues, removedFilters };
+}
+
+export function normalizeImportedWidget(params: {
+ widget: WidgetImport;
+ allowedValuesByColumn: Map<string, Set<string>>;
+}): {
+ widget: WidgetImport;
+ removedValues: boolean;
+ removedFilters: boolean;
+} {
+ const sanitizedFilters = normalizeImportedFilters({
+ view: params.widget.view,
+ filters: params.widget.filters,
+ allowedValuesByColumn: params.allowedValuesByColumn,
+ });
+
+ return {
+ widget: {
+ ...params.widget,
+ filters: sanitizedFilters.filters,
+ },
+ removedValues: sanitizedFilters.removedValues,
+ removedFilters: sanitizedFilters.removedFilters,
+ };
+}
+
+export function parseAndNormalizeImportedWidget(params: {
+ parsedJson: unknown;
+ allowedValuesByColumn: Map<string, Set<string>>;
+}): {
+ widget: WidgetImport;
+ removedValues: boolean;
+ removedFilters: boolean;
+} {
+ const parsed = widgetImportSchema.parse(params.parsedJson);
+ const normalized = normalizeImportedWidget({
+ widget: parsed,
+ allowedValuesByColumn: params.allowedValuesByColumn,
+ });
+
+ return normalized;
+}
+
+export function validateImportedWidget(params: {
+ widget: WidgetImport;
+ importedViewVersion: ViewVersion;
+}): void {
+ const viewDeclaration =
+ viewDeclarations[params.importedViewVersion][params.widget.view];
+
+ const dimensionsAreValid = params.widget.dimensions.every(
+ (dimension) =>
+ Boolean(viewDeclaration.dimensions[dimension.field]) &&
+ !viewDeclaration.dimensions[dimension.field]?.uiHidden,
+ );
+
+ const metricsAreValid = params.widget.metrics.every((metric) => {
+ const measureDefinition = viewDeclaration.measures[metric.measure];
+ if (!measureDefinition) {
+ return false;
+ }
+
+ return getValidAggregationsForMeasureType(measureDefinition.type).some(
+ (aggregation) => aggregation === metric.agg,
+ );
+ });
+
+ const dimensionsFitChartType =
+ params.widget.chartType === "PIVOT_TABLE"
+ ? true
+ : params.widget.dimensions.length <= 1;
+ const pivotTableShapeIsValid =
+ params.widget.chartType !== "PIVOT_TABLE" ||
+ (params.widget.dimensions.length <= MAX_PIVOT_TABLE_DIMENSIONS &&
+ params.widget.metrics.length <= MAX_PIVOT_TABLE_METRICS);
+
+ if (
+ !dimensionsAreValid ||
+ !metricsAreValid ||
+ !dimensionsFitChartType ||
+ !pivotTableShapeIsValid
+ ) {
+ throw new Error("malformed");
+ }
+}
+
+export function toImportedWidgetFormSnapshot(
+ widget: WidgetImport,
+): ImportedWidgetFormSnapshot {
+ const importedMetrics =
+ widget.metrics.length > 0
+ ? widget.metrics
+ : [{ measure: "count", agg: "count" as const }];
+ const importedDimensions =
+ widget.chartType === "PIVOT_TABLE"
+ ? widget.dimensions
+ : widget.dimensions.slice(0, 1);
+ const importedChartConfig = widget.chartConfig;
+
+ return {
+ widgetMinVersion: widget.minVersion ?? 1,
+ widgetName: widget.name,
+ widgetDescription: widget.description,
+ selectedView: widget.view,
+ selectedChartType: widget.chartType,
+ selectedMeasure: importedMetrics[0]?.measure ?? "count",
+ selectedAggregation: importedMetrics[0]?.agg ?? "count",
+ selectedMetrics: importedMetrics.map((metric) => ({
+ id: `${metric.agg}_${metric.measure}`,
+ measure: metric.measure,
+ aggregation: metric.agg,
+ label: `${startCase(metric.agg)} ${startCase(metric.measure)}`,
+ })),
+ selectedDimension: importedDimensions[0]?.field ?? "none",
+ pivotDimensions: importedDimensions.map((dimension) => dimension.field),
+ userFilterState: normalizeStoredWidgetFiltersForEditor(
+ widget.view,
+ widget.filters,
+ ).editorFilters,
+ rowLimit:
+ "row_limit" in importedChartConfig
+ ? (importedChartConfig.row_limit ?? 100)
+ : 100,
+ histogramBins:
+ importedChartConfig.type === "HISTOGRAM"
+ ? (importedChartConfig.bins ?? 10)
+ : 10,
+ defaultSortColumn:
+ importedChartConfig.type === "PIVOT_TABLE"
+ ? (importedChartConfig.defaultSort?.column ?? "none")
+ : "none",
+ defaultSortOrder:
+ importedChartConfig.type === "PIVOT_TABLE"
+ ? (importedChartConfig.defaultSort?.order ?? "DESC")
+ : "DESC",
+ };
+}
+
+function normalizeImportedWidgetVersion(widget: WidgetImport): WidgetImport {
+ if (widget.view !== "traces") {
+ return widget;
+ }
+
+ return {
+ ...widget,
+ minVersion: 1,
+ };
+}
+
+export async function importWidgetFile(params: {
+ file: File;
+ optionSets: WidgetImportOptionSets;
+ isBetaEnabled: boolean;
+}): Promise<ImportedWidgetResult> {
+ const rawContent = await params.file.text();
+ const parsedJson: unknown = JSON.parse(rawContent);
+ const allowedValuesByColumn = buildWidgetImportAllowedValues(
+ params.optionSets,
+ parsedJson,
+ );
+
+ const {
+ widget: importedWidget,
+ removedValues,
+ removedFilters,
+ } = parseAndNormalizeImportedWidget({
+ parsedJson,
+ allowedValuesByColumn,
+ });
+
+ const normalizedWidget = normalizeImportedWidgetVersion(importedWidget);
+ const importedMinVersion = normalizedWidget.minVersion ?? 1;
+ const importedViewVersion: ViewVersion =
+ (params.isBetaEnabled && normalizedWidget.view !== "traces") ||
+ importedMinVersion >= 2
+ ? "v2"
+ : "v1";
+
+ validateImportedWidget({
+ widget: normalizedWidget,
+ importedViewVersion,
+ });
+
+ return {
+ snapshot: toImportedWidgetFormSnapshot(normalizedWidget),
+ removedValues,
+ removedFilters,
+ };
+}
diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
index b2e8eec0ec..c73d7c491e 100644
--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
@@ -4,7 +4,7 @@ import { api } from "@/src/utils/api";
import { WidgetForm } from "@/src/features/widgets/components/WidgetForm";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
-import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+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";
diff --git a/web/src/server/api/routers/dashboardWidgets.ts b/web/src/server/api/routers/dashboardWidgets.ts
index 2a32f14fa4..01aa2d15aa 100644
--- a/web/src/server/api/routers/dashboardWidgets.ts
+++ b/web/src/server/api/routers/dashboardWidgets.ts
@@ -73,7 +73,10 @@ const viewMapping: Record<string, DashboardWidgetViews> = {
};
// Reverse mapping for client-side use
-const reverseViewMapping: Record<DashboardWidgetViews, string> = {
+const reverseViewMapping: Record<
+ DashboardWidgetViews,
+ z.infer<typeof views>
+> = {
[DashboardWidgetViews.TRACES]: "traces",
[DashboardWidgetViews.OBSERVATIONS]: "observations",
[DashboardWidgetViews.SCORES_NUMERIC]: "scores-numeric",
@@ -208,6 +211,7 @@ export const dashboardWidgetRouter = createTRPCRouter({
return {
...widget,
view: reverseViewMapping[widget.view],
+ metrics: widget.metrics,
owner: widget.owner,
};
}),