🪢 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 beta preview for customizable dashboards (#6376)
Steffen Schmitz9951364ff0b3
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 4f6091cb5b..54ed1ef5be 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -92,6 +92,21 @@ export const BlobStorageIntegrationType = {AZURE_BLOB_STORAGE: "AZURE_BLOB_STORAGE"} as const;export type BlobStorageIntegrationType = (typeof BlobStorageIntegrationType)[keyof typeof BlobStorageIntegrationType];+export const DashboardWidgetViews = {+ TRACES: "TRACES",+ OBSERVATIONS: "OBSERVATIONS",+ SCORES_NUMERIC: "SCORES_NUMERIC",+ SCORES_CATEGORICAL: "SCORES_CATEGORICAL"+} as const;+export type DashboardWidgetViews = (typeof DashboardWidgetViews)[keyof typeof DashboardWidgetViews];+export const DashboardWidgetChartType = {+ LINE_TIME_SERIES: "LINE_TIME_SERIES",+ BAR_TIME_SERIES: "BAR_TIME_SERIES",+ HORIZONTAL_BAR: "HORIZONTAL_BAR",+ VERTICAL_BAR: "VERTICAL_BAR",+ PIE: "PIE"+} as const;+export type DashboardWidgetChartType = (typeof DashboardWidgetChartType)[keyof typeof DashboardWidgetChartType];export type Account = {id: string;user_id: string;@@ -234,6 +249,33 @@ export type CronJobs = {job_started_at: Timestamp | null;state: string | null;};+export type Dashboard = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ created_by: string | null;+ updated_by: string | null;+ project_id: string | null;+ name: string;+ description: string;+ definition: unknown;+};+export type DashboardWidget = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ created_by: string | null;+ updated_by: string | null;+ project_id: string | null;+ name: string;+ description: string;+ view: DashboardWidgetViews;+ dimensions: unknown;+ metrics: unknown;+ filters: unknown;+ chart_type: DashboardWidgetChartType;+ chart_config: unknown;+};export type Dataset = {id: string;project_id: string;@@ -630,6 +672,8 @@ export type DB = {blob_storage_integrations: BlobStorageIntegration;comments: Comment;cron_jobs: CronJobs;+ dashboard_widgets: DashboardWidget;+ dashboards: Dashboard;dataset_items: DatasetItem;dataset_run_items: DatasetRunItems;dataset_runs: DatasetRuns;diff --git a/packages/shared/prisma/migrations/20250409154352_add_dashboard_data_model/migration.sql b/packages/shared/prisma/migrations/20250409154352_add_dashboard_data_model/migration.sqlnew file mode 100644index 0000000000..92ded7b377--- /dev/null+++ b/packages/shared/prisma/migrations/20250409154352_add_dashboard_data_model/migration.sql@@ -0,0 +1,58 @@+-- CreateEnum+CREATE TYPE "DashboardWidgetViews" AS ENUM ('TRACES', 'OBSERVATIONS', 'SCORES_NUMERIC', 'SCORES_CATEGORICAL');++-- CreateEnum+CREATE TYPE "DashboardWidgetChartType" AS ENUM ('LINE_TIME_SERIES', 'BAR_TIME_SERIES', 'HORIZONTAL_BAR', 'VERTICAL_BAR', 'PIE');++-- CreateTable+CREATE TABLE "dashboards" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "created_by" TEXT,+ "updated_by" TEXT,+ "project_id" TEXT,+ "name" TEXT NOT NULL,+ "description" TEXT NOT NULL,+ "definition" JSONB NOT NULL,++ CONSTRAINT "dashboards_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "dashboard_widgets" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "created_by" TEXT,+ "updated_by" TEXT,+ "project_id" TEXT,+ "name" TEXT NOT NULL,+ "description" TEXT NOT NULL,+ "view" "DashboardWidgetViews" NOT NULL,+ "dimensions" JSONB NOT NULL,+ "metrics" JSONB NOT NULL,+ "filters" JSONB NOT NULL,+ "chart_type" "DashboardWidgetChartType" NOT NULL,+ "chart_config" JSONB NOT NULL,++ CONSTRAINT "dashboard_widgets_pkey" PRIMARY KEY ("id")+);++-- AddForeignKey+ALTER TABLE "dashboards" ADD CONSTRAINT "dashboards_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "dashboards" ADD CONSTRAINT "dashboards_updated_by_fkey" FOREIGN KEY ("updated_by") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "dashboards" ADD CONSTRAINT "dashboards_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "dashboard_widgets" ADD CONSTRAINT "dashboard_widgets_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "dashboard_widgets" ADD CONSTRAINT "dashboard_widgets_updated_by_fkey" FOREIGN KEY ("updated_by") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "dashboard_widgets" ADD CONSTRAINT "dashboard_widgets_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 8e520822c8..d3a144e1f1 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -82,6 +82,10 @@ model User {featureFlags String[] @default([]) @map("feature_flags")annotatedLockedItem AnnotationQueueItem[] @relation("LockedByUser")annotatedCompletedItem AnnotationQueueItem[] @relation("AnnotatorUser")+ dashboardWidgetsCreated DashboardWidget[] @relation("CreatedByUser")+ dashboardWidgetsUpdated DashboardWidget[] @relation("UpdatedByUser")+ dashboardCreated Dashboard[] @relation("CreatedByUser")+ dashboardUpdated Dashboard[] @relation("UpdatedByUser")@@map("users")}@@ -145,6 +149,8 @@ model Project {LlmSchema LlmSchema[]LlmTool LlmTool[]PromptProtectedLabels PromptProtectedLabels[]+ Dashboard Dashboard[]+ DashboardWidget DashboardWidget[]@@index([orgId])@@map("projects")@@ -1067,3 +1073,68 @@ model LlmTool {@@unique([projectId, name])@@map("llm_tools")}++model Dashboard {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ createdBy String? @map("created_by")+ createdByUser User? @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)+ updatedBy String? @map("updated_by")+ updatedByUser User? @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)++ // Optional to account for Langfuse-managed dashboards+ projectId String? @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)++ name String @map("name")+ description String @map("description")++ definition Json @map("definition")++ @@map("dashboards")+}++enum DashboardWidgetViews {+ TRACES+ OBSERVATIONS+ SCORES_NUMERIC+ SCORES_CATEGORICAL+}++enum DashboardWidgetChartType {+ LINE_TIME_SERIES+ BAR_TIME_SERIES+ HORIZONTAL_BAR+ VERTICAL_BAR+ PIE+}++model DashboardWidget {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ createdBy String? @map("created_by")+ createdByUser User? @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)+ updatedBy String? @map("updated_by")+ updatedByUser User? @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)++ // Optional to account for Langfuse-managed dashboards+ projectId String? @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)++ name String @map("name")+ description String @map("description")++ view DashboardWidgetViews @map("view")+ dimensions Json @map("dimensions")+ metrics Json @map("metrics")+ filters Json @map("filters")++ chartType DashboardWidgetChartType @map("chart_type")+ chartConfig Json @map("chart_config")++ @@map("dashboard_widgets")+}diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex 387feb82a1..1b98871b87 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -14,6 +14,7 @@ import { ModelUsageUnit } from "../src";import { getDisplaySecretKey, hashSecretKey, logger } from "../src/server";import { encrypt } from "../src/encryption";import { redis } from "../src/server/redis/redis";+import { randomUUID } from "crypto";const LOAD_TRACE_VOLUME = 10_000;@@ -375,6 +376,8 @@ async function main() {await createDatasets(project1, project2, observations);+ await createDashboardsAndWidgets([project1, project2]);+await prisma.llmSchema.createMany({data: [{@@ -431,6 +434,85 @@ main()process.exit(1);});+async function createDashboardsAndWidgets(projects: Project[]) {+ logger.info("Creating dashboards and widgets");++ // Process each project+ for (const project of projects) {+ const widget = await prisma.dashboardWidget.upsert({+ where: { id: "cabc" },+ create: {+ id: "cabc",+ projectId: project.id,+ name: "Trace Counts",+ description: "Trace Counts by Name Over Time",+ view: "TRACES",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", agg: "count" }],+ filters: [],+ chartType: "BAR_TIME_SERIES",+ chartConfig: {+ type: "BAR_TIME_SERIES",+ },+ },+ update: {},+ });++ const widget2 = await prisma.dashboardWidget.upsert({+ where: { id: "cdef" },+ create: {+ id: "cdef",+ projectId: project.id,+ name: "Observation Latencies by Model",+ description: "p95 Observation Latencies by Model Name",+ view: "OBSERVATIONS",+ dimensions: [{ field: "providedModelName" }],+ metrics: [{ measure: "count", agg: "sum" }],+ filters: [],+ chartType: "LINE_TIME_SERIES",+ chartConfig: {+ type: "LINE_TIME_SERIES",+ },+ },+ update: {},+ });++ // Create a dashboard with multiple widgets+ await prisma.dashboard.upsert({+ where: { id: "seed-dashboard" },+ create: {+ id: "seed-dashboard",+ projectId: project.id,+ name: "Performance Overview",+ description: "Dashboard with various performance metrics",+ definition: {+ widgets: [+ {+ type: "widget",+ id: randomUUID(),+ widgetId: widget.id,+ x: 0,+ y: 0,+ x_size: 6,+ y_size: 2,+ },+ {+ type: "widget",+ id: randomUUID(),+ widgetId: widget2.id,+ x: 6,+ y: 0,+ x_size: 6,+ y_size: 2,+ },+ ],+ },+ },+ update: {},+ });+ }+}+export async function createDatasets(project1: {id: string;diff --git a/packages/shared/src/errors/ConflictError.ts b/packages/shared/src/errors/ConflictError.tsnew file mode 100644index 0000000000..8f7096ee21--- /dev/null+++ b/packages/shared/src/errors/ConflictError.ts@@ -0,0 +1,7 @@+import { BaseError } from "./BaseError";++export class LangfuseConflictError extends BaseError {+ constructor(description = "Conflict") {+ super("LangfuseConflictError", 409, description, true);+ }+}diff --git a/packages/shared/src/errors/index.ts b/packages/shared/src/errors/index.tsindex 3be39c580a..1be42af99b 100644--- a/packages/shared/src/errors/index.ts+++ b/packages/shared/src/errors/index.ts@@ -6,3 +6,4 @@ export { ForbiddenError } from "./ForbiddenError";export { MethodNotAllowedError } from "./MethodNotAllowedError";export { ApiError } from "./ApiError";export { InternalServerError } from "./InternalServerError";+export { LangfuseConflictError } from "./ConflictError";diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 5db3f13977..ab97541028 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -52,6 +52,7 @@ export * from "./repositories";export * from "./redis/evalExecutionQueue";export * from "./services/sessions-ui-table-service";export * from "./services/datasets-ui-table-service";+export * from "./services/DashboardService";// test utilsexport * from "./test-utils";diff --git a/packages/shared/src/server/services/DashboardService/DashboardService.ts b/packages/shared/src/server/services/DashboardService/DashboardService.tsnew file mode 100644index 0000000000..cd9e0d0aa9--- /dev/null+++ b/packages/shared/src/server/services/DashboardService/DashboardService.ts@@ -0,0 +1,329 @@+import { prisma } from "../../../db";+import { LangfuseConflictError, type OrderByState } from "../../../";+import {+ CreateWidgetInput,+ WidgetDomain,+ WidgetListResponse,+ DashboardDomain,+ DashboardListResponse,+ DashboardDomainSchema,+ WidgetDomainSchema,+ DashboardDefinitionSchema,+} from "./types";+import { z } from "zod";++export class DashboardService {+ /**+ * Retrieves a list of dashboards for a given project.+ */+ public static async listDashboards(props: {+ projectId: string;+ limit?: number;+ page?: number;+ orderBy?: OrderByState;+ }): Promise<DashboardListResponse> {+ const { projectId, limit, page, orderBy } = props;++ const skip = page && limit ? (page - 1) * limit : undefined;+ const take = limit;++ const [dashboards, totalCount] = await Promise.all([+ prisma.dashboard.findMany({+ where: {+ projectId,+ },+ orderBy: orderBy+ ? [{ [orderBy.column]: orderBy.order.toLowerCase() }]+ : [{ updatedAt: "desc" }],+ skip,+ take,+ }),+ prisma.dashboard.count({+ where: {+ projectId,+ },+ }),+ ]);++ const domainDashboards = dashboards.map((dashboard) =>+ DashboardDomainSchema.parse(dashboard),+ );++ return {+ dashboards: domainDashboards,+ totalCount,+ };+ }++ /**+ * Creates a new dashboard.+ */+ public static async createDashboard(+ projectId: string,+ name: string,+ description: string,+ userId?: string,+ initialDefinition: z.infer<typeof DashboardDefinitionSchema> = {+ widgets: [],+ },+ ): Promise<DashboardDomain> {+ const newDashboard = await prisma.dashboard.create({+ data: {+ name,+ description,+ projectId,+ createdBy: userId,+ updatedBy: userId,+ definition: initialDefinition,+ },+ });++ return DashboardDomainSchema.parse(newDashboard);+ }++ /**+ * Updates a dashboard's definition.+ */+ public static async updateDashboardDefinition(+ dashboardId: string,+ projectId: string,+ definition: z.infer<typeof DashboardDefinitionSchema>,+ userId?: string,+ ): Promise<DashboardDomain> {+ const updatedDashboard = await prisma.dashboard.update({+ where: {+ id: dashboardId,+ projectId,+ },+ data: {+ updatedBy: userId,+ definition: {+ widgets: definition.widgets.map((widget) => ({+ type: "widget",+ id: widget.id,+ widgetId: widget.widgetId,+ x: widget.x,+ y: widget.y,+ x_size: widget.x_size,+ y_size: widget.y_size,+ })),+ },+ },+ });++ return DashboardDomainSchema.parse(updatedDashboard);+ }++ /**+ * Gets a dashboard by ID.+ */+ public static async getDashboard(+ dashboardId: string,+ projectId: string,+ ): Promise<DashboardDomain | null> {+ const dashboard = await prisma.dashboard.findFirst({+ where: {+ id: dashboardId,+ projectId,+ },+ });++ if (!dashboard) {+ return null;+ }++ return DashboardDomainSchema.parse(dashboard);+ }++ /**+ * Deletes a dashboard.+ */+ public static async deleteDashboard(+ dashboardId: string,+ projectId: string,+ ): Promise<void> {+ await prisma.dashboard.delete({+ where: {+ id: dashboardId,+ projectId,+ },+ });+ }++ /**+ * Retrieves a list of dashboard widgets for a given project.+ */+ public static async listWidgets(props: {+ projectId: string;+ limit?: number;+ page?: number;+ orderBy?: OrderByState;+ }): Promise<WidgetListResponse> {+ const { projectId, limit, page, orderBy } = props;++ const skip = page && limit ? (page - 1) * limit : undefined;+ const take = limit;++ const [widgets, totalCount] = await Promise.all([+ prisma.dashboardWidget.findMany({+ where: {+ projectId,+ },+ orderBy: orderBy+ ? [{ [orderBy.column]: orderBy.order.toLowerCase() }]+ : [{ updatedAt: "desc" }],+ skip,+ take,+ }),+ prisma.dashboardWidget.count({+ where: {+ projectId,+ },+ }),+ ]);++ const domainWidgets = widgets.map((widget) =>+ WidgetDomainSchema.parse(widget),+ );++ return {+ widgets: domainWidgets,+ totalCount,+ };+ }++ /**+ * Creates a new dashboard widget.+ */+ public static async createWidget(+ projectId: string,+ input: CreateWidgetInput,+ userId?: string,+ ): Promise<WidgetDomain> {+ const newWidget = await prisma.dashboardWidget.create({+ data: {+ name: input.name,+ description: input.description,+ projectId,+ view: input.view,+ dimensions: input.dimensions,+ metrics: input.metrics,+ filters: input.filters,+ chartType: input.chartType,+ chartConfig: input.chartConfig,+ createdBy: userId,+ updatedBy: userId,+ },+ });++ return WidgetDomainSchema.parse(newWidget);+ }++ /**+ * Gets a dashboard widget by ID.+ */+ public static async getWidget(+ widgetId: string,+ projectId: string,+ ): Promise<WidgetDomain | null> {+ const widget = await prisma.dashboardWidget.findFirst({+ where: {+ id: widgetId,+ projectId,+ },+ });++ if (!widget) {+ return null;+ }++ return WidgetDomainSchema.parse(widget);+ }++ /**+ * Updates an existing dashboard widget.+ */+ public static async updateWidget(+ projectId: string,+ widgetId: string,+ input: CreateWidgetInput,+ userId?: string,+ ): Promise<WidgetDomain> {+ const updatedWidget = await prisma.dashboardWidget.update({+ where: {+ id: widgetId,+ projectId,+ },+ data: {+ name: input.name,+ description: input.description,+ view: input.view,+ dimensions: input.dimensions,+ metrics: input.metrics,+ filters: input.filters,+ chartType: input.chartType,+ chartConfig: input.chartConfig,+ updatedBy: userId,+ },+ });++ 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"],+ });+ }++ /**+ * Deletes a dashboard widget.+ * Throws an error if the widget is still referenced in any dashboard.+ */+ public static async deleteWidget(+ widgetId: string,+ projectId: string,+ ): Promise<void> {+ // First check if this widget is referenced in any dashboard definitions+ const referencingDashboards = await prisma.dashboard.findMany({+ where: {+ projectId,+ definition: {+ path: ["widgets"],+ array_contains: [{ widgetId }],+ },+ },+ select: {+ id: true,+ name: true,+ },+ });++ if (referencingDashboards.length > 0) {+ const dashboardNames = referencingDashboards+ .map((d) => `"${d.name}"`)+ .join(", ");++ throw new LangfuseConflictError(+ `Cannot delete widget because it is still used in the following dashboards: ${dashboardNames}. Please remove the widget from these dashboards first.`,+ );+ }++ // Delete the widget if it's not referenced+ await prisma.dashboardWidget.delete({+ where: {+ id: widgetId,+ projectId,+ },+ });+ }+}diff --git a/packages/shared/src/server/services/DashboardService/index.ts b/packages/shared/src/server/services/DashboardService/index.tsnew file mode 100644index 0000000000..93b85a5e8e--- /dev/null+++ b/packages/shared/src/server/services/DashboardService/index.ts@@ -0,0 +1,2 @@+export * from "./DashboardService";+export * from "./types";diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.tsnew file mode 100644index 0000000000..af73e17c5f--- /dev/null+++ b/packages/shared/src/server/services/DashboardService/types.ts@@ -0,0 +1,125 @@+import { DashboardWidgetChartType, DashboardWidgetViews } from "@prisma/client";+import { z } from "zod";+import { singleFilter } from "../../../";++export const BaseTimeSeriesChartConfig = z.object({});+export const BaseTotalValueChartConfig = z.object({+ row_limit: z.number().int().positive().lte(1000).optional(),+});++export const LineChartTimeSeriesConfig = BaseTimeSeriesChartConfig.extend({+ type: z.literal("LINE_TIME_SERIES"),+});+export const BarChartTimeSeriesConfig = BaseTimeSeriesChartConfig.extend({+ type: z.literal("BAR_TIME_SERIES"),+});++export const HorizontalBarChartConfig = BaseTotalValueChartConfig.extend({+ type: z.literal("HORIZONTAL_BAR"),+});+export const VerticalBarChartConfig = BaseTotalValueChartConfig.extend({+ type: z.literal("VERTICAL_BAR"),+});+export const PieChartConfig = BaseTotalValueChartConfig.extend({+ type: z.literal("PIE"),+});++// Define dimension schema+export const DimensionSchema = z.object({+ field: z.string(),+});++// Define metric schema+export const MetricSchema = z.object({+ measure: z.string(),+ agg: z.string(),+});++// Define chart config schema based on chart type+export const ChartConfigSchema = z.discriminatedUnion("type", [+ LineChartTimeSeriesConfig,+ BarChartTimeSeriesConfig,+ HorizontalBarChartConfig,+ VerticalBarChartConfig,+ PieChartConfig,+]);++export const DashboardDefinitionWidgetWidgetSchema = z.object({+ type: z.literal("widget"),+ id: z.string(),+ widgetId: z.string(),+ x: z.number().int().gte(0),+ y: z.number().int().gte(0),+ x_size: z.number().int().positive(),+ y_size: z.number().int().positive(),+});++export const DashboardDefinitionWidgetSchema = z.discriminatedUnion("type", [+ DashboardDefinitionWidgetWidgetSchema,+]);++export const DashboardDefinitionSchema = z.object({+ widgets: z.array(DashboardDefinitionWidgetSchema),+});++// Define the dashboard domain object+export const DashboardDomainSchema = z.object({+ id: z.string(),+ createdAt: z.date(),+ updatedAt: z.date(),+ createdBy: z.string().nullable(),+ updatedBy: z.string().nullable(),+ projectId: z.string().nullable(),+ name: z.string(),+ description: z.string(),+ definition: DashboardDefinitionSchema,+});++// Define the dashboard list response+export const DashboardListResponseSchema = z.object({+ dashboards: z.array(DashboardDomainSchema),+ totalCount: z.number(),+});++// Define the widget domain object+export const WidgetDomainSchema = z.object({+ id: z.string(),+ createdAt: z.date(),+ updatedAt: z.date(),+ createdBy: z.string().nullable(),+ updatedBy: z.string().nullable(),+ projectId: z.string().nullable(),+ name: z.string(),+ description: z.string(),+ view: z.nativeEnum(DashboardWidgetViews),+ dimensions: z.array(DimensionSchema),+ metrics: z.array(MetricSchema),+ filters: z.array(singleFilter),+ chartType: z.nativeEnum(DashboardWidgetChartType),+ chartConfig: ChartConfigSchema,+});++// Define create widget input schema+export const CreateWidgetInputSchema = z.object({+ name: z.string().min(1, "Widget name is required"),+ description: z.string(),+ view: z.nativeEnum(DashboardWidgetViews),+ dimensions: z.array(DimensionSchema),+ metrics: z.array(MetricSchema),+ filters: z.array(singleFilter),+ chartType: z.nativeEnum(DashboardWidgetChartType),+ chartConfig: ChartConfigSchema,+});++// Define the widget list response+export const WidgetListResponseSchema = z.object({+ widgets: z.array(WidgetDomainSchema),+ totalCount: z.number(),+});++// Export types derived from schemas+export type DashboardDomain = z.infer<typeof DashboardDomainSchema>;+export type DashboardListResponse = z.infer<typeof DashboardListResponseSchema>;+export type WidgetDomain = z.infer<typeof WidgetDomainSchema>;+export type CreateWidgetInput = z.infer<typeof CreateWidgetInputSchema>;+export type WidgetListResponse = z.infer<typeof WidgetListResponseSchema>;diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex bfc564f63f..292554cfdd 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -14,6 +14,7 @@ import {Sparkle,FileJson,Search,+ Home,} from "lucide-react";import { type ReactNode } from "react";import { type Entitlement } from "@/src/features/entitlements/constants/entitlements";@@ -64,9 +65,16 @@ export const ROUTES: Route[] = [icon: Grid2X2,},{- title: "Dashboard",+ title: "Home",pathname: `/project/[projectId]`,+ icon: Home,+ },+ {+ title: "Dashboards",+ pathname: `/project/[projectId]/dashboards`,icon: LayoutDashboard,+ label: "Beta",+ entitlements: ["custom-dashboards"],},{title: "Tracing",diff --git a/web/src/features/dashboard/components/DashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable.tsxnew file mode 100644index 0000000000..5afdda500d--- /dev/null+++ b/web/src/features/dashboard/components/DashboardTable.tsx@@ -0,0 +1,210 @@+import { useEffect } from "react";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { api } from "@/src/utils/api";+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { createColumnHelper } from "@tanstack/react-table";+import TableLink from "@/src/components/table/table-link";+import { LocalIsoDate } from "@/src/components/LocalIsoDate";+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { Button } from "@/src/components/ui/button";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { Trash } from "lucide-react";+import { useState } from "react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";++type DashboardTableRow = {+ id: string;+ name: string;+ description: string;+ createdAt: Date;+ updatedAt: Date;+};++function DeleteDashboard({ dashboardId }: { dashboardId: string }) {+ const projectId = useProjectIdFromURL();+ const utils = api.useUtils();+ const [isOpen, setIsOpen] = useState(false);+ const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });+ const capture = usePostHogClientCapture();++ const mutDeleteDashboard = api.dashboard.delete.useMutation({+ onSuccess: () => {+ void utils.dashboard.invalidate();+ capture("dashboard:delete_dashboard_form_open");+ },+ onError: (e) => {+ showErrorToast("Failed to delete dashboard", e.message);+ },+ });++ 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="text-md mb-3 font-semibold">Please confirm</h2>+ <p className="mb-3 text-sm">+ This action permanently deletes this dashboard and cannot be undone.+ </p>+ <div className="flex justify-end space-x-4">+ <Button+ type="button"+ variant="destructive"+ loading={mutDeleteDashboard.isLoading}+ onClick={() => {+ if (!projectId) {+ console.error("Project ID is missing");+ return;+ }++ void mutDeleteDashboard.mutateAsync({+ projectId,+ dashboardId,+ });+ setIsOpen(false);+ }}+ >+ Delete Dashboard+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+}++export function DashboardTable() {+ const projectId = useProjectIdFromURL();+ const { setDetailPageList } = useDetailPageLists();++ const [orderByState, setOrderByState] = useOrderByState({+ column: "updatedAt",+ order: "DESC",+ });+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });++ const dashboards = api.dashboard.allDashboards.useQuery(+ {+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ projectId: projectId as string, // Typecast as query is enabled only when projectId is present+ orderBy: orderByState,+ },+ {+ enabled: Boolean(projectId),+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ useEffect(() => {+ if (dashboards.isSuccess) {+ setDetailPageList(+ "dashboards",+ dashboards.data?.dashboards.map((d) => ({ id: d.id })),+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dashboards.isSuccess, dashboards.data]);++ const columnHelper = createColumnHelper<DashboardTableRow>();+ const dashboardColumns = [+ columnHelper.accessor("name", {+ header: "Name",+ id: "name",+ enableSorting: true,+ size: 200,+ cell: (row) => {+ const name = row.getValue();+ return name ? (+ <TableLink+ path={`/project/${projectId}/dashboards/${encodeURIComponent(row.row.original.id)}`}+ value={name}+ />+ ) : undefined;+ },+ }),+ columnHelper.accessor("description", {+ header: "Description",+ id: "description",+ size: 300,+ cell: (row) => {+ return row.getValue();+ },+ }),+ columnHelper.accessor("createdAt", {+ header: "Created At",+ id: "createdAt",+ enableSorting: true,+ size: 150,+ cell: (row) => {+ const createdAt = row.getValue();+ return <LocalIsoDate date={createdAt} />;+ },+ }),+ columnHelper.accessor("updatedAt", {+ header: "Updated At",+ id: "updatedAt",+ enableSorting: true,+ size: 150,+ cell: (row) => {+ const updatedAt = row.getValue();+ return <LocalIsoDate date={updatedAt} />;+ },+ }),+ columnHelper.display({+ id: "actions",+ header: "Actions",+ size: 70,+ cell: (row) => {+ const id = row.row.original.id;+ return <DeleteDashboard dashboardId={id} />;+ },+ }),+ ] as LangfuseColumnDef<DashboardTableRow>[];++ return (+ <DataTable+ columns={dashboardColumns}+ data={+ dashboards.isLoading+ ? { isLoading: true, isError: false }+ : dashboards.isError+ ? {+ isLoading: false,+ isError: true,+ error: dashboards.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: dashboards.data.dashboards,+ }+ }+ orderBy={orderByState}+ setOrderBy={setOrderByState}+ pagination={{+ totalCount: dashboards.data?.totalCount ?? null,+ onChange: setPaginationState,+ state: paginationState,+ }}+ />+ );+}diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 3c208c5296..9b068e8eea 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -17,6 +17,8 @@ import {getObservationCostByTypeByTime,getObservationUsageByTypeByTime,queryClickhouse,+ DashboardService,+ DashboardDefinitionSchema,} from "@langfuse/shared/src/server";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { QueryBuilder } from "@/src/features/query/server/queryBuilder";@@ -24,6 +26,35 @@ import {type QueryType,query as customQuery,} from "@/src/features/query/types";+import { paginationZod, orderBy } from "@langfuse/shared";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";++// Define the dashboard list input schema+const ListDashboardsInput = z.object({+ projectId: z.string(),+ ...paginationZod,+ orderBy: orderBy,+});++// Get dashboard by ID input schema+const GetDashboardInput = z.object({+ projectId: z.string(),+ dashboardId: z.string(),+});++// Update dashboard definition input schema+const UpdateDashboardDefinitionInput = z.object({+ projectId: z.string(),+ dashboardId: z.string(),+ definition: DashboardDefinitionSchema,+});++// Create dashboard input schema+const CreateDashboardInput = z.object({+ projectId: z.string(),+ name: z.string().min(1, "Dashboard name is required"),+ description: z.string(),+});export const dashboardRouter = createTRPCRouter({chart: protectedProjectProcedure@@ -109,6 +140,110 @@ export const dashboardRouter = createTRPCRouter({.query(async ({ input }) => {return executeQuery(input.projectId, input.query as QueryType);}),++ allDashboards: protectedProjectProcedure+ .input(ListDashboardsInput)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:read",+ });++ const result = await DashboardService.listDashboards({+ projectId: input.projectId,+ limit: input.limit,+ page: input.page,+ orderBy: input.orderBy,+ });++ return result;+ }),++ getDashboard: protectedProjectProcedure+ .input(GetDashboardInput)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:read",+ });++ const dashboard = await DashboardService.getDashboard(+ input.dashboardId,+ input.projectId,+ );++ if (!dashboard) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Dashboard not found",+ });+ }++ return dashboard;+ }),++ createDashboard: protectedProjectProcedure+ .input(CreateDashboardInput)+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ const dashboard = await DashboardService.createDashboard(+ input.projectId,+ input.name,+ input.description,+ ctx.session.user.id,+ );++ return dashboard;+ }),++ updateDashboardDefinition: protectedProjectProcedure+ .input(UpdateDashboardDefinitionInput)+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ const dashboard = await DashboardService.updateDashboardDefinition(+ input.dashboardId,+ input.projectId,+ input.definition,+ ctx.session.user.id,+ );++ return dashboard;+ }),++ // Delete dashboard input schema+ delete: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ dashboardId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ await DashboardService.deleteDashboard(+ input.dashboardId,+ input.projectId,+ );++ return { success: true };+ }),});/**diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsindex e25babb8dd..5d19e2e0f6 100644--- a/web/src/features/entitlements/constants/entitlements.ts+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -18,6 +18,7 @@ const entitlements = ["audit-logs","data-retention","prompt-protected-labels",+ "custom-dashboards",] as const;export type Entitlement = (typeof entitlements)[number];@@ -29,6 +30,7 @@ const cloudAllPlansEntitlements: Entitlement[] = ["annotation-queues","prompt-experiments","trace-deletion",+ "custom-dashboards",];const selfHostedAllPlansEntitlements: Entitlement[] = ["trace-deletion"];diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex e7b4a6151a..336193ea59 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -87,7 +87,14 @@ const events = {"save_to_new_prompt_button_click","save_to_prompt_version_button_click",],- dashboard: ["chart_tab_switch", "date_range_changed"],+ dashboard: [+ "chart_tab_switch",+ "date_range_changed",+ "new_widget_form_open",+ "new_dashboard_form_open",+ "delete_widget_form_open",+ "delete_dashboard_form_open",+ ],datasets: ["delete_form_open","delete_dataset_button_click",diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 3cbfc2f6f1..830bd08f4e 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -33,6 +33,9 @@ const projectScopes = ["prompts:read","promptProtectedLabels:CUD",+ "dashboards:read",+ "dashboards:CUD",+"models:CUD","batchExports:create",@@ -109,6 +112,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"promptExperiments:CUD","promptExperiments:read","auditLogs:read",+ "dashboards:read",+ "dashboards:CUD",],ADMIN: ["project:read",@@ -151,6 +156,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"promptExperiments:CUD","promptExperiments:read","auditLogs:read",+ "dashboards:read",+ "dashboards:CUD",],MEMBER: ["project:read",@@ -181,6 +188,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"annotationQueues:CUD","promptExperiments:CUD","promptExperiments:read",+ "dashboards:read",+ "dashboards:CUD",],VIEWER: ["project:read",@@ -195,6 +204,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"comments:read","annotationQueues:read","promptExperiments:read",+ "dashboards:read",],NONE: [],};diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxindex 98161c421f..455d903355 100644--- a/web/src/features/widgets/chart-library/Chart.tsx+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -6,13 +6,14 @@ import VerticalBarChartTimeSeries from "@/src/features/widgets/chart-library/Verimport HorizontalBarChart from "@/src/features/widgets/chart-library/HorizontalBarChart";import VerticalBarChart from "@/src/features/widgets/chart-library/VerticalBarChart";import PieChart from "@/src/features/widgets/chart-library/PieChart";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";export const Chart = ({chartType,data,rowLimit,}: {- chartType: string;+ chartType: DashboardWidgetChartType;data: DataPoint[];rowLimit: number;}) => {@@ -20,15 +21,15 @@ export const Chart = ({<CardContent>{(() => {switch (chartType) {- case "line-time-series":+ case "LINE_TIME_SERIES":return <LineChartTimeSeries data={data} />;- case "bar-time-series":+ case "BAR_TIME_SERIES":return <VerticalBarChartTimeSeries data={data} />;- case "bar-horizontal":+ case "HORIZONTAL_BAR":return <HorizontalBarChart data={data.slice(0, rowLimit)} />;- case "bar-vertical":+ case "VERTICAL_BAR":return <VerticalBarChart data={data.slice(0, rowLimit)} />;- case "pie":+ case "PIE":return <PieChart data={data.slice(0, rowLimit)} />;default:return <HorizontalBarChart data={data.slice(0, rowLimit)} />;diff --git a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx b/web/src/features/widgets/chart-library/HorizontalBarChart.tsxindex 3271809f60..024c6025be 100644--- a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx+++ b/web/src/features/widgets/chart-library/HorizontalBarChart.tsx@@ -52,7 +52,10 @@ export const HorizontalBarChart: React.FC<ChartProps> = ({radius={[0, 4, 4, 0]}className="fill-[--color-metric]"/>- <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ <ChartTooltip+ content={<ChartTooltipContent />}+ cursor={{ opacity: 0.8 }}+ /></BarChart></ChartContainer>);diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsxindex 8b3a3d16ae..5ad1430eda 100644--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx@@ -60,7 +60,10 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({stroke={`hsl(var(--chart-${(index % 4) + 1}))`}/>))}- <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ <ChartTooltip+ content={<ChartTooltipContent />}+ cursor={{ opacity: 0.8 }}+ /></LineChart></ChartContainer>);diff --git a/web/src/features/widgets/chart-library/PieChart.tsx b/web/src/features/widgets/chart-library/PieChart.tsxindex 26c68c80c1..2e54977d47 100644--- a/web/src/features/widgets/chart-library/PieChart.tsx+++ b/web/src/features/widgets/chart-library/PieChart.tsx@@ -43,8 +43,8 @@ export const PieChart: React.FC<ChartProps> = ({<ChartContainer config={config}><PieChartComponent accessibilityLayer={accessibilityLayer}><ChartTooltip- cursor={false}- content={<ChartTooltipContent hideLabel />}+ content={<ChartTooltipContent />}+ cursor={{ opacity: 0.8 }}/><Piedata={chartData}diff --git a/web/src/features/widgets/chart-library/VerticalBarChart.tsx b/web/src/features/widgets/chart-library/VerticalBarChart.tsxindex 1203805519..8a40cfb64e 100644--- a/web/src/features/widgets/chart-library/VerticalBarChart.tsx+++ b/web/src/features/widgets/chart-library/VerticalBarChart.tsx@@ -48,7 +48,10 @@ export const VerticalBarChart: React.FC<ChartProps> = ({radius={[4, 4, 0, 0]}className="fill-[--color-metric]"/>- <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ <ChartTooltip+ content={<ChartTooltipContent />}+ cursor={{ opacity: 0.8 }}+ /></BarChart></ChartContainer>);diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsxindex 239138b7b9..1ba9153ae8 100644--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx@@ -59,7 +59,10 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({stackId={dimensions.length > 1 ? "stack" : undefined}/>))}- <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ <ChartTooltip+ content={<ChartTooltipContent />}+ cursor={{ opacity: 0.8 }}+ /></BarChart></ChartContainer>);diff --git a/web/src/features/widgets/chart-library/utils.ts b/web/src/features/widgets/chart-library/utils.tsindex 6818b92dd5..935b3ec52f 100644--- a/web/src/features/widgets/chart-library/utils.ts+++ b/web/src/features/widgets/chart-library/utils.ts@@ -1,4 +1,5 @@import { type DataPoint } from "./chart-props";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";/*** Groups data by dimension to prepare it for time series breakdowns@@ -37,3 +38,19 @@ export const getUniqueDimensions = (data: DataPoint[]) => {});return Array.from(uniqueDimensions);};++export const isTimeSeriesChart = (+ chartType: DashboardWidgetChartType,+): boolean => {+ switch (chartType) {+ case "LINE_TIME_SERIES":+ case "BAR_TIME_SERIES":+ return true;+ case "HORIZONTAL_BAR":+ case "VERTICAL_BAR":+ case "PIE":+ return false;+ default:+ return false;+ }+};diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxnew file mode 100644index 0000000000..f2c113bdaa--- /dev/null+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -0,0 +1,201 @@+import { useMemo } from "react";+import { api } from "@/src/utils/api";+import {+ type views,+ type metricAggregations,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";+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 { useRouter } from "next/router";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { startCase } from "lodash";++interface WidgetPlacement {+ id: string;+ widgetId: string;+ x: number;+ y: number;+ x_size: number;+ y_size: number;+ type: "widget";+}++// Generate grid classes for each widget based on position and size+const getGridClasses = (widget: WidgetPlacement) => {+ return `col-start-${widget.x + 1} col-span-${widget.x_size} row-start-${widget.y + 1} row-span-${widget.y_size}`;+};++export function DashboardWidget({+ projectId,+ placement,+ dateRange,+ filterState,+ onDeleteWidget,+}: {+ projectId: string;+ placement: WidgetPlacement;+ dateRange: { from: Date; to: Date } | undefined;+ filterState: FilterState;+ onDeleteWidget: (tileId: string) => void;+}) {+ const router = useRouter();+ const widget = api.dashboardWidgets.get.useQuery(+ {+ widgetId: placement.widgetId,+ projectId,+ },+ {+ enabled: Boolean(projectId),+ },+ );++ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });++ const fromTimestamp = dateRange+ ? dateRange.from+ : new Date(new Date().getTime() - 1000);+ const toTimestamp = dateRange ? dateRange.to : new Date();++ const queryResult = api.dashboard.executeQuery.useQuery(+ {+ projectId,+ query: {+ view: (widget.data?.view as z.infer<typeof views>) ?? "traces",+ dimensions: widget.data?.dimensions ?? [],+ metrics:+ widget.data?.metrics.map((metric) => ({+ measure: metric.measure,+ aggregation: metric.agg as z.infer<typeof metricAggregations>,+ })) ?? [],+ filters: [+ ...(widget.data?.filters ?? []),+ ...mapLegacyUiTableFilterToView(+ (widget.data?.view as z.infer<typeof views>) ?? "traces",+ filterState,+ ),+ ],+ timeDimension: isTimeSeriesChart(+ widget.data?.chartType ?? "LINE_TIME_SERIES",+ )+ ? { granularity: "auto" }+ : null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ },+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ enabled: !widget.isLoading && Boolean(widget.data),+ },+ );++ const transformedData = useMemo(() => {+ if (!widget.data || !queryResult.data) {+ return [];+ }+ return queryResult.data.map((item: any) => {+ // Get the dimension field (first dimension in the query)+ const dimensionField =+ widget.data.dimensions.slice().shift()?.field ?? "none";+ // Get the metric field (first metric in the query with its aggregation)+ const metric = widget.data.metrics.slice().shift() ?? {+ measure: "count",+ agg: "count",+ };+ const metricField = `${metric.agg}_${metric.measure}`;++ return {+ dimension: item[dimensionField]+ ? (item[dimensionField] as string)+ : startCase(metricField === "count_count" ? "Count" : metricField),+ metric: Number(item[metricField] || 0),+ time_dimension: item["time_dimension"],+ };+ });+ }, [queryResult.data, widget.data]);++ if (widget.isLoading) {+ return (+ <div+ className={`${getGridClasses(placement)} flex items-center justify-center rounded-lg border bg-background p-4`}+ >+ <div className="text-muted-foreground">Loading...</div>+ </div>+ );+ }++ if (!widget.data) {+ return (+ <div+ className={`${getGridClasses(placement)} flex items-center justify-center rounded-lg border bg-background p-4`}+ >+ <div className="text-muted-foreground">Widget not found</div>+ </div>+ );+ }++ const handleEdit = () => {+ router.push(`/project/${projectId}/widgets/${placement.widgetId}`);+ };++ const handleDelete = () => {+ if (onDeleteWidget && confirm("Please confirm deletion")) {+ onDeleteWidget(placement.id);+ }+ };++ return (+ <div+ className={`${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>+ </div>+ <div className="mb-4 text-sm text-muted-foreground">+ {widget.data.description}+ </div>+ <div className="min-h-0 flex-1">+ <Chart+ chartType={widget.data.chartType}+ data={transformedData}+ rowLimit={+ widget.data.chartConfig.type === "LINE_TIME_SERIES" ||+ widget.data.chartConfig.type === "BAR_TIME_SERIES"+ ? 100+ : (widget.data.chartConfig.row_limit ?? 100)+ }+ />+ </div>+ </div>+ );+}diff --git a/web/src/features/widgets/components/SelectWidgetDialog.tsx b/web/src/features/widgets/components/SelectWidgetDialog.tsxnew file mode 100644index 0000000000..1cf13bb840--- /dev/null+++ b/web/src/features/widgets/components/SelectWidgetDialog.tsx@@ -0,0 +1,165 @@+import React, { useState } from "react";+import { useRouter } from "next/router";+import { api } from "@/src/utils/api";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "@/src/components/ui/dialog";+import { Button } from "@/src/components/ui/button";+import { PlusIcon } from "lucide-react";+import {+ Table,+ TableHeader,+ TableRow,+ TableHead,+ TableBody,+ TableCell,+} from "@/src/components/ui/table";+import { startCase } from "lodash";++export type WidgetItem = {+ id: string;+ name: string;+ description: string;+ view: string;+ chartType: string;+ createdAt: Date;+ updatedAt: Date;+};++interface SelectWidgetDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ projectId: string;+ onSelectWidget: (widget: WidgetItem) => void;+}++export function SelectWidgetDialog({+ open,+ onOpenChange,+ projectId,+ onSelectWidget,+}: SelectWidgetDialogProps) {+ const router = useRouter();+ const [selectedWidgetId, setSelectedWidgetId] = useState<string | null>(null);++ // Fetch widgets+ const widgets = api.dashboardWidgets.all.useQuery(+ {+ projectId,+ orderBy: {+ column: "updatedAt",+ order: "DESC",+ },+ },+ {+ enabled: Boolean(projectId) && open,+ },+ );++ const handleNavigateToNewWidget = () => {+ router.push(`/project/${projectId}/widgets/new`);+ };++ const handleAddWidget = () => {+ if (selectedWidgetId) {+ const selectedWidget = widgets.data?.widgets.find(+ (widget) => widget.id === selectedWidgetId,+ );+ if (selectedWidget) {+ onSelectWidget(selectedWidget as WidgetItem);+ onOpenChange(false);+ }+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[800px]">+ <DialogHeader>+ <DialogTitle>Select widget to add</DialogTitle>+ </DialogHeader>++ <div className="mt-4 max-h-[400px] overflow-y-auto">+ {widgets.isLoading ? (+ <div className="py-8 text-center">Loading widgets...</div>+ ) : widgets.isError ? (+ <div className="py-8 text-center text-destructive">+ Error: {widgets.error.message}+ </div>+ ) : widgets.data?.widgets.length === 0 ? (+ <div className="py-8 text-center text-muted-foreground">+ No widgets found. Create a new widget to get started.+ </div>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Description</TableHead>+ <TableHead>View Type</TableHead>+ <TableHead>Chart Type</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {widgets.data?.widgets.map((widget) => (+ <TableRow+ key={widget.id}+ onClick={() => setSelectedWidgetId(widget.id)}+ className={`cursor-pointer hover:bg-muted ${+ selectedWidgetId === widget.id ? "bg-muted" : ""+ }`}+ >+ <TableCell className="font-medium">{widget.name}</TableCell>+ <TableCell className="max-w-[200px] truncate">+ {widget.description}+ </TableCell>+ <TableCell>+ {startCase(widget.view.toLowerCase())}+ </TableCell>+ <TableCell>+ {(() => {+ switch (widget.chartType) {+ case "LINE_TIME_SERIES":+ return "Line Chart (Time Series)";+ case "BAR_TIME_SERIES":+ return "Bar Chart (Time Series)";+ case "HORIZONTAL_BAR":+ return "Horizontal Bar Chart (Total Value)";+ case "VERTICAL_BAR":+ return "Vertical Bar Chart (Total Value)";+ case "PIE":+ return "Pie Chart (Total Value)";+ default:+ return widget.chartType;+ }+ })()}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </div>++ <DialogFooter className="mt-4 flex justify-between">+ <Button onClick={handleNavigateToNewWidget} variant="outline">+ <PlusIcon className="mr-2 h-4 w-4" />+ Create New Widget+ </Button>+ <div className="flex gap-2">+ <Button onClick={() => onOpenChange(false)} variant="outline">+ Cancel+ </Button>+ <Button onClick={handleAddWidget} disabled={!selectedWidgetId}>+ Add Selected Widget+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsxnew file mode 100644index 0000000000..4a39e94aef--- /dev/null+++ b/web/src/features/widgets/components/WidgetForm.tsx@@ -0,0 +1,617 @@+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ CardFooter,+} from "@/src/components/ui/card";+import { api } from "@/src/utils/api";+import {+ metricAggregations,+ type QueryType,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";+import React, { useState, useMemo, useEffect } from "react";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Label } from "@/src/components/ui/label";+import { viewDeclarations } from "@/src/features/query/dataModel";+import { type z } from "zod";+import { views } from "@/src/features/query/types";+import { Input } from "@/src/components/ui/input";+import { startCase } from "lodash";+import { DatePickerWithRange } from "@/src/components/date-picker";+import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";+import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";+import { type ColumnDefinition } from "@langfuse/shared";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { Button } from "@/src/components/ui/button";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { type FilterState } from "@langfuse/shared";+import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";+import {+ BarChart,+ PieChart,+ LineChart,+ BarChartHorizontal,+} from "lucide-react";++export function WidgetForm({+ initialValues,+ projectId,+ onSave,+}: {+ initialValues: {+ name: string;+ description: string;+ view: z.infer<typeof views>;+ measure: string;+ aggregation: z.infer<typeof metricAggregations>;+ dimension: string;+ filters?: FilterState;+ chartType: DashboardWidgetChartType;+ chartConfig?: { type: DashboardWidgetChartType; row_limit?: number };+ };+ projectId: string;+ onSave: (widgetData: {+ name: string;+ description: string;+ view: string;+ dimensions: { field: string }[];+ metrics: { measure: string; agg: string }[];+ filters: any[];+ chartType: DashboardWidgetChartType;+ chartConfig: { type: DashboardWidgetChartType; row_limit?: number };+ }) => void;+}) {+ // State for form fields+ const [widgetName, setWidgetName] = useState<string>(initialValues.name);+ const [widgetDescription, setWidgetDescription] = useState<string>(+ initialValues.description,+ );+ const [selectedView, setSelectedView] = useState<z.infer<typeof views>>(+ initialValues.view,+ );+ const [selectedMeasure, setSelectedMeasure] = useState<string>(+ initialValues.measure,+ );+ const [selectedAggregation, setSelectedAggregation] = useState<+ z.infer<typeof metricAggregations>+ >(initialValues.aggregation);+ const [selectedDimension, setSelectedDimension] = useState<string>(+ initialValues.dimension,+ );++ const [selectedChartType, setSelectedChartType] = useState<string>(+ initialValues.chartType,+ );+ const [rowLimit, setRowLimit] = useState<number>(+ initialValues.chartConfig?.row_limit ?? 100,+ );++ // Filter state+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useDashboardDateRange();+ const [userFilterState, setUserFilterState] = useState<FilterState>(+ initialValues.filters ?? [],+ );++ const traceFilterOptions = api.traces.filterOptions.useQuery(+ {+ projectId,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );++ const environmentFilterOptions =+ api.projects.environmentFilterOptions.useQuery(+ { projectId },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );+ const environmentOptions =+ environmentFilterOptions.data?.map((value) => ({+ value: value.environment,+ })) || [];+ const nameOptions = traceFilterOptions.data?.name || [];+ const tagsOptions = traceFilterOptions.data?.tags || [];++ // Filter columns for PopoverFilterBuilder+ const filterColumns: ColumnDefinition[] = [+ {+ name: "Environment",+ id: "environment",+ type: "stringOptions",+ options: environmentOptions,+ internal: "internalValue",+ },+ {+ name: "Trace Name",+ id: "traceName",+ type: "stringOptions",+ options: nameOptions,+ internal: "internalValue",+ },+ {+ name: "Tags",+ id: "tags",+ type: "arrayOptions",+ options: tagsOptions,+ internal: "internalValue",+ },+ {+ name: "User",+ id: "user",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Session",+ id: "session",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Release",+ id: "release",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Version",+ id: "version",+ type: "string",+ internal: "internalValue",+ },+ ];++ // Chart type options+ type ChartType = {+ group: "time-series" | "total-value";+ name: string;+ value: DashboardWidgetChartType;+ icon: React.ElementType;+ };++ const chartTypes: ChartType[] = useMemo(+ () => [+ {+ group: "time-series",+ name: "Line Chart",+ value: "LINE_TIME_SERIES",+ icon: LineChart,+ },+ {+ group: "time-series",+ name: "Vertical Bar Chart",+ value: "BAR_TIME_SERIES",+ icon: BarChart,+ },+ {+ group: "total-value",+ name: "Horizontal Bar Chart",+ value: "HORIZONTAL_BAR",+ icon: BarChartHorizontal,+ },+ {+ group: "total-value",+ name: "Vertical Bar Chart",+ value: "VERTICAL_BAR",+ icon: BarChart,+ },+ { group: "total-value", name: "Pie Chart", value: "PIE", icon: PieChart },+ ],+ [],+ );++ // Set aggregation to "count" when metric is "count"+ useEffect(() => {+ if (selectedMeasure === "count") {+ setSelectedAggregation("count");+ }+ }, [selectedMeasure]);++ // Get available metrics for the selected view+ const availableMetrics = useMemo(() => {+ const viewDeclaration = viewDeclarations[selectedView];+ return Object.entries(viewDeclaration.measures).map(([key]) => ({+ value: key,+ label: startCase(key),+ }));+ }, [selectedView]);++ // Get available dimensions for the selected view+ const availableDimensions = useMemo(() => {+ const viewDeclaration = viewDeclarations[selectedView];+ return Object.entries(viewDeclaration.dimensions).map(([key]) => ({+ value: key,+ label: startCase(key),+ }));+ }, [selectedView]);++ // Create a dynamic query based on the selected view+ const query = useMemo<QueryType>(() => {+ // Calculate fromTimestamp and toTimestamp from dateRange+ const fromTimestamp = dateRange+ ? dateRange.from+ : new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000); // Default to last 7 days+ const toTimestamp = dateRange ? dateRange.to : new Date();++ return {+ view: selectedView,+ dimensions:+ selectedDimension !== "none" ? [{ field: selectedDimension }] : [],+ metrics: [{ measure: selectedMeasure, aggregation: selectedAggregation }],+ filters: [...mapLegacyUiTableFilterToView(selectedView, userFilterState)],+ timeDimension: isTimeSeriesChart(+ selectedChartType as DashboardWidgetChartType,+ )+ ? { granularity: "auto" }+ : null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };+ }, [+ selectedView,+ selectedDimension,+ selectedAggregation,+ selectedMeasure,+ userFilterState,+ dateRange,+ selectedChartType,+ ]);++ const queryResult = api.dashboard.executeQuery.useQuery(+ {+ projectId,+ query,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ // Transform the query results to a consistent format for charts+ const transformedData: DataPoint[] = useMemo(+ () =>+ queryResult.data?.map((item: any) => {+ // Get the dimension field (first dimension in the query)+ const dimensionField = selectedDimension;+ // Get the metric field (first metric in the query with its aggregation)+ const metricField = `${selectedAggregation}_${selectedMeasure}`;++ return {+ dimension: item[dimensionField]+ ? (item[dimensionField] as string)+ : startCase(metricField === "count_count" ? "Count" : metricField),+ metric: Number(item[metricField] || 0),+ time_dimension: item["time_dimension"],+ };+ }) ?? [],+ [queryResult.data, selectedAggregation, selectedDimension, selectedMeasure],+ );++ const handleSaveWidget = () => {+ if (!widgetName.trim()) {+ showErrorToast("Error", "Widget name is required");+ return;+ }++ onSave({+ name: widgetName,+ description: widgetDescription,+ view: selectedView,+ dimensions:+ selectedDimension !== "none" ? [{ field: selectedDimension }] : [],+ metrics: [{ measure: selectedMeasure, agg: selectedAggregation }],+ filters: mapLegacyUiTableFilterToView(selectedView, userFilterState),+ chartType: selectedChartType as DashboardWidgetChartType,+ chartConfig: isTimeSeriesChart(+ selectedChartType as DashboardWidgetChartType,+ )+ ? { type: selectedChartType as DashboardWidgetChartType }+ : {+ type: selectedChartType as DashboardWidgetChartType,+ row_limit: rowLimit,+ },+ });+ };++ return (+ <div className="flex h-full gap-4">+ {/* Left column - Form */}+ <div className="h-full w-1/3 min-w-[430px]">+ <Card className="flex h-full flex-col">+ <CardHeader>+ <CardTitle>Widget Configuration</CardTitle>+ <CardDescription>+ Configure your widget by selecting data and visualization options+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4 overflow-y-auto">+ {/* Data Selection Section */}+ <div className="space-y-4">+ <h3 className="text-lg font-bold">Data Selection</h3>++ {/* View Selection */}+ <div className="space-y-2">+ <Label htmlFor="view-select">View</Label>+ <Select+ value={selectedView}+ onValueChange={(value) => {+ if (value !== selectedView) {+ setSelectedMeasure("count");+ setSelectedAggregation("count");+ setSelectedDimension("none");+ }+ setSelectedView(value as z.infer<typeof views>);+ }}+ >+ <SelectTrigger id="view-select">+ <SelectValue placeholder="Select a view" />+ </SelectTrigger>+ <SelectContent>+ {views.options.map((view) => (+ <SelectItem key={view} value={view}>+ {startCase(view)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ {/* Metrics Selection */}+ <div className="space-y-2">+ <Label htmlFor="metrics-select">Metric</Label>+ <Select+ value={selectedMeasure}+ onValueChange={(value) => setSelectedMeasure(value)}+ >+ <SelectTrigger id="metrics-select">+ <SelectValue placeholder="Select metrics" />+ </SelectTrigger>+ <SelectContent>+ {availableMetrics.map((metric) => (+ <SelectItem key={metric.value} value={metric.value}>+ {metric.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {selectedMeasure !== "count" && (+ <Select+ value={selectedAggregation}+ onValueChange={(value) =>+ setSelectedAggregation(+ value as z.infer<typeof metricAggregations>,+ )+ }+ >+ <SelectTrigger id="aggregation-select">+ <SelectValue placeholder="Select Aggregation" />+ </SelectTrigger>+ <SelectContent>+ {metricAggregations.options.map((aggregation) => (+ <SelectItem key={aggregation} value={aggregation}>+ {startCase(aggregation)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </div>++ {/* Filters Section */}+ <div className="space-y-2">+ <Label>Filters</Label>+ <div className="space-y-2">+ <InlineFilterBuilder+ columns={filterColumns}+ filterState={userFilterState}+ onChange={setUserFilterState}+ />+ </div>+ </div>++ {/* Dimension Selection (Breakdown) */}+ <div className="space-y-2">+ <Label htmlFor="dimension-select">+ Breakdown Dimension (Optional)+ </Label>+ <Select+ value={selectedDimension}+ onValueChange={setSelectedDimension}+ >+ <SelectTrigger id="dimension-select">+ <SelectValue placeholder="Select a dimension" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">None</SelectItem>+ {availableDimensions.map((dimension) => (+ <SelectItem key={dimension.value} value={dimension.value}>+ {dimension.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>++ {/* Visualization Section */}+ <div className="mt-6 space-y-4">+ <h3 className="text-lg font-bold">Visualization</h3>++ {/* Widget Name */}+ <div className="space-y-2">+ <Label htmlFor="widget-name">Name</Label>+ <Input+ id="widget-name"+ value={widgetName}+ onChange={(e) => setWidgetName(e.target.value)}+ placeholder="Enter widget name"+ />+ </div>++ {/* Widget Description */}+ <div className="space-y-2">+ <Label htmlFor="widget-description">Description</Label>+ <Input+ id="widget-description"+ value={widgetDescription}+ onChange={(e) => setWidgetDescription(e.target.value)}+ placeholder="Enter widget description"+ />+ </div>++ {/* Chart Type Selection */}+ <div className="space-y-2">+ <Label htmlFor="chart-type-select">Chart Type</Label>+ <Select+ value={selectedChartType}+ onValueChange={setSelectedChartType}+ >+ <SelectTrigger id="chart-type-select">+ <SelectValue placeholder="Select a chart type" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Time Series</SelectLabel>+ {chartTypes+ .filter((item) => item.group === "time-series")+ .map((chart) => (+ <SelectItem key={chart.value} value={chart.value}>+ <div className="flex items-center">+ {" "}+ {React.createElement(chart.icon, {+ className: "mr-2 w-4",+ })}+ <span>{chart.name}</span>+ </div>+ </SelectItem>+ ))}+ </SelectGroup>+ <SelectGroup>+ <SelectLabel>Total Value</SelectLabel>+ {chartTypes+ .filter((item) => item.group === "total-value")+ .map((chart) => (+ <SelectItem key={chart.value} value={chart.value}>+ <div className="flex items-center">+ {" "}+ {React.createElement(chart.icon, {+ className: "mr-2 w-4",+ })}+ <span>{chart.name}</span>+ </div>+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-2">+ <Label htmlFor="date-select">Date Range</Label>+ <DatePickerWithRange+ dateRange={dateRange}+ setDateRangeAndOption={setDateRangeAndOption}+ selectedOption={selectedOption}+ className="w-full"+ />+ </div>++ {/* Row Limit Selection - Only shown for non-time series charts */}+ {!isTimeSeriesChart(+ selectedChartType as DashboardWidgetChartType,+ ) && (+ <div className="space-y-2">+ <Label htmlFor="row-limit">+ Breakdown Row Limit (0-1000)+ </Label>+ <Input+ id="row-limit"+ type="number"+ min={0}+ max={1000}+ value={rowLimit}+ onChange={(e) => {+ const value = parseInt(e.target.value);+ if (!isNaN(value) && value >= 0 && value <= 1000) {+ setRowLimit(value);+ }+ }}+ placeholder="Enter breakdown row limit (0-1000)"+ />+ </div>+ )}+ </div>+ </CardContent>+ <CardFooter className="mt-auto">+ <Button className="w-full" size="lg" onClick={handleSaveWidget}>+ Save Widget+ </Button>+ </CardFooter>+ </Card>+ </div>++ {/* Right column - Chart */}+ <div className="w-2/3">+ <Card>+ <CardHeader>+ <CardTitle>{widgetName}</CardTitle>+ <CardDescription>{widgetDescription}</CardDescription>+ </CardHeader>+ {queryResult.data ? (+ <Chart+ chartType={selectedChartType as DashboardWidgetChartType}+ data={transformedData}+ rowLimit={rowLimit}+ />+ ) : (+ <CardContent>+ <div className="flex h-[300px] items-center justify-center">+ <p className="text-muted-foreground">+ Waiting for Input / Loading...+ </p>+ </div>+ </CardContent>+ )}+ </Card>+ </div>+ </div>+ );+}diff --git a/web/src/features/widgets/components/WidgetTable.tsx b/web/src/features/widgets/components/WidgetTable.tsxnew file mode 100644index 0000000000..7d8093b019--- /dev/null+++ b/web/src/features/widgets/components/WidgetTable.tsx@@ -0,0 +1,253 @@+import { useEffect } from "react";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { api } from "@/src/utils/api";+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { createColumnHelper } from "@tanstack/react-table";+import TableLink from "@/src/components/table/table-link";+import { LocalIsoDate } from "@/src/components/LocalIsoDate";+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { startCase } from "lodash";+import { Button } from "@/src/components/ui/button";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { Trash } from "lucide-react";+import { useState } from "react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";++type WidgetTableRow = {+ id: string;+ name: string;+ description: string;+ view: string;+ chartType: string;+ createdAt: Date;+ updatedAt: Date;+};++export function DeleteWidget({ widgetId }: { widgetId: string }) {+ const projectId = useProjectIdFromURL();+ const utils = api.useUtils();+ const [isOpen, setIsOpen] = useState(false);+ const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });+ const capture = usePostHogClientCapture();++ const mutDeleteWidget = api.dashboardWidgets.delete.useMutation({+ onSuccess: () => {+ void utils.dashboardWidgets.invalidate();+ capture("dashboard:delete_widget_form_open");+ },+ onError: (error) => {+ if (error.data?.code === "CONFLICT") {+ showErrorToast(+ "Widget in use",+ "Widget is still in use. Please remove it from all dashboards before deleting it.",+ );+ } else {+ showErrorToast("Failed to delete widget", error.message);+ }+ },+ });++ 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="text-md 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.isLoading}+ onClick={() => {+ if (!projectId) {+ console.error("Project ID is missing");+ return;+ }++ void mutDeleteWidget.mutateAsync({+ projectId,+ widgetId,+ });+ setIsOpen(false);+ }}+ >+ Delete Widget+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+}++export function DashboardWidgetTable() {+ const projectId = useProjectIdFromURL();+ const { setDetailPageList } = useDetailPageLists();++ const [orderByState, setOrderByState] = useOrderByState({+ column: "updatedAt",+ order: "DESC",+ });+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });++ const widgets = api.dashboardWidgets.all.useQuery(+ {+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ projectId: projectId as string, // Typecast as query is enabled only when projectId is present+ orderBy: orderByState,+ },+ {+ enabled: Boolean(projectId),+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ useEffect(() => {+ if (widgets.isSuccess) {+ setDetailPageList(+ "widgets",+ widgets.data?.widgets.map((w) => ({ id: w.id })),+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [widgets.isSuccess, widgets.data]);++ const columnHelper = createColumnHelper<WidgetTableRow>();+ const widgetColumns = [+ columnHelper.accessor("name", {+ header: "Name",+ id: "name",+ enableSorting: true,+ size: 200,+ cell: (row) => {+ const name = row.getValue();+ return name ? (+ <TableLink+ path={`/project/${projectId}/widgets/${encodeURIComponent(row.row.original.id)}`}+ value={name}+ />+ ) : undefined;+ },+ }),+ columnHelper.accessor("description", {+ header: "Description",+ id: "description",+ size: 300,+ cell: (row) => {+ return row.getValue();+ },+ }),+ columnHelper.accessor("view", {+ header: "View Type",+ id: "view",+ enableSorting: true,+ size: 100,+ cell: (row) => {+ return startCase(row.getValue().toLowerCase());+ },+ }),+ columnHelper.accessor("chartType", {+ header: "Chart Type",+ id: "chartType",+ enableSorting: true,+ size: 100,+ cell: (row) => {+ switch (row.getValue()) {+ case "LINE_TIME_SERIES":+ return "Line Chart (Time Series)";+ case "BAR_TIME_SERIES":+ return "Bar Chart (Time Series)";+ case "HORIZONTAL_BAR":+ return "Horizontal Bar Chart (Total Value)";+ case "VERTICAL_BAR":+ return "Vertical Bar Chart (Total Value)";+ case "PIE":+ return "Pie Chart (Total Value)";+ default:+ return "Unknown Chart Type";+ }+ },+ }),+ columnHelper.accessor("createdAt", {+ header: "Created At",+ id: "createdAt",+ enableSorting: true,+ size: 150,+ cell: (row) => {+ const createdAt = row.getValue();+ return <LocalIsoDate date={createdAt} />;+ },+ }),+ columnHelper.accessor("updatedAt", {+ header: "Updated At",+ id: "updatedAt",+ enableSorting: true,+ size: 150,+ cell: (row) => {+ const updatedAt = row.getValue();+ return <LocalIsoDate date={updatedAt} />;+ },+ }),+ columnHelper.display({+ id: "actions",+ header: "Actions",+ size: 70,+ cell: (row) => {+ const id = row.row.original.id;+ return <DeleteWidget widgetId={id} />;+ },+ }),+ ] as LangfuseColumnDef<WidgetTableRow>[];++ return (+ <DataTable+ columns={widgetColumns}+ data={+ widgets.isLoading+ ? { isLoading: true, isError: false }+ : widgets.isError+ ? {+ isLoading: false,+ isError: true,+ error: widgets.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: widgets.data.widgets,+ }+ }+ orderBy={orderByState}+ setOrderBy={setOrderByState}+ pagination={{+ totalCount: widgets.data?.totalCount ?? null,+ onChange: setPaginationState,+ state: paginationState,+ }}+ />+ );+}diff --git a/web/src/features/widgets/index.ts b/web/src/features/widgets/index.tsnew file mode 100644index 0000000000..d138e81b28--- /dev/null+++ b/web/src/features/widgets/index.ts@@ -0,0 +1,8 @@+// Export the DataPoint type+export { type DataPoint } from "./chart-library/chart-props";+export { Chart } from "./chart-library/Chart";++// Export components+export { WidgetForm } from "./components/WidgetForm";+export { DashboardWidgetTable, DeleteWidget } from "./components/WidgetTable";+export { DashboardWidget } from "./components/DashboardWidget";diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsxnew file mode 100644index 0000000000..8825e7217d--- /dev/null+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx@@ -0,0 +1,329 @@+import { useRouter } from "next/router";+import { api } from "@/src/utils/api";+import Page from "@/src/components/layouts/page";+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import { DashboardWidget } from "@/src/features/widgets";+import { DatePickerWithRange } from "@/src/components/date-picker";+import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";+import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";+import { useEffect, useState } from "react";+import type { ColumnDefinition, FilterState } from "@langfuse/shared";+import { Button } from "@/src/components/ui/button";+import { PlusIcon } from "lucide-react";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import {+ SelectWidgetDialog,+ type WidgetItem,+} from "@/src/features/widgets/components/SelectWidgetDialog";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { v4 as uuidv4 } from "uuid";++interface WidgetPlacement {+ id: string;+ widgetId: string;+ x: number;+ y: number;+ x_size: number;+ y_size: number;+ type: "widget";+}++export default function DashboardDetail() {+ const router = useRouter();+ const { projectId, dashboardId } = router.query as {+ projectId: string;+ dashboardId: string;+ };++ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });++ // Filter state+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useDashboardDateRange();+ const [userFilterState, setUserFilterState] = useState<FilterState>([]);++ // State for handling widget deletion and addition+ const [localDashboardDefinition, setLocalDashboardDefinition] = useState<{+ widgets: WidgetPlacement[];+ } | null>(null);+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);++ // State for the widget selection dialog+ const [isWidgetDialogOpen, setIsWidgetDialogOpen] = useState(false);++ // Mutation for updating dashboard definition+ const updateDashboardDefinition =+ api.dashboard.updateDashboardDefinition.useMutation({+ onSuccess: () => {+ showSuccessToast({+ title: "Dashboard updated",+ description: "Your changes have been saved successfully",+ });+ setHasUnsavedChanges(false);+ // Invalidate the dashboard query to refetch the data+ dashboard.refetch();+ },+ onError: (error) => {+ showErrorToast("Error updating dashboard", error.message);+ },+ });++ const traceFilterOptions = api.traces.filterOptions.useQuery(+ {+ projectId,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );++ const environmentFilterOptions =+ api.projects.environmentFilterOptions.useQuery(+ { projectId },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );+ const environmentOptions =+ environmentFilterOptions.data?.map((value) => ({+ value: value.environment,+ })) || [];+ const nameOptions = traceFilterOptions.data?.name || [];+ const tagsOptions = traceFilterOptions.data?.tags || [];++ // Filter columns for PopoverFilterBuilder+ const filterColumns: ColumnDefinition[] = [+ {+ name: "Environment",+ id: "environment",+ type: "stringOptions",+ options: environmentOptions,+ internal: "internalValue",+ },+ {+ name: "Trace Name",+ id: "traceName",+ type: "stringOptions",+ options: nameOptions,+ internal: "internalValue",+ },+ {+ name: "Tags",+ id: "tags",+ type: "arrayOptions",+ options: tagsOptions,+ internal: "internalValue",+ },+ {+ name: "User",+ id: "user",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Session",+ id: "session",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Release",+ id: "release",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Version",+ id: "version",+ type: "string",+ internal: "internalValue",+ },+ ];++ // Fetch dashboard data+ const dashboard = api.dashboard.getDashboard.useQuery(+ { projectId, dashboardId },+ {+ enabled: Boolean(projectId) && Boolean(dashboardId),+ },+ );++ useEffect(() => {+ if (dashboard.data && !localDashboardDefinition) {+ setLocalDashboardDefinition(dashboard.data.definition);+ }+ }, [dashboard.data, localDashboardDefinition]);++ // Handle deleting a widget+ const handleDeleteWidget = (tileId: string) => {+ if (localDashboardDefinition) {+ const updatedWidgets = localDashboardDefinition.widgets.filter(+ (widget) => widget.id !== tileId,+ );++ setLocalDashboardDefinition({+ ...localDashboardDefinition,+ widgets: updatedWidgets,+ });++ setHasUnsavedChanges(true);+ }+ };++ // Handle adding a widget+ const handleAddWidget = () => {+ setIsWidgetDialogOpen(true);+ };++ // Handle widget selection from dialog+ const handleSelectWidget = (widget: WidgetItem) => {+ if (localDashboardDefinition) {+ // Find the maximum y position to place the new widget at the bottom+ const maxY =+ localDashboardDefinition.widgets.length > 0+ ? Math.max(+ ...localDashboardDefinition.widgets.map((w) => w.y + w.y_size),+ )+ : 0;++ debugger;++ // Create a new widget placement+ const newWidgetPlacement: WidgetPlacement = {+ 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: 2, // Default height of 2 rows+ type: "widget",+ };++ // Add the widget to the local dashboard definition+ setLocalDashboardDefinition({+ ...localDashboardDefinition,+ widgets: [...localDashboardDefinition.widgets, newWidgetPlacement],+ });++ setHasUnsavedChanges(true);++ showSuccessToast({+ title: "Widget added",+ description: `"${widget.name}" has been added to the dashboard. Click Save to apply changes.`,+ });+ }+ };++ // Handle saving the dashboard+ const handleSaveDashboard = () => {+ if (localDashboardDefinition && hasUnsavedChanges) {+ updateDashboardDefinition.mutate({+ projectId,+ dashboardId,+ definition: localDashboardDefinition,+ });+ }+ };++ return (+ <>+ <SelectWidgetDialog+ open={isWidgetDialogOpen}+ onOpenChange={setIsWidgetDialogOpen}+ projectId={projectId}+ onSelectWidget={handleSelectWidget}+ />++ <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>+ <Button+ onClick={handleSaveDashboard}+ disabled={+ !hasUnsavedChanges ||+ updateDashboardDefinition.isLoading ||+ !hasCUDAccess+ }+ loading={updateDashboardDefinition.isLoading}+ >+ Save+ </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>+ </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>+ )}+ </Page>+ </>+ );+}diff --git a/web/src/pages/project/[projectId]/dashboards/index.tsx b/web/src/pages/project/[projectId]/dashboards/index.tsxnew file mode 100644index 0000000000..c28ec0b376--- /dev/null+++ b/web/src/pages/project/[projectId]/dashboards/index.tsx@@ -0,0 +1,60 @@+import { useRouter } from "next/router";+import Page from "@/src/components/layouts/page";+import { DashboardTable } from "@/src/features/dashboard/components/DashboardTable";+import {+ TabsBar,+ TabsBarList,+ TabsBarTrigger,+} from "@/src/components/ui/tabs-bar";+import Link from "next/link";+import { ActionButton } from "@/src/components/ActionButton";+import { PlusIcon } from "lucide-react";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++export default function Dashboards() {+ const router = useRouter();+ const { projectId } = router.query as { projectId: string };+ const capture = usePostHogClientCapture();+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });++ return (+ <Page+ headerProps={{+ title: "Dashboards",+ help: {+ description: "Manage and create dashboards for your project.",+ href: "https://langfuse.com/docs/analytics/custom-dashboards",+ },+ tabsComponent: (+ <TabsBar value="dashboards">+ <TabsBarList>+ <TabsBarTrigger value="dashboards">Dashboards</TabsBarTrigger>+ <TabsBarTrigger value="widgets" asChild>+ <Link href={`/project/${projectId}/widgets`}>Widgets</Link>+ </TabsBarTrigger>+ </TabsBarList>+ </TabsBar>+ ),+ actionButtonsRight: (+ <ActionButton+ icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}+ hasAccess={hasCUDAccess}+ href={`/project/${projectId}/dashboards/new`}+ variant="default"+ onClick={() => {+ capture("dashboard:new_dashboard_form_open");+ }}+ >+ New dashboard+ </ActionButton>+ ),+ }}+ >+ <DashboardTable />+ </Page>+ );+}diff --git a/web/src/pages/project/[projectId]/dashboards/new.tsx b/web/src/pages/project/[projectId]/dashboards/new.tsxnew file mode 100644index 0000000000..3be7b72103--- /dev/null+++ b/web/src/pages/project/[projectId]/dashboards/new.tsx@@ -0,0 +1,122 @@+import { useState } from "react";+import { useRouter } from "next/router";+import { api } from "@/src/utils/api";+import Page from "@/src/components/layouts/page";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { Textarea } from "@/src/components/ui/textarea";+import { Label } from "@/src/components/ui/label";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";++export default function NewDashboard() {+ const router = useRouter();+ const { projectId } = router.query as { projectId: string };++ // State for new dashboard+ const [dashboardName, setDashboardName] = useState("New Dashboard");+ const [dashboardDescription, setDashboardDescription] = useState("");++ // Check project access+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });++ // Mutation for creating a new dashboard+ const createDashboard = api.dashboard.createDashboard.useMutation({+ onSuccess: (data) => {+ showSuccessToast({+ title: "Dashboard created",+ description: "Your new dashboard has been created successfully",+ });+ // Navigate to the newly created dashboard+ router.push(`/project/${projectId}/dashboards/${data.id}`);+ },+ onError: (error) => {+ showErrorToast("Error creating dashboard", error.message);+ },+ });++ // Handle form submission+ const handleCreateDashboard = () => {+ if (dashboardName.trim()) {+ createDashboard.mutate({+ projectId,+ name: dashboardName,+ description: dashboardDescription,+ });+ } else {+ showErrorToast("Validation error", "Dashboard name is required");+ }+ };++ return (+ <Page+ withPadding+ headerProps={{+ title: "Create Dashboard",+ help: {+ description: "Create a new dashboard for your project",+ },+ actionButtonsRight: (+ <>+ <Button+ variant="outline"+ onClick={() => router.push(`/project/${projectId}/dashboards`)}+ >+ Cancel+ </Button>+ <Button+ onClick={handleCreateDashboard}+ disabled={+ !dashboardName.trim() ||+ createDashboard.isLoading ||+ !hasCUDAccess+ }+ loading={createDashboard.isLoading}+ >+ Create+ </Button>+ </>+ ),+ }}+ >+ <div className="mx-auto my-8 max-w-xl space-y-6">+ <div className="space-y-2">+ <Label htmlFor="dashboard-name">Dashboard Name</Label>+ <Input+ id="dashboard-name"+ value={dashboardName}+ onChange={(e) => {+ setDashboardName(e.target.value);+ }}+ placeholder="Enter dashboard name"+ required+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="dashboard-description">Description</Label>+ <Textarea+ id="dashboard-description"+ value={dashboardDescription}+ onChange={(e) => {+ setDashboardDescription(e.target.value);+ }}+ placeholder="Describe the purpose of this dashboard. Optional, but very helpful."+ rows={4}+ />+ </div>++ <div className="text-sm text-muted-foreground">+ <p>+ After creating the dashboard, you can add widgets to visualize your+ data.+ </p>+ </div>+ </div>+ </Page>+ );+}diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex a2e7295a47..2f37d287c1 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -168,7 +168,7 @@ export default function Dashboard() {withPaddingscrollableheaderProps={{- title: "Dashboard",+ title: "Home",actionButtonsRight: <SetupTracingButton />,}}>diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsxnew file mode 100644index 0000000000..383be046eb--- /dev/null+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx@@ -0,0 +1,111 @@+import { useRouter } from "next/router";+import Page from "@/src/components/layouts/page";+import { api } from "@/src/utils/api";+import { WidgetForm } from "@/src/features/widgets/components/WidgetForm";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import { type views, type metricAggregations } from "@/src/features/query";+import { type z } from "zod";++export default function EditWidget() {+ const router = useRouter();+ const { projectId, widgetId } = router.query as {+ projectId: string;+ widgetId: string;+ };++ // Fetch the widget details+ const { data: widgetData, isLoading: isWidgetLoading } =+ api.dashboardWidgets.get.useQuery(+ {+ projectId,+ widgetId,+ },+ {+ enabled: Boolean(projectId) && Boolean(widgetId),+ },+ );++ // Update widget mutation+ const updateWidgetMutation = api.dashboardWidgets.update.useMutation({+ onSuccess: () => {+ showSuccessToast({+ title: "Widget updated successfully",+ description: "Your widget has been updated.",+ });+ // Navigate back to widgets list+ void router.push(`/project/${projectId}/widgets`);+ },+ onError: (error) => {+ showErrorToast("Failed to update widget", error.message);+ },+ });++ // Handle update widget+ const handleUpdateWidget = (widgetFormData: {+ name: string;+ description: string;+ view: string;+ dimensions: { field: string }[];+ metrics: { measure: string; agg: string }[];+ filters: any[];+ chartType: DashboardWidgetChartType;+ chartConfig: { type: DashboardWidgetChartType; row_limit?: number };+ }) => {+ if (!widgetId) return;++ updateWidgetMutation.mutate({+ projectId,+ widgetId,+ name: widgetFormData.name,+ description: widgetFormData.description,+ view: widgetFormData.view as z.infer<typeof views>,+ dimensions: widgetFormData.dimensions,+ metrics: widgetFormData.metrics.map((metric) => ({+ measure: metric.measure,+ agg: metric.agg as z.infer<typeof metricAggregations>,+ })),+ filters: widgetFormData.filters,+ chartType: widgetFormData.chartType,+ chartConfig: widgetFormData.chartConfig,+ });+ };++ return (+ <Page+ withPadding+ headerProps={{+ title: "Edit Widget",+ help: {+ description: "Edit an existing widget",+ },+ }}+ >+ {!isWidgetLoading && widgetData ? (+ <WidgetForm+ projectId={projectId}+ onSave={handleUpdateWidget}+ initialValues={{+ name: widgetData.name,+ description: widgetData.description,+ view: widgetData.view as z.infer<typeof views>,+ dimension: widgetData.dimensions.slice().shift()?.field ?? "none",+ measure: widgetData.metrics.slice().shift()?.measure ?? "count",+ aggregation:+ (widgetData.metrics.slice().shift()?.agg as z.infer<+ typeof metricAggregations+ >) ?? "count",+ filters: widgetData.filters,+ chartType: widgetData.chartType,+ chartConfig: widgetData.chartConfig,+ }}+ />+ ) : (+ <div className="flex h-[300px] items-center justify-center">+ <p className="text-muted-foreground">Loading...</p>+ </div>+ )}+ </Page>+ );+}diff --git a/web/src/pages/project/[projectId]/widgets/index.tsx b/web/src/pages/project/[projectId]/widgets/index.tsxnew file mode 100644index 0000000000..442d604e15--- /dev/null+++ b/web/src/pages/project/[projectId]/widgets/index.tsx@@ -0,0 +1,62 @@+import { useRouter } from "next/router";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import Page from "@/src/components/layouts/page";+import { ActionButton } from "@/src/components/ActionButton";+import { PlusIcon } from "lucide-react";+import { DashboardWidgetTable } from "@/src/features/widgets";+import {+ TabsBar,+ TabsBarList,+ TabsBarTrigger,+} from "@/src/components/ui/tabs-bar";+import Link from "next/link";++export default function Widgets() {+ const router = useRouter();+ const { projectId } = router.query as { projectId: string };+ const capture = usePostHogClientCapture();+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "prompts:CUD",+ });++ return (+ <Page+ headerProps={{+ title: "Widgets",+ help: {+ description: "Manage and create widgets for your dashboard.",+ href: "https://langfuse.com/docs/analytics/custom-dashboards",+ },+ tabsComponent: (+ <TabsBar value="widgets">+ <TabsBarList>+ <TabsBarTrigger value="dashboards" asChild>+ <Link href={`/project/${projectId}/dashboards`}>+ Dashboards+ </Link>+ </TabsBarTrigger>+ <TabsBarTrigger value="widgets">Widgets</TabsBarTrigger>+ </TabsBarList>+ </TabsBar>+ ),+ actionButtonsRight: (+ <ActionButton+ icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}+ hasAccess={hasCUDAccess}+ href={`/project/${projectId}/widgets/new`}+ variant="default"+ onClick={() => {+ capture("dashboard:new_widget_form_open");+ }}+ >+ New widget+ </ActionButton>+ ),+ }}+ >+ <DashboardWidgetTable />+ </Page>+ );+}diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsxindex abc7f0e25f..b2d904df1f 100644--- a/web/src/pages/project/[projectId]/widgets/new.tsx+++ b/web/src/pages/project/[projectId]/widgets/new.tsx@@ -1,302 +1,67 @@-import { useSession } from "next-auth/react";import { useRouter } from "next/router";import Page from "@/src/components/layouts/page";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@/src/components/ui/card";import { api } from "@/src/utils/api";+import { WidgetForm } from "@/src/features/widgets";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";import {- metricAggregations,- type QueryType,- mapLegacyUiTableFilterToView,-} from "@/src/features/query";-import { useState, useMemo, useEffect } from "react";-import {- Select,- SelectContent,- SelectGroup,- SelectItem,- SelectLabel,- SelectTrigger,- SelectValue,-} from "@/src/components/ui/select";-import { Label } from "@/src/components/ui/label";-import { viewDeclarations } from "@/src/features/query/dataModel";+ type views,+ type metricAggregations,+} from "@/src/features/query/types";import { type z } from "zod";-import { views } from "@/src/features/query/types";-import { Input } from "@/src/components/ui/input";-import { startCase } from "lodash";-import { DatePickerWithRange } from "@/src/components/date-picker";-import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";-import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";-import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";-import { type ColumnDefinition } from "@langfuse/shared";-import { Chart } from "@/src/features/widgets/chart-library/Chart";-import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";export default function NewWidget() {- const session = useSession();- const isAdmin = session.data?.user?.admin === true;-const router = useRouter();const { projectId } = router.query as { projectId: string };- // State for form fields- const [widgetName, setWidgetName] = useState<string>("Traces");- const [widgetDescription, setWidgetDescription] = useState<string>(- "Traces grouped by name for the last 30 days.",- );- const [selectedView, setSelectedView] =- useState<z.infer<typeof views>>("traces");- const [selectedMetric, setSelectedMetric] = useState<string>("count");- const [selectedAggregation, setSelectedAggregation] =- useState<z.infer<typeof metricAggregations>>("count");- const [selectedDimension, setSelectedDimension] = useState<string>("none");-- // Filter state- const { selectedOption, dateRange, setDateRangeAndOption } =- useDashboardDateRange();- const [userFilterState, setUserFilterState] = useQueryFilterState(- [],- "widgets",- projectId,- );-- const traceFilterOptions = api.traces.filterOptions.useQuery(- {- projectId,- },- {- trpc: {- context: {- skipBatch: true,- },- },- refetchOnMount: false,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- staleTime: Infinity,- },- );-- const environmentFilterOptions =- api.projects.environmentFilterOptions.useQuery(- { projectId },- {- trpc: {- context: {- skipBatch: true,- },- },- refetchOnMount: false,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- staleTime: Infinity,- },- );- const environmentOptions =- environmentFilterOptions.data?.map((value) => ({- value: value.environment,- })) || [];- const nameOptions = traceFilterOptions.data?.name || [];- const tagsOptions = traceFilterOptions.data?.tags || [];-- // Filter columns for PopoverFilterBuilder- const filterColumns: ColumnDefinition[] = [- {- name: "Environment",- id: "environment",- type: "stringOptions",- options: environmentOptions,- internal: "internalValue",- },- {- name: "Trace Name",- id: "traceName",- type: "stringOptions",- options: nameOptions,- internal: "internalValue",- },- {- name: "Tags",- id: "tags",- type: "arrayOptions",- options: tagsOptions,- internal: "internalValue",- },- {- name: "User",- id: "user",- type: "string",- internal: "internalValue",- },- {- name: "Session",- id: "session",- type: "string",- internal: "internalValue",- },- {- name: "Release",- id: "release",- type: "string",- internal: "internalValue",+ // Save widget mutation+ const createWidgetMutation = api.dashboardWidgets.create.useMutation({+ onSuccess: () => {+ showSuccessToast({+ title: "Widget created successfully",+ description: "Your widget has been created.",+ });+ // Navigate back to widgets list+ void router.push(`/project/${projectId}/widgets`);},- {- name: "Version",- id: "version",- type: "string",- internal: "internalValue",+ onError: (error) => {+ showErrorToast("Failed to save widget", error.message);},- ];+ });- // Chart type options- type ChartType = {- group: "time-series" | "total-value";+ // Handle save widget+ const handleSaveWidget = (widgetData: {name: string;- value: string;- };-- const chartTypes: ChartType[] = useMemo(- () => [- { group: "time-series", name: "Line Chart", value: "line-time-series" },- {- group: "time-series",- name: "Vertical Bar Chart",- value: "bar-time-series",- },- {- group: "total-value",- name: "Horizontal Bar Chart",- value: "bar-horizontal",- },- {- group: "total-value",- name: "Vertical Bar Chart",- value: "bar-vertical",- },- { group: "total-value", name: "Pie Chart", value: "pie" },- ],- [],- );-- const [selectedChartType, setSelectedChartType] =- useState<string>("line-time-series");- const [rowLimit, setRowLimit] = useState<number>(100);-- // Reset form fields when view changes- useEffect(() => {- if (selectedView) {- setSelectedMetric("count");- setSelectedAggregation("count");- setSelectedDimension("none");- }- }, [selectedView]);-- // Set aggregation to "count" when metric is "count"- useEffect(() => {- if (selectedMetric === "count") {- setSelectedAggregation("count");+ description: string;+ view: string;+ dimensions: { field: string }[];+ metrics: { measure: string; agg: string }[];+ filters: any[];+ chartType: DashboardWidgetChartType;+ chartConfig: { type: DashboardWidgetChartType; row_limit?: number };+ }) => {+ if (!widgetData.name.trim()) {+ showErrorToast("Error", "Widget name is required");+ return;}- }, [selectedMetric]);-- // Get available metrics for the selected view- const availableMetrics = useMemo(() => {- const viewDeclaration = viewDeclarations[selectedView];- return Object.entries(viewDeclaration.measures).map(([key]) => ({- value: key,- label: startCase(key),- }));- }, [selectedView]);-- // Get available dimensions for the selected view- const availableDimensions = useMemo(() => {- const viewDeclaration = viewDeclarations[selectedView];- return Object.entries(viewDeclaration.dimensions).map(([key]) => ({- value: key,- label: startCase(key),- }));- }, [selectedView]);-- // Check if the selected chart type is a time series chart- const isTimeSeriesChart = useMemo(() => {- return (- chartTypes.find((chart) => chart.value === selectedChartType)?.group ===- "time-series"- );- }, [selectedChartType, chartTypes]);- // Create a dynamic query based on the selected view- const query = useMemo<QueryType>(() => {- // Calculate fromTimestamp and toTimestamp from dateRange- const fromTimestamp = dateRange- ? dateRange.from- : new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000); // Default to last 7 days- const toTimestamp = dateRange ? dateRange.to : new Date();-- return {- view: selectedView,- dimensions:- selectedDimension !== "none" ? [{ field: selectedDimension }] : [],- metrics: [{ measure: selectedMetric, aggregation: selectedAggregation }],- filters: [...mapLegacyUiTableFilterToView(selectedView, userFilterState)],- timeDimension: isTimeSeriesChart ? { granularity: "auto" } : null,- fromTimestamp: fromTimestamp.toISOString(),- toTimestamp: toTimestamp.toISOString(),- orderBy: null,- };- }, [- selectedView,- selectedDimension,- selectedAggregation,- selectedMetric,- userFilterState,- dateRange,- isTimeSeriesChart,- ]);-- const queryResult = api.dashboard.executeQuery.useQuery(- {+ // Prepare the widget data+ createWidgetMutation.mutate({projectId,- query,- },- {- trpc: {- context: {- skipBatch: true,- },- },- enabled: isAdmin, // Only run query if isAdmin is true- },- );-- // Transform the query results to a consistent format for charts- const transformedData: DataPoint[] = useMemo(- () =>- queryResult.data?.map((item: any) => {- // Get the dimension field (first dimension in the query)- const dimensionField = selectedDimension;- // Get the metric field (first metric in the query with its aggregation)- const metricField = `${selectedAggregation}_${selectedMetric}`;-- return {- dimension: item[dimensionField]- ? (item[dimensionField] as string)- : "n/a",- metric: Number(item[metricField] || 0),- time_dimension: item["time_dimension"],- };- }) ?? [],- [queryResult.data, selectedAggregation, selectedDimension, selectedMetric],- );-- if (!isAdmin) {- return null; // Blank page for non-admins- }+ name: widgetData.name,+ description: widgetData.description,+ view: widgetData.view as z.infer<typeof views>,+ dimensions: widgetData.dimensions,+ metrics: widgetData.metrics.map((metric) => ({+ measure: metric.measure,+ agg: metric.agg as z.infer<typeof metricAggregations>,+ })),+ filters: widgetData.filters,+ chartType: widgetData.chartType,+ chartConfig: widgetData.chartConfig,+ });+ };return (<Page@@ -308,245 +73,20 @@ export default function NewWidget() {},}}>- <div className="flex h-full gap-4">- {/* Left column - Form */}- <div className="h-full w-1/3">- <Card className="flex h-full flex-col">- <CardHeader>- <CardTitle>Widget Configuration</CardTitle>- <CardDescription>- Configure your widget by selecting data and visualization- options- </CardDescription>- </CardHeader>- <CardContent className="space-y-4 overflow-y-auto">- {/* Widget Name */}- <div className="space-y-2">- <Label htmlFor="widget-name">Name</Label>- <Input- id="widget-name"- value={widgetName}- onChange={(e) => setWidgetName(e.target.value)}- placeholder="Enter widget name"- />- </div>-- {/* Widget Description */}- <div className="space-y-2">- <Label htmlFor="widget-description">Description</Label>- <Input- id="widget-description"- value={widgetDescription}- onChange={(e) => setWidgetDescription(e.target.value)}- placeholder="Enter widget description"- />- </div>-- {/* Data Selection Section */}- <div className="mt-6 space-y-4">- <h3 className="text-lg font-bold">Data Selection</h3>-- {/* View Selection */}- <div className="space-y-2">- <Label htmlFor="view-select">View</Label>- <Select- value={selectedView}- onValueChange={(value) =>- setSelectedView(value as z.infer<typeof views>)- }- >- <SelectTrigger id="view-select">- <SelectValue placeholder="Select a view" />- </SelectTrigger>- <SelectContent>- {views.options.map((view) => (- <SelectItem key={view} value={view}>- {startCase(view)}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- {/* Metrics Selection */}- <div className="space-y-2">- <Label htmlFor="metrics-select">Metric</Label>- <Select- value={selectedMetric}- onValueChange={(value) => setSelectedMetric(value)}- >- <SelectTrigger id="metrics-select">- <SelectValue placeholder="Select metrics" />- </SelectTrigger>- <SelectContent>- {availableMetrics.map((metric) => (- <SelectItem key={metric.value} value={metric.value}>- {metric.label}- </SelectItem>- ))}- </SelectContent>- </Select>- {selectedMetric !== "count" && (- <Select- value={selectedAggregation}- onValueChange={(value) =>- setSelectedAggregation(- value as z.infer<typeof metricAggregations>,- )- }- >- <SelectTrigger id="aggregation-select">- <SelectValue placeholder="Select Aggregation" />- </SelectTrigger>- <SelectContent>- {metricAggregations.options.map((aggregation) => (- <SelectItem key={aggregation} value={aggregation}>- {startCase(aggregation)}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- </div>-- {/* Filters Section */}- <div className="space-y-2">- <Label>Filters</Label>- <div className="space-y-2">- <InlineFilterBuilder- columns={filterColumns}- filterState={userFilterState}- onChange={setUserFilterState}- />- </div>- </div>-- {/* Dimension Selection (Breakdown) */}- <div className="space-y-2">- <Label htmlFor="dimension-select">- Breakdown Dimension (Optional)- </Label>- <Select- value={selectedDimension}- onValueChange={setSelectedDimension}- >- <SelectTrigger id="dimension-select">- <SelectValue placeholder="Select a dimension" />- </SelectTrigger>- <SelectContent>- <SelectItem value="none">None</SelectItem>- {availableDimensions.map((dimension) => (- <SelectItem- key={dimension.value}- value={dimension.value}- >- {dimension.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>-- {/* Visualization Section */}- <div className="mt-6 space-y-4">- <h3 className="text-lg font-bold">Visualization</h3>-- {/* Chart Type Selection */}- <div className="space-y-2">- <Label htmlFor="chart-type-select">Chart Type</Label>- <Select- value={selectedChartType}- onValueChange={setSelectedChartType}- >- <SelectTrigger id="chart-type-select">- <SelectValue placeholder="Select a chart type" />- </SelectTrigger>- <SelectContent>- <SelectGroup>- <SelectLabel>Time Series</SelectLabel>- {chartTypes- .filter((item) => item.group === "time-series")- .map((chart) => (- <SelectItem key={chart.value} value={chart.value}>- {chart.name}- </SelectItem>- ))}- </SelectGroup>- <SelectGroup>- <SelectLabel>Total Value</SelectLabel>- {chartTypes- .filter((item) => item.group === "total-value")- .map((chart) => (- <SelectItem key={chart.value} value={chart.value}>- {chart.name}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </div>-- <div className="space-y-2">- <Label htmlFor="date-select">Date Range</Label>- <DatePickerWithRange- dateRange={dateRange}- setDateRangeAndOption={setDateRangeAndOption}- selectedOption={selectedOption}- className="w-full"- />- </div>-- {/* Row Limit Selection - Only shown for non-time series charts */}- {!isTimeSeriesChart && (- <div className="space-y-2">- <Label htmlFor="row-limit">Row Limit (1-1000)</Label>- <Input- id="row-limit"- type="number"- min={1}- max={1000}- value={rowLimit}- onChange={(e) => {- const value = parseInt(e.target.value);- if (!isNaN(value) && value >= 1 && value <= 1000) {- setRowLimit(value);- }- }}- placeholder="Enter row limit (1-1000)"- />- </div>- )}- </div>- </CardContent>- </Card>- </div>-- {/* Right column - Chart */}- <div className="w-2/3">- <Card>- <CardHeader>- <CardTitle>{widgetName}</CardTitle>- <CardDescription>{widgetDescription}</CardDescription>- </CardHeader>- {queryResult.data ? (- <Chart- chartType={selectedChartType}- data={transformedData}- rowLimit={rowLimit}- />- ) : (- <CardContent>- <div className="flex h-[300px] items-center justify-center">- <p className="text-muted-foreground">- Waiting for Input / Loading...- </p>- </div>- </CardContent>- )}- </Card>- </div>- </div>+ <WidgetForm+ projectId={projectId}+ onSave={handleSaveWidget}+ initialValues={{+ name: "Trace Chart",+ description: "This is a new widget",+ view: "traces",+ dimension: "none",+ measure: "count",+ aggregation: "count",+ filters: [],+ chartType: "LINE_TIME_SERIES",+ }}+ /></Page>);}diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 0838652edb..ffc7fe62a5 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -35,6 +35,7 @@ import { backgroundMigrationsRouter } from "@/src/features/background-migrationsimport { auditLogsRouter } from "./routers/auditLogs";import { tableRouter } from "@/src/features/table/server/tableRouter";import { cloudStatusRouter } from "@/src/features/cloud-status-notification/server/cloud-status-router";+import { dashboardWidgetRouter } from "./routers/dashboardWidgets";/*** This is the primary router for your server.@@ -78,6 +79,7 @@ export const appRouter = createTRPCRouter({auditLogs: auditLogsRouter,table: tableRouter,cloudStatus: cloudStatusRouter,+ dashboardWidgets: dashboardWidgetRouter,});// export type definition of APIdiff --git a/web/src/server/api/routers/dashboardWidgets.ts b/web/src/server/api/routers/dashboardWidgets.tsnew file mode 100644index 0000000000..1d58775267--- /dev/null+++ b/web/src/server/api/routers/dashboardWidgets.ts@@ -0,0 +1,213 @@+import { z } from "zod";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { paginationZod, orderBy, singleFilter } from "@langfuse/shared";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ DashboardWidgetChartType,+ DashboardWidgetViews,+} from "@langfuse/shared/src/db";+import {+ DashboardService,+ DimensionSchema,+ MetricSchema,+ ChartConfigSchema,+} from "@langfuse/shared/src/server";+import { views } from "@/src/features/query";+import { TRPCError } from "@trpc/server";+import { LangfuseConflictError } from "@langfuse/shared";++const CreateDashboardWidgetInput = z.object({+ projectId: z.string(),+ name: z.string().min(1, "Widget name is required"),+ description: z.string(),+ view: views,+ dimensions: z.array(DimensionSchema),+ metrics: z.array(MetricSchema),+ filters: z.array(singleFilter),+ chartType: z.nativeEnum(DashboardWidgetChartType),+ chartConfig: ChartConfigSchema,+});++// Define update widget input schema (without projectId)+const UpdateDashboardWidgetInput = z.object({+ projectId: z.string(),+ widgetId: z.string(),+ name: z.string().min(1, "Widget name is required"),+ description: z.string(),+ view: views,+ dimensions: z.array(DimensionSchema),+ metrics: z.array(MetricSchema),+ filters: z.array(singleFilter),+ chartType: z.nativeEnum(DashboardWidgetChartType),+ chartConfig: ChartConfigSchema,+});++// Define the widget list input schema+const ListDashboardWidgetsInput = z.object({+ projectId: z.string(),+ ...paginationZod,+ orderBy: orderBy,+});++// Get widget by ID input schema+const GetDashboardWidgetInput = z.object({+ projectId: z.string(),+ widgetId: z.string(),+});++const viewMapping: Record<string, DashboardWidgetViews> = {+ traces: DashboardWidgetViews.TRACES,+ observations: DashboardWidgetViews.OBSERVATIONS,+ "scores-numeric": DashboardWidgetViews.SCORES_NUMERIC,+ "scores-categorical": DashboardWidgetViews.SCORES_CATEGORICAL,+};++// Reverse mapping for client-side use+const reverseViewMapping: Record<DashboardWidgetViews, string> = {+ [DashboardWidgetViews.TRACES]: "traces",+ [DashboardWidgetViews.OBSERVATIONS]: "observations",+ [DashboardWidgetViews.SCORES_NUMERIC]: "scores-numeric",+ [DashboardWidgetViews.SCORES_CATEGORICAL]: "scores-categorical",+};++export const dashboardWidgetRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateDashboardWidgetInput)+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ // Create the widget using the DashboardService+ const widget = await DashboardService.createWidget(+ input.projectId,+ { ...input, view: viewMapping[input.view] },+ ctx.session.user?.id,+ );++ return {+ success: true,+ widget,+ };+ }),++ all: protectedProjectProcedure+ .input(ListDashboardWidgetsInput)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:read",+ });++ const result = await DashboardService.listWidgets({+ projectId: input.projectId,+ limit: input.limit,+ page: input.page,+ orderBy: input.orderBy,+ });++ return result;+ }),++ get: protectedProjectProcedure+ .input(GetDashboardWidgetInput)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:read",+ });++ const widget = await DashboardService.getWidget(+ input.widgetId,+ input.projectId,+ );++ if (!widget) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Widget not found",+ });+ }++ return {+ ...widget,+ view: reverseViewMapping[widget.view],+ };+ }),++ update: protectedProjectProcedure+ .input(UpdateDashboardWidgetInput)+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ // Update the widget using the DashboardService+ const widget = await DashboardService.updateWidget(+ input.projectId,+ input.widgetId,+ {+ name: input.name,+ description: input.description,+ view: viewMapping[input.view],+ dimensions: input.dimensions,+ metrics: input.metrics,+ filters: input.filters,+ chartType: input.chartType,+ chartConfig: input.chartConfig,+ },+ ctx.session.user?.id,+ );++ return {+ success: true,+ widget,+ };+ }),++ // Define delete widget input schema+ delete: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ widgetId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ try {+ // Delete the widget using the DashboardService+ await DashboardService.deleteWidget(input.widgetId, input.projectId);++ return {+ success: true,+ };+ } catch (error) {+ // If the widget is still referenced in dashboards, throw a CONFLICT error+ if (error instanceof LangfuseConflictError) {+ throw new TRPCError({+ code: "CONFLICT",+ message: error.message,+ });+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: (error as Error)?.message,+ });+ }+ }),+});