🪢 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): add langfuse managed read-only dashboard support (#6873)
Steffen Schmitz5e942f020885
diff --git a/packages/shared/src/server/services/DashboardService/DashboardService.ts b/packages/shared/src/server/services/DashboardService/DashboardService.tsindex 766dff7e54..d91cf57bac 100644--- a/packages/shared/src/server/services/DashboardService/DashboardService.ts+++ b/packages/shared/src/server/services/DashboardService/DashboardService.ts@@ -1,5 +1,9 @@import { prisma } from "../../../db";-import { LangfuseConflictError, type OrderByState } from "../../../";+import {+ LangfuseConflictError,+ LangfuseNotFoundError,+ type OrderByState,+} from "../../../";import {CreateWidgetInput,WidgetDomain,@@ -30,7 +34,7 @@ export class DashboardService {const [dashboards, totalCount] = await Promise.all([prisma.dashboard.findMany({where: {- projectId,+ OR: [{ projectId }, { projectId: null }],},orderBy: orderBy? [{ [orderBy.column]: orderBy.order.toLowerCase() }]@@ -40,13 +44,16 @@ export class DashboardService {}),prisma.dashboard.count({where: {- projectId,+ OR: [{ projectId }, { projectId: null }],},}),]);const domainDashboards = dashboards.map((dashboard) =>- DashboardDomainSchema.parse(dashboard),+ DashboardDomainSchema.parse({+ ...dashboard,+ owner: dashboard.projectId ? "PROJECT" : "LANGFUSE",+ }),);return {@@ -78,7 +85,10 @@ export class DashboardService {},});- return DashboardDomainSchema.parse(newDashboard);+ return DashboardDomainSchema.parse({+ ...newDashboard,+ owner: newDashboard.projectId ? "PROJECT" : "LANGFUSE",+ });}/**@@ -111,7 +121,10 @@ export class DashboardService {},});- return DashboardDomainSchema.parse(updatedDashboard);+ return DashboardDomainSchema.parse({+ ...updatedDashboard,+ owner: updatedDashboard.projectId ? "PROJECT" : "LANGFUSE",+ });}/**@@ -136,7 +149,10 @@ export class DashboardService {},});- return DashboardDomainSchema.parse(updatedDashboard);+ return DashboardDomainSchema.parse({+ ...updatedDashboard,+ owner: updatedDashboard.projectId ? "PROJECT" : "LANGFUSE",+ });}/**@@ -149,7 +165,7 @@ export class DashboardService {const dashboard = await prisma.dashboard.findFirst({where: {id: dashboardId,- projectId,+ OR: [{ projectId }, { projectId: null }],},});@@ -157,7 +173,10 @@ export class DashboardService {return null;}- return DashboardDomainSchema.parse(dashboard);+ return DashboardDomainSchema.parse({+ ...dashboard,+ owner: dashboard.projectId ? "PROJECT" : "LANGFUSE",+ });}/**@@ -208,7 +227,10 @@ export class DashboardService {]);const domainWidgets = widgets.map((widget) =>- WidgetDomainSchema.parse(widget),+ WidgetDomainSchema.parse({+ ...widget,+ owner: widget.projectId ? "PROJECT" : "LANGFUSE",+ }),);return {@@ -241,11 +263,14 @@ export class DashboardService {},});- return WidgetDomainSchema.parse(newWidget);+ return WidgetDomainSchema.parse({+ ...newWidget,+ owner: newWidget.projectId ? "PROJECT" : "LANGFUSE",+ });}/**- * Gets a dashboard widget by ID.+ * Gets a dashboard widget by ID. Look either in the current project or in the Langfuse managed widgets.*/public static async getWidget(widgetId: string,@@ -254,7 +279,7 @@ export class DashboardService {const widget = await prisma.dashboardWidget.findFirst({where: {id: widgetId,- projectId,+ OR: [{ projectId }, { projectId: null }],},});@@ -262,7 +287,10 @@ export class DashboardService {return null;}- return WidgetDomainSchema.parse(widget);+ return WidgetDomainSchema.parse({+ ...widget,+ owner: widget.projectId ? "PROJECT" : "LANGFUSE",+ });}/**@@ -293,20 +321,8 @@ export class DashboardService {});return WidgetDomainSchema.parse({- id: widgetId,- projectId,- createdAt: updatedWidget.createdAt,- updatedAt: updatedWidget.updatedAt,- createdBy: updatedWidget.createdBy,- updatedBy: updatedWidget.updatedBy,- name: updatedWidget.name,- description: updatedWidget.description,- view: updatedWidget.view,- dimensions: updatedWidget.dimensions as WidgetDomain["dimensions"],- metrics: updatedWidget.metrics as WidgetDomain["metrics"],- filters: updatedWidget.filters as WidgetDomain["filters"],- chartType: updatedWidget.chartType,- chartConfig: updatedWidget.chartConfig as WidgetDomain["chartConfig"],+ ...updatedWidget,+ owner: updatedWidget.projectId ? "PROJECT" : "LANGFUSE",});}@@ -351,4 +367,80 @@ export class DashboardService {},});}++ /**+ * Copies a Langfuse-owned widget into the user project, rewires the specified dashboard placement to the new widget and returns the new widget id.+ */+ public static async copyWidgetToProject(props: {+ sourceWidgetId: string;+ projectId: string;+ dashboardId: string;+ placementId: string;+ userId?: string;+ }): Promise<string> {+ const { sourceWidgetId, projectId, dashboardId, placementId, userId } =+ props;++ const sourceWidget = await prisma.dashboardWidget.findFirst({+ where: {+ id: sourceWidgetId,+ projectId: null,+ },+ });++ if (!sourceWidget) {+ throw new LangfuseNotFoundError(+ `Source widget ${sourceWidgetId} not found`,+ );+ }++ // Duplicate widget and update dashboard definition atomically+ return prisma.$transaction(async (tx) => {+ // 1. create duplicate in project scope+ const newWidget = await tx.dashboardWidget.create({+ data: {+ name: sourceWidget.name,+ description: sourceWidget.description,+ view: sourceWidget.view,+ dimensions: sourceWidget.dimensions ?? [],+ metrics: sourceWidget.metrics ?? [],+ filters: sourceWidget.filters ?? [],+ chartType: sourceWidget.chartType,+ chartConfig: sourceWidget.chartConfig ?? {},+ projectId, // project owned+ createdBy: userId,+ updatedBy: userId,+ },+ });++ // 2. fetch dashboard to change reference+ const dashboard = await tx.dashboard.findFirst({+ where: { id: dashboardId, projectId },+ });++ if (!dashboard) {+ throw new LangfuseNotFoundError(+ `Dashboard ${dashboardId} not found in project ${projectId}`,+ );+ }++ const definition = (dashboard.definition ?? {+ widgets: [],+ }) as z.infer<typeof DashboardDefinitionSchema>;+ const updatedWidgets = (definition.widgets || []).map((w: any) =>+ w.id === placementId ? { ...w, widgetId: newWidget.id } : w,+ );++ // 3. update dashboard with new widget reference+ await tx.dashboard.update({+ where: { id: dashboardId, projectId },+ data: {+ updatedBy: userId,+ definition: { widgets: updatedWidgets },+ },+ });++ return newWidget.id;+ });+ }}diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.tsindex af73e17c5f..23dce06d33 100644--- a/packages/shared/src/server/services/DashboardService/types.ts+++ b/packages/shared/src/server/services/DashboardService/types.ts@@ -62,6 +62,8 @@ export const DashboardDefinitionSchema = z.object({widgets: z.array(DashboardDefinitionWidgetSchema),});+export const OwnerEnum = z.enum(["PROJECT", "LANGFUSE"]);+// Define the dashboard domain objectexport const DashboardDomainSchema = z.object({id: z.string(),@@ -73,6 +75,7 @@ export const DashboardDomainSchema = z.object({name: z.string(),description: z.string(),definition: DashboardDefinitionSchema,+ owner: OwnerEnum,});// Define the dashboard list response@@ -97,6 +100,7 @@ export const WidgetDomainSchema = z.object({filters: z.array(singleFilter),chartType: z.nativeEnum(DashboardWidgetChartType),chartConfig: ChartConfigSchema,+ owner: OwnerEnum,});// Define create widget input schemadiff --git a/web/src/features/dashboard/components/DashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable.tsxindex 383b880957..ead435e9fa 100644--- a/web/src/features/dashboard/components/DashboardTable.tsx+++ b/web/src/features/dashboard/components/DashboardTable.tsx@@ -24,6 +24,8 @@ import {} from "@/src/components/ui/dropdown-menu";import { DeleteDashboardButton } from "@/src/components/deleteButton";import { EditDashboardDialog } from "@/src/features/dashboard/components/EditDashboardDialog";+import { User as UserIcon } from "lucide-react";+import { useRouter } from "next/router";type DashboardTableRow = {id: string;@@ -31,6 +33,7 @@ type DashboardTableRow = {description: string;createdAt: Date;updatedAt: Date;+ owner: "PROJECT" | "LANGFUSE";};function CloneDashboardButton({@@ -124,6 +127,7 @@ function EditDashboardButton({export function DashboardTable() {const projectId = useProjectIdFromURL() as string;const { setDetailPageList } = useDetailPageLists();+ const router = useRouter();const [orderByState, setOrderByState] = useOrderByState({column: "updatedAt",@@ -186,6 +190,25 @@ export function DashboardTable() {return row.getValue();},}),+ columnHelper.display({+ id: "ownerTag",+ header: "Owner",+ size: 80,+ cell: (row) => {+ return row.row.original.owner === "LANGFUSE" ? (+ <span className="flex gap-1 px-2 py-0.5 text-xs">+ <span role="img" aria-label="Langfuse">+ 🪢+ </span>+ Langfuse+ </span>+ ) : (+ <span className="flex gap-1 px-2 py-0.5 text-xs">+ <UserIcon className="h-3 w-3" /> Project+ </span>+ );+ },+ }),columnHelper.accessor("createdAt", {header: "Created At",id: "createdAt",@@ -214,34 +237,41 @@ export function DashboardTable() {const id = row.row.original.id;const name = row.row.original.name;const description = row.row.original.description;+ const owner = row.row.original.owner;return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost">- <MoreVertical className="h-4 w-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="flex flex-col [&>*]:w-full [&>*]:justify-start">- <DropdownMenuItem asChild>- <EditDashboardButton- dashboardId={id}- projectId={projectId}- dashboardName={name}- dashboardDescription={description}- />- </DropdownMenuItem>- <DropdownMenuItem asChild>- <CloneDashboardButton dashboardId={id} projectId={projectId} />- </DropdownMenuItem>- <DropdownMenuItem asChild>- <DeleteDashboardButton- itemId={id}- projectId={projectId}- isTableAction- />- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <div onClick={(e) => e.stopPropagation()}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost">+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="flex flex-col [&>*]:w-full [&>*]:justify-start">+ {owner === "PROJECT" && (+ <DropdownMenuItem asChild>+ <EditDashboardButton+ dashboardId={id}+ projectId={projectId}+ dashboardName={name}+ dashboardDescription={description}+ />+ </DropdownMenuItem>+ )}+ <DropdownMenuItem asChild>+ <CloneDashboardButton dashboardId={id} projectId={projectId} />+ </DropdownMenuItem>+ {owner === "PROJECT" && (+ <DropdownMenuItem asChild>+ <DeleteDashboardButton+ itemId={id}+ projectId={projectId}+ isTableAction+ />+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>);},}),@@ -272,6 +302,11 @@ export function DashboardTable() {onChange: setPaginationState,state: paginationState,}}+ onRowClick={(row) => {+ router.push(+ `/project/${projectId}/dashboards/${encodeURIComponent(row.id)}`,+ );+ }}/>);}diff --git a/web/src/features/dashboard/components/SelectDashboardDialog.tsx b/web/src/features/dashboard/components/SelectDashboardDialog.tsxindex 63bd768677..55dfa3245a 100644--- a/web/src/features/dashboard/components/SelectDashboardDialog.tsx+++ b/web/src/features/dashboard/components/SelectDashboardDialog.tsx@@ -89,23 +89,25 @@ export function SelectDashboardDialog({</TableRow></TableHeader><TableBody>- {dashboards.data?.dashboards.map((d) => (- <TableRow- key={d.id}- onClick={() => setSelectedDashboardId(d.id)}- className={`cursor-pointer hover:bg-muted ${- selectedDashboardId === d.id ? "bg-muted" : ""- }`}- >- <TableCell className="font-medium">{d.name}</TableCell>- <TableCell className="max-w-[200px] truncate">- {d.description}- </TableCell>- <TableCell>- {new Date(d.updatedAt).toLocaleString()}- </TableCell>- </TableRow>- ))}+ {dashboards.data?.dashboards+ .filter((d) => d.owner === "PROJECT")+ .map((d) => (+ <TableRow+ key={d.id}+ onClick={() => setSelectedDashboardId(d.id)}+ className={`cursor-pointer hover:bg-muted ${+ selectedDashboardId === d.id ? "bg-muted" : ""+ }`}+ >+ <TableCell className="font-medium">{d.name}</TableCell>+ <TableCell className="max-w-[200px] truncate">+ {d.description}+ </TableCell>+ <TableCell>+ {new Date(d.updatedAt).toLocaleString()}+ </TableCell>+ </TableRow>+ ))}</TableBody></Table>)}diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex b47de444c3..db65b77554 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -9,10 +9,11 @@ import { type z } from "zod";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { type FilterState } from "@langfuse/shared";import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";-import { PencilIcon, TrashIcon } from "lucide-react";+import { PencilIcon, TrashIcon, CopyIcon } from "lucide-react";import { useRouter } from "next/router";-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { startCase } from "lodash";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";interface WidgetPlacement {id: string;@@ -31,18 +32,23 @@ const getGridClasses = (widget: WidgetPlacement) => {export function DashboardWidget({projectId,+ dashboardId,placement,dateRange,filterState,onDeleteWidget,+ dashboardOwner,}: {projectId: string;+ dashboardId: string;placement: WidgetPlacement;dateRange: { from: Date; to: Date } | undefined;filterState: FilterState;onDeleteWidget: (tileId: string) => void;+ dashboardOwner: "LANGFUSE" | "PROJECT";}) {const router = useRouter();+ const utils = api.useUtils();const widget = api.dashboardWidgets.get.useQuery({widgetId: placement.widgetId,@@ -52,11 +58,9 @@ export function DashboardWidget({enabled: Boolean(projectId),},);-- const hasCUDAccess = useHasProjectAccess({- projectId,- scope: "dashboards:CUD",- });+ const hasCUDAccess =+ useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&+ dashboardOwner !== "LANGFUSE";const fromTimestamp = dateRange? dateRange.from@@ -129,6 +133,39 @@ export function DashboardWidget({});}, [queryResult.data, widget.data]);+ const handleEdit = () => {+ router.push(+ `/project/${projectId}/widgets/${placement.widgetId}?dashboardId=${dashboardId}`,+ );+ };++ const copyMutation = api.dashboardWidgets.copyToProject.useMutation({+ onSuccess: (data) => {+ utils.dashboard.getDashboard.invalidate().then(() => {+ router.push(+ `/project/${projectId}/widgets/${data.widgetId}?dashboardId=${dashboardId}`,+ );+ });+ },+ onError: (e) => {+ showErrorToast("Failed to clone widget", e.message);+ },+ });+ const handleCopy = () => {+ copyMutation.mutate({+ projectId,+ widgetId: placement.widgetId,+ dashboardId: router.query.dashboardId as string,+ placementId: placement.id,+ });+ };++ const handleDelete = () => {+ if (onDeleteWidget && confirm("Please confirm deletion")) {+ onDeleteWidget(placement.id);+ }+ };+if (widget.isLoading) {return (<div@@ -149,40 +186,45 @@ export function DashboardWidget({);}- const handleEdit = () => {- router.push(`/project/${projectId}/widgets/${placement.widgetId}`);- };-- const handleDelete = () => {- if (onDeleteWidget && confirm("Please confirm deletion")) {- onDeleteWidget(placement.id);- }- };-return (<divclassName={`${getGridClasses(placement)} group flex flex-col overflow-hidden rounded-lg border bg-background p-4`}><div className="mb-2 flex items-center justify-between">- <span className="font-medium">{widget.data.name}</span>- <div className="flex space-x-2">- <button- onClick={handleEdit}- className="hidden text-muted-foreground hover:text-foreground group-hover:block"- aria-label="Edit widget"- disabled={!hasCUDAccess}- >- <PencilIcon size={16} />- </button>- <button- onClick={handleDelete}- className="hidden text-muted-foreground hover:text-destructive group-hover:block"- aria-label="Delete widget"- disabled={!hasCUDAccess}- >- <TrashIcon size={16} />- </button>- </div>+ <span className="font-medium">+ {widget.data.name}{" "}+ {dashboardOwner === "PROJECT" && widget.data.owner === "LANGFUSE"+ ? " ( 🪢 )"+ : null}+ </span>+ {hasCUDAccess && (+ <div className="flex space-x-2">+ {widget.data.owner === "PROJECT" ? (+ <button+ onClick={handleEdit}+ className="hidden text-muted-foreground hover:text-foreground group-hover:block"+ aria-label="Edit widget"+ >+ <PencilIcon size={16} />+ </button>+ ) : widget.data.owner === "LANGFUSE" ? (+ <button+ onClick={handleCopy}+ className="hidden text-muted-foreground hover:text-foreground group-hover:block"+ aria-label="Copy widget"+ >+ <CopyIcon size={16} />+ </button>+ ) : null}+ <button+ onClick={handleDelete}+ className="hidden text-muted-foreground hover:text-destructive group-hover:block"+ aria-label="Delete widget"+ >+ <TrashIcon size={16} />+ </button>+ </div>+ )}</div><div className="mb-4 text-sm text-muted-foreground">{widget.data.description}diff --git a/web/src/features/widgets/components/WidgetTable.tsx b/web/src/features/widgets/components/WidgetTable.tsxindex 7d8093b019..32797216d3 100644--- a/web/src/features/widgets/components/WidgetTable.tsx+++ b/web/src/features/widgets/components/WidgetTable.tsx@@ -21,6 +21,7 @@ import {} from "@/src/components/ui/popover";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { useRouter } from "next/router";type WidgetTableRow = {id: string;@@ -30,13 +31,22 @@ type WidgetTableRow = {chartType: string;createdAt: Date;updatedAt: Date;+ owner: "PROJECT" | "LANGFUSE";};-export function DeleteWidget({ widgetId }: { widgetId: string }) {+export function DeleteWidget({+ widgetId,+ owner,+}: {+ widgetId: string;+ owner: "PROJECT" | "LANGFUSE";+}) {const projectId = useProjectIdFromURL();const utils = api.useUtils();const [isOpen, setIsOpen] = useState(false);- const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });+ const hasAccess =+ useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&+ owner !== "LANGFUSE";const capture = usePostHogClientCapture();const mutDeleteWidget = api.dashboardWidgets.delete.useMutation({@@ -99,6 +109,7 @@ export function DeleteWidget({ widgetId }: { widgetId: string }) {export function DashboardWidgetTable() {const projectId = useProjectIdFromURL();const { setDetailPageList } = useDetailPageLists();+ const router = useRouter();const [orderByState, setOrderByState] = useOrderByState({column: "updatedAt",@@ -218,7 +229,11 @@ export function DashboardWidgetTable() {size: 70,cell: (row) => {const id = row.row.original.id;- return <DeleteWidget widgetId={id} />;+ return (+ <div onClick={(e) => e.stopPropagation()}>+ <DeleteWidget widgetId={id} owner={row.row.original.owner} />+ </div>+ );},}),] as LangfuseColumnDef<WidgetTableRow>[];@@ -248,6 +263,11 @@ export function DashboardWidgetTable() {onChange: setPaginationState,state: paginationState,}}+ onRowClick={(row) => {+ router.push(+ `/project/${projectId}/widgets/${encodeURIComponent(row.id)}`,+ );+ }}/>);}diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsxindex dc18097fa1..d85fccf3c7 100644--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx@@ -9,7 +9,7 @@ import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";import { useEffect, useState, useCallback } from "react";import type { ColumnDefinition, FilterState } from "@langfuse/shared";import { Button } from "@/src/components/ui/button";-import { PlusIcon } from "lucide-react";+import { PlusIcon, Copy } from "lucide-react";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import {@@ -19,6 +19,7 @@ import {import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { v4 as uuidv4 } from "uuid";import { useDebounce } from "@/src/hooks/useDebounce";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";interface WidgetPlacement {id: string;@@ -32,17 +33,34 @@ interface WidgetPlacement {export default function DashboardDetail() {const router = useRouter();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+const { projectId, dashboardId, addWidgetId } = router.query as {projectId: string;dashboardId: string;addWidgetId?: string;};- const hasCUDAccess = useHasProjectAccess({+ // Fetch dashboard data+ const dashboard = api.dashboard.getDashboard.useQuery({projectId,- scope: "dashboards:CUD",+ dashboardId,});+ const hasCUDAccess =+ useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ }) && dashboard.data?.owner !== "LANGFUSE";++ // Access for cloning (independent of dashboard owner)+ const hasCloneAccess =+ useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ }) && dashboard.data?.owner === "LANGFUSE";+// Filter stateconst { selectedOption, dateRange, setDateRangeAndOption } =useDashboardDateRange({ defaultRelativeAggregation: "7 days" });@@ -75,6 +93,7 @@ export default function DashboardDetail() {const saveDashboardChanges = useDebounce((definition: { widgets: WidgetPlacement[] }) => {+ if (!hasCUDAccess) return;updateDashboardDefinition.mutate({projectId,dashboardId,@@ -230,14 +249,6 @@ export default function DashboardDetail() {},];- // Fetch dashboard data- const dashboard = api.dashboard.getDashboard.useQuery(- { projectId, dashboardId },- {- enabled: Boolean(projectId) && Boolean(dashboardId),- },- );-// Fetch widget data if addWidgetId is presentconst widgetToAdd = api.dashboardWidgets.get.useQuery({ projectId, widgetId: addWidgetId || "" },@@ -303,8 +314,62 @@ export default function DashboardDetail() {addWidgetToDashboard(widget);};+ const mutateCloneDashboard = api.dashboard.cloneDashboard.useMutation({+ onSuccess: (data) => {+ void utils.dashboard.invalidate();+ capture("dashboard:clone_dashboard");+ // Redirect to new dashboard+ if (data?.id) {+ router.replace(+ `/project/${projectId}/dashboards/${encodeURIComponent(data.id)}`,+ );+ }+ },+ onError: (e) => {+ showErrorToast("Failed to clone dashboard", e.message);+ },+ });++ const handleCloneDashboard = () => {+ if (!projectId || !dashboardId) return;+ mutateCloneDashboard.mutate({ projectId, dashboardId });+ };+return (- <>+ <Page+ withPadding+ scrollable+ headerProps={{+ title:+ (dashboard.data?.name || "Dashboard") ++ (dashboard.data?.owner === "LANGFUSE"+ ? " (Maintained by Langfuse 🪢)"+ : ""),+ help: {+ description:+ dashboard.data?.description || "No description available",+ },+ actionButtonsRight: (+ <>+ {hasCUDAccess && (+ <Button onClick={handleAddWidget}>+ <PlusIcon size={16} className="mr-1 h-4 w-4" />+ Add Widget+ </Button>+ )}+ {hasCloneAccess && (+ <Button+ onClick={handleCloneDashboard}+ disabled={mutateCloneDashboard.isLoading}+ >+ <Copy size={16} className="mr-1 h-4 w-4" />+ Clone+ </Button>+ )}+ </>+ ),+ }}+ ><SelectWidgetDialogopen={isWidgetDialogOpen}onOpenChange={setIsWidgetDialogOpen}@@ -312,66 +377,47 @@ export default function DashboardDetail() {onSelectWidget={handleSelectWidget}dashboardId={dashboardId}/>-- <Page- withPadding- scrollable- headerProps={{- title: dashboard.data?.name || "Dashboard",- help: {- description:- dashboard.data?.description || "No description available",- },- actionButtonsRight: (- <>- <Button onClick={handleAddWidget} disabled={!hasCUDAccess}>- <PlusIcon size={16} />- Add Widget- </Button>- </>- ),- }}- >- {dashboard.isLoading || !localDashboardDefinition ? (- <NoDataOrLoading isLoading={true} />- ) : dashboard.isError ? (- <div className="flex h-64 items-center justify-center">- <div className="text-destructive">- Error: {dashboard.error.message}- </div>+ {dashboard.isLoading || !localDashboardDefinition ? (+ <NoDataOrLoading isLoading={true} />+ ) : dashboard.isError ? (+ <div className="flex h-64 items-center justify-center">+ <div className="text-destructive">+ Error: {dashboard.error.message}</div>- ) : (- <div>- <div className="my-3 flex flex-wrap items-center justify-between gap-2">- <div className="flex flex-col gap-2 lg:flex-row lg:gap-3">- <DatePickerWithRange- dateRange={dateRange}- setDateRangeAndOption={setDateRangeAndOption}- selectedOption={selectedOption}- className="my-0 max-w-full overflow-x-auto"- />- <PopoverFilterBuilder- columns={filterColumns}- filterState={userFilterState}- onChange={setUserFilterState}- />- </div>- </div>- <div className="grid grid-cols-12 gap-4">- {localDashboardDefinition.widgets.map((widgetPlacement) => (- <DashboardWidget- key={widgetPlacement.id}- projectId={projectId}- placement={widgetPlacement}- dateRange={dateRange}- filterState={userFilterState}- onDeleteWidget={handleDeleteWidget}- />- ))}+ </div>+ ) : (+ <div>+ <div className="my-3 flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-col gap-2 lg:flex-row lg:gap-3">+ <DatePickerWithRange+ dateRange={dateRange}+ setDateRangeAndOption={setDateRangeAndOption}+ selectedOption={selectedOption}+ className="my-0 max-w-full overflow-x-auto"+ />+ <PopoverFilterBuilder+ columns={filterColumns}+ filterState={userFilterState}+ onChange={setUserFilterState}+ /></div></div>- )}- </Page>- </>+ <div className="grid grid-cols-12 gap-4">+ {localDashboardDefinition.widgets.map((widgetPlacement) => (+ <DashboardWidget+ key={widgetPlacement.id}+ dashboardId={dashboardId}+ projectId={projectId}+ placement={widgetPlacement}+ dateRange={dateRange}+ filterState={userFilterState}+ onDeleteWidget={handleDeleteWidget}+ dashboardOwner={dashboard.data?.owner}+ />+ ))}+ </div>+ </div>+ )}+ </Page>);}diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsxindex 383be046eb..9be97e54cd 100644--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx@@ -10,9 +10,10 @@ import { type z } from "zod";export default function EditWidget() {const router = useRouter();- const { projectId, widgetId } = router.query as {+ const { projectId, widgetId, dashboardId } = router.query as {projectId: string;widgetId: string;+ dashboardId?: string;};// Fetch the widget details@@ -34,8 +35,14 @@ export default function EditWidget() {title: "Widget updated successfully",description: "Your widget has been updated.",});- // Navigate back to widgets list- void router.push(`/project/${projectId}/widgets`);+ // Navigate back to dashboard if provided else widgets list+ if (dashboardId) {+ void router.push(+ `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${widgetId}`,+ );+ } else {+ void router.push(`/project/${projectId}/widgets`);+ }},onError: (error) => {showErrorToast("Failed to update widget", error.message);diff --git a/web/src/server/api/routers/dashboardWidgets.ts b/web/src/server/api/routers/dashboardWidgets.tsindex 1d58775267..f1bdf02e60 100644--- a/web/src/server/api/routers/dashboardWidgets.ts+++ b/web/src/server/api/routers/dashboardWidgets.ts@@ -139,6 +139,7 @@ export const dashboardWidgetRouter = createTRPCRouter({return {...widget,view: reverseViewMapping[widget.view],+ owner: widget.owner,};}),@@ -174,6 +175,33 @@ export const dashboardWidgetRouter = createTRPCRouter({};}),+ copyToProject: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ widgetId: z.string(),+ dashboardId: z.string(),+ placementId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ const newWidgetId = await DashboardService.copyWidgetToProject({+ sourceWidgetId: input.widgetId,+ projectId: input.projectId,+ dashboardId: input.dashboardId,+ placementId: input.placementId,+ userId: ctx.session.user?.id,+ });++ return { widgetId: newWidgetId };+ }),+// Define delete widget input schemadelete: protectedProjectProcedure.input(