πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(dashboards): widget menus, copy-paste, and versioned JSON import/export (LFE-10807) (#14965)
Nikita Kabardinf378e6c94fd3
diff --git a/web/src/features/dashboard/utils/dashboard-import-export.clienttest.ts b/web/src/features/dashboard/utils/dashboard-import-export.clienttest.tsnew file mode 100644index 0000000000..330ace1fe9--- /dev/null+++ b/web/src/features/dashboard/utils/dashboard-import-export.clienttest.ts@@ -0,0 +1,272 @@+import { HOME_DASHBOARD_PRESET_IDS } from "@langfuse/shared";+import {+ buildDashboardExport,+ buildPresetExport,+ DASHBOARD_FILE_FORMAT_VERSION,+ isPasteablePlacementPayload,+ parseDashboardImport,+ parsePastedPreset,+ PRESET_FILE_FORMAT_VERSION,+} from "./dashboard-import-export";+import {+ buildWidgetExport,+ type WidgetExportSource,+} from "@/src/features/widgets/utils/import-export-utils";++const baseWidget: WidgetExportSource = {+ name: "Trace count",+ description: "",+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", agg: "count" }],+ filters: [],+ chartType: "NUMBER",+ chartConfig: { type: "NUMBER" },+ minVersion: 1,+};++const basePosition = { x: 0, y: 0, x_size: 6, y_size: 6 };++describe("buildDashboardExport", () => {+ it("wraps the definition in the dashboard envelope and inlines widgets", () => {+ const { exportPayload, skippedWidgetCount } = buildDashboardExport({+ name: "My dashboard",+ description: "desc",+ filters: [],+ placements: [+ { type: "widget", widgetId: "w1", ...basePosition },+ {+ type: "preset",+ presetId: HOME_DASHBOARD_PRESET_IDS[0],+ ...basePosition,+ x: 6,+ },+ ],+ widgetsById: new Map([["w1", baseWidget]]),+ });++ expect(exportPayload.$langfuseDashboard).toBe(true);+ expect(exportPayload.version).toBe(DASHBOARD_FILE_FORMAT_VERSION);+ expect(skippedWidgetCount).toBe(0);+ const widgets = exportPayload.widgets as Record<string, any>[];+ expect(widgets).toHaveLength(2);+ expect(widgets[0].widget.$langfuseWidget).toBe(true);+ expect(widgets[0].widget.name).toBe("Trace count");+ expect(widgets[1].presetId).toBe(HOME_DASHBOARD_PRESET_IDS[0]);+ });++ it("skips placements whose widget row cannot be resolved", () => {+ const { exportPayload, skippedWidgetCount } = buildDashboardExport({+ name: "My dashboard",+ description: "",+ filters: [],+ placements: [+ { type: "widget", widgetId: "gone", ...basePosition },+ { type: "widget", widgetId: "w1", ...basePosition },+ ],+ widgetsById: new Map([["w1", baseWidget]]),+ });++ expect(skippedWidgetCount).toBe(1);+ expect(exportPayload.widgets as unknown[]).toHaveLength(1);+ });+});++describe("parseDashboardImport", () => {+ const validExport = () =>+ buildDashboardExport({+ name: "Shared dashboard",+ description: "",+ filters: [],+ placements: [+ { type: "widget", widgetId: "w1", ...basePosition },+ {+ type: "preset",+ presetId: HOME_DASHBOARD_PRESET_IDS[0],+ ...basePosition,+ y: 6,+ },+ ],+ widgetsById: new Map([["w1", baseWidget]]),+ }).exportPayload;++ it("ignores payloads without the dashboard envelope", () => {+ expect(+ parseDashboardImport(JSON.stringify({ widgets: [] }), {+ isBetaEnabled: false,+ }),+ ).toEqual({ status: "not-dashboard" });+ expect(+ parseDashboardImport("plain text", { isBetaEnabled: false }),+ ).toEqual({ status: "not-dashboard" });+ });++ it("round-trips an exported dashboard", () => {+ const result = parseDashboardImport(JSON.stringify(validExport()), {+ isBetaEnabled: false,+ });++ expect(result.status).toBe("dashboard");+ if (result.status === "dashboard") {+ expect(result.dashboard.name).toBe("Shared dashboard");+ expect(result.dashboard.placements).toHaveLength(2);+ expect(result.dashboard.placements[0]).toMatchObject({+ type: "widget",+ x: 0,+ y: 0,+ x_size: 6,+ y_size: 6,+ });+ expect(result.dashboard.placements[1]).toMatchObject({+ type: "preset",+ presetId: HOME_DASHBOARD_PRESET_IDS[0],+ });+ expect(result.dashboard.skippedPresetCount).toBe(0);+ }+ });++ it("rejects a newer format version with a reason", () => {+ const result = parseDashboardImport(+ JSON.stringify({+ ...validExport(),+ version: DASHBOARD_FILE_FORMAT_VERSION + 1,+ }),+ { isBetaEnabled: false },+ );++ expect(result.status).toBe("invalid");+ if (result.status === "invalid") {+ expect(result.reason).toContain("format version");+ }+ });++ it("skips unknown preset cards instead of failing", () => {+ const payload = validExport();+ (payload.widgets as Record<string, unknown>[]).push({+ type: "preset",+ presetId: "from-the-future",+ ...basePosition,+ y: 12,+ });++ const result = parseDashboardImport(JSON.stringify(payload), {+ isBetaEnabled: false,+ });++ expect(result.status).toBe("dashboard");+ if (result.status === "dashboard") {+ expect(result.dashboard.skippedPresetCount).toBe(1);+ expect(result.dashboard.placements).toHaveLength(2);+ }+ });++ it("rejects a dashboard containing a malformed widget, naming it", () => {+ const payload = validExport();+ const widgets = payload.widgets as Record<string, any>[];+ widgets[0].widget = { ...widgets[0].widget, chartConfig: { type: "PIE" } };++ const result = parseDashboardImport(JSON.stringify(payload), {+ isBetaEnabled: false,+ });++ expect(result.status).toBe("invalid");+ if (result.status === "invalid") {+ expect(result.reason).toContain("Trace count");+ }+ });++ it("rejects a dashboard with no importable widgets", () => {+ const result = parseDashboardImport(+ JSON.stringify({+ $langfuseDashboard: true,+ version: 1,+ name: "Empty",+ widgets: [],+ }),+ { isBetaEnabled: false },+ );++ expect(result.status).toBe("invalid");+ });++ it("explains a dashboard whose only content is unknown preset cards", () => {+ const result = parseDashboardImport(+ JSON.stringify({+ $langfuseDashboard: true,+ version: 1,+ name: "Future presets",+ widgets: [+ {+ type: "preset",+ presetId: "from-the-future",+ ...basePosition,+ },+ ],+ }),+ { isBetaEnabled: false },+ );++ expect(result.status).toBe("invalid");+ if (result.status === "invalid") {+ expect(result.reason).toContain("preset cards");+ }+ });+});++describe("parsePastedPreset", () => {+ it("round-trips a preset export", () => {+ const result = parsePastedPreset(+ JSON.stringify(buildPresetExport(HOME_DASHBOARD_PRESET_IDS[0])),+ );++ expect(result).toEqual({+ status: "preset",+ presetId: HOME_DASHBOARD_PRESET_IDS[0],+ });+ });++ it("ignores payloads without the preset envelope", () => {+ expect(parsePastedPreset("not json")).toEqual({ status: "not-preset" });+ expect(parsePastedPreset(JSON.stringify({ presetId: "x" }))).toEqual({+ status: "not-preset",+ });+ });++ it("rejects unknown preset ids and newer format versions", () => {+ expect(+ parsePastedPreset(JSON.stringify(buildPresetExport("from-the-future"))),+ ).toMatchObject({ status: "invalid" });+ expect(+ parsePastedPreset(+ JSON.stringify({+ ...buildPresetExport(HOME_DASHBOARD_PRESET_IDS[0]),+ version: PRESET_FILE_FORMAT_VERSION + 1,+ }),+ ),+ ).toMatchObject({ status: "invalid" });+ });+});++describe("isPasteablePlacementPayload", () => {+ it("accepts widget and preset payloads, rejects everything else", () => {+ expect(+ isPasteablePlacementPayload(+ JSON.stringify(buildWidgetExport(baseWidget)),+ {+ isBetaEnabled: false,+ },+ ),+ ).toBe(true);+ expect(+ isPasteablePlacementPayload(+ JSON.stringify(buildPresetExport(HOME_DASHBOARD_PRESET_IDS[0])),+ { isBetaEnabled: false },+ ),+ ).toBe(true);+ expect(+ isPasteablePlacementPayload('{"hello": "world"}', {+ isBetaEnabled: false,+ }),+ ).toBe(false);+ });+});diff --git a/web/src/features/dashboard/utils/dashboard-import-export.ts b/web/src/features/dashboard/utils/dashboard-import-export.tsnew file mode 100644index 0000000000..bb82cc822a--- /dev/null+++ b/web/src/features/dashboard/utils/dashboard-import-export.ts@@ -0,0 +1,342 @@+import { z } from "zod";+import {+ HOME_DASHBOARD_PRESET_IDS,+ type HomeDashboardPresetId,+ type FilterState,+} from "@langfuse/shared";+import {+ buildWidgetExport,+ parseImportedWidgetJson,+ parsePastedWidget,+ type WidgetExportSource,+ type WidgetImport,+} from "@/src/features/widgets/utils/import-export-utils";++/**+ * Dashboard JSON file-format version. `$langfuseDashboard: true` marks a JSON+ * payload as a Langfuse dashboard export; `version` is the version of that+ * envelope. A dashboard file inlines each referenced widget's portable+ * configuration (widgets are recreated on import β DB widget ids do not+ * travel across projects/instances).+ */+export const DASHBOARD_FILE_FORMAT_VERSION = 1;++export function isLangfuseDashboardPayload(parsed: unknown): boolean {+ return (+ typeof parsed === "object" &&+ parsed !== null &&+ "$langfuseDashboard" in parsed &&+ (parsed as Record<string, unknown>).$langfuseDashboard === true+ );+}++/**+ * Preset cards (curated Home components) have no widget configuration β the+ * portable payload is just the preset id in its own envelope, so copy-paste+ * works uniformly across every tile on a dashboard.+ */+export const PRESET_FILE_FORMAT_VERSION = 1;++export function buildPresetExport(presetId: string) {+ return {+ $langfusePreset: true as const,+ version: PRESET_FILE_FORMAT_VERSION,+ presetId,+ };+}++export type PastedPresetParseResult =+ | { status: "not-preset" }+ | { status: "invalid"; reason: string }+ | { status: "preset"; presetId: HomeDashboardPresetId };++export function parsePastedPreset(text: string): PastedPresetParseResult {+ let parsedJson: unknown;+ try {+ parsedJson = JSON.parse(text);+ } catch {+ return { status: "not-preset" };+ }++ if (+ typeof parsedJson !== "object" ||+ parsedJson === null ||+ (parsedJson as Record<string, unknown>).$langfusePreset !== true+ ) {+ return { status: "not-preset" };+ }++ const payload = parsedJson as Record<string, unknown>;+ if (+ typeof payload.version === "number" &&+ payload.version > PRESET_FILE_FORMAT_VERSION+ ) {+ return {+ status: "invalid",+ reason: `This card uses format version ${payload.version}; this Langfuse version supports up to ${PRESET_FILE_FORMAT_VERSION}.`,+ };+ }++ if (+ typeof payload.presetId !== "string" ||+ !(HOME_DASHBOARD_PRESET_IDS as readonly string[]).includes(payload.presetId)+ ) {+ return {+ status: "invalid",+ reason: "This preset card is not available in this Langfuse version.",+ };+ }++ return {+ status: "preset",+ presetId: payload.presetId as HomeDashboardPresetId,+ };+}++/**+ * True when the text is a payload our paste surfaces can place on a+ * dashboard β a widget export or a preset-card export. Used to gate "Paste"+ * menu items via the clipboard probe.+ */+export function isPasteablePlacementPayload(+ text: string,+ params: { isBetaEnabled: boolean },+): boolean {+ if (parsePastedWidget(text, params).status === "widget") return true;+ return parsePastedPreset(text).status === "preset";+}++type PlacementPosition = {+ x: number;+ y: number;+ x_size: number;+ y_size: number;+};++const placementPositionSchema = {+ x: z.number().int().gte(0),+ y: z.number().int().gte(0),+ x_size: z.number().int().positive(),+ y_size: z.number().int().positive(),+};++const dashboardImportPlacementSchema = z.discriminatedUnion("type", [+ z+ .object({+ type: z.literal("widget"),+ ...placementPositionSchema,+ // Validated per widget via parseImportedWidgetJson for normalization+ // and precise failure reasons.+ widget: z.unknown(),+ })+ .loose(),+ z+ .object({+ type: z.literal("preset"),+ ...placementPositionSchema,+ presetId: z.string(),+ })+ .loose(),+]);++const dashboardImportSchema = z+ .object({+ $langfuseDashboard: z.literal(true),+ version: z.number().int().positive(),+ name: z.string(),+ description: z.string().optional(),+ widgets: z.array(dashboardImportPlacementSchema),+ })+ .loose();++export type DashboardExportPlacement =+ | ({ type: "widget"; widgetId: string } & PlacementPosition)+ | ({ type: "preset"; presetId: string } & PlacementPosition);++/**+ * The canonical dashboard file shape accepted by drag-drop import: dashboard+ * metadata plus each placement with its widget's portable configuration+ * inlined. There is deliberately no in-app dashboard download (widget-level+ * export covers sharing; Clone covers same-project duplication) β this+ * builder documents the format and backs the import round-trip tests.+ * Placements whose widget cannot be resolved are skipped and counted.+ */+export function buildDashboardExport(params: {+ name: string;+ description: string;+ filters: FilterState;+ placements: DashboardExportPlacement[];+ widgetsById: Map<string, WidgetExportSource>;+}): { exportPayload: Record<string, unknown>; skippedWidgetCount: number } {+ let skippedWidgetCount = 0;+ const widgets: Record<string, unknown>[] = [];++ for (const placement of params.placements) {+ const position = {+ x: placement.x,+ y: placement.y,+ x_size: placement.x_size,+ y_size: placement.y_size,+ };+ if (placement.type === "preset") {+ widgets.push({+ type: "preset",+ presetId: placement.presetId,+ ...position,+ });+ continue;+ }+ const source = params.widgetsById.get(placement.widgetId);+ if (!source) {+ skippedWidgetCount += 1;+ continue;+ }+ widgets.push({+ type: "widget",+ ...position,+ widget: buildWidgetExport(source),+ });+ }++ return {+ exportPayload: {+ $langfuseDashboard: true,+ version: DASHBOARD_FILE_FORMAT_VERSION,+ name: params.name,+ description: params.description,+ filters: params.filters,+ widgets,+ },+ skippedWidgetCount,+ };+}++export type ParsedDashboardImportPlacement =+ | ({ type: "widget"; widget: WidgetImport } & PlacementPosition)+ | ({ type: "preset"; presetId: HomeDashboardPresetId } & PlacementPosition);++export type ParsedDashboardImport = {+ name: string;+ placements: ParsedDashboardImportPlacement[];+ /** Presets in the file this Langfuse version does not know β dropped. */+ skippedPresetCount: number;+ /** True when any widget lost filters during column normalization. */+ removedFilters: boolean;+};++export type DashboardImportParseResult =+ | { status: "not-dashboard" }+ | { status: "invalid"; reason: string }+ | { status: "dashboard"; dashboard: ParsedDashboardImport };++/**+ * Parses dropped text into a dashboard import. Payloads without the Langfuse+ * dashboard envelope are "not-dashboard" (callers may fall back to the widget+ * parser); enveloped payloads that fail validation are "invalid" with a+ * user-facing reason.+ */+export function parseDashboardImport(+ text: string,+ params: { isBetaEnabled: boolean },+): DashboardImportParseResult {+ let parsedJson: unknown;+ try {+ parsedJson = JSON.parse(text);+ } catch {+ return { status: "not-dashboard" };+ }++ if (!isLangfuseDashboardPayload(parsedJson)) {+ return { status: "not-dashboard" };+ }++ const declaredVersion = (parsedJson as Record<string, unknown>).version;+ if (+ typeof declaredVersion === "number" &&+ declaredVersion > DASHBOARD_FILE_FORMAT_VERSION+ ) {+ return {+ status: "invalid",+ reason: `This dashboard uses format version ${declaredVersion}; this Langfuse version supports up to ${DASHBOARD_FILE_FORMAT_VERSION}.`,+ };+ }++ const parsed = dashboardImportSchema.safeParse(parsedJson);+ if (!parsed.success) {+ return {+ status: "invalid",+ reason: "The dashboard configuration is malformed or not supported.",+ };+ }++ const placements: ParsedDashboardImportPlacement[] = [];+ let skippedPresetCount = 0;+ let removedFilters = false;++ for (const [index, placement] of parsed.data.widgets.entries()) {+ const position = {+ x: placement.x,+ y: placement.y,+ x_size: placement.x_size,+ y_size: placement.y_size,+ };++ if (placement.type === "preset") {+ if (+ (HOME_DASHBOARD_PRESET_IDS as readonly string[]).includes(+ placement.presetId,+ )+ ) {+ placements.push({+ type: "preset",+ presetId: placement.presetId as HomeDashboardPresetId,+ ...position,+ });+ } else {+ skippedPresetCount += 1;+ }+ continue;+ }++ try {+ const result = parseImportedWidgetJson({+ parsedJson: placement.widget,+ isBetaEnabled: params.isBetaEnabled,+ });+ removedFilters = removedFilters || result.removedFilters;+ placements.push({ type: "widget", widget: result.widget, ...position });+ } catch {+ const widgetName =+ typeof placement.widget === "object" &&+ placement.widget !== null &&+ "name" in placement.widget &&+ typeof placement.widget.name === "string"+ ? `"${placement.widget.name}"`+ : `#${index + 1}`;+ return {+ status: "invalid",+ reason: `Widget ${widgetName} in the dashboard file is malformed or not supported.`,+ };+ }+ }++ if (placements.length === 0) {+ return {+ status: "invalid",+ reason:+ skippedPresetCount > 0+ ? "The dashboard file only contains preset cards that are not available in this Langfuse version."+ : "The dashboard file contains no importable widgets.",+ };+ }++ return {+ status: "dashboard",+ dashboard: {+ name: parsed.data.name,+ placements,+ skippedPresetCount,+ removedFilters,+ },+ };+}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 9336a6e9b0..501f28b884 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -155,6 +155,12 @@ export const events = {"clone_open_existing_click","widget_copy_first_open","widget_copied_to_project",+ "widget_json_downloaded",+ "widget_copied_to_clipboard",+ "widget_pasted",+ "widget_paste_rejected",+ "widget_duplicated",+ "dashboard_json_imported","add_widget_dialog_open","add_widget_tab_switch","widget_added",diff --git a/web/src/features/widgets/chart-library/DownloadButton.tsx b/web/src/features/widgets/chart-library/DownloadButton.tsxdeleted file mode 100644index b178c1b5e0..0000000000--- a/web/src/features/widgets/chart-library/DownloadButton.tsx+++ /dev/null@@ -1,79 +0,0 @@-import { Download, Check } from "lucide-react";-import { useState } from "react";--export function DownloadButton({- data,- fileName = "chart-data",- className,-}: {- data: Record<string, any>[];- fileName?: string;- className?: string;-}) {- const [isDownloaded, setIsDownloaded] = useState(false);-- const escapeCsvValue = (value: any): string => {- const stringValue = String(value ?? "");- if (- stringValue.includes(",") ||- stringValue.includes('"') ||- stringValue.includes("\n")- ) {- return `"${stringValue.replace(/"/g, '""')}"`;- }- return stringValue;- };-- const triggerDownload = (csvContent: string) => {- const blob = new Blob([csvContent], { type: "text/csv" });- const url = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = url;- a.download = `${fileName}.csv`;- document.body.appendChild(a);- a.click();- a.remove();- URL.revokeObjectURL(url);-- // Show checkmark for 1 second- setIsDownloaded(true);- setTimeout(() => {- setIsDownloaded(false);- }, 1000);- };-- const downloadCsv = () => {- if (data.length === 0) {- triggerDownload("");- return;- }-- const headers = Object.keys(data[0]);- const csvRows = [- headers.join(","),- ...data.map((row) =>- headers.map((h) => escapeCsvValue(row[h])).join(","),- ),- ];-- const csvContent = csvRows.join("\n");- triggerDownload(csvContent);- };-- return (- <button- onClick={() => {- if (isDownloaded) {- return;- }- downloadCsv();- }}- className={`text-muted-foreground hover:text-foreground ${className || ""}`}- aria-label="Download chart data as CSV"- title="Download CSV"- disabled={isDownloaded}- >- {isDownloaded ? <Check size={16} /> : <Download size={16} />}- </button>- );-}diff --git a/web/src/features/widgets/chart-library/downloadChartDataCsv.ts b/web/src/features/widgets/chart-library/downloadChartDataCsv.tsnew file mode 100644index 0000000000..27f9488d21--- /dev/null+++ b/web/src/features/widgets/chart-library/downloadChartDataCsv.ts@@ -0,0 +1,41 @@+const escapeCsvValue = (value: any): string => {+ const stringValue = String(value ?? "");+ if (+ stringValue.includes(",") ||+ stringValue.includes('"') ||+ stringValue.includes("\n")+ ) {+ return `"${stringValue.replace(/"/g, '""')}"`;+ }+ return stringValue;+};++/**+ * Downloads a widget's chart DATA rows as CSV. Not to be confused with the+ * widget's configuration export (`downloadWidgetJson`).+ */+export function downloadChartDataCsv(+ data: Record<string, any>[],+ fileName = "chart-data",+) {+ const headers = data.length > 0 ? Object.keys(data[0]) : [];+ const csvContent =+ data.length === 0+ ? ""+ : [+ headers.join(","),+ ...data.map((row) =>+ headers.map((h) => escapeCsvValue(row[h])).join(","),+ ),+ ].join("\n");++ const blob = new Blob([csvContent], { type: "text/csv" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `${fileName}.csv`;+ document.body.appendChild(a);+ a.click();+ a.remove();+ URL.revokeObjectURL(url);+}diff --git a/web/src/features/widgets/components/DashboardGrid.tsx b/web/src/features/widgets/components/DashboardGrid.tsxindex 7e2689d6e3..85282ddce7 100644--- a/web/src/features/widgets/components/DashboardGrid.tsx+++ b/web/src/features/widgets/components/DashboardGrid.tsx@@ -2,6 +2,7 @@ import { Responsive } from "react-grid-layout";import "react-grid-layout/css/styles.css";import "react-resizable/css/styles.css";import { type WidgetPlacement } from "../components/DashboardWidget";+import { type WidgetExportSource } from "@/src/features/widgets/utils/import-export-utils";import {PresetDashboardWidget,type PresetPlacement,@@ -77,6 +78,9 @@ export function DashboardGrid({getWidgetSchedulerId,onLockedEditAttempt,readOnly,+ onPasteWidget,+ onDuplicateWidget,+ onDuplicatePreset,}: {widgets: DashboardPlacement[];onChange: (widgets: DashboardPlacement[]) => void;@@ -97,6 +101,15 @@ export function DashboardGrid({onLockedEditAttempt?: () => void;/** Pure viewing surface (e.g. Home): tiles render no edit affordances. */readOnly?: boolean;+ /** Paste the clipboard widget/card next to a tile (editable dashboards only). */+ onPasteWidget?: (anchor: DashboardPlacement) => void;+ /** Duplicate a tile's widget next to it (editable dashboards only). */+ onDuplicateWidget?: (+ anchor: WidgetPlacement,+ widget: WidgetExportSource,+ ) => void;+ /** Duplicate a preset card next to it (editable dashboards only). */+ onDuplicatePreset?: (anchor: PresetPlacement) => void;}) {const { containerRef, width } = useDebouncedContainerWidth(200);// Rows stay 16:9-proportional to column width, with a floor so tiles keep a@@ -166,6 +179,8 @@ export function DashboardGrid({schedulerId={getWidgetSchedulerId?.(widget.id)}onLockedEditAttempt={onLockedEditAttempt}readOnly={readOnly}+ onPasteWidget={onPasteWidget}+ onDuplicatePreset={onDuplicatePreset}/>) : (<DashboardWidget@@ -179,6 +194,8 @@ export function DashboardGrid({schedulerId={getWidgetSchedulerId?.(widget.id)}onLockedEditAttempt={onLockedEditAttempt}readOnly={readOnly}+ onPasteWidget={onPasteWidget}+ onDuplicateWidget={onDuplicateWidget}/>);diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex bb1db82f2f..9da5d46125 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -17,11 +17,36 @@ import { type z } from "zod";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { type FilterState, type OrderByState } from "@langfuse/shared";import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";-import { PencilIcon, TrashIcon, GripVerticalIcon } from "lucide-react";+import {+ PencilIcon,+ TrashIcon,+ GripVerticalIcon,+ MoreVerticalIcon,+ CopyIcon,+ ClipboardPasteIcon,+ CopyPlusIcon,+ FileJsonIcon,+ DownloadIcon,+} from "lucide-react";import { useRouter } from "next/router";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { showErrorToast } from "@/src/features/notifications/showErrorToast";-import { DownloadButton } from "@/src/features/widgets/chart-library/DownloadButton";+import { downloadChartDataCsv } from "@/src/features/widgets/chart-library/downloadChartDataCsv";+import {+ buildWidgetExport,+ downloadWidgetJson,+ type WidgetExportSource,+} from "@/src/features/widgets/utils/import-export-utils";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import { useClipboardWidgetProbe } from "@/src/features/widgets/hooks/useClipboardWidgetProbe";+import { isPasteablePlacementPayload } from "@/src/features/dashboard/utils/dashboard-import-export";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";import {formatMetricName,shouldUseWidgetSSE,@@ -61,6 +86,8 @@ export function DashboardWidget({schedulerId,onLockedEditAttempt,readOnly,+ onPasteWidget,+ onDuplicateWidget,}: {projectId: string;dashboardId: string;@@ -78,6 +105,19 @@ export function DashboardWidget({onLockedEditAttempt?: () => void;/** Pure viewing surface (e.g. Home): render no edit affordances. */readOnly?: boolean;+ /**+ * Pastes the clipboard widget next to this tile. Passed only on editable+ * (non-locked) dashboards; absent β no "Paste to the right" menu item.+ */+ onPasteWidget?: (anchor: WidgetPlacement) => void;+ /**+ * Duplicates this widget (new widget row seeded from `widget`) next to this+ * tile. Passed only on editable (non-locked) dashboards.+ */+ onDuplicateWidget?: (+ anchor: WidgetPlacement,+ widget: WidgetExportSource,+ ) => void;}) {const router = useRouter();const utils = api.useUtils();@@ -133,6 +173,17 @@ export function DashboardWidget({});const [retryCount, setRetryCount] = useState(0);const [isCopyDialogOpen, setIsCopyDialogOpen] = useState(false);+ const [isActionsMenuOpen, setIsActionsMenuOpen] = useState(false);+ // Gate "Paste to the right" on the clipboard actually holding a pasteable+ // payload, where the browser lets us check silently.+ const isPasteablePayload = useCallback(+ (text: string) => isPasteablePlacementPayload(text, { isBetaEnabled }),+ [isBetaEnabled],+ );+ const clipboardProbe = useClipboardWidgetProbe(+ isActionsMenuOpen && Boolean(onPasteWidget),+ isPasteablePayload,+ );// Apply defaultSort when it becomes available (after widget data loads)// but only if user hasn't interacted yet@@ -467,6 +518,48 @@ export function DashboardWidget({);}+ // Portable configuration of this widget, used by the copy / download /+ // duplicate menu actions.+ const widgetExportSource: WidgetExportSource = {+ name: widget.data.name,+ description: widget.data.description,+ view: widget.data.view,+ dimensions: widget.data.dimensions,+ metrics: widget.data.metrics.map((metric) => ({+ measure: metric.measure,+ agg: metric.agg as z.infer<typeof metricAggregations>,+ })),+ filters: widget.data.filters,+ chartType: widget.data.chartType,+ chartConfig: widget.data.chartConfig,+ minVersion: widget.data.minVersion,+ };++ const handleCopyToClipboard = async () => {+ try {+ await copyTextToClipboard(+ JSON.stringify(buildWidgetExport(widgetExportSource), null, 2),+ );+ capture("dashboard:widget_copied_to_clipboard", {+ surface: "grid_menu",+ kind: "widget",+ widget_id: placement.widgetId,+ dashboard_id: dashboardId,+ });+ } catch {+ showErrorToast("Copy failed", "Could not write to the clipboard.");+ }+ };++ const handleDownloadJson = () => {+ downloadWidgetJson(widgetExportSource);+ capture("dashboard:widget_json_downloaded", {+ surface: "grid_menu",+ widget_id: placement.widgetId,+ dashboard_id: dashboardId,+ });+ };+return (<div className="bg-background group flex h-full w-full flex-col overflow-hidden rounded-lg border p-4">{isCopyDialogOpen && (@@ -543,14 +636,56 @@ export function DashboardWidget({</button></>)}- {/* Download button is available once chart data has loaded */}- {!queryResult.isPending ? (- <DownloadButton- data={transformedData}- fileName={widget.data.name}- className="hidden group-hover:block"- />- ) : null}+ <DropdownMenu onOpenChange={setIsActionsMenuOpen}>+ <DropdownMenuTrigger asChild>+ <button+ className="text-muted-foreground hover:text-foreground hidden group-hover:block data-[state=open]:block"+ aria-label="Widget actions"+ >+ <MoreVerticalIcon size={16} />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={handleCopyToClipboard}>+ <CopyIcon className="mr-2 h-4 w-4" />+ Copy to clipboard+ </DropdownMenuItem>+ {onPasteWidget && (+ <DropdownMenuItem+ disabled={clipboardProbe === "no-widget"}+ onClick={() => onPasteWidget(placement)}+ >+ <ClipboardPasteIcon className="mr-2 h-4 w-4" />+ Paste to the right+ </DropdownMenuItem>+ )}+ {onDuplicateWidget && (+ <DropdownMenuItem+ onClick={() =>+ onDuplicateWidget(placement, widgetExportSource)+ }+ >+ <CopyPlusIcon className="mr-2 h-4 w-4" />+ Duplicate+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={handleDownloadJson}>+ <FileJsonIcon className="mr-2 h-4 w-4" />+ Download as JSON+ </DropdownMenuItem>+ {/* Chart data download needs the query result to have loaded */}+ <DropdownMenuItem+ disabled={queryResult.isPending}+ onClick={() =>+ downloadChartDataCsv(transformedData, widget.data.name)+ }+ >+ <DownloadIcon className="mr-2 h-4 w-4" />+ Download data as CSV+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></div></div><divdiff --git a/web/src/features/widgets/components/PresetDashboardWidget.tsx b/web/src/features/widgets/components/PresetDashboardWidget.tsxindex bad3306268..881c89262f 100644--- a/web/src/features/widgets/components/PresetDashboardWidget.tsx+++ b/web/src/features/widgets/components/PresetDashboardWidget.tsx@@ -1,5 +1,12 @@-import { useMemo } from "react";-import { GripVerticalIcon, TrashIcon } from "lucide-react";+import { useCallback, useMemo, useState } from "react";+import {+ ClipboardPasteIcon,+ CopyIcon,+ CopyPlusIcon,+ GripVerticalIcon,+ MoreVerticalIcon,+ TrashIcon,+} from "lucide-react";import { type FilterState } from "@langfuse/shared";import { type ViewVersion } from "@langfuse/shared/query";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";@@ -9,6 +16,20 @@ import {getHomePreset,type PresetWidgetContext,} from "@/src/features/dashboard/components/home-preset-registry";+import {+ buildPresetExport,+ isPasteablePlacementPayload,+} from "@/src/features/dashboard/utils/dashboard-import-export";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useClipboardWidgetProbe } from "@/src/features/widgets/hooks/useClipboardWidgetProbe";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";/*** A "preset" dashboard placement: renders a registered curated component by@@ -36,6 +57,8 @@ export function PresetDashboardWidget({schedulerId,onLockedEditAttempt,readOnly,+ onPasteWidget,+ onDuplicatePreset,}: {projectId: string;dashboardId: string;@@ -53,6 +76,16 @@ export function PresetDashboardWidget({onLockedEditAttempt?: () => void;/** Pure viewing surface (e.g. Home): render no edit affordances. */readOnly?: boolean;+ /**+ * Pastes the clipboard widget/card next to this tile. Passed only on+ * editable (non-locked) dashboards.+ */+ onPasteWidget?: (anchor: PresetPlacement) => void;+ /**+ * Adds another placement of this preset card next to this tile. Passed+ * only on editable (non-locked) dashboards.+ */+ onDuplicatePreset?: (anchor: PresetPlacement) => void;}) {const { isBetaEnabled } = useV4Beta();const metricsVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";@@ -133,6 +166,35 @@ export function PresetDashboardWidget({}};+ const capture = usePostHogClientCapture();+ const [isActionsMenuOpen, setIsActionsMenuOpen] = useState(false);+ // Gate "Paste to the right" on the clipboard actually holding a pasteable+ // payload, where the browser lets us check silently.+ const isPasteablePayload = useCallback(+ (text: string) => isPasteablePlacementPayload(text, { isBetaEnabled }),+ [isBetaEnabled],+ );+ const clipboardProbe = useClipboardWidgetProbe(+ isActionsMenuOpen && Boolean(onPasteWidget),+ isPasteablePayload,+ );++ const handleCopyToClipboard = async () => {+ try {+ await copyTextToClipboard(+ JSON.stringify(buildPresetExport(placement.presetId), null, 2),+ );+ capture("dashboard:widget_copied_to_clipboard", {+ surface: "grid_menu",+ kind: "preset",+ preset_id: placement.presetId,+ dashboard_id: dashboardId,+ });+ } catch {+ showErrorToast("Copy failed", "Could not write to the clipboard.");+ }+ };+if (!renderPreset) {return (<div className="bg-background flex h-full items-center justify-center rounded-lg border p-4">@@ -146,21 +208,56 @@ export function PresetDashboardWidget({return (<div className="group relative h-full w-full"><div className="h-full w-full overflow-y-auto">{renderPreset(ctx)}</div>- {!readOnly && (hasCUDAccess || isLockedEditable) && (- <div className="bg-background/95 absolute top-2 right-2 z-10 hidden items-center gap-2 rounded-md border px-1.5 py-1 shadow-sm group-hover:flex">- <GripVerticalIcon- size={16}- className="drag-handle text-muted-foreground hover:text-foreground hidden cursor-grab active:cursor-grabbing lg:block"- />- <button- onClick={handleDelete}- className="text-muted-foreground hover:text-destructive"- aria-label="Delete widget"- >- <TrashIcon size={16} />- </button>- </div>- )}+ {/* The menu (copy) stays available on read-only surfaces like Home β+ only the edit affordances (drag, delete) are gated. */}+ <div className="bg-background/95 absolute top-2 right-2 z-10 hidden items-center gap-2 rounded-md border px-1.5 py-1 shadow-sm group-hover:flex has-data-[state=open]:flex">+ {!readOnly && (hasCUDAccess || isLockedEditable) && (+ <>+ <GripVerticalIcon+ size={16}+ className="drag-handle text-muted-foreground hover:text-foreground hidden cursor-grab active:cursor-grabbing lg:block"+ />+ <button+ onClick={handleDelete}+ className="text-muted-foreground hover:text-destructive"+ aria-label="Delete widget"+ >+ <TrashIcon size={16} />+ </button>+ </>+ )}+ <DropdownMenu onOpenChange={setIsActionsMenuOpen}>+ <DropdownMenuTrigger asChild>+ <button+ className="text-muted-foreground hover:text-foreground"+ aria-label="Widget actions"+ >+ <MoreVerticalIcon size={16} />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={handleCopyToClipboard}>+ <CopyIcon className="mr-2 h-4 w-4" />+ Copy to clipboard+ </DropdownMenuItem>+ {onPasteWidget && (+ <DropdownMenuItem+ disabled={clipboardProbe === "no-widget"}+ onClick={() => onPasteWidget(placement)}+ >+ <ClipboardPasteIcon className="mr-2 h-4 w-4" />+ Paste to the right+ </DropdownMenuItem>+ )}+ {onDuplicatePreset && (+ <DropdownMenuItem onClick={() => onDuplicatePreset(placement)}>+ <CopyPlusIcon className="mr-2 h-4 w-4" />+ Duplicate+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div></div>);}diff --git a/web/src/features/widgets/components/WidgetTable.tsx b/web/src/features/widgets/components/WidgetTable.tsxindex ee01b869b1..9bdfcb7378 100644--- a/web/src/features/widgets/components/WidgetTable.tsx+++ b/web/src/features/widgets/components/WidgetTable.tsx@@ -12,17 +12,26 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/contextimport startCase from "lodash/startCase";import { Button } from "@/src/components/ui/button";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { Download, Trash } from "lucide-react";+import { Copy, CopyPlus, FileJson, MoreVertical, 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,- PopoverTrigger,-} from "@/src/components/ui/popover";+ buildWidgetExport,+ downloadWidgetJson,+ toWidgetCreateFields,+ type WidgetExportSource,+} from "@/src/features/widgets/utils/import-export-utils";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";+import { copyTextToClipboard } from "@/src/utils/clipboard";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { useRouter } from "next/router";import { getChartTypeDisplayName } from "@/src/features/widgets/chart-library/utils";import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";@@ -40,7 +49,7 @@ type WidgetTableRow = {owner: "PROJECT" | "LANGFUSE";};-export function DeleteWidget({+function WidgetActionsCell({widgetId,owner,}: {@@ -49,11 +58,13 @@ export function DeleteWidget({}) {const projectId = useProjectIdFromURL();const utils = api.useUtils();- const [isOpen, setIsOpen] = useState(false);- const hasAccess =- useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&- owner !== "LANGFUSE";const capture = usePostHogClientCapture();+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });+ const hasDeleteAccess = hasCUDAccess && owner !== "LANGFUSE";const mutDeleteWidget = api.dashboardWidgets.delete.useMutation({onSuccess: () => {@@ -71,103 +82,157 @@ export function DeleteWidget({}},});+ const { mutateAsync: createWidgetAsync } =+ api.dashboardWidgets.create.useMutation();- return (- <Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>- <PopoverTrigger asChild>- <Button variant="ghost" size="xs" disabled={!hasAccess}>- <Trash className="h-4 w-4" />- </Button>- </PopoverTrigger>- <PopoverContent>- <h2 className="mb-3 font-semibold">Please confirm</h2>- <p className="mb-3 text-sm">- This action permanently deletes this widget. If the widget is- currently used in any dashboard, you will need to remove it from those- dashboards first.- </p>- <div className="flex justify-end space-x-4">- <Button- type="button"- variant="destructive"- loading={mutDeleteWidget.isPending}- onClick={() => {- if (!projectId) {- console.error("Project ID is missing");- return;- }-- mutDeleteWidget.mutate({- projectId,- widgetId,- });- setIsOpen(false);- }}- >- Delete Widget- </Button>- </div>- </PopoverContent>- </Popover>- );-}+ const fetchExportSource = async (): Promise<WidgetExportSource> => {+ if (!projectId) {+ throw new Error("Project ID is missing");+ }+ const widget = await utils.dashboardWidgets.get.fetch(+ {+ projectId,+ widgetId,+ },+ // Serve rapid repeat actions (double-click, copy-then-download) from+ // the cache instead of firing a request per menu click.+ { staleTime: 30_000 },+ );-function ShareWidgetButton({ widgetId }: { widgetId: string }) {- const projectId = useProjectIdFromURL();- const utils = api.useUtils();- const [isDownloading, setIsDownloading] = useState(false);+ return {+ 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,+ };+ };- return (- <Button- variant="ghost"- size="xs"- disabled={!projectId}- loading={isDownloading}- onClick={async () => {- if (!projectId) {- return;- }+ const handleDownloadJson = async () => {+ try {+ downloadWidgetJson(await fetchExportSource());+ capture("dashboard:widget_json_downloaded", {+ surface: "widget_table",+ widget_id: widgetId,+ });+ } catch (error) {+ showErrorToast(+ "Failed to download widget",+ error instanceof Error ? error.message : "Unknown error",+ );+ }+ };- setIsDownloading(true);+ const handleCopyToClipboard = async () => {+ try {+ const exportSource = await fetchExportSource();+ await copyTextToClipboard(+ JSON.stringify(buildWidgetExport(exportSource), null, 2),+ );+ capture("dashboard:widget_copied_to_clipboard", {+ surface: "widget_table",+ kind: "widget",+ widget_id: widgetId,+ });+ } catch (error) {+ showErrorToast(+ "Failed to copy widget",+ error instanceof Error ? error.message : "Unknown error",+ );+ }+ };- try {- const widget = await utils.dashboardWidgets.get.fetch({- projectId,- widgetId,- });+ const handleDuplicate = async () => {+ try {+ if (!projectId) {+ throw new Error("Project ID is missing");+ }+ const exportSource = await fetchExportSource();+ await createWidgetAsync({+ projectId,+ ...toWidgetCreateFields(exportSource),+ name: `${exportSource.name} (Copy)`,+ });+ capture("dashboard:widget_duplicated", {+ surface: "widget_table",+ kind: "widget",+ chart_type: exportSource.chartType,+ view: exportSource.view,+ });+ utils.dashboardWidgets.invalidate();+ showSuccessToast({+ title: "Widget duplicated",+ description: `Created "${exportSource.name} (Copy)".`,+ });+ } catch (error) {+ showErrorToast(+ "Failed to duplicate widget",+ error instanceof Error ? error.message : "Unknown error",+ );+ }+ };- 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>+ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="xs" aria-label="Widget actions">+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={handleCopyToClipboard}>+ <Copy className="mr-2 h-4 w-4" />+ Copy to clipboard+ </DropdownMenuItem>+ <DropdownMenuItem disabled={!hasCUDAccess} onClick={handleDuplicate}>+ <CopyPlus className="mr-2 h-4 w-4" />+ Duplicate+ </DropdownMenuItem>+ <DropdownMenuItem onClick={handleDownloadJson}>+ <FileJson className="mr-2 h-4 w-4" />+ Download as JSON+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={!hasDeleteAccess}+ onClick={() => setIsDeleteDialogOpen(true)}+ className="text-destructive focus:text-destructive"+ >+ <Trash className="mr-2 h-4 w-4" />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <ConfirmDialog+ open={isDeleteDialogOpen}+ onOpenChange={setIsDeleteDialogOpen}+ title="Delete widget"+ description="This action permanently deletes this widget. If the widget is currently used in any dashboard, you will need to remove it from those dashboards first."+ confirmLabel="Delete Widget"+ loading={mutDeleteWidget.isPending}+ onConfirm={() => {+ if (!projectId) {+ console.error("Project ID is missing");+ return;+ }+ mutDeleteWidget.mutate({ projectId, widgetId });+ setIsDeleteDialogOpen(false);+ }}+ />+ </>);}export function DashboardWidgetTable() {const projectId = useProjectIdFromURL();- const { isBetaEnabled } = useV4Beta();const { setDetailPageList } = useDetailPageLists();const router = useRouter();@@ -280,8 +345,7 @@ export function DashboardWidgetTable() {className="flex items-center gap-1"onClick={(e) => e.stopPropagation()}>- {isBetaEnabled && <ShareWidgetButton widgetId={id} />}- <DeleteWidget widgetId={id} owner={row.row.original.owner} />+ <WidgetActionsCell widgetId={id} owner={row.row.original.owner} /></div>);},diff --git a/web/src/features/widgets/hooks/useClipboardWidgetProbe.ts b/web/src/features/widgets/hooks/useClipboardWidgetProbe.tsnew file mode 100644index 0000000000..0a7a3662cb--- /dev/null+++ b/web/src/features/widgets/hooks/useClipboardWidgetProbe.ts@@ -0,0 +1,59 @@+import { useEffect, useState } from "react";++export type ClipboardWidgetProbe = "unknown" | "widget" | "no-widget";++/**+ * Best-effort check whether the clipboard currently holds a pasteable+ * payload, used to gate "Paste" menu items. The probe only reads the+ * clipboard when the browser allows doing so silently (clipboard-read+ * permission already granted); otherwise it stays "unknown" β the menu item+ * then stays visible and the paste action validates on click. It never+ * triggers a permission prompt on menu open.+ *+ * @param enabled probe when true (typically: the menu is open)+ * @param isPasteable decides whether clipboard text is a pasteable payload;+ * pass a stable reference (useCallback) β it is an effect dependency+ */+export function useClipboardWidgetProbe(+ enabled: boolean,+ isPasteable: (text: string) => boolean,+): ClipboardWidgetProbe {+ const [probe, setProbe] = useState<ClipboardWidgetProbe>("unknown");++ useEffect(() => {+ if (!enabled) {+ setProbe("unknown");+ return;+ }++ let cancelled = false;+ (async () => {+ try {+ if (+ !navigator.permissions?.query ||+ typeof navigator.clipboard?.readText !== "function"+ ) {+ return;+ }+ const status = await navigator.permissions.query({+ // Not in TS's PermissionName union everywhere, but supported by+ // Chromium; browsers without it throw and we stay "unknown".+ name: "clipboard-read" as PermissionName,+ });+ if (status.state !== "granted") return;+ const text = await navigator.clipboard.readText();+ if (cancelled) return;+ setProbe(isPasteable(text) ? "widget" : "no-widget");+ } catch {+ // Permission query unsupported (Firefox/Safari) or read failed β+ // cannot know silently, keep "unknown".+ }+ })();++ return () => {+ cancelled = true;+ };+ }, [enabled, isPasteable]);++ return probe;+}diff --git a/web/src/features/widgets/index.ts b/web/src/features/widgets/index.tsindex 8fd9b709eb..76d4f5d036 100644--- a/web/src/features/widgets/index.ts+++ b/web/src/features/widgets/index.ts@@ -4,7 +4,7 @@ export { Chart } from "./chart-library/Chart";// Export componentsexport { WidgetForm } from "./components/WidgetForm";-export { DashboardWidgetTable, DeleteWidget } from "./components/WidgetTable";+export { DashboardWidgetTable } from "./components/WidgetTable";export { DashboardWidget } from "./components/DashboardWidget";// Export types and utilitiesdiff --git a/web/src/features/widgets/utils/grid-placement.clienttest.ts b/web/src/features/widgets/utils/grid-placement.clienttest.tsnew file mode 100644index 0000000000..c0ed8ba336--- /dev/null+++ b/web/src/features/widgets/utils/grid-placement.clienttest.ts@@ -0,0 +1,67 @@+import { pushDownForInsertion } from "./grid-placement";++const tile = (id: string, x: number, y: number, x_size = 6, y_size = 6) => ({+ id,+ x,+ y,+ x_size,+ y_size,+});++describe("pushDownForInsertion", () => {+ it("leaves tiles alone when the inserted rect is free", () => {+ const existing = [tile("a", 0, 0), tile("b", 0, 6)];+ const result = pushDownForInsertion(existing, {+ x: 6,+ y: 0,+ x_size: 6,+ y_size: 6,+ });++ expect(result).toEqual(existing);+ // pure: inputs untouched, outputs are copies+ expect(result[0]).not.toBe(existing[0]);+ });++ it("pushes an occupying tile below the inserted rect", () => {+ const result = pushDownForInsertion(+ [tile("a", 0, 0), tile("right-neighbor", 6, 0)],+ { x: 6, y: 0, x_size: 6, y_size: 6 },+ );++ expect(result.find((w) => w.id === "a")?.y).toBe(0);+ expect(result.find((w) => w.id === "right-neighbor")?.y).toBe(6);+ });++ it("cascades pushes onto tiles further down the column", () => {+ const result = pushDownForInsertion(+ [tile("top", 6, 0), tile("below", 6, 6)],+ { x: 6, y: 0, x_size: 6, y_size: 6 },+ );++ expect(result.find((w) => w.id === "top")?.y).toBe(6);+ expect(result.find((w) => w.id === "below")?.y).toBe(12);+ });++ it("does not disturb other columns during a cascade", () => {+ const result = pushDownForInsertion(+ [tile("pushed", 6, 0), tile("left-below", 0, 6)],+ { x: 6, y: 0, x_size: 6, y_size: 6 },+ );++ expect(result.find((w) => w.id === "pushed")?.y).toBe(6);+ expect(result.find((w) => w.id === "left-below")?.y).toBe(6);+ });++ it("pushes partially overlapping tiles of different sizes", () => {+ // inserted 6-wide rect overlaps a 4-wide tile shifted right of it+ const result = pushDownForInsertion([tile("narrow", 8, 0, 4, 3)], {+ x: 6,+ y: 0,+ x_size: 6,+ y_size: 6,+ });++ expect(result.find((w) => w.id === "narrow")?.y).toBe(6);+ });+});diff --git a/web/src/features/widgets/utils/grid-placement.ts b/web/src/features/widgets/utils/grid-placement.tsnew file mode 100644index 0000000000..cb89a8eddc--- /dev/null+++ b/web/src/features/widgets/utils/grid-placement.ts@@ -0,0 +1,57 @@+type GridRect = {+ x: number;+ y: number;+ x_size: number;+ y_size: number;+};++function collides(a: GridRect, b: GridRect): boolean {+ return (+ a.x < b.x + b.x_size &&+ b.x < a.x + a.x_size &&+ a.y < b.y + b.y_size &&+ b.y < a.y + a.y_size+ );+}++/**+ * Makes room for a tile inserted at a specific grid position ("paste to the+ * right", duplicate-next-to): every existing tile that overlaps the inserted+ * rect is pushed straight down below it, cascading onto tiles below β+ * the same displacement react-grid-layout performs when a tile is dragged+ * into an occupied slot. Without this, handing the grid an overlapping+ * layout makes it move the NEW tile down instead, so "to the right" only+ * ever worked into empty space.+ *+ * Pure: returns adjusted copies (only `y` changes); tiles that are not in+ * the way keep their position. The grid's vertical compaction then closes+ * any gaps the cascade left.+ */+export function pushDownForInsertion<T extends GridRect>(+ existing: T[],+ inserted: GridRect,+): T[] {+ const result = existing.map((widget) => ({ ...widget }));++ // Settle tiles in reading order so pushes cascade top-down+ // deterministically; each tile is placed below everything already settled+ // that it overlaps (the inserted rect settles first).+ const settled: GridRect[] = [inserted];+ const inReadingOrder = [...result].sort((a, b) => a.y - b.y || a.x - b.x);++ for (const widget of inReadingOrder) {+ let moved = true;+ while (moved) {+ moved = false;+ for (const other of settled) {+ if (collides(widget, other)) {+ widget.y = other.y + other.y_size;+ moved = true;+ }+ }+ }+ settled.push(widget);+ }++ return result;+}diff --git a/web/src/features/widgets/utils/import-export-utils.clienttest.ts b/web/src/features/widgets/utils/import-export-utils.clienttest.tsindex 3bc8f73193..9bee5fa23c 100644--- a/web/src/features/widgets/utils/import-export-utils.clienttest.ts+++ b/web/src/features/widgets/utils/import-export-utils.clienttest.ts@@ -1,7 +1,10 @@import {+ buildWidgetExport,buildWidgetImportAllowedValues,importWidgetFile,parseAndNormalizeImportedWidget,+ parsePastedWidget,+ WIDGET_FILE_FORMAT_VERSION,} from "./import-export-utils";describe("parseAndNormalizeImportedWidget", () => {@@ -148,4 +151,124 @@ describe("parseAndNormalizeImportedWidget", () => {expect(result.snapshot.selectedView).toBe("traces");expect(result.snapshot.widgetMinVersion).toBe(1);});++ it("accepts an enveloped export file (round-trip)", async () => {+ const result = await importWidgetFile({+ file: {+ text: async () =>+ JSON.stringify(buildWidgetExport({ ...baseWidget, filters: [] })),+ } as File,+ optionSets: {+ observationLevels: [],+ },+ isBetaEnabled: false,+ });++ expect(result.snapshot.widgetName).toBe("Imported widget");+ });++ it("rejects an enveloped file with a newer format version", async () => {+ await expect(+ importWidgetFile({+ file: {+ text: async () =>+ JSON.stringify({+ ...buildWidgetExport({ ...baseWidget, filters: [] }),+ version: WIDGET_FILE_FORMAT_VERSION + 1,+ }),+ } as File,+ optionSets: {+ observationLevels: [],+ },+ isBetaEnabled: false,+ }),+ ).rejects.toThrow();+ });+});++describe("buildWidgetExport", () => {+ it("wraps the widget config in the Langfuse widget envelope", () => {+ const exported = buildWidgetExport({+ name: "My widget",+ description: "",+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", agg: "count" }],+ filters: [],+ chartType: "NUMBER",+ chartConfig: { type: "NUMBER" },+ minVersion: 1,+ });++ expect(exported.$langfuseWidget).toBe(true);+ expect(exported.version).toBe(WIDGET_FILE_FORMAT_VERSION);+ expect(exported.name).toBe("My widget");+ });+});++describe("parsePastedWidget", () => {+ const baseWidget = {+ name: "Pasted widget",+ description: "",+ view: "traces" as const,+ dimensions: [],+ metrics: [{ measure: "count", agg: "count" as const }],+ filters: [],+ chartType: "NUMBER" as const,+ chartConfig: { type: "NUMBER" as const },+ minVersion: 1,+ };++ it("ignores non-JSON text", () => {+ expect(parsePastedWidget("hello world", { isBetaEnabled: false })).toEqual({+ status: "not-widget",+ });+ });++ it("ignores JSON without the widget envelope", () => {+ expect(+ parsePastedWidget(JSON.stringify(baseWidget), { isBetaEnabled: false }),+ ).toEqual({ status: "not-widget" });+ });++ it("parses an enveloped widget export", () => {+ const result = parsePastedWidget(+ JSON.stringify(buildWidgetExport(baseWidget)),+ { isBetaEnabled: false },+ );++ expect(result.status).toBe("widget");+ if (result.status === "widget") {+ expect(result.widget.name).toBe("Pasted widget");+ expect(result.widget.chartType).toBe("NUMBER");+ }+ });++ it("rejects a newer format version with a reason", () => {+ const result = parsePastedWidget(+ JSON.stringify({+ ...buildWidgetExport(baseWidget),+ version: WIDGET_FILE_FORMAT_VERSION + 1,+ }),+ { isBetaEnabled: false },+ );++ expect(result.status).toBe("invalid");+ if (result.status === "invalid") {+ expect(result.reason).toContain("format version");+ }+ });++ it("rejects an enveloped payload with a malformed config", () => {+ const result = parsePastedWidget(+ JSON.stringify({+ ...buildWidgetExport(baseWidget),+ // chartConfig.type no longer matches chartType+ chartConfig: { type: "PIE" },+ }),+ { isBetaEnabled: false },+ );++ expect(result.status).toBe("invalid");+ });});diff --git a/web/src/features/widgets/utils/import-export-utils.ts b/web/src/features/widgets/utils/import-export-utils.tsindex 3afec12c45..e9d98bebf1 100644--- a/web/src/features/widgets/utils/import-export-utils.ts+++ b/web/src/features/widgets/utils/import-export-utils.ts@@ -30,8 +30,19 @@ const widgetMetricSchema = MetricSchema.extend({agg: metricAggregations,});-const widgetImportBaseSchema = z+/**+ * Widget JSON file-format version. `$langfuseWidget: true` marks a JSON+ * payload (file or clipboard text) as a Langfuse widget export and `version`+ * is the version of that envelope β bump it when the export shape changes+ * incompatibly. Distinct from the widget's own `minVersion`, which is the+ * query-engine (v1/v2) version.+ */+export const WIDGET_FILE_FORMAT_VERSION = 1;++export const widgetImportBaseSchema = z.object({+ $langfuseWidget: z.literal(true).optional(),+ version: z.number().int().positive().optional(),name: z.string(),description: z.string(),view: views,@@ -53,10 +64,35 @@ export const widgetImportSchema = widgetImportBaseSchema.superRefine(message: "chartConfig.type must match chartType",});}+ if (+ widget.$langfuseWidget === true &&+ (widget.version ?? 1) > WIDGET_FILE_FORMAT_VERSION+ ) {+ ctx.addIssue({+ code: "custom",+ path: ["version"],+ message: `Unsupported widget format version ${widget.version}`,+ });+ }},);-type WidgetImport = z.infer<typeof widgetImportSchema>;+export type WidgetImport = z.infer<typeof widgetImportSchema>;++/**+ * True when a parsed JSON payload carries the Langfuse widget envelope.+ * Clipboard and drag-drop flows use this to distinguish "not a widget at all"+ * (silently ignore) from "claims to be a widget but is malformed" (surface an+ * error).+ */+export function isLangfuseWidgetPayload(parsed: unknown): boolean {+ return (+ typeof parsed === "object" &&+ parsed !== null &&+ "$langfuseWidget" in parsed &&+ (parsed as Record<string, unknown>).$langfuseWidget === true+ );+}export type WidgetImportOptionSets = {environmentValues?: string[];@@ -150,21 +186,28 @@ export function buildWidgetImportAllowedValues(return allowedValuesByColumn;}-export function downloadWidgetJson(- widget: Pick<- WidgetImport,- | "name"- | "description"- | "view"- | "dimensions"- | "metrics"- | "filters"- | "chartType"- | "chartConfig"- | "minVersion"- >,-) {- const exportWidget = {+export type WidgetExportSource = Pick<+ WidgetImport,+ | "name"+ | "description"+ | "view"+ | "dimensions"+ | "metrics"+ | "filters"+ | "chartType"+ | "chartConfig"+ | "minVersion"+>;++/**+ * The canonical widget export shape: the widget's portable configuration+ * wrapped in the Langfuse widget envelope. Downloaded files and+ * copied-to-clipboard widgets both serialize exactly this object.+ */+export function buildWidgetExport(widget: WidgetExportSource) {+ return {+ $langfuseWidget: true as const,+ version: WIDGET_FILE_FORMAT_VERSION,name: widget.name,description: widget.description,view: widget.view,@@ -175,8 +218,10 @@ export function downloadWidgetJson(chartConfig: widget.chartConfig,minVersion: widget.minVersion,};+}- const blob = new Blob([JSON.stringify(exportWidget, null, 2)], {+export function downloadWidgetJson(widget: WidgetExportSource) {+ const blob = new Blob([JSON.stringify(buildWidgetExport(widget), null, 2)], {type: "application/json",});const url = URL.createObjectURL(blob);@@ -409,24 +454,28 @@ function normalizeImportedWidgetVersion(widget: WidgetImport): WidgetImport {};}-export async function importWidgetFile(params: {- file: File;- optionSets: WidgetImportOptionSets;+/**+ * 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.+ * Throws on any payload that cannot become a valid widget.+ */+export function parseImportedWidgetJson(params: {+ parsedJson: unknown;+ optionSets?: WidgetImportOptionSets;isBetaEnabled: boolean;-}): Promise<ImportedWidgetResult> {- const rawContent = await params.file.text();- const parsedJson: unknown = JSON.parse(rawContent);- const allowedValuesByColumn = buildWidgetImportAllowedValues(- params.optionSets,- parsedJson,- );+}): { widget: WidgetImport; removedValues: boolean; removedFilters: boolean } {+ const allowedValuesByColumn = params.optionSets+ ? buildWidgetImportAllowedValues(params.optionSets, params.parsedJson)+ : new Map<string, Set<string>>();const {widget: importedWidget,removedValues,removedFilters,} = parseAndNormalizeImportedWidget({- parsedJson,+ parsedJson: params.parsedJson,allowedValuesByColumn,});@@ -443,9 +492,96 @@ export async function importWidgetFile(params: {importedViewVersion,});+ return { widget: normalizedWidget, removedValues, removedFilters };+}++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 { widget, removedValues, removedFilters } = parseImportedWidgetJson({+ parsedJson,+ optionSets: params.optionSets,+ isBetaEnabled: params.isBetaEnabled,+ });+return {- snapshot: toImportedWidgetFormSnapshot(normalizedWidget),+ snapshot: toImportedWidgetFormSnapshot(widget),removedValues,removedFilters,};}++export type PastedWidgetParseResult =+ | { status: "not-widget" }+ | { status: "invalid"; reason: string }+ | { status: "widget"; widget: WidgetImport; removedFilters: boolean };++/**+ * Parses clipboard or dropped text into a widget. Anything that does not+ * carry the Langfuse widget envelope is "not-widget" (callers ignore it+ * silently); an enveloped payload that fails validation is "invalid" with a+ * user-facing reason.+ */+export function parsePastedWidget(+ text: string,+ params: { isBetaEnabled: boolean },+): PastedWidgetParseResult {+ let parsedJson: unknown;+ try {+ parsedJson = JSON.parse(text);+ } catch {+ return { status: "not-widget" };+ }++ if (!isLangfuseWidgetPayload(parsedJson)) {+ return { status: "not-widget" };+ }++ const declaredVersion = (parsedJson as Record<string, unknown>).version;+ if (+ typeof declaredVersion === "number" &&+ declaredVersion > WIDGET_FILE_FORMAT_VERSION+ ) {+ return {+ status: "invalid",+ reason: `This widget uses format version ${declaredVersion}; this Langfuse version supports up to ${WIDGET_FILE_FORMAT_VERSION}.`,+ };+ }++ try {+ const { widget, removedFilters } = parseImportedWidgetJson({+ parsedJson,+ isBetaEnabled: params.isBetaEnabled,+ });+ return { status: "widget", widget, removedFilters };+ } catch {+ return {+ status: "invalid",+ reason: "The widget configuration is malformed or not supported.",+ };+ }+}++/**+ * Portable widget fields in the shape of the `dashboardWidgets.create`+ * mutation input (minus projectId) β used to recreate a pasted, dropped, or+ * duplicated widget as a new project-owned widget.+ */+export function toWidgetCreateFields(widget: WidgetExportSource) {+ return {+ 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,+ };+}diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsxindex d3f7622266..fcff60c78b 100644--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx@@ -6,7 +6,7 @@ import Page from "@/src/components/layouts/page";import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";import { TimeRangePicker } from "@/src/components/date-picker";import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";-import { useEffect, useState, useMemo, useCallback } from "react";+import { useEffect, useState, useMemo, useCallback, useRef } from "react";import type { ColumnDefinition, FilterState } from "@langfuse/shared";import { Button } from "@/src/components/ui/button";import { PlusIcon, Copy } from "lucide-react";@@ -37,7 +37,13 @@ import {LANGFUSE_HOME_DASHBOARD_ID,type HomeDashboardPresetId,} from "@langfuse/shared";-import { HomeIcon, Loader2, MoreVertical, PencilIcon } from "lucide-react";+import {+ ClipboardPasteIcon,+ HomeIcon,+ Loader2,+ MoreVertical,+ PencilIcon,+} from "lucide-react";import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";import {DASHBOARD_AGGREGATION_OPTIONS,@@ -55,6 +61,38 @@ import {getDashboardQuerySchedulerMaxConcurrent,useDashboardQueryScheduler,} from "@/src/hooks/useDashboardQueryScheduler";+import {+ parsePastedWidget,+ toWidgetCreateFields,+ type PastedWidgetParseResult,+ type WidgetExportSource,+} from "@/src/features/widgets/utils/import-export-utils";+import {+ isPasteablePlacementPayload,+ parseDashboardImport,+ parsePastedPreset,+ type ParsedDashboardImport,+} from "@/src/features/dashboard/utils/dashboard-import-export";+import { type PresetPlacement } from "@/src/features/widgets/components/PresetDashboardWidget";+import { pushDownForInsertion } from "@/src/features/widgets/utils/grid-placement";+import { readTextFromClipboard } from "@/src/utils/clipboard";+import { useClipboardWidgetProbe } from "@/src/features/widgets/hooks/useClipboardWidgetProbe";+import { extractTransferFiles } from "@/src/components/editor/fileDropPaste";+import { Layer } from "@/src/components/ui/layer";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";++// Position for a tile inserted "next to" an anchor tile: same size,+// immediately to the right when that fits the 12-column grid, otherwise+// directly below the anchor. Collisions are resolved by the grid layout.+function placementNextTo(anchor: DashboardPlacement) {+ const fitsRight = anchor.x + anchor.x_size * 2 <= 12;+ return {+ x: fitsRight ? anchor.x + anchor.x_size : anchor.x,+ y: fitsRight ? anchor.y : anchor.y + anchor.y_size,+ x_size: anchor.x_size,+ y_size: anchor.y_size,+ };+}export default function DashboardDetail() {const router = useRouter();@@ -141,6 +179,13 @@ export default function DashboardDetail() {const [localDashboardDefinition, setLocalDashboardDefinition] = useState<{widgets: DashboardPlacement[];} | null>(null);+ // The async flows below (paste/duplicate/import) commit a definition change+ // only after a network round-trip. They must compute it from this ref β the+ // definition as of NOW β not from the state captured when the handler+ // started, or a drag/delete/paste that landed during the await gets+ // silently discarded.+ const localDashboardDefinitionRef = useRef(localDashboardDefinition);+ localDashboardDefinitionRef.current = localDashboardDefinition;// State for the widget selection dialogconst [isWidgetDialogOpen, setIsWidgetDialogOpen] = useState(false);@@ -215,6 +260,18 @@ export default function DashboardDetail() {false,);+ // Single write path for definition changes: keeps the ref in sync for+ // readers that commit before the next render, updates state, and schedules+ // the debounced save.+ const applyDashboardDefinition = useCallback(+ (updated: { widgets: DashboardPlacement[] }) => {+ localDashboardDefinitionRef.current = updated;+ setLocalDashboardDefinition(updated);+ saveDashboardChanges(updated);+ },+ [saveDashboardChanges],+ );+// Function to save current filtersconst handleSaveFilters = () => {if (!hasCUDAccess) return;@@ -226,80 +283,96 @@ export default function DashboardDetail() {});};- // Helper function to add a widget to the dashboard- const addWidgetToDashboard = useCallback(- (widget: WidgetItem) => {- if (!localDashboardDefinition) return;+ // Helper function to add a widget placement to the dashboard. Defaults to a+ // 6x6 tile below all existing widgets; callers can pass an explicit position+ // (e.g. "paste to the right" of an anchor tile).+ const insertWidgetPlacement = useCallback(+ (+ widgetId: string,+ position?: { x: number; y: number; x_size: number; y_size: number },+ ) => {+ // Read through the ref: async callers (paste/duplicate) reach here+ // after a network round-trip.+ const currentDefinition = localDashboardDefinitionRef.current;+ if (!currentDefinition) return;// Find the maximum y position to place the new widget at the bottomconst maxY =- localDashboardDefinition.widgets.length > 0- ? Math.max(- ...localDashboardDefinition.widgets.map((w) => w.y + w.y_size),- )+ currentDefinition.widgets.length > 0+ ? Math.max(...currentDefinition.widgets.map((w) => w.y + w.y_size)): 0;// Create a new widget placementconst newWidgetPlacement: DashboardPlacement = {id: uuidv4(),- widgetId: widget.id,- x: 0, // Start at left- y: maxY, // Place below existing widgets- x_size: 6, // Default size (half of 12-column grid)- y_size: 6, // Default height of 6 rows+ widgetId,type: "widget",+ x: position?.x ?? 0, // Default: start at left+ y: position?.y ?? maxY, // Default: place below existing widgets+ x_size: position?.x_size ?? 6, // Default size (half of 12-column grid)+ y_size: position?.y_size ?? 6, // Default height of 6 rows};- // Add the widget to the local dashboard definition- const updatedDefinition = {- ...localDashboardDefinition,- widgets: [...localDashboardDefinition.widgets, newWidgetPlacement],- };- setLocalDashboardDefinition(updatedDefinition);- saveDashboardChanges(updatedDefinition);+ // An explicit position may target an occupied slot ("paste to the+ // right") β push the tiles in the way below it; bottom inserts are+ // collision-free by construction.+ const existingWidgets = position+ ? pushDownForInsertion(currentDefinition.widgets, newWidgetPlacement)+ : currentDefinition.widgets;+ applyDashboardDefinition({+ ...currentDefinition,+ widgets: [...existingWidgets, newWidgetPlacement],+ });- // The new widget lands at the bottom of the grid β bring it into view.+ // The new widget may land outside the viewport β bring it into view.setTimeout(() => {document.querySelector(`[data-placement-id="${newWidgetPlacement.id}"]`)?.scrollIntoView({ behavior: "smooth", block: "center" });}, 150);},- [- localDashboardDefinition,- setLocalDashboardDefinition,- saveDashboardChanges,- ],+ [applyDashboardDefinition],);- // Add a Langfuse Home card as a preset placement (no widget row involved)- const addPresetToDashboard = useCallback(- (presetId: HomeDashboardPresetId) => {- if (!localDashboardDefinition) return;+ const addWidgetToDashboard = useCallback(+ (widget: WidgetItem) => insertWidgetPlacement(widget.id),+ [insertWidgetPlacement],+ );++ // Add a Langfuse Home card as a preset placement (no widget row involved).+ // Defaults to a 6x6 tile below all existing widgets; callers can pass an+ // explicit position (e.g. paste/duplicate next to an anchor tile).+ const insertPresetPlacement = useCallback(+ (+ presetId: HomeDashboardPresetId,+ position?: { x: number; y: number; x_size: number; y_size: number },+ ) => {+ const currentDefinition = localDashboardDefinitionRef.current;+ if (!currentDefinition) return;const maxY =- localDashboardDefinition.widgets.length > 0- ? Math.max(- ...localDashboardDefinition.widgets.map((w) => w.y + w.y_size),- )+ currentDefinition.widgets.length > 0+ ? Math.max(...currentDefinition.widgets.map((w) => w.y + w.y_size)): 0;const newPresetPlacement: DashboardPlacement = {id: uuidv4(),presetId,type: "preset",- x: 0,- y: maxY,- x_size: 6,- y_size: 6,+ x: position?.x ?? 0,+ y: position?.y ?? maxY,+ x_size: position?.x_size ?? 6,+ y_size: position?.y_size ?? 6,};- const updatedDefinition = {- ...localDashboardDefinition,- widgets: [...localDashboardDefinition.widgets, newPresetPlacement],- };- setLocalDashboardDefinition(updatedDefinition);- saveDashboardChanges(updatedDefinition);+ // See insertWidgetPlacement: anchored inserts displace occupying tiles.+ const existingWidgets = position+ ? pushDownForInsertion(currentDefinition.widgets, newPresetPlacement)+ : currentDefinition.widgets;+ applyDashboardDefinition({+ ...currentDefinition,+ widgets: [...existingWidgets, newPresetPlacement],+ });setTimeout(() => {document@@ -307,9 +380,496 @@ export default function DashboardDetail() {?.scrollIntoView({ behavior: "smooth", block: "center" });}, 150);},- [localDashboardDefinition, saveDashboardChanges],+ [applyDashboardDefinition],+ );++ const addPresetToDashboard = useCallback(+ (presetId: HomeDashboardPresetId) => insertPresetPlacement(presetId),+ [insertPresetPlacement],+ );++ // Duplicate a preset card: another placement of the same preset next to+ // the anchor tile (no widget row involved).+ const handleDuplicatePreset = useCallback(+ (anchor: PresetPlacement) => {+ capture("dashboard:widget_duplicated", {+ surface: "grid_menu",+ kind: "preset",+ preset_id: anchor.presetId,+ dashboard_id: dashboardId,+ });+ insertPresetPlacement(+ anchor.presetId as HomeDashboardPresetId,+ placementNextTo(anchor),+ );+ },+ [capture, dashboardId, insertPresetPlacement],+ );++ // Place a pasted preset card (next to `anchor` when given, else at the+ // bottom).+ const handlePastedPreset = useCallback(+ (+ presetId: HomeDashboardPresetId,+ source: "cmd_v" | "dashboard_menu" | "paste_right" | "drop",+ anchor?: DashboardPlacement,+ ) => {+ capture("dashboard:widget_pasted", {+ source,+ kind: "preset",+ preset_id: presetId,+ dashboard_id: dashboardId,+ });+ insertPresetPlacement(+ presetId,+ anchor ? placementNextTo(anchor) : undefined,+ );+ },+ [capture, dashboardId, insertPresetPlacement],+ );++ const { mutateAsync: createWidgetAsync } =+ api.dashboardWidgets.create.useMutation();+ const { mutateAsync: deleteWidgetAsync } =+ api.dashboardWidgets.delete.useMutation();++ // Duplicate a tile's widget: create an independent widget row seeded from+ // the source configuration, placed next to the source tile.+ const handleDuplicateWidget = useCallback(+ async (anchor: DashboardPlacement, widget: WidgetExportSource) => {+ try {+ const result = await createWidgetAsync({+ projectId,+ ...toWidgetCreateFields(widget),+ name: `${widget.name} (Copy)`,+ });+ capture("dashboard:widget_duplicated", {+ surface: "grid_menu",+ kind: "widget",+ dashboard_id: dashboardId,+ chart_type: widget.chartType,+ view: widget.view,+ });+ insertWidgetPlacement(result.widget.id, placementNextTo(anchor));+ } catch (e) {+ showErrorToast(+ "Failed to duplicate widget",+ e instanceof Error ? e.message : "Unknown error",+ );+ }+ },+ [createWidgetAsync, projectId, dashboardId, capture, insertWidgetPlacement],+ );++ // Recreate a parsed clipboard widget as a project widget and place it on+ // the dashboard (next to `anchor` when given, else at the bottom).+ const handleParsedWidgetPaste = useCallback(+ async (+ parsed: Exclude<PastedWidgetParseResult, { status: "not-widget" }>,+ source: "cmd_v" | "dashboard_menu" | "paste_right" | "drop",+ anchor?: DashboardPlacement,+ ) => {+ if (parsed.status === "invalid") {+ capture("dashboard:widget_paste_rejected", {+ source,+ reason: "invalid",+ dashboard_id: dashboardId,+ });+ showErrorToast("Cannot paste widget", parsed.reason, "WARNING");+ return;+ }+ // Don't create a widget row the placement step couldn't attach β a+ // paste firing before the dashboard definition has loaded would+ // otherwise leave an orphan widget in the library.+ if (!localDashboardDefinitionRef.current) return;+ try {+ const result = await createWidgetAsync({+ projectId,+ ...toWidgetCreateFields(parsed.widget),+ });+ capture("dashboard:widget_pasted", {+ source,+ kind: "widget",+ dashboard_id: dashboardId,+ chart_type: parsed.widget.chartType,+ view: parsed.widget.view,+ });+ insertWidgetPlacement(+ result.widget.id,+ anchor ? placementNextTo(anchor) : undefined,+ );+ if (parsed.removedFilters) {+ showErrorToast(+ "Widget filters were adjusted",+ "Some pasted filters were removed because they are not available in this view.",+ "WARNING",+ );+ }+ } catch (e) {+ showErrorToast(+ "Failed to paste widget",+ e instanceof Error ? e.message : "Unknown error",+ );+ }+ },+ [capture, createWidgetAsync, dashboardId, insertWidgetPlacement, projectId],);+ // Menu-driven paste ("Paste widget" / "Paste to the right"): read the+ // clipboard and reject non-widget payloads visibly.+ const pasteWidgetFromClipboard = useCallback(+ async (+ source: "dashboard_menu" | "paste_right",+ anchor?: DashboardPlacement,+ ) => {+ const text = await readTextFromClipboard();+ if (text === null) {+ showErrorToast(+ "Clipboard unavailable",+ "Your browser did not allow reading the clipboard. Paste with Cmd/Ctrl+V on the dashboard instead.",+ "WARNING",+ );+ return;+ }+ const parsed = parsePastedWidget(text, { isBetaEnabled });+ if (parsed.status === "not-widget") {+ const preset = parsePastedPreset(text);+ if (preset.status === "preset") {+ handlePastedPreset(preset.presetId, source, anchor);+ return;+ }+ if (preset.status === "invalid") {+ capture("dashboard:widget_paste_rejected", {+ source,+ reason: "invalid",+ dashboard_id: dashboardId,+ });+ showErrorToast("Cannot paste card", preset.reason, "WARNING");+ return;+ }+ capture("dashboard:widget_paste_rejected", {+ source,+ reason: "not_widget",+ dashboard_id: dashboardId,+ });+ showErrorToast(+ "No widget in clipboard",+ "The clipboard does not contain a Langfuse widget JSON. Copy one via a widget's β― menu first.",+ "WARNING",+ );+ return;+ }+ await handleParsedWidgetPaste(parsed, source, anchor);+ },+ [+ capture,+ dashboardId,+ handleParsedWidgetPaste,+ handlePastedPreset,+ isBetaEnabled,+ ],+ );++ // Cmd/Ctrl+V on the dashboard pastes a copied widget. Only intercepts when+ // the clipboard actually holds a Langfuse widget payload and the paste is+ // not aimed at a text input.+ useEffect(() => {+ if (!hasCUDAccess) return;++ const onPaste = (event: ClipboardEvent) => {+ if (event.defaultPrevented) return;+ const target = event.target;+ if (+ target instanceof HTMLElement &&+ target.closest("input, textarea, select, [contenteditable]")+ ) {+ return;+ }+ const text = event.clipboardData?.getData("text/plain");+ if (!text) return;+ const parsed = parsePastedWidget(text, { isBetaEnabled });+ if (parsed.status === "not-widget") {+ const preset = parsePastedPreset(text);+ // Neither widget nor preset payload: leave the event alone (silent,+ // per spec).+ if (preset.status === "not-preset") return;+ event.preventDefault();+ if (preset.status === "invalid") {+ capture("dashboard:widget_paste_rejected", {+ source: "cmd_v",+ reason: "invalid",+ dashboard_id: dashboardId,+ });+ showErrorToast("Cannot paste card", preset.reason, "WARNING");+ return;+ }+ handlePastedPreset(preset.presetId, "cmd_v");+ return;+ }+ event.preventDefault();+ handleParsedWidgetPaste(parsed, "cmd_v");+ };++ document.addEventListener("paste", onPaste);+ return () => document.removeEventListener("paste", onPaste);+ }, [+ hasCUDAccess,+ isBetaEnabled,+ handleParsedWidgetPaste,+ handlePastedPreset,+ capture,+ dashboardId,+ ]);++ // Gate the dashboard-menu "Paste widget" item on the clipboard actually+ // holding a pasteable payload, where the browser lets us check silently.+ const [isDashboardMenuOpen, setIsDashboardMenuOpen] = useState(false);+ const isPasteablePayload = useCallback(+ (text: string) => isPasteablePlacementPayload(text, { isBetaEnabled }),+ [isBetaEnabled],+ );+ const clipboardProbe = useClipboardWidgetProbe(+ isDashboardMenuOpen && hasCUDAccess,+ isPasteablePayload,+ );++ // Import a dropped dashboard file: recreate its widgets as project widgets+ // and append the placements below the existing content, preserving the+ // file's relative layout.+ const handleDashboardImport = useCallback(+ async (imported: ParsedDashboardImport) => {+ if (!localDashboardDefinitionRef.current) return;+ try {+ const widgetPlacements = imported.placements.flatMap((p) =>+ p.type === "widget" ? [p] : [],+ );+ const settled = await Promise.allSettled(+ widgetPlacements.map((p) =>+ createWidgetAsync({+ projectId,+ ...toWidgetCreateFields(p.widget),+ }),+ ),+ );+ const createdWidgets = settled.flatMap((s) =>+ s.status === "fulfilled" ? [s.value] : [],+ );+ if (createdWidgets.length !== widgetPlacements.length) {+ // Partial failure: best-effort delete of the widgets that did get+ // created, so no orphan rows pile up in the widget library.+ await Promise.allSettled(+ createdWidgets.map((created) =>+ deleteWidgetAsync({ projectId, widgetId: created.widget.id }),+ ),+ );+ const firstError = settled.find(+ (s): s is PromiseRejectedResult => s.status === "rejected",+ )?.reason;+ showErrorToast(+ "Failed to import dashboard",+ firstError instanceof Error+ ? firstError.message+ : "Could not create the dashboard's widgets.",+ );+ return;+ }++ // Re-read the definition after the awaits: a drag/delete/paste may+ // have landed while the widgets were being created.+ const currentDefinition = localDashboardDefinitionRef.current;+ if (!currentDefinition) return;+ const maxY =+ currentDefinition.widgets.length > 0+ ? Math.max(...currentDefinition.widgets.map((w) => w.y + w.y_size))+ : 0;+ const minImportedY = Math.min(...imported.placements.map((p) => p.y));+ const yOffset = maxY - minImportedY;++ let createdIndex = 0;+ const newPlacements: DashboardPlacement[] = imported.placements.map(+ (p) => {+ const base = {+ id: uuidv4(),+ x: p.x,+ y: p.y + yOffset,+ x_size: p.x_size,+ y_size: p.y_size,+ };+ if (p.type === "preset") {+ return { ...base, type: "preset" as const, presetId: p.presetId };+ }+ const widgetId = createdWidgets[createdIndex]!.widget.id;+ createdIndex += 1;+ return { ...base, type: "widget" as const, widgetId };+ },+ );++ applyDashboardDefinition({+ ...currentDefinition,+ widgets: [...currentDefinition.widgets, ...newPlacements],+ });++ capture("dashboard:dashboard_json_imported", {+ dashboard_id: dashboardId,+ widget_count: widgetPlacements.length,+ preset_count: imported.placements.length - widgetPlacements.length,+ skipped_preset_count: imported.skippedPresetCount,+ });++ setTimeout(() => {+ document+ .querySelector(`[data-placement-id="${newPlacements[0]?.id}"]`)+ ?.scrollIntoView({ behavior: "smooth", block: "center" });+ }, 150);++ showSuccessToast({+ title: "Dashboard imported",+ description: `Added ${newPlacements.length} widget${+ newPlacements.length === 1 ? "" : "s"+ } from "${imported.name}".`,+ });+ if (imported.removedFilters) {+ showErrorToast(+ "Widget filters were adjusted",+ "Some imported filters were removed because they are not available in this view.",+ "WARNING",+ );+ }+ if (imported.skippedPresetCount > 0) {+ showErrorToast(+ "Some cards were skipped",+ `${imported.skippedPresetCount} preset card(s) in the file are not available in this Langfuse version.`,+ "WARNING",+ );+ }+ } catch (e) {+ showErrorToast(+ "Failed to import dashboard",+ e instanceof Error ? e.message : "Unknown error",+ );+ }+ },+ [+ createWidgetAsync,+ deleteWidgetAsync,+ projectId,+ applyDashboardDefinition,+ capture,+ dashboardId,+ ],+ );++ // A dropped file may be a dashboard export or a single widget export.+ const handleDroppedFile = useCallback(+ async (file: File) => {+ const text = await file.text();++ const dashboardResult = parseDashboardImport(text, { isBetaEnabled });+ if (dashboardResult.status === "dashboard") {+ await handleDashboardImport(dashboardResult.dashboard);+ return;+ }+ if (dashboardResult.status === "invalid") {+ capture("dashboard:widget_paste_rejected", {+ source: "drop",+ reason: "invalid",+ dashboard_id: dashboardId,+ });+ showErrorToast(+ "Cannot import dashboard",+ dashboardResult.reason,+ "WARNING",+ );+ return;+ }++ const widgetResult = parsePastedWidget(text, { isBetaEnabled });+ if (widgetResult.status === "not-widget") {+ const preset = parsePastedPreset(text);+ if (preset.status === "preset") {+ handlePastedPreset(preset.presetId, "drop");+ return;+ }+ if (preset.status === "invalid") {+ capture("dashboard:widget_paste_rejected", {+ source: "drop",+ reason: "invalid",+ dashboard_id: dashboardId,+ });+ showErrorToast("Cannot import card", preset.reason, "WARNING");+ return;+ }+ capture("dashboard:widget_paste_rejected", {+ source: "drop",+ reason: "not_widget",+ dashboard_id: dashboardId,+ });+ showErrorToast(+ "Unsupported file",+ "Only Langfuse dashboard or widget JSON files can be dropped here.",+ "WARNING",+ );+ return;+ }+ await handleParsedWidgetPaste(widgetResult, "drop");+ },+ [+ isBetaEnabled,+ handleDashboardImport,+ handleParsedWidgetPaste,+ handlePastedPreset,+ capture,+ dashboardId,+ ],+ );++ // Page-wide drop target: dragging a file over the dashboard shows an+ // overlay; dropping imports it.+ const [isDraggingFile, setIsDraggingFile] = useState(false);+ const dragDepthRef = useRef(0);++ useEffect(() => {+ if (!hasCUDAccess) return;++ const isFileDrag = (event: DragEvent) =>+ Array.from(event.dataTransfer?.types ?? []).includes("Files");++ const onDragEnter = (event: DragEvent) => {+ if (!isFileDrag(event)) return;+ dragDepthRef.current += 1;+ setIsDraggingFile(true);+ };+ const onDragOver = (event: DragEvent) => {+ if (!isFileDrag(event)) return;+ // Required for the drop event to fire.+ event.preventDefault();+ };+ const onDragLeave = (event: DragEvent) => {+ if (!isFileDrag(event)) return;+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);+ if (dragDepthRef.current === 0) setIsDraggingFile(false);+ };+ const onDrop = (event: DragEvent) => {+ dragDepthRef.current = 0;+ setIsDraggingFile(false);+ if (!isFileDrag(event)) return;+ event.preventDefault();+ const file = extractTransferFiles(event.dataTransfer)[0];+ if (file) handleDroppedFile(file);+ };++ document.addEventListener("dragenter", onDragEnter);+ document.addEventListener("dragover", onDragOver);+ document.addEventListener("dragleave", onDragLeave);+ document.addEventListener("drop", onDrop);+ return () => {+ document.removeEventListener("dragenter", onDragEnter);+ document.removeEventListener("dragover", onDragOver);+ document.removeEventListener("dragleave", onDragLeave);+ document.removeEventListener("drop", onDrop);+ };+ }, [hasCUDAccess, handleDroppedFile]);+const { nameOptions, tagsOptions } = useDashboardFilterOptions({projectId,isBetaEnabled,@@ -475,8 +1035,7 @@ export default function DashboardDetail() {return;}- setLocalDashboardDefinition(updatedDefinition);- saveDashboardChanges(updatedDefinition);+ applyDashboardDefinition(updatedDefinition);}};@@ -660,7 +1219,7 @@ export default function DashboardDetail() {</Button>)}{hasRbacCUDAccess && (- <DropdownMenu>+ <DropdownMenu onOpenChange={setIsDashboardMenuOpen}><DropdownMenuTrigger asChild><Buttonvariant="ghost"@@ -671,6 +1230,17 @@ export default function DashboardDetail() {</Button></DropdownMenuTrigger><DropdownMenuContent align="end">+ {hasCUDAccess && (+ <DropdownMenuItem+ disabled={clipboardProbe === "no-widget"}+ onClick={() =>+ pasteWidgetFromClipboard("dashboard_menu")+ }+ >+ <ClipboardPasteIcon className="mr-2 h-4 w-4" />+ Paste widget+ </DropdownMenuItem>+ )}<DropdownMenuItemdisabled={isCurrentHome || setHomeDashboard.isPending}onClick={() => {@@ -724,6 +1294,18 @@ export default function DashboardDetail() {}/></PageHeaderControlsPortal>+ {isDraggingFile && (+ <Layer name="modal">+ <div className="bg-background/80 pointer-events-none fixed inset-0 flex items-center justify-center backdrop-blur-xs">+ <div className="border-primary bg-background rounded-lg border-2 border-dashed px-8 py-6 text-center shadow-lg">+ <p className="font-medium">Drop to import</p>+ <p className="text-muted-foreground text-sm">+ Langfuse dashboard or widget JSON+ </p>+ </div>+ </div>+ </Layer>+ )}<SelectWidgetDialogopen={isWidgetDialogOpen}onOpenChange={setIsWidgetDialogOpen}@@ -780,11 +1362,7 @@ export default function DashboardDetail() {});return;}- setLocalDashboardDefinition({- ...localDashboardDefinition,- widgets: updatedWidgets,- });- saveDashboardChanges({+ applyDashboardDefinition({...localDashboardDefinition,widgets: updatedWidgets,});@@ -802,6 +1380,19 @@ export default function DashboardDetail() {? () => openCloneFirst("widget_pencil"): undefined}+ onDuplicateWidget={+ hasCUDAccess ? handleDuplicateWidget : undefined+ }+ onDuplicatePreset={+ hasCUDAccess ? handleDuplicatePreset : undefined+ }+ onPasteWidget={+ hasCUDAccess+ ? (anchor) => {+ pasteWidgetFromClipboard("paste_right", anchor);+ }+ : undefined+ }/></div>)}diff --git a/web/src/utils/clipboard.ts b/web/src/utils/clipboard.tsindex 090b938793..be4f96eecd 100644--- a/web/src/utils/clipboard.ts+++ b/web/src/utils/clipboard.ts@@ -44,3 +44,20 @@ export const copyTextToClipboard = async (text: string) => {}return _unsafeNonSecureCopyToClipboard(text);};++/**+ * Read text from the clipboard. Returns null when the async Clipboard API is+ * unavailable (non-secure context) or the user/browser denied the read β+ * there is no legacy fallback for reading. Callers should treat null as+ * "cannot know what's in the clipboard", not as "clipboard is empty".+ */+export const readTextFromClipboard = async (): Promise<string | null> => {+ if (typeof navigator.clipboard?.readText !== "function") {+ return null;+ }+ try {+ return await navigator.clipboard.readText();+ } catch {+ return null;+ }+};