πͺ’ 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(dashboard): make Home a dashboard β preset widgets, curated default, per-project selection (LFE-10693) (#14824)
Nikita Kabardin548ee887eb2b
diff --git a/packages/shared/prisma/migrations/20260707170000_add_project_home_dashboard/migration.sql b/packages/shared/prisma/migrations/20260707170000_add_project_home_dashboard/migration.sqlnew file mode 100644index 0000000000..8660cb8305--- /dev/null+++ b/packages/shared/prisma/migrations/20260707170000_add_project_home_dashboard/migration.sql@@ -0,0 +1,5 @@+-- AlterTable+ALTER TABLE "projects" ADD COLUMN "home_dashboard_id" TEXT;++-- AddForeignKey+ALTER TABLE "projects" ADD CONSTRAINT "projects_home_dashboard_id_fkey" FOREIGN KEY ("home_dashboard_id") REFERENCES "dashboards"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 5d70d36907..78fd859c6a 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -132,6 +132,10 @@ model Project {retentionDays Int? @map("retention_days")hasTraces Boolean @default(false) @map("has_traces")metadata Json?+ // Which dashboard renders on the project home page; null = the+ // Langfuse-curated default (LANGFUSE_HOME_DASHBOARD_ID).+ homeDashboardId String? @map("home_dashboard_id")+ homeDashboard Dashboard? @relation("ProjectHomeDashboard", fields: [homeDashboardId], references: [id], onDelete: SetNull)projectMembers ProjectMembership[]organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)apiKeys ApiKey[]@@ -1538,6 +1542,8 @@ model Dashboard {definition Json @map("definition")filters Json @default("[]") @map("filters")+ homeDashboardProjects Project[] @relation("ProjectHomeDashboard")+@@map("dashboards")}diff --git a/packages/shared/src/domain/home-dashboard.test.ts b/packages/shared/src/domain/home-dashboard.test.tsnew file mode 100644index 0000000000..5565345492--- /dev/null+++ b/packages/shared/src/domain/home-dashboard.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";+import {+ HOME_DASHBOARD_PRESET_IDS,+ LANGFUSE_HOME_DASHBOARD,+ LANGFUSE_HOME_DASHBOARD_ID,+} from "./home-dashboard";+import { DashboardDomainSchema } from "../server/services/DashboardService/types";++describe("LANGFUSE_HOME_DASHBOARD", () => {+ it("parses through DashboardDomainSchema the way the worker upsert consumes it", () => {+ const parsed = DashboardDomainSchema.parse({+ ...LANGFUSE_HOME_DASHBOARD,+ createdAt: new Date(LANGFUSE_HOME_DASHBOARD.createdAt),+ updatedAt: new Date(LANGFUSE_HOME_DASHBOARD.updatedAt),+ projectId: null,+ createdBy: null,+ updatedBy: null,+ owner: "LANGFUSE",+ });++ expect(parsed.id).toBe(LANGFUSE_HOME_DASHBOARD_ID);+ expect(parsed.definition.widgets.length).toBeGreaterThan(0);+ expect(parsed.definition.widgets.every((w) => w.type === "preset")).toBe(+ true,+ );+ });++ it("places every registered preset exactly once", () => {+ const placedPresetIds = LANGFUSE_HOME_DASHBOARD.definition.widgets.flatMap(+ (w) => (w.type === "preset" ? [w.presetId] : []),+ );++ expect([...placedPresetIds].sort()).toEqual(+ [...HOME_DASHBOARD_PRESET_IDS].sort(),+ );+ // Placement ids must be unique within the dashboard (react keys,+ // scheduler ids, delete targets).+ const placementIds = LANGFUSE_HOME_DASHBOARD.definition.widgets.map(+ (w) => w.id,+ );+ expect(new Set(placementIds).size).toBe(placementIds.length);+ });++ it("fits the 12-column grid without overlapping tiles", () => {+ const tiles = LANGFUSE_HOME_DASHBOARD.definition.widgets;++ for (const tile of tiles) {+ expect(tile.x + tile.x_size).toBeLessThanOrEqual(12);+ }++ for (let i = 0; i < tiles.length; i++) {+ for (let j = i + 1; j < tiles.length; j++) {+ const a = tiles[i];+ const b = tiles[j];+ const overlaps =+ a.x < b.x + b.x_size &&+ b.x < a.x + a.x_size &&+ a.y < b.y + b.y_size &&+ b.y < a.y + a.y_size;+ expect(overlaps, `${a.id} overlaps ${b.id}`).toBe(false);+ }+ }+ });+});diff --git a/packages/shared/src/domain/home-dashboard.ts b/packages/shared/src/domain/home-dashboard.tsnew file mode 100644index 0000000000..9c6ea7ae8e--- /dev/null+++ b/packages/shared/src/domain/home-dashboard.ts@@ -0,0 +1,93 @@+import type { DashboardDefinition } from "../server/services/DashboardService/types";++/**+ * The Langfuse-curated Home dashboard (projectId = null).+ *+ * The worker upserts it into Postgres at startup (see+ * worker/src/scripts/upsertLangfuseDashboards.ts) so it behaves like any other+ * Langfuse-maintained dashboard (listed, read-only, cloneable). The web Home+ * page fetches it by this well-known id and falls back to this constant when+ * the row does not exist yet (e.g. the worker has not run).+ *+ * All placements are "preset" placements: they render the existing Home card+ * components (registered by presetId in the web preset registry) with their+ * existing data fetches β no DashboardWidget rows, no query configuration.+ *+ * When changing the definition, bump `updatedAt` so the worker upsert+ * overwrites the existing row.+ */+export const LANGFUSE_HOME_DASHBOARD_ID = "langfuse-home-dashboard";++export const HOME_DASHBOARD_PRESET_IDS = [+ "home-traces",+ "home-model-costs",+ "home-scores-table",+ "home-traces-obs-time-series",+ "home-model-usage",+ "home-users",+ "home-chart-scores",+ "home-latency-table-traces",+ "home-latency-table-generations",+ "home-latency-table-observations",+ "home-generation-latency",+ "home-score-analytics",+] as const;++export type HomeDashboardPresetId = (typeof HOME_DASHBOARD_PRESET_IDS)[number];++const placement = (+ presetId: HomeDashboardPresetId,+ x: number,+ y: number,+ x_size: number,+ y_size: number,+) => ({+ type: "preset" as const,+ // Placement ids only need to be unique within the dashboard, so the+ // presetId doubles as a stable, readable placement id.+ id: presetId,+ presetId,+ x,+ y,+ x_size,+ y_size,+});++export const LANGFUSE_HOME_DASHBOARD_DEFINITION: DashboardDefinition = {+ widgets: [+ // Grid rows are 16:9-proportional to column width (see DashboardGrid), so+ // row heights shrink with the viewport while the Home cards have fixed+ // intrinsic minimum heights (headline metrics, tabs, min-h chart floors).+ // Sizes below fit the densest card down to ~1240px viewports; below that+ // the preset tile scrolls internally, and below 1025px the grid stacks.+ // Row 1: overview tables+ placement("home-traces", 0, 0, 4, 6),+ placement("home-model-costs", 4, 0, 4, 6),+ placement("home-scores-table", 8, 0, 4, 6),+ // Row 2: traffic + usage time series (tabbed cards with headline metrics+ // have the largest intrinsic height)+ placement("home-traces-obs-time-series", 0, 6, 6, 8),+ placement("home-model-usage", 6, 6, 6, 8),+ // Row 3: users + scores over time+ placement("home-users", 0, 14, 6, 7),+ placement("home-chart-scores", 6, 14, 6, 7),+ // Row 4: latency percentile tables+ placement("home-latency-table-traces", 0, 21, 4, 6),+ placement("home-latency-table-generations", 4, 21, 4, 6),+ placement("home-latency-table-observations", 8, 21, 4, 6),+ // Row 5+: full-width analytics+ placement("home-generation-latency", 0, 27, 12, 8),+ placement("home-score-analytics", 0, 35, 12, 7),+ ],+};++export const LANGFUSE_HOME_DASHBOARD = {+ id: LANGFUSE_HOME_DASHBOARD_ID,+ name: "Langfuse Home",+ description:+ "Overview of traces, costs, scores, usage, and latencies in this project. Shown on the project home page.",+ definition: LANGFUSE_HOME_DASHBOARD_DEFINITION,+ filters: [],+ createdAt: "2026-07-06T00:00:00.000Z",+ updatedAt: "2026-07-06T13:00:00.000Z",+};diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex aaed36aac4..3de406a547 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -26,6 +26,7 @@ export * from "./domain/webhooks";export * from "./domain/dataset-run-items";export * from "./domain/dataset-items";export * from "./domain/score-configs";+export * from "./domain/home-dashboard";// llm apiexport * from "./server/llm/types";diff --git a/packages/shared/src/server/services/DashboardService/DashboardService.ts b/packages/shared/src/server/services/DashboardService/DashboardService.tsindex bf7ee670cf..7f4e1d214c 100644--- a/packages/shared/src/server/services/DashboardService/DashboardService.ts+++ b/packages/shared/src/server/services/DashboardService/DashboardService.ts@@ -109,15 +109,9 @@ export class DashboardService {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,- })),+ // Already sanitized: the input is parsed against+ // DashboardDefinitionSchema, which strips unknown keys.+ widgets: definition.widgets,},},});diff --git a/packages/shared/src/server/services/DashboardService/types.ts b/packages/shared/src/server/services/DashboardService/types.tsindex 64e8b00d5c..4e14a07050 100644--- a/packages/shared/src/server/services/DashboardService/types.ts+++ b/packages/shared/src/server/services/DashboardService/types.ts@@ -81,8 +81,22 @@ export const DashboardDefinitionWidgetWidgetSchema = z.object({y_size: z.number().int().positive(),});+// A "preset" placement renders a registered curated component (looked up by+// presetId in the web preset registry) instead of a DashboardWidget row β+// presets carry no query configuration.+export const DashboardDefinitionPresetWidgetSchema = z.object({+ type: z.literal("preset"),+ id: z.string(),+ presetId: 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,+ DashboardDefinitionPresetWidgetSchema,]);export const DashboardDefinitionSchema = z.object({@@ -152,6 +166,7 @@ export const WidgetListResponseSchema = z.object({});// Export types derived from schemas+export type DashboardDefinition = z.infer<typeof DashboardDefinitionSchema>;export type DashboardDomain = z.infer<typeof DashboardDomainSchema>;export type DashboardListResponse = z.infer<typeof DashboardListResponseSchema>;export type WidgetDomain = z.infer<typeof WidgetDomainSchema>;diff --git a/web/src/__tests__/server/dashboard-widget-version.servertest.ts b/web/src/__tests__/server/dashboard-widget-version.servertest.tsindex 398074d3bd..0e352e94ca 100644--- a/web/src/__tests__/server/dashboard-widget-version.servertest.ts+++ b/web/src/__tests__/server/dashboard-widget-version.servertest.ts@@ -3,6 +3,10 @@ import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import { DashboardService } from "@langfuse/shared/src/server";import { DashboardWidgetViews } from "@langfuse/shared/src/db";import { prisma } from "@langfuse/shared/src/db";+import {+ LANGFUSE_HOME_DASHBOARD_DEFINITION,+ LANGFUSE_HOME_DASHBOARD_ID,+} from "@langfuse/shared";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import type { Session } from "next-auth";@@ -329,6 +333,203 @@ describe("dashboard widget minVersion", () => {expect(copiedWidget!.minVersion).toBe(2);expect(copiedWidget!.owner).toBe("PROJECT");});++ it("should round-trip preset placements in the dashboard definition", async () => {+ const dashboard = await DashboardService.createDashboard(+ projectId,+ "Preset Dashboard",+ "A dashboard mixing widget and preset placements",+ userId,+ );++ const definition = {+ widgets: [+ {+ type: "widget" as const,+ id: "placement-widget",+ widgetId: uuidv4(),+ x: 0,+ y: 0,+ x_size: 6,+ y_size: 4,+ },+ {+ type: "preset" as const,+ id: "placement-preset",+ presetId: "home-traces",+ x: 6,+ y: 0,+ x_size: 6,+ y_size: 4,+ },+ ],+ };++ await DashboardService.updateDashboardDefinition(+ dashboard.id,+ projectId,+ definition,+ userId,+ );++ const fetched = await DashboardService.getDashboard(+ dashboard.id,+ projectId,+ );++ expect(fetched).not.toBeNull();+ expect(fetched!.definition.widgets).toEqual(definition.widgets);+ });+ });++ describe("home dashboard pointer", () => {+ beforeAll(async () => {+ // The worker upserts the curated Home dashboard at startup; ensure it+ // exists in this test database.+ await prisma.dashboard.upsert({+ where: { id: LANGFUSE_HOME_DASHBOARD_ID },+ update: {},+ create: {+ id: LANGFUSE_HOME_DASHBOARD_ID,+ projectId: null,+ name: "Langfuse Home",+ description: "Curated home dashboard",+ definition: LANGFUSE_HOME_DASHBOARD_DEFINITION,+ },+ });+ });++ afterEach(async () => {+ // Pointer state is project-level; reset so tests stay independent.+ await prisma.project.update({+ where: { id: projectId },+ data: { homeDashboardId: null },+ });+ });++ it("falls back to the curated default when no pointer is set", async () => {+ const caller = makeCaller();++ const res = await caller.dashboard.getHomeDashboard({ projectId });++ expect(res.homeDashboardId).toBeNull();+ expect(res.dashboard?.id).toBe(LANGFUSE_HOME_DASHBOARD_ID);+ expect(res.dashboard?.owner).toBe("LANGFUSE");+ });++ it("resolves a set pointer and clears back to the default", async () => {+ const caller = makeCaller();+ const dashboard = await DashboardService.createDashboard(+ projectId,+ "My Home",+ "Project home dashboard",+ userId,+ );++ await caller.dashboard.setHomeDashboard({+ projectId,+ dashboardId: dashboard.id,+ });+ const res = await caller.dashboard.getHomeDashboard({ projectId });+ expect(res.homeDashboardId).toBe(dashboard.id);+ expect(res.dashboard?.id).toBe(dashboard.id);+ expect(res.dashboard?.owner).toBe("PROJECT");++ await caller.dashboard.setHomeDashboard({ projectId, dashboardId: null });+ const cleared = await caller.dashboard.getHomeDashboard({ projectId });+ expect(cleared.homeDashboardId).toBeNull();+ expect(cleared.dashboard?.id).toBe(LANGFUSE_HOME_DASHBOARD_ID);+ });++ it("rejects pointing at a nonexistent dashboard", async () => {+ const caller = makeCaller();++ await expect(+ caller.dashboard.setHomeDashboard({+ projectId,+ dashboardId: uuidv4(),+ }),+ ).rejects.toThrow("Dashboard not found");+ });++ it("falls back to the curated default when the pointed dashboard is deleted", async () => {+ const caller = makeCaller();+ const dashboard = await DashboardService.createDashboard(+ projectId,+ "Doomed Home",+ "Will be deleted",+ userId,+ );+ await caller.dashboard.setHomeDashboard({+ projectId,+ dashboardId: dashboard.id,+ });++ await DashboardService.deleteDashboard(dashboard.id, projectId);++ // The FK is ON DELETE SET NULL, so the pointer clears at the DB level.+ const res = await caller.dashboard.getHomeDashboard({ projectId });+ expect(res.homeDashboardId).toBeNull();+ expect(res.dashboard?.id).toBe(LANGFUSE_HOME_DASHBOARD_ID);+ });++ it("numbers clone names when copies already exist", async () => {+ const caller = makeCaller();+ const source = await DashboardService.createDashboard(+ projectId,+ "Numbering Source",+ "Clone naming test",+ userId,+ );++ const first = await caller.dashboard.cloneDashboard({+ projectId,+ dashboardId: source.id,+ });+ const second = await caller.dashboard.cloneDashboard({+ projectId,+ dashboardId: source.id,+ });+ const third = await caller.dashboard.cloneDashboard({+ projectId,+ dashboardId: source.id,+ });++ expect(first.name).toBe("Numbering Source (Clone)");+ expect(second.name).toBe("Numbering Source (Clone 2)");+ expect(third.name).toBe("Numbering Source (Clone 3)");+ });++ it("clones with a definition override and sets the clone as home", async () => {+ const caller = makeCaller();+ const overrideDefinition = {+ widgets: [+ {+ type: "preset" as const,+ id: "home-traces",+ presetId: "home-traces",+ x: 0,+ y: 0,+ x_size: 6,+ y_size: 4,+ },+ ],+ };++ const clone = await caller.dashboard.cloneDashboard({+ projectId,+ dashboardId: LANGFUSE_HOME_DASHBOARD_ID,+ definition: overrideDefinition,+ setAsHome: true,+ });++ expect(clone.owner).toBe("PROJECT");+ expect(clone.definition.widgets).toEqual(overrideDefinition.widgets);++ const res = await caller.dashboard.getHomeDashboard({ projectId });+ expect(res.homeDashboardId).toBe(clone.id);+ expect(res.dashboard?.id).toBe(clone.id);+ });});// ββ tRPC measure-aggregation validation ββββββββββββββββββββββββββββββdiff --git a/web/src/components/design-system/InlineEditText/InlineEditText.stories.tsx b/web/src/components/design-system/InlineEditText/InlineEditText.stories.tsxnew file mode 100644index 0000000000..848cdd73c7--- /dev/null+++ b/web/src/components/design-system/InlineEditText/InlineEditText.stories.tsx@@ -0,0 +1,85 @@+import { expect, fn, userEvent, within } from "storybook/test";+import preview from "../../../../.storybook/preview";+import { InlineEditText } from "./InlineEditText";++const meta = preview.meta({+ component: InlineEditText,+ args: {+ onSave: fn(),+ value: "Latency overview",+ },+});++export const Default = meta.story({});++export const Empty = meta.story({+ args: {+ value: "",+ placeholder: "Untitled dashboard",+ },+});++export const Disabled = meta.story({+ args: {+ disabled: true,+ },+});++export const WithLongValue = meta.story({+ args: {+ value:+ "A dashboard name that is far too long to fit comfortably in most layouts and should truncate",+ },+});++export const InHeading = meta.story({+ render: (args) => (+ <h2 className="text-lg leading-7 font-semibold">+ <InlineEditText {...args} />+ </h2>+ ),+});++export const TestCommitsOnEnter = meta.story({+ name: "(Test) Commits on Enter",+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button"));+ const input = canvas.getByRole("textbox");+ await userEvent.clear(input);+ await userEvent.type(input, "Renamed dashboard{enter}");+ await expect(args.onSave).toHaveBeenCalledWith("Renamed dashboard");+ // Back in display mode with the edit affordance+ await expect(canvas.getByRole("button")).toBeInTheDocument();+ },+});++export const TestEscapeReverts = meta.story({+ name: "(Test) Escape reverts",+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button"));+ const input = canvas.getByRole("textbox");+ await userEvent.clear(input);+ await userEvent.type(input, "Discarded{escape}");+ await expect(args.onSave).not.toHaveBeenCalled();+ await expect(canvas.getByRole("button")).toHaveTextContent(+ "Latency overview",+ );+ },+});++export const TestEmptyRequiredReverts = meta.story({+ name: "(Test) Empty required reverts",+ args: {+ required: true,+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button"));+ const input = canvas.getByRole("textbox");+ await userEvent.clear(input);+ await userEvent.keyboard("{enter}");+ await expect(args.onSave).not.toHaveBeenCalled();+ },+});diff --git a/web/src/components/design-system/InlineEditText/InlineEditText.tsx b/web/src/components/design-system/InlineEditText/InlineEditText.tsxnew file mode 100644index 0000000000..1766b28f54--- /dev/null+++ b/web/src/components/design-system/InlineEditText/InlineEditText.tsx@@ -0,0 +1,104 @@+import * as React from "react";+import { cn } from "@/src/utils/tailwind";++export interface InlineEditTextProps {+ value: string;+ /** Called with the trimmed value when a change is committed (Enter/blur). */+ onSave: (value: string) => void;+ /** Render as plain text without any edit affordance. */+ disabled?: boolean;+ /** Revert instead of committing an empty value. */+ required?: boolean;+ placeholder?: string;+ "aria-label"?: string;+}++/**+ * Click-to-edit text: renders as text (with a hover/focus pencil affordance),+ * turns into an input on click. Enter or blur commits, Escape reverts.+ * Inherits the surrounding typography so it can sit inside headings, labels,+ * or table cells.+ */+export const InlineEditText = ({+ value,+ onSave,+ disabled = false,+ required = false,+ placeholder,+ "aria-label": ariaLabel,+}: InlineEditTextProps) => {+ const [editing, setEditing] = React.useState(false);+ const [draft, setDraft] = React.useState(value);+ const inputRef = React.useRef<HTMLInputElement>(null);++ React.useEffect(() => {+ if (editing) {+ inputRef.current?.focus();+ inputRef.current?.select();+ }+ }, [editing]);++ const commit = () => {+ setEditing(false);+ const next = draft.trim();+ if (next === value.trim()) return;+ if (!next && required) return;+ onSave(next);+ };++ const cancel = () => {+ setEditing(false);+ setDraft(value);+ };++ if (disabled) {+ return <span className="wrap-break-word">{value}</span>;+ }++ if (editing) {+ return (+ <input+ ref={inputRef}+ value={draft}+ placeholder={placeholder}+ aria-label={ariaLabel ?? "Edit text"}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commit();+ } else if (e.key === "Escape") {+ e.preventDefault();+ cancel();+ }+ }}+ // size is the fallback width where field-sizing is unsupported+ size={Math.max(draft.length, 4)}+ // h-[1lh] + align-bottom keep the box exactly one text line tall in+ // both modes so swapping display/edit never changes layout height.+ className="ring-input focus:ring-ring field-sizing-content h-[1lh] max-w-full min-w-16 rounded-sm border-0 bg-transparent p-0 px-1 align-bottom ring-1 outline-hidden [font:inherit]"+ />+ );+ }++ return (+ <button+ type="button"+ onClick={() => {+ setDraft(value);+ setEditing(true);+ }}+ aria-label={ariaLabel ?? "Edit text"}+ title="Click to edit"+ className="hover:bg-accent/50 focus-visible:ring-ring inline-flex h-[1lh] max-w-full items-center rounded-sm px-1 text-left align-bottom [font:inherit] focus-visible:ring-2 focus-visible:outline-hidden"+ >+ <span+ title={value || placeholder}+ className={cn("truncate", !value && "text-muted-foreground")}+ >+ {value || placeholder}+ </span>+ </button>+ );+};diff --git a/web/src/components/layouts/page-header.tsx b/web/src/components/layouts/page-header.tsxindex 8cec5d9b67..1bce9afa1b 100644--- a/web/src/components/layouts/page-header.tsx+++ b/web/src/components/layouts/page-header.tsx@@ -40,6 +40,9 @@ const containerLayoutClassName =export type PageHeaderProps = {title: string;+ /** Rich title rendering (e.g. inline-editable); replaces the plain title+ * span inside the heading. `title` stays the canonical string. */+ titleContent?: ReactNode;breadcrumb?: { name: string; href?: string }[];actionButtonsLeft?: React.ReactNode; // Right-side actions (buttons, etc.)actionButtonsRight?: React.ReactNode; // Right-side actions (buttons, etc.)@@ -57,6 +60,7 @@ export type PageHeaderProps = {const PageHeader = ({title,+ titleContent,itemType,actionButtonsLeft,actionButtonsRight,@@ -139,7 +143,9 @@ const PageHeader = ({)}<div className="relative inline-block max-w-md md:max-w-none"><h2 className="line-clamp-1 text-lg leading-7 font-semibold">- {titleTooltip ? (+ {titleContent ? (+ titleContent+ ) : titleTooltip ? (<TooltipProvider><Tooltip><TooltipTrigger asChild>diff --git a/web/src/components/ui/combobox.tsx b/web/src/components/ui/combobox.tsxindex 38fe2bb007..e1ff3378f5 100644--- a/web/src/components/ui/combobox.tsx+++ b/web/src/components/ui/combobox.tsx@@ -18,12 +18,17 @@ import {PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";+import { Badge } from "@/src/components/ui/badge";export interface ComboboxOption<T extends string | number | boolean | { id: string },> {value: T;label?: string;+ /** Rendered before the label (e.g. a brand/ownership icon). */+ icon?: React.ReactNode;+ /** Small tag rendered after the label (e.g. "Default"). */+ badge?: string;disabled?: boolean;}@@ -123,9 +128,19 @@ export function Combobox<T extends string | number | boolean | { id: string }>({disabled={disabled}name={name}>+ {selectedOption?.icon && (+ <span className="mr-1.5 flex shrink-0 items-center">+ {selectedOption.icon}+ </span>+ )}<span className="truncate" title={buttonText}>{buttonText}</span>+ {selectedOption?.badge && (+ <Badge variant="secondary" className="ml-1.5 shrink-0">+ {selectedOption.badge}+ </Badge>+ )}<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /></Button></PopoverTrigger>@@ -145,7 +160,12 @@ export function Combobox<T extends string | number | boolean | { id: string }>({? (option.value as { id: string }).id: String(option.value)}- value={option.label ?? String(option.value)}+ value={+ typeof option.value === "object"+ ? (option.value as { id: string }).id+ : String(option.value)+ }+ keywords={[option.label ?? String(option.value)]}disabled={option.disabled}onSelect={() => {if (!option.disabled && onValueChange) {@@ -166,7 +186,17 @@ export function Combobox<T extends string | number | boolean | { id: string }>({: "opacity-0",)}/>+ {option.icon && (+ <span className="mr-1.5 flex shrink-0 items-center">+ {option.icon}+ </span>+ )}{option.label ?? String(option.value)}+ {option.badge && (+ <Badge variant="secondary" className="ml-auto">+ {option.badge}+ </Badge>+ )}</CommandItem>))}</CommandGroup>@@ -181,7 +211,12 @@ export function Combobox<T extends string | number | boolean | { id: string }>({? (option.value as { id: string }).id: String(option.value)}- value={option.label ?? String(option.value)}+ value={+ typeof option.value === "object"+ ? (option.value as { id: string }).id+ : String(option.value)+ }+ keywords={[option.label ?? String(option.value)]}disabled={option.disabled}onSelect={() => {if (!option.disabled && onValueChange) {@@ -202,7 +237,17 @@ export function Combobox<T extends string | number | boolean | { id: string }>({: "opacity-0",)}/>+ {option.icon && (+ <span className="mr-1.5 flex shrink-0 items-center">+ {option.icon}+ </span>+ )}{option.label ?? String(option.value)}+ {option.badge && (+ <Badge variant="secondary" className="ml-auto">+ {option.badge}+ </Badge>+ )}</CommandItem>))}</CommandGroup>diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsxindex 9258693915..6892527e70 100644--- a/web/src/features/dashboard/components/ChartScores.tsx+++ b/web/src/features/dashboard/components/ChartScores.tsx@@ -118,7 +118,7 @@ export function ChartScores(props: {isLoading={props.isLoading || scores.isPending}>{!isEmptyTimeSeries({ data: extractedScores }) ? (- <div className="min-h-80">+ <div className="h-80 w-full shrink-0"><ChartchartType="LINE_TIME_SERIES"data={chartData}diff --git a/web/src/features/dashboard/components/CloneFirstDialog.tsx b/web/src/features/dashboard/components/CloneFirstDialog.tsxnew file mode 100644index 0000000000..cfc54bd482--- /dev/null+++ b/web/src/features/dashboard/components/CloneFirstDialog.tsx@@ -0,0 +1,202 @@+import React, { useMemo } from "react";+import { useRouter } from "next/router";+import { ExternalLinkIcon } from "lucide-react";+import { api } from "@/src/utils/api";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+ DialogBody,+} from "@/src/components/ui/dialog";+import { Button } from "@/src/components/ui/button";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { type DashboardPlacement } from "@/src/features/widgets/components/DashboardGrid";++/**+ * Clone-first flow for Langfuse-managed (read-only) dashboards: any edit+ * attempt routes here instead of being blocked. Confirming clones the+ * dashboard into the project (optionally carrying the attempted change via+ * `pendingDefinition` and setting the clone as the project's Home) and+ * navigates to the editable copy.+ */+export function CloneFirstDialog({+ open,+ onOpenChange,+ projectId,+ dashboardId,+ dashboardName,+ setAsHome = false,+ pendingDefinition,+ onCancel,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ projectId: string;+ dashboardId: string;+ dashboardName: string;+ /** Set the clone as this project's Home dashboard in the same gesture. */+ setAsHome?: boolean;+ /** The attempted edit (e.g. moved/removed tile) to apply to the clone. */+ pendingDefinition?: { widgets: DashboardPlacement[] } | null;+ /** Called when the user dismisses without cloning (revert the attempt). */+ onCancel?: () => void;+}) {+ const router = useRouter();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();++ // Detect existing copies of this dashboard so we can offer navigating to+ // one instead of accumulating "(Clone)" duplicates.+ const dashboards = api.dashboard.allDashboards.useQuery(+ {+ projectId,+ page: 1,+ limit: 500,+ orderBy: { column: "updatedAt", order: "DESC" },+ },+ { enabled: open },+ );+ const existingClone = useMemo(() => {+ const clonePattern = new RegExp(+ `^${dashboardName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} \\(Clone( \\d+)?\\)$`,+ );+ return dashboards.data?.dashboards.find(+ (d) => d.owner === "PROJECT" && clonePattern.test(d.name),+ );+ }, [dashboards.data?.dashboards, dashboardName]);++ const cloneDashboard = api.dashboard.cloneDashboard.useMutation({+ onSuccess: (data) => {+ utils.dashboard.invalidate();+ capture("dashboard:clone_dashboard", {+ source: "clone_first_dialog",+ set_as_home: setAsHome,+ had_pending_change: Boolean(pendingDefinition),+ });+ showSuccessToast({+ title: "Editable copy created",+ description: setAsHome+ ? "The copy is now this project's Home dashboard"+ : "You are now working on your own copy",+ duration: 3000,+ });+ onOpenChange(false);+ if (data?.id) {+ router.push(+ `/project/${projectId}/dashboards/${encodeURIComponent(data.id)}`,+ );+ }+ },+ onError: (e) => {+ showErrorToast("Failed to create copy", e.message);+ },+ });++ const handleConfirm = () => {+ cloneDashboard.mutate({+ projectId,+ dashboardId,+ definition: pendingDefinition ?? undefined,+ setAsHome,+ });+ };++ const handleOpenChange = (nextOpen: boolean) => {+ // Keep the dialog open while the clone is in flight (it navigates on+ // success); closing mid-flight would revert the grid and then surprise-+ // navigate.+ if (!nextOpen && cloneDashboard.isPending) return;+ if (!nextOpen) {+ capture("dashboard:clone_first_cancelled", {+ dashboard_id: dashboardId,+ had_pending_change: Boolean(pendingDefinition),+ });+ onCancel?.();+ }+ onOpenChange(nextOpen);+ };++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="sm:max-w-[500px]">+ <DialogHeader>+ <DialogTitle>Create your editable copy</DialogTitle>+ </DialogHeader>+ <DialogBody>+ <div className="text-muted-foreground grid gap-3 py-4 text-sm">+ <p>+ <span className="text-foreground font-medium">+ “{dashboardName}”+ </span>{" "}+ is maintained by Langfuse and can’t be edited directly.+ We’ll create your own editable copy in this project+ {pendingDefinition ? " with your change applied" : ""}+ {setAsHome ? " and show it on your Home page from now on" : ""}.+ </p>+ <p>+ Langfuse-maintained tiles on the copy can be rearranged or+ removed; editing their content will become available in a future+ release.+ </p>+ {existingClone && (+ <div className="bg-muted/50 flex flex-wrap items-center justify-between gap-2 rounded-md border p-3">+ <span>+ You already have a copy:{" "}+ <span className="text-foreground font-medium">+ “{existingClone.name}”+ </span>+ {pendingDefinition+ ? " β opening it will discard your attempted change"+ : ""}+ </span>+ <Button+ variant="outline"+ size="sm"+ type="button"+ onClick={() => {+ capture("dashboard:clone_open_existing_click", {+ dashboard_id: dashboardId,+ existing_clone_id: existingClone.id,+ had_pending_change: Boolean(pendingDefinition),+ });+ onOpenChange(false);+ onCancel?.();+ router.push(+ `/project/${projectId}/dashboards/${encodeURIComponent(existingClone.id)}`,+ );+ }}+ >+ <ExternalLinkIcon size={14} className="mr-1" />+ Open it instead+ </Button>+ </div>+ )}+ </div>+ </DialogBody>+ <DialogFooter>+ <div className="flex gap-2">+ <Button+ onClick={() => handleOpenChange(false)}+ variant="outline"+ type="button"+ disabled={cloneDashboard.isPending}+ >+ Cancel+ </Button>+ <Button+ onClick={handleConfirm}+ type="button"+ loading={cloneDashboard.isPending}+ >+ Create my copy+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/dashboard/components/DashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable.tsxindex 89e16f41e2..d30879ba61 100644--- a/web/src/features/dashboard/components/DashboardTable.tsx+++ b/web/src/features/dashboard/components/DashboardTable.tsx@@ -25,6 +25,7 @@ import {} from "@/src/components/ui/dropdown-menu";import { DeleteDashboardButton } from "@/src/components/deleteButton";import { EditDashboardDialog } from "@/src/features/dashboard/components/EditDashboardDialog";+import { CloneFirstDialog } from "@/src/features/dashboard/components/CloneFirstDialog";import { User as UserIcon } from "lucide-react";import { useRouter } from "next/router";@@ -51,7 +52,7 @@ function CloneDashboardButton({const mutCloneDashboard = api.dashboard.cloneDashboard.useMutation({onSuccess: () => {utils.dashboard.invalidate();- capture("dashboard:clone_dashboard");+ capture("dashboard:clone_dashboard", { source: "list_clone_button" });showSuccessToast({title: "Dashboard cloned",description: "The dashboard has been cloned successfully",@@ -125,6 +126,49 @@ function EditDashboardButton({);}+function LockedEditDashboardButton({+ dashboardId,+ projectId,+ dashboardName,+}: {+ dashboardId: string;+ projectId: string;+ dashboardName: string;+}) {+ const [isDialogOpen, setIsDialogOpen] = useState(false);+ const hasAccess = useHasProjectAccess({ projectId, scope: "dashboards:CUD" });+ const capture = usePostHogClientCapture();++ return (+ <>+ <Button+ variant="ghost"+ size="default"+ disabled={!hasAccess}+ onClick={() => {+ capture("dashboard:locked_edit_attempt", {+ dashboard_id: dashboardId,+ attempt: "list_edit",+ surface: "list",+ });+ setIsDialogOpen(true);+ }}+ >+ <Edit className="mr-2 h-4 w-4" />+ Edit+ </Button>++ <CloneFirstDialog+ open={isDialogOpen}+ onOpenChange={setIsDialogOpen}+ projectId={projectId}+ dashboardId={dashboardId}+ dashboardName={dashboardName}+ />+ </>+ );+}+export function DashboardTable() {const projectId = useProjectIdFromURL() as string;const { setDetailPageList } = useDetailPageLists();@@ -248,7 +292,7 @@ export function DashboardTable() {</Button></DropdownMenuTrigger><DropdownMenuContent className="flex flex-col *:w-full *:justify-start">- {owner === "PROJECT" && (+ {owner === "PROJECT" ? (<DropdownMenuItem asChild><EditDashboardButtondashboardId={id}@@ -257,6 +301,14 @@ export function DashboardTable() {dashboardDescription={description}/></DropdownMenuItem>+ ) : (+ <DropdownMenuItem asChild>+ <LockedEditDashboardButton+ dashboardId={id}+ projectId={projectId}+ dashboardName={name}+ />+ </DropdownMenuItem>)}<DropdownMenuItem asChild><CloneDashboardButtondiff --git a/web/src/features/dashboard/components/EditDashboardDialog.tsx b/web/src/features/dashboard/components/EditDashboardDialog.tsxindex 27553e8d69..71efa3e38e 100644--- a/web/src/features/dashboard/components/EditDashboardDialog.tsx+++ b/web/src/features/dashboard/components/EditDashboardDialog.tsx@@ -12,7 +12,6 @@ import { Button } from "@/src/components/ui/button";import { Input } from "@/src/components/ui/input";import { Label } from "@/src/components/ui/label";import { Textarea } from "@/src/components/ui/textarea";-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { showErrorToast } from "@/src/features/notifications/showErrorToast";interface EditDashboardDialogProps {@@ -39,10 +38,6 @@ export function EditDashboardDialog({const updateDashboard = api.dashboard.updateDashboardMetadata.useMutation({onSuccess: () => {utils.dashboard.invalidate();- showSuccessToast({- title: "Dashboard updated",- description: "The dashboard has been updated successfully",- });onOpenChange(false);},onError: (e) => {diff --git a/web/src/features/dashboard/components/HomeDashboardSelect.tsx b/web/src/features/dashboard/components/HomeDashboardSelect.tsxnew file mode 100644index 0000000000..24619be906--- /dev/null+++ b/web/src/features/dashboard/components/HomeDashboardSelect.tsx@@ -0,0 +1,100 @@+import { useMemo } from "react";+import { LayoutDashboard } from "lucide-react";+import { api } from "@/src/utils/api";+import { Combobox } from "@/src/components/ui/combobox";+import { LangfuseIcon } from "@/src/components/design-system/LangfuseIcon/LangfuseIcon";+import { Button } from "@/src/components/ui/button";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";++/**+ * Home's dashboard picker: selecting immediately shows ("peeks") the chosen+ * dashboard on Home without changing anything for the project. Persisting it+ * as the project default is a separate, explicit "Set default" action owned+ * by the Home page.+ */+export function HomeDashboardSelect({+ projectId,+ value,+ defaultDashboardId,+ onValueChange,+ currentDashboardName,+}: {+ projectId: string;+ /** Id of the dashboard currently displayed on Home. */+ value: string;+ /** The project's persisted default (pointer or the curated fallback). */+ defaultDashboardId: string;+ onValueChange: (dashboardId: string) => void;+ currentDashboardName: string;+}) {+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });++ const dashboards = api.dashboard.allDashboards.useQuery(+ {+ projectId,+ page: 1,+ limit: 500,+ orderBy: { column: "name", order: "ASC" },+ },+ { enabled: Boolean(projectId) && hasCUDAccess },+ );++ const options = useMemo(() => {+ const items = dashboards.data?.dashboards ?? [];+ const toOption = (d: { id: string; name: string; owner: string }) => ({+ value: d.id,+ label: d.name,+ ...(d.owner === "LANGFUSE" ? { icon: <LangfuseIcon size={14} /> } : {}),+ ...(d.id === defaultDashboardId ? { badge: "Default" } : {}),+ });+ const curated = items.filter((d) => d.owner === "LANGFUSE");+ const project = items.filter((d) => d.owner === "PROJECT");+ return [+ ...(project.length > 0+ ? [+ {+ heading: "This project",+ options: project.map(toOption),+ },+ ]+ : []),+ {+ heading: "Langfuse-maintained",+ options: curated.map(toOption),+ },+ ];+ }, [dashboards.data?.dashboards, defaultDashboardId]);++ if (!hasCUDAccess) {+ return (+ <Button+ variant="ghost"+ disabled+ title="The dashboard shown on this project's home page"+ className="text-muted-foreground my-0"+ >+ <LayoutDashboard className="mr-1 h-4 w-4" />+ {currentDashboardName}+ </Button>+ );+ }++ return (+ <Combobox+ options={options}+ value={value}+ onValueChange={(id) => {+ if (typeof id !== "string" || id === value) return;+ onValueChange(id);+ }}+ placeholder={currentDashboardName}+ searchPlaceholder="Search dashboards..."+ emptyText="No dashboards found"+ className="my-0 w-auto max-w-56"+ name="home-dashboard"+ />+ );+}diff --git a/web/src/features/dashboard/components/LatencyTables.tsx b/web/src/features/dashboard/components/LatencyTables.tsxindex da3919d4e7..1ef69dd165 100644--- a/web/src/features/dashboard/components/LatencyTables.tsx+++ b/web/src/features/dashboard/components/LatencyTables.tsx@@ -14,7 +14,151 @@ import { type QueryType, type ViewVersion } from "@langfuse/shared/query";import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";-export const LatencyTables = ({+export type LatencyTableKind = "traces" | "generations" | "observations";++const LATENCY_TABLE_KINDS: Record<+ LatencyTableKind,+ {+ title: string;+ nameHeader: string;+ buildQuery: (+ globalFilterState: FilterState,+ fromTimestamp: Date,+ toTimestamp: Date,+ ) => QueryType;+ }+> = {+ traces: {+ title: "Trace latency percentiles",+ nameHeader: "Trace Name",+ buildQuery: (globalFilterState, fromTimestamp, toTimestamp) => ({+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "latency", aggregation: "p50" },+ { measure: "latency", aggregation: "p90" },+ { measure: "latency", aggregation: "p95" },+ { measure: "latency", aggregation: "p99" },+ ],+ filters: mapLegacyUiTableFilterToView("traces", globalFilterState),+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: [{ field: "p95_latency", direction: "desc" }],+ chartConfig: { type: "table", row_limit: 20 },+ }),+ },+ generations: {+ title: "Generation latency percentiles",+ nameHeader: "Generation Name",+ buildQuery: (globalFilterState, fromTimestamp, toTimestamp) => ({+ view: "observations",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "latency", aggregation: "p50" },+ { measure: "latency", aggregation: "p90" },+ { measure: "latency", aggregation: "p95" },+ { measure: "latency", aggregation: "p99" },+ ],+ filters: [+ ...mapLegacyUiTableFilterToView("observations", globalFilterState),+ {+ column: "type",+ operator: "any of",+ value: getGenerationLikeTypes(),+ type: "stringOptions",+ },+ ],+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: [{ field: "p95_latency", direction: "desc" }],+ chartConfig: { type: "table", row_limit: 20 },+ }),+ },+ observations: {+ title: "Observation latency percentiles",+ nameHeader: "Observation",+ buildQuery: (globalFilterState, fromTimestamp, toTimestamp) => ({+ view: "observations",+ dimensions: [{ field: "type" }, { field: "name" }],+ metrics: [+ { measure: "latency", aggregation: "p50" },+ { measure: "latency", aggregation: "p90" },+ { measure: "latency", aggregation: "p95" },+ { measure: "latency", aggregation: "p99" },+ ],+ filters: [+ ...mapLegacyUiTableFilterToView("observations", globalFilterState),+ {+ column: "type",+ operator: "none of",+ value: [ObservationType.GENERATION],+ type: "stringOptions",+ },+ ],+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: [{ field: "p95_latency", direction: "desc" }],+ chartConfig: { type: "table", row_limit: 20 },+ }),+ },+};++const generateLatencyData = (data?: Record<string, unknown>[]) => {+ return data+ ? data+ .filter((item) => item.name !== null)+ .map((item, i) => [+ <div key={`${item.name as string}-${i}`}>+ <Popup+ triggerContent={+ item.type ? (+ <div className="flex items-center gap-2">+ <span className="text-muted-foreground text-[10px] font-medium tracking-wide uppercase">+ {String(item.type)}+ </span>+ <span>{truncate(item.name as string)}</span>+ </div>+ ) : (+ truncate(item.name as string)+ )+ }+ description={+ item.type+ ? `${String(item.type)} Β· ${item.name as string}`+ : (item.name as string)+ }+ />+ </div>,+ <RightAlignedCell key={`${i}-p50`}>+ {item.p50_latency+ ? formatIntervalSeconds(Number(item.p50_latency) / 1000, 2)+ : "-"}+ </RightAlignedCell>,+ <RightAlignedCell key={`${i}-p90`}>+ {item.p90_latency+ ? formatIntervalSeconds(Number(item.p90_latency) / 1000, 2)+ : "-"}+ </RightAlignedCell>,+ <RightAlignedCell key={`${i}-p95`}>+ {item.p95_latency+ ? formatIntervalSeconds(Number(item.p95_latency) / 1000, 2)+ : "-"}+ </RightAlignedCell>,+ <RightAlignedCell key={`${i}-p99`}>+ {item.p99_latency+ ? formatIntervalSeconds(Number(item.p99_latency) / 1000, 2)+ : "-"}+ </RightAlignedCell>,+ ])+ : [];+};++export const LatencyTable = ({+ kind,+ className,projectId,globalFilterState,fromTimestamp,@@ -23,6 +167,8 @@ export const LatencyTables = ({metricsVersion,schedulerId,}: {+ kind: LatencyTableKind;+ className?: string;projectId: string;globalFilterState: FilterState;fromTimestamp: Date;@@ -31,111 +177,12 @@ export const LatencyTables = ({metricsVersion?: ViewVersion;schedulerId?: string;}) => {- const generationsLatenciesQuery: QueryType = {- view: "observations",- dimensions: [{ field: "name" }],- metrics: [- { measure: "latency", aggregation: "p50" },- { measure: "latency", aggregation: "p90" },- { measure: "latency", aggregation: "p95" },- { measure: "latency", aggregation: "p99" },- ],- filters: [- ...mapLegacyUiTableFilterToView("observations", globalFilterState),- {- column: "type",- operator: "any of",- value: getGenerationLikeTypes(),- type: "stringOptions",- },- ],- timeDimension: null,- fromTimestamp: fromTimestamp.toISOString(),- toTimestamp: toTimestamp.toISOString(),- orderBy: [{ field: "p95_latency", direction: "desc" }],- chartConfig: { type: "table", row_limit: 20 },- };-- const generationsLatencies = useScheduledDashboardExecuteQuery(- {- projectId,- query: generationsLatenciesQuery,- version: metricsVersion,- },- {- trpc: {- context: {- skipBatch: true,- },- },- queryId: `${schedulerId ?? "home:latency-tables"}:generations`,- enabled: !isLoading,- },- );-- const observationsLatenciesQuery: QueryType = {- view: "observations",- dimensions: [{ field: "type" }, { field: "name" }],- metrics: [- { measure: "latency", aggregation: "p50" },- { measure: "latency", aggregation: "p90" },- { measure: "latency", aggregation: "p95" },- { measure: "latency", aggregation: "p99" },- ],- filters: [- ...mapLegacyUiTableFilterToView("observations", globalFilterState),- {- column: "type",- operator: "none of",- value: [ObservationType.GENERATION],- type: "stringOptions",- },- ],- timeDimension: null,- fromTimestamp: fromTimestamp.toISOString(),- toTimestamp: toTimestamp.toISOString(),- orderBy: [{ field: "p95_latency", direction: "desc" }],- chartConfig: { type: "table", row_limit: 20 },- };-- const observationsLatencies = useScheduledDashboardExecuteQuery(- {- projectId,- query: observationsLatenciesQuery,- version: metricsVersion,- },- {- trpc: {- context: {- skipBatch: true,- },- },- queryId: `${schedulerId ?? "home:latency-tables"}:observations`,- enabled: !isLoading,- },- );+ const { title, nameHeader, buildQuery } = LATENCY_TABLE_KINDS[kind];- const tracesLatenciesQuery: QueryType = {- view: "traces",- dimensions: [{ field: "name" }],- metrics: [- { measure: "latency", aggregation: "p50" },- { measure: "latency", aggregation: "p90" },- { measure: "latency", aggregation: "p95" },- { measure: "latency", aggregation: "p99" },- ],- filters: mapLegacyUiTableFilterToView("traces", globalFilterState),- timeDimension: null,- fromTimestamp: fromTimestamp.toISOString(),- toTimestamp: toTimestamp.toISOString(),- orderBy: [{ field: "p95_latency", direction: "desc" }],- chartConfig: { type: "table", row_limit: 20 },- };-- const tracesLatencies = useScheduledDashboardExecuteQuery(+ const latencies = useScheduledDashboardExecuteQuery({projectId,- query: tracesLatenciesQuery,+ query: buildQuery(globalFilterState, fromTimestamp, toTimestamp),version: metricsVersion,},{@@ -144,123 +191,31 @@ export const LatencyTables = ({skipBatch: true,},},- queryId: `${schedulerId ?? "home:latency-tables"}:traces`,+ queryId: schedulerId ?? `home:latency-table-${kind}`,enabled: !isLoading,},);- const generateLatencyData = (data?: Record<string, unknown>[]) => {- return data- ? data- .filter((item) => item.name !== null)- .map((item, i) => [- <div key={`${item.name as string}-${i}`}>- <Popup- triggerContent={- item.type ? (- <div className="flex items-center gap-2">- <span className="text-muted-foreground text-[10px] font-medium tracking-wide uppercase">- {String(item.type)}- </span>- <span>{truncate(item.name as string)}</span>- </div>- ) : (- truncate(item.name as string)- )- }- description={- item.type- ? `${String(item.type)} Β· ${item.name as string}`- : (item.name as string)- }- />- </div>,- <RightAlignedCell key={`${i}-p50`}>- {item.p50_latency- ? formatIntervalSeconds(Number(item.p50_latency) / 1000, 2)- : "-"}- </RightAlignedCell>,- <RightAlignedCell key={`${i}-p90`}>- {item.p90_latency- ? formatIntervalSeconds(Number(item.p90_latency) / 1000, 2)- : "-"}- </RightAlignedCell>,- <RightAlignedCell key={`${i}-p95`}>- {item.p95_latency- ? formatIntervalSeconds(Number(item.p95_latency) / 1000, 2)- : "-"}- </RightAlignedCell>,- <RightAlignedCell key={`${i}-p99`}>- {item.p99_latency- ? formatIntervalSeconds(Number(item.p99_latency) / 1000, 2)- : "-"}- </RightAlignedCell>,- ])- : [];- };-return (- <>- <DashboardCard- className="col-span-1 xl:col-span-2"- title="Trace latency percentiles"- isLoading={isLoading || tracesLatencies.isPending}- >- <DashboardTable- headers={[- "Trace Name",- <RightAlignedCell key="p50">p50</RightAlignedCell>,- <RightAlignedCell key="p90">p90</RightAlignedCell>,- <RightAlignedCell key="p95">- p95<span className="ml-1">βΌ</span>- </RightAlignedCell>,- <RightAlignedCell key="p99">p99</RightAlignedCell>,- ]}- rows={generateLatencyData(tracesLatencies.data)}- isLoading={isLoading || tracesLatencies.isPending}- collapse={{ collapsed: 5, expanded: 20 }}- />- </DashboardCard>- <DashboardCard- className="col-span-1 xl:col-span-2"- title="Generation latency percentiles"- isLoading={isLoading || generationsLatencies.isPending}- >- <DashboardTable- headers={[- "Generation Name",- <RightAlignedCell key="p50">p50</RightAlignedCell>,- <RightAlignedCell key="p90">p90</RightAlignedCell>,- <RightAlignedCell key="p95">- p95<span className="ml-1">βΌ</span>- </RightAlignedCell>,- <RightAlignedCell key="p99">p99</RightAlignedCell>,- ]}- rows={generateLatencyData(generationsLatencies.data)}- isLoading={isLoading || generationsLatencies.isPending}- collapse={{ collapsed: 5, expanded: 20 }}- />- </DashboardCard>- <DashboardCard- className="col-span-1 xl:col-span-2"- title="Observation latency percentiles"- isLoading={isLoading || observationsLatencies.isPending}- >- <DashboardTable- headers={[- "Observation",- <RightAlignedCell key="p50">p50</RightAlignedCell>,- <RightAlignedCell key="p90">p90</RightAlignedCell>,- <RightAlignedCell key="p95">- p95<span className="ml-1">βΌ</span>- </RightAlignedCell>,- <RightAlignedCell key="p99">p99</RightAlignedCell>,- ]}- rows={generateLatencyData(observationsLatencies.data)}- isLoading={isLoading || observationsLatencies.isPending}- collapse={{ collapsed: 5, expanded: 20 }}- />- </DashboardCard>- </>+ <DashboardCard+ className={className}+ title={title}+ isLoading={isLoading || latencies.isPending}+ >+ <DashboardTable+ headers={[+ nameHeader,+ <RightAlignedCell key="p50">p50</RightAlignedCell>,+ <RightAlignedCell key="p90">p90</RightAlignedCell>,+ <RightAlignedCell key="p95">+ p95<span className="ml-1">βΌ</span>+ </RightAlignedCell>,+ <RightAlignedCell key="p99">p99</RightAlignedCell>,+ ]}+ rows={generateLatencyData(latencies.data)}+ isLoading={isLoading || latencies.isPending}+ collapse={{ collapsed: 5, expanded: 20 }}+ />+ </DashboardCard>);};diff --git a/web/src/features/dashboard/components/home-preset-registry.tsx b/web/src/features/dashboard/components/home-preset-registry.tsxnew file mode 100644index 0000000000..798c8ce142--- /dev/null+++ b/web/src/features/dashboard/components/home-preset-registry.tsx@@ -0,0 +1,285 @@+import { type ReactNode } from "react";+import { type FilterState, type HomeDashboardPresetId } from "@langfuse/shared";+import { type ViewVersion } from "@langfuse/shared/query";+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";+import { TracesBarListChart } from "@/src/features/dashboard/components/TracesBarListChart";+import { ModelCostTable } from "@/src/features/dashboard/components/ModelCostTable";+import { ScoresTable } from "@/src/features/dashboard/components/ScoresTable";+import { TracesAndObservationsTimeSeriesChart } from "@/src/features/dashboard/components/TracesTimeSeriesChart";+import { ModelUsageChart } from "@/src/features/dashboard/components/ModelUsageChart";+import { UserChart } from "@/src/features/dashboard/components/UserChart";+import { ChartScores } from "@/src/features/dashboard/components/ChartScores";+import { LatencyTable } from "@/src/features/dashboard/components/LatencyTables";+import { GenerationLatencyChart } from "@/src/features/dashboard/components/LatencyChart";+import { ScoreAnalytics } from "@/src/features/dashboard/components/score-analytics/ScoreAnalytics";++/**+ * Props bag a "preset" dashboard placement is rendered with. Derived by+ * PresetDashboardWidget from the surrounding dashboard's state (time range,+ * filters, scheduler) so the registered Home cards receive the same props the+ * bespoke Home page used to pass them.+ */+export interface PresetWidgetContext {+ projectId: string;+ /** Page-level filters WITHOUT the time window (time arrives as timestamps). */+ globalFilterState: FilterState;+ /** globalFilterState plus the time window as datetime filters β for legacy cards that expect it inline. */+ mergedFilterState: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;+ agg: DashboardDateRangeAggregationOption;+ isLoading: boolean;+ metricsVersion: ViewVersion;+ schedulerId?: string;+ /** Shared recharts syncId so time-series tiles move their crosshairs together. */+ syncId: string;+ className: string;+}++/**+ * presetId β existing Home card component, rendered verbatim with its+ * existing data fetches (LFE-10693 phase 1: presets reuse today's queries+ * untouched). Keyed by the shared HomeDashboardPresetId union so this registry+ * and the curated Home dashboard definition cannot drift apart silently.+ */+const HOME_PRESETS: Record<+ HomeDashboardPresetId,+ (ctx: PresetWidgetContext) => ReactNode+> = {+ "home-traces": (ctx) => (+ <TracesBarListChart+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ />+ ),+ "home-model-costs": (ctx) => (+ <ModelCostTable+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ />+ ),+ "home-scores-table": (ctx) => (+ <ScoresTable+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.mergedFilterState}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ />+ ),+ "home-traces-obs-time-series": (ctx) => (+ <TracesAndObservationsTimeSeriesChart+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ agg={ctx.agg}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ syncId={ctx.syncId}+ />+ ),+ "home-model-usage": (ctx) => (+ <ModelUsageChart+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.mergedFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ userAndEnvFilterState={ctx.globalFilterState}+ agg={ctx.agg}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ syncId={ctx.syncId}+ />+ ),+ "home-users": (ctx) => (+ <UserChart+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ />+ ),+ "home-chart-scores": (ctx) => (+ <ChartScores+ className={ctx.className}+ agg={ctx.agg}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ syncId={ctx.syncId}+ />+ ),+ "home-latency-table-traces": (ctx) => (+ <LatencyTable+ kind="traces"+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ />+ ),+ "home-latency-table-generations": (ctx) => (+ <LatencyTable+ kind="generations"+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ />+ ),+ "home-latency-table-observations": (ctx) => (+ <LatencyTable+ kind="observations"+ className={ctx.className}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ />+ ),+ "home-generation-latency": (ctx) => (+ <GenerationLatencyChart+ className={ctx.className}+ projectId={ctx.projectId}+ agg={ctx.agg}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ syncId={ctx.syncId}+ />+ ),+ "home-score-analytics": (ctx) => (+ <ScoreAnalytics+ className={ctx.className}+ agg={ctx.agg}+ projectId={ctx.projectId}+ globalFilterState={ctx.globalFilterState}+ fromTimestamp={ctx.fromTimestamp}+ toTimestamp={ctx.toTimestamp}+ isLoading={ctx.isLoading}+ metricsVersion={ctx.metricsVersion}+ schedulerId={ctx.schedulerId}+ syncId={ctx.syncId}+ />+ ),+};++/**+ * Display metadata for the preset picker (Add Widget dialog). `illustration`+ * keys into ChartTypeIllustration.+ */+export const HOME_PRESET_METADATA: Record<+ HomeDashboardPresetId,+ { name: string; description: string; illustration: string }+> = {+ "home-traces": {+ name: "Traces",+ description: "Total traces with the top trace names",+ illustration: "HORIZONTAL_BAR",+ },+ "home-model-costs": {+ name: "Model Costs",+ description: "Cost and token usage per model",+ illustration: "PIVOT_TABLE",+ },+ "home-scores-table": {+ name: "Scores",+ description: "Score counts and averages by name",+ illustration: "PIVOT_TABLE",+ },+ "home-traces-obs-time-series": {+ name: "Traces & Observations over time",+ description: "Traffic volume with tabbed trace/observation views",+ illustration: "BAR_TIME_SERIES",+ },+ "home-model-usage": {+ name: "Model Usage",+ description: "Cost and usage over time, by model or by type",+ illustration: "AREA_TIME_SERIES",+ },+ "home-users": {+ name: "User Consumption",+ description: "Token cost and trace counts per user",+ illustration: "HORIZONTAL_BAR",+ },+ "home-chart-scores": {+ name: "Scores over time",+ description: "Moving average per score",+ illustration: "LINE_TIME_SERIES",+ },+ "home-latency-table-traces": {+ name: "Trace Latency Percentiles",+ description: "p50βp99 latencies per trace name",+ illustration: "PIVOT_TABLE",+ },+ "home-latency-table-generations": {+ name: "Generation Latency Percentiles",+ description: "p50βp99 latencies per generation name",+ illustration: "PIVOT_TABLE",+ },+ "home-latency-table-observations": {+ name: "Observation Latency Percentiles",+ description: "p50βp99 latencies per observation type and name",+ illustration: "PIVOT_TABLE",+ },+ "home-generation-latency": {+ name: "Model Latencies",+ description: "Latency percentiles per LLM, tabbed by percentile",+ illustration: "LINE_TIME_SERIES",+ },+ "home-score-analytics": {+ name: "Score Analytics",+ description: "Per-score charts and distributions for selected scores",+ illustration: "HISTOGRAM",+ },+};++export function getHomePreset(+ presetId: string,+): ((ctx: PresetWidgetContext) => ReactNode) | undefined {+ return (+ HOME_PRESETS as Record<+ string,+ ((ctx: PresetWidgetContext) => ReactNode) | undefined+ >+ )[presetId];+}diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 4791a3498b..a95e094536 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -34,6 +34,7 @@ import {StringNoHTML,InvalidRequestError,singleFilter,+ LANGFUSE_HOME_DASHBOARD_ID,type FilterState,} from "@langfuse/shared";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";@@ -42,6 +43,9 @@ import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAcconst ListDashboardsInput = z.object({projectId: z.string(),...paginationZod,+ // The Home-dashboard picker and clone detection fetch the whole list in one+ // page, so allow a higher ceiling than the default table pagination.+ limit: z.coerce.number().int().positive().lte(500).default(50),orderBy: orderBy,});@@ -77,6 +81,18 @@ const CreateDashboardInput = z.object({const CloneDashboardInput = z.object({projectId: z.string(),dashboardId: z.string(),+ // Optional definition override so an edit attempted on a read-only+ // dashboard (e.g. a tile moved on the curated Home) carries into the clone.+ definition: DashboardDefinitionSchema.optional(),+ // Set the clone as the project's home dashboard in the same gesture.+ setAsHome: z.boolean().optional(),+});++// Set home dashboard input schema+const SetHomeDashboardInput = z.object({+ projectId: z.string(),+ // null resets to the Langfuse-curated default+ dashboardId: z.string().min(1).nullable(),});// Update dashboard filters input schema@@ -86,6 +102,18 @@ const UpdateDashboardFiltersInput = z.object({filters: z.array(singleFilter),});+/**+ * First free clone name: "ABC (Clone)", then "ABC (Clone 2)", "ABC (Clone 3)", β¦+ */+function nextCloneName(sourceName: string, existingNames: string[]): string {+ const taken = new Set(existingNames);+ const base = `${sourceName} (Clone)`;+ if (!taken.has(base)) return base;+ let n = 2;+ while (taken.has(`${sourceName} (Clone ${n})`)) n++;+ return `${sourceName} (Clone ${n})`;+}+// Map camelCase legacy column names (used by scoreHistogram component)// to view-native field names before passing through the general mapper.const LEGACY_CAMEL_CASE_MAP: Record<string, string> = {@@ -575,18 +603,106 @@ export const dashboardRouter = createTRPCRouter({});}- // Create a new dashboard with the same data but modified name+ // Create a new dashboard with the same data but a numbered clone name+ const existingClones = await ctx.prisma.dashboard.findMany({+ where: {+ projectId: input.projectId,+ name: { startsWith: `${sourceDashboard.name} (Clone` },+ },+ select: { name: true },+ });+const clonedDashboard = await DashboardService.createDashboard(input.projectId,- `${sourceDashboard.name} (Clone)`,+ nextCloneName(+ sourceDashboard.name,+ existingClones.map((d) => d.name),+ ),sourceDashboard.description,ctx.session.user.id,- sourceDashboard.definition,+ input.definition ?? sourceDashboard.definition,);+ if (input.setAsHome) {+ await ctx.prisma.project.update({+ where: { id: input.projectId },+ data: { homeDashboardId: clonedDashboard.id },+ });+ }+return clonedDashboard;}),+ getHomeDashboard: protectedProjectProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:read",+ });++ const project = await ctx.prisma.project.findUnique({+ where: { id: input.projectId },+ select: { homeDashboardId: true },+ });++ // Resolve the pointer; a missing/foreign target silently falls back to+ // the Langfuse-curated default (like an unset pointer).+ const pointedDashboard = project?.homeDashboardId+ ? await DashboardService.getDashboard(+ project.homeDashboardId,+ input.projectId,+ )+ : null;++ const dashboard =+ pointedDashboard ??+ (await DashboardService.getDashboard(+ LANGFUSE_HOME_DASHBOARD_ID,+ input.projectId,+ ));++ return {+ // null only when the curated row is also absent β the client then+ // renders from the shared constant.+ dashboard,+ homeDashboardId: pointedDashboard+ ? (project?.homeDashboardId ?? null)+ : null,+ };+ }),++ setHomeDashboard: protectedProjectProcedure+ .input(SetHomeDashboardInput)+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "dashboards:CUD",+ });++ if (input.dashboardId) {+ const dashboard = await DashboardService.getDashboard(+ input.dashboardId,+ input.projectId,+ );+ if (!dashboard) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Dashboard not found",+ });+ }+ }++ await ctx.prisma.project.update({+ where: { id: input.projectId },+ data: { homeDashboardId: input.dashboardId },+ });++ return { success: true };+ }),+updateDashboardFilters: protectedProjectProcedure.input(UpdateDashboardFiltersInput).mutation(async ({ ctx, input }) => {diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 8a0972bf5b..f27797d192 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -134,6 +134,19 @@ export const events = {],dashboard: ["clone_dashboard",+ "home_dashboard_viewed",+ "home_dashboard_peeked",+ "home_dashboard_set_default",+ "home_edit_pencil_click",+ "locked_edit_attempt",+ "clone_first_cancelled",+ "clone_open_existing_click",+ "widget_copy_first_open",+ "widget_copied_to_project",+ "add_widget_dialog_open",+ "add_widget_tab_switch",+ "widget_added",+ "dashboard_renamed_inline","chart_tab_switch","date_range_changed","new_widget_form_open",diff --git a/web/src/features/widgets/components/ChartTypeIllustration.tsx b/web/src/features/widgets/components/ChartTypeIllustration.tsxnew file mode 100644index 0000000000..cae834c785--- /dev/null+++ b/web/src/features/widgets/components/ChartTypeIllustration.tsx@@ -0,0 +1,258 @@+import * as React from "react";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import { cn } from "@/src/utils/tailwind";++/**+ * Small hand-drawn chart sketches for widget pickers. Base strokes inherit+ * the muted foreground; the data series pops in the primary color so each+ * chart type reads at a glance.+ */+export function ChartTypeIllustration({+ type,+ className,+}: {+ type: DashboardWidgetChartType | "CUSTOM";+ className?: string;+}) {+ return (+ <svg+ viewBox="0 0 72 48"+ fill="none"+ aria-hidden+ className={cn("text-muted-foreground/60", className)}+ >+ {illustrations[type] ?? illustrations.LINE_TIME_SERIES}+ </svg>+ );+}++const axis = (+ <path+ d="M8 6 V38 H66"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ />+);++const illustrations: Record<string, React.ReactNode> = {+ CUSTOM: (+ <>+ <rect+ x="6"+ y="6"+ width="60"+ height="36"+ rx="6"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeDasharray="4 4"+ />+ <path+ d="M36 17 V31 M29 24 H43"+ className="text-primary"+ stroke="currentColor"+ strokeWidth="2.5"+ strokeLinecap="round"+ />+ </>+ ),+ LINE_TIME_SERIES: (+ <>+ {axis}+ <path+ d="M12 32 L26 20 L38 26 L52 12 L64 18"+ className="text-primary"+ stroke="currentColor"+ strokeWidth="2.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </>+ ),+ AREA_TIME_SERIES: (+ <>+ {axis}+ <path+ d="M12 32 L26 18 L40 24 L64 12 V38 H12 Z"+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.2"+ />+ <path+ d="M12 32 L26 18 L40 24 L64 12"+ className="text-primary"+ stroke="currentColor"+ strokeWidth="2.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </>+ ),+ BAR_TIME_SERIES: (+ <>+ {axis}+ {[+ [12, 26],+ [19, 20],+ [26, 28],+ [33, 16],+ [40, 22],+ [47, 12],+ [54, 18],+ [61, 8],+ ].map(([x, y]) => (+ <rect+ key={x}+ x={x}+ y={y}+ width="4.5"+ height={38 - (y as number)}+ rx="1.5"+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.85"+ />+ ))}+ </>+ ),+ VERTICAL_BAR: (+ <>+ {axis}+ {[+ [14, 18],+ [25, 10],+ [36, 24],+ [47, 14],+ [58, 28],+ ].map(([x, y]) => (+ <rect+ key={x}+ x={x}+ y={y}+ width="7"+ height={38 - (y as number)}+ rx="2"+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.85"+ />+ ))}+ </>+ ),+ HORIZONTAL_BAR: (+ <>+ <path+ d="M10 6 V42"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ />+ {[+ [8, 52],+ [17, 40],+ [26, 30],+ [35, 18],+ ].map(([y, w]) => (+ <rect+ key={y}+ x="12"+ y={y}+ width={w}+ height="6"+ rx="2"+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.85"+ />+ ))}+ </>+ ),+ HISTOGRAM: (+ <>+ {axis}+ {[+ [12, 32],+ [19, 24],+ [26, 14],+ [33, 8],+ [40, 12],+ [47, 20],+ [54, 28],+ [61, 34],+ ].map(([x, y]) => (+ <rect+ key={x}+ x={x}+ y={y}+ width="7"+ height={38 - (y as number)}+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.85"+ />+ ))}+ </>+ ),+ PIE: (+ <>+ <circle cx="36" cy="24" r="15" stroke="currentColor" strokeWidth="2" />+ <path+ d="M36 24 L36 9 A15 15 0 0 1 50.3 28.6 Z"+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.85"+ />+ </>+ ),+ NUMBER: (+ <>+ <text+ x="36"+ y="28"+ textAnchor="middle"+ className="text-primary"+ fill="currentColor"+ fontSize="22"+ fontWeight="700"+ fontFamily="inherit"+ >+ 128+ </text>+ <path+ d="M26 36 H46"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </>+ ),+ PIVOT_TABLE: (+ <>+ <rect+ x="10"+ y="8"+ width="52"+ height="32"+ rx="3"+ stroke="currentColor"+ strokeWidth="1.5"+ />+ <rect+ x="10"+ y="8"+ width="52"+ height="9"+ rx="3"+ className="text-primary"+ fill="currentColor"+ fillOpacity="0.3"+ />+ <path+ d="M10 17 H62 M10 25 H62 M10 33 H62 M28 8 V40 M45 8 V40"+ stroke="currentColor"+ strokeWidth="1.2"+ />+ </>+ ),+};diff --git a/web/src/features/widgets/components/CopyWidgetDialog.tsx b/web/src/features/widgets/components/CopyWidgetDialog.tsxnew file mode 100644index 0000000000..9e8d275de8--- /dev/null+++ b/web/src/features/widgets/components/CopyWidgetDialog.tsx@@ -0,0 +1,72 @@+import React from "react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+ DialogBody,+} from "@/src/components/ui/dialog";+import { Button } from "@/src/components/ui/button";++/**+ * Copy-first flow for Langfuse-managed widgets on a project dashboard:+ * editing one creates the project's own copy (the placement is rewired to+ * it) and opens the copy in the widget editor.+ */+export function CopyWidgetDialog({+ open,+ onOpenChange,+ widgetName,+ onConfirm,+ isPending,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ widgetName: string;+ onConfirm: () => void;+ isPending: boolean;+}) {+ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ // Keep the dialog open while the copy is in flight (it navigates on+ // success).+ if (!nextOpen && isPending) return;+ onOpenChange(nextOpen);+ }}+ >+ <DialogContent className="sm:max-w-[480px]">+ <DialogHeader>+ <DialogTitle>Edit your copy of this widget</DialogTitle>+ </DialogHeader>+ <DialogBody>+ <p className="text-muted-foreground py-4 text-sm">+ <span className="text-foreground font-medium">+ “{widgetName}”+ </span>{" "}+ is maintained by Langfuse and can’t be edited directly.+ We’ll replace this tile with your own editable copy and open+ it in the widget editor β the rest of the dashboard stays unchanged.+ </p>+ </DialogBody>+ <DialogFooter>+ <div className="flex gap-2">+ <Button+ onClick={() => onOpenChange(false)}+ variant="outline"+ type="button"+ disabled={isPending}+ >+ Cancel+ </Button>+ <Button onClick={onConfirm} type="button" loading={isPending}>+ Create my copy+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/widgets/components/DashboardGrid.tsx b/web/src/features/widgets/components/DashboardGrid.tsxindex f7bad46713..34b0732cb1 100644--- a/web/src/features/widgets/components/DashboardGrid.tsx+++ b/web/src/features/widgets/components/DashboardGrid.tsx@@ -1,12 +1,50 @@-import { Responsive, WidthProvider } from "react-grid-layout";+import { Responsive } from "react-grid-layout";import "react-grid-layout/css/styles.css";import "react-resizable/css/styles.css";import { type WidgetPlacement } from "../components/DashboardWidget";+import {+ PresetDashboardWidget,+ type PresetPlacement,+} from "../components/PresetDashboardWidget";import { DashboardWidget } from "@/src/features/widgets";import { type FilterState } from "@langfuse/shared";-import { useState, useCallback, useEffect } from "react";+import { useState, useEffect, useRef } from "react";-const ResponsiveGridLayout = WidthProvider(Responsive);+export type DashboardPlacement = WidgetPlacement | PresetPlacement;++/**+ * Container width, measured once immediately and then with a trailing+ * debounce. WidthProvider re-renders the whole grid (and every chart in it)+ * on each resize frame; measuring ourselves keeps continuous window resizes+ * from burning CPU β the layout snaps once, when the resize settles.+ */+function useDebouncedContainerWidth(delayMs: number) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState<number | null>(null);++ useEffect(() => {+ const element = containerRef.current;+ if (!element) return;++ setWidth(element.getBoundingClientRect().width);++ let timeout: ReturnType<typeof setTimeout> | undefined;+ const observer = new ResizeObserver(() => {+ clearTimeout(timeout);+ timeout = setTimeout(() => {+ setWidth(element.getBoundingClientRect().width);+ }, delayMs);+ });+ observer.observe(element);++ return () => {+ clearTimeout(timeout);+ observer.disconnect();+ };+ }, [delayMs]);++ return { containerRef, width };+}// Hook to detect screen sizefunction useMediaQuery(query: string) {@@ -37,9 +75,11 @@ export function DashboardGrid({onDeleteWidget,dashboardOwner,getWidgetSchedulerId,+ onLockedEditAttempt,+ readOnly,}: {- widgets: WidgetPlacement[];- onChange: (widgets: WidgetPlacement[]) => void;+ widgets: DashboardPlacement[];+ onChange: (widgets: DashboardPlacement[]) => void;canEdit: boolean;dashboardId: string;projectId: string;@@ -48,22 +88,23 @@ export function DashboardGrid({onDeleteWidget: (tileId: string) => void;dashboardOwner: "LANGFUSE" | "PROJECT" | undefined;getWidgetSchedulerId?: (widgetPlacementId: string) => string;+ /**+ * Present on Langfuse-managed (read-only) dashboards: tiles keep their edit+ * affordances and route edit attempts here (clone-first flow). Layout+ * changes still arrive via onChange β the caller decides whether to persist+ * or route them through the same flow.+ */+ onLockedEditAttempt?: () => void;+ /** Pure viewing surface (e.g. Home): tiles render no edit affordances. */+ readOnly?: boolean;}) {- const [rowHeight, setRowHeight] = useState(150);+ const { containerRef, width } = useDebouncedContainerWidth(200);+ // Rows stay 16:9-proportional to column width+ const rowHeight = width !== null ? ((width / 12) * 9) / 16 : 150;// Detect if screen is medium or smaller (1024px and below)const isSmallScreen = useMediaQuery("(max-width: 1024px)");- const handleWidthChange = useCallback(- (containerWidth: number) => {- const calculatedRowHeight = ((containerWidth / 12) * 9) / 16;- if (calculatedRowHeight !== rowHeight) {- setRowHeight(calculatedRowHeight);- }- },- [rowHeight],- );-// Convert WidgetPlacement to react-grid-layout formatconst layout = widgets.map((w) => ({i: w.id,@@ -101,6 +142,38 @@ export function DashboardGrid({onChange(updatedWidgets);};+ // Dispatch a placement to its renderer: "preset" placements render a+ // registered curated component; "widget" placements render the generic+ // query-backed widget.+ const renderPlacement = (widget: DashboardPlacement) =>+ widget.type === "preset" ? (+ <PresetDashboardWidget+ dashboardId={dashboardId}+ projectId={projectId}+ placement={widget}+ dateRange={dateRange}+ filterState={filterState}+ onDeleteWidget={onDeleteWidget}+ dashboardOwner={dashboardOwner || "PROJECT"}+ schedulerId={getWidgetSchedulerId?.(widget.id)}+ onLockedEditAttempt={onLockedEditAttempt}+ readOnly={readOnly}+ />+ ) : (+ <DashboardWidget+ dashboardId={dashboardId}+ projectId={projectId}+ placement={widget}+ dateRange={dateRange}+ filterState={filterState}+ onDeleteWidget={onDeleteWidget}+ dashboardOwner={dashboardOwner || "PROJECT"}+ schedulerId={getWidgetSchedulerId?.(widget.id)}+ onLockedEditAttempt={onLockedEditAttempt}+ readOnly={readOnly}+ />+ );+// Render flex layout for small screensif (isSmallScreen) {return (@@ -111,19 +184,16 @@ export function DashboardGrid({.map((widget) => (<divkey={widget.id}+ data-placement-id={widget.id}className="w-full"- style={{ height: "300px" }} // Fixed height for all widgets on small screens+ // Fixed height for query widgets (their charts fill whatever+ // space they get); presets size to their content like the+ // stacked bespoke Home did.+ style={{+ height: widget.type === "preset" ? "auto" : "300px",+ }}>- <DashboardWidget- dashboardId={dashboardId}- projectId={projectId}- placement={widget}- dateRange={dateRange}- filterState={filterState}- onDeleteWidget={onDeleteWidget}- dashboardOwner={dashboardOwner || "PROJECT"}- schedulerId={getWidgetSchedulerId?.(widget.id)}- />+ {renderPlacement(widget)}</div>))}</div>@@ -132,34 +202,33 @@ export function DashboardGrid({// Render grid layout for larger screensreturn (- <ResponsiveGridLayout- className="layout"- layouts={{ lg: layout }}- cols={{ lg: 12, md: 12, sm: 12, xs: 12, xxs: 12 }}- margin={[16, 16]}- rowHeight={rowHeight}- isDraggable={canEdit}- isResizable={canEdit}- onDragStop={handleLayoutChange} // Save immediately when drag stops- onResizeStop={handleLayoutChange} // Save immediately when resize stops- onWidthChange={handleWidthChange}- draggableHandle=".drag-handle"- useCSSTransforms- >- {widgets.map((widget) => (- <div key={widget.id} className="max-h-full max-w-full">- <DashboardWidget- dashboardId={dashboardId}- projectId={projectId}- placement={widget}- dateRange={dateRange}- filterState={filterState}- onDeleteWidget={onDeleteWidget}- dashboardOwner={dashboardOwner || "PROJECT"}- schedulerId={getWidgetSchedulerId?.(widget.id)}- />- </div>- ))}- </ResponsiveGridLayout>+ <div ref={containerRef}>+ {width !== null && (+ <Responsive+ className="layout"+ width={width}+ layouts={{ lg: layout }}+ cols={{ lg: 12, md: 12, sm: 12, xs: 12, xxs: 12 }}+ margin={[16, 16]}+ rowHeight={rowHeight}+ isDraggable={canEdit}+ isResizable={canEdit}+ onDragStop={handleLayoutChange} // Save immediately when drag stops+ onResizeStop={handleLayoutChange} // Save immediately when resize stops+ draggableHandle=".drag-handle"+ useCSSTransforms+ >+ {widgets.map((widget) => (+ <div+ key={widget.id}+ data-placement-id={widget.id}+ className="max-h-full max-w-full"+ >+ {renderPlacement(widget)}+ </div>+ ))}+ </Responsive>+ )}+ </div>);}diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex f58014b2ca..bb1db82f2f 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -17,12 +17,7 @@ import { type z } from "zod";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { type FilterState, type OrderByState } from "@langfuse/shared";import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";-import {- PencilIcon,- TrashIcon,- CopyIcon,- GripVerticalIcon,-} from "lucide-react";+import { PencilIcon, TrashIcon, GripVerticalIcon } from "lucide-react";import { useRouter } from "next/router";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { showErrorToast } from "@/src/features/notifications/showErrorToast";@@ -41,6 +36,9 @@ import {} from "@/src/features/widgets/chart-library/chartLoadingStateUtils";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";+import { CopyWidgetDialog } from "@/src/features/widgets/components/CopyWidgetDialog";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { Badge } from "@/src/components/ui/badge";export interface WidgetPlacement {id: string;@@ -61,6 +59,8 @@ export function DashboardWidget({onDeleteWidget,dashboardOwner,schedulerId,+ onLockedEditAttempt,+ readOnly,}: {projectId: string;dashboardId: string;@@ -70,9 +70,18 @@ export function DashboardWidget({onDeleteWidget: (tileId: string) => void;dashboardOwner: "LANGFUSE" | "PROJECT";schedulerId?: string;+ /**+ * Present on Langfuse-managed (read-only) dashboards: edit affordances stay+ * visible and any edit attempt routes here (clone-first flow) instead of+ * mutating.+ */+ onLockedEditAttempt?: () => void;+ /** Pure viewing surface (e.g. Home): render no edit affordances. */+ readOnly?: boolean;}) {const router = useRouter();const utils = api.useUtils();+ const capture = usePostHogClientCapture();const { isBetaEnabled } = useV4Beta();const widget = api.dashboardWidgets.get.useQuery({@@ -98,9 +107,17 @@ export function DashboardWidget({: isBetaEnabled && (widget.data?.view ?? "traces") !== "traces"? "v2": "v1";- const hasCUDAccess =- useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&- dashboardOwner !== "LANGFUSE";+ const hasRbacCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });+ const hasCUDAccess = hasRbacCUDAccess && dashboardOwner !== "LANGFUSE";+ // Langfuse-managed dashboard, but the user could edit a clone: show the+ // same edit affordances and route attempts through the clone-first flow.+ const isLockedEditable =+ hasRbacCUDAccess &&+ dashboardOwner === "LANGFUSE" &&+ Boolean(onLockedEditAttempt);// Initialize sort state for pivot tablesconst defaultSort =@@ -115,6 +132,7 @@ export function DashboardWidget({return defaultSort || null;});const [retryCount, setRetryCount] = useState(0);+ const [isCopyDialogOpen, setIsCopyDialogOpen] = useState(false);// Apply defaultSort when it becomes available (after widget data loads)// but only if user hasn't interacted yet@@ -398,6 +416,11 @@ export function DashboardWidget({const copyMutation = api.dashboardWidgets.copyToProject.useMutation({onSuccess: (data) => {+ capture("dashboard:widget_copied_to_project", {+ source_widget_id: placement.widgetId,+ new_widget_id: data.widgetId,+ dashboard_id: dashboardId,+ });utils.dashboard.getDashboard.invalidate().then(() => {router.push(`/project/${projectId}/widgets/${data.widgetId}?dashboardId=${dashboardId}`,@@ -418,6 +441,11 @@ export function DashboardWidget({};const handleDelete = () => {+ if (isLockedEditable) {+ // The clone-first dialog is the confirmation on locked dashboards.+ onDeleteWidget(placement.id);+ return;+ }if (onDeleteWidget && confirm("Please confirm deletion")) {onDeleteWidget(placement.id);}@@ -441,21 +469,49 @@ export function DashboardWidget({return (<div className="bg-background group flex h-full w-full flex-col overflow-hidden rounded-lg border p-4">+ {isCopyDialogOpen && (+ <CopyWidgetDialog+ open={isCopyDialogOpen}+ onOpenChange={setIsCopyDialogOpen}+ widgetName={widget.data.name}+ onConfirm={handleCopy}+ isPending={copyMutation.isPending}+ />+ )}<div className="flex items-center justify-between">- <span className="truncate font-medium" title={widget.data.name}>- {widget.data.name}{" "}- {dashboardOwner === "PROJECT" && widget.data.owner === "LANGFUSE"- ? " ( πͺ’ )"- : null}+ <span+ className="flex min-w-0 items-center gap-1.5 truncate font-medium"+ title={widget.data.name}+ >+ <span className="truncate" title={widget.data.name}>+ {widget.data.name}+ </span>+ {dashboardOwner === "PROJECT" && widget.data.owner === "LANGFUSE" && (+ <Badge+ variant="secondary"+ className="shrink-0"+ title="Maintained by Langfuse β editing creates your own copy"+ >+ Langfuse+ </Badge>+ )}</span><div className="flex space-x-2">- {hasCUDAccess && (+ {!readOnly && (hasCUDAccess || isLockedEditable) && (<><GripVerticalIconsize={16}className="drag-handle text-muted-foreground hover:text-foreground hidden cursor-grab active:cursor-grabbing lg:group-hover:block"/>- {widget.data.owner === "PROJECT" ? (+ {isLockedEditable ? (+ <button+ onClick={onLockedEditAttempt}+ className="text-muted-foreground hover:text-foreground hidden group-hover:block"+ aria-label="Edit widget"+ >+ <PencilIcon size={16} />+ </button>+ ) : widget.data.owner === "PROJECT" ? (<buttononClick={handleEdit}className="text-muted-foreground hover:text-foreground hidden group-hover:block"@@ -465,11 +521,17 @@ export function DashboardWidget({</button>) : widget.data.owner === "LANGFUSE" ? (<button- onClick={handleCopy}+ onClick={() => {+ capture("dashboard:widget_copy_first_open", {+ widget_id: placement.widgetId,+ dashboard_id: dashboardId,+ });+ setIsCopyDialogOpen(true);+ }}className="text-muted-foreground hover:text-foreground hidden group-hover:block"- aria-label="Copy widget"+ aria-label="Edit widget">- <CopyIcon size={16} />+ <PencilIcon size={16} /></button>) : null}<buttondiff --git a/web/src/features/widgets/components/PresetDashboardWidget.tsx b/web/src/features/widgets/components/PresetDashboardWidget.tsxnew file mode 100644index 0000000000..bad3306268--- /dev/null+++ b/web/src/features/widgets/components/PresetDashboardWidget.tsx@@ -0,0 +1,166 @@+import { useMemo } from "react";+import { GripVerticalIcon, TrashIcon } from "lucide-react";+import { type FilterState } from "@langfuse/shared";+import { type ViewVersion } from "@langfuse/shared/query";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { findClosestDashboardInterval } from "@/src/utils/date-range-utils";+import {+ getHomePreset,+ type PresetWidgetContext,+} from "@/src/features/dashboard/components/home-preset-registry";++/**+ * A "preset" dashboard placement: renders a registered curated component by+ * presetId (with its own chrome and data fetches) instead of a+ * DashboardWidget row + executeQuery. See the preset registry.+ */+export interface PresetPlacement {+ id: string;+ presetId: string;+ x: number;+ y: number;+ x_size: number;+ y_size: number;+ type: "preset";+}++export function PresetDashboardWidget({+ projectId,+ dashboardId,+ placement,+ dateRange,+ filterState,+ onDeleteWidget,+ dashboardOwner,+ schedulerId,+ onLockedEditAttempt,+ readOnly,+}: {+ projectId: string;+ dashboardId: string;+ placement: PresetPlacement;+ dateRange: { from: Date; to: Date } | undefined;+ filterState: FilterState;+ onDeleteWidget: (tileId: string) => void;+ dashboardOwner: "LANGFUSE" | "PROJECT";+ schedulerId?: string;+ /**+ * Present on Langfuse-managed (read-only) dashboards: edit affordances stay+ * visible and any edit attempt routes here (clone-first flow) instead of+ * mutating.+ */+ onLockedEditAttempt?: () => void;+ /** Pure viewing surface (e.g. Home): render no edit affordances. */+ readOnly?: boolean;+}) {+ const { isBetaEnabled } = useV4Beta();+ const metricsVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";++ // Presets on project-owned dashboards (e.g. a clone of the curated Home)+ // can be moved/removed, but their content stays fixed until extended into a+ // configurable widget. On Langfuse-owned dashboards the same affordances+ // show, routing through the clone-first flow.+ const hasRbacCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });+ const hasCUDAccess = hasRbacCUDAccess && dashboardOwner !== "LANGFUSE";+ const isLockedEditable =+ hasRbacCUDAccess &&+ dashboardOwner === "LANGFUSE" &&+ Boolean(onLockedEditAttempt);++ const renderPreset = getHomePreset(placement.presetId);++ const ctx: PresetWidgetContext = useMemo(() => {+ const fromTimestamp = dateRange+ ? dateRange.from+ : new Date(new Date().getTime() - 1000);+ const toTimestamp = dateRange ? dateRange.to : new Date();+ const timeFilter: FilterState = [+ {+ type: "datetime",+ column: "startTime",+ operator: ">",+ value: fromTimestamp,+ },+ {+ type: "datetime",+ column: "startTime",+ operator: "<",+ value: toTimestamp,+ },+ ];++ return {+ projectId,+ globalFilterState: filterState,+ mergedFilterState: [...filterState, ...timeFilter],+ fromTimestamp,+ toTimestamp,+ agg:+ findClosestDashboardInterval({+ from: fromTimestamp,+ to: toTimestamp,+ }) ?? "last7Days",+ isLoading: false,+ metricsVersion,+ schedulerId,+ syncId: dashboardId,+ // Stretch to the tile; when the card's intrinsic content is taller+ // (fixed chart min-heights, expanded tables) the wrapper scrolls+ // instead of clipping.+ className: "min-h-full",+ };+ }, [+ dashboardId,+ dateRange,+ filterState,+ metricsVersion,+ projectId,+ schedulerId,+ ]);++ const handleDelete = () => {+ if (isLockedEditable) {+ // The clone-first dialog is the confirmation on locked dashboards.+ onDeleteWidget(placement.id);+ return;+ }+ if (confirm("Please confirm deletion")) {+ onDeleteWidget(placement.id);+ }+ };++ if (!renderPreset) {+ return (+ <div className="bg-background flex h-full items-center justify-center rounded-lg border p-4">+ <div className="text-muted-foreground">+ Unknown preset: {placement.presetId}+ </div>+ </div>+ );+ }++ return (+ <div className="group relative h-full w-full">+ <div className="h-full w-full overflow-y-auto">{renderPreset(ctx)}</div>+ {!readOnly && (hasCUDAccess || isLockedEditable) && (+ <div className="bg-background/95 absolute top-2 right-2 z-10 hidden items-center gap-2 rounded-md border px-1.5 py-1 shadow-sm group-hover:flex">+ <GripVerticalIcon+ size={16}+ className="drag-handle text-muted-foreground hover:text-foreground hidden cursor-grab active:cursor-grabbing lg:block"+ />+ <button+ onClick={handleDelete}+ className="text-muted-foreground hover:text-destructive"+ aria-label="Delete widget"+ >+ <TrashIcon size={16} />+ </button>+ </div>+ )}+ </div>+ );+}diff --git a/web/src/features/widgets/components/SelectWidgetDialog.tsx b/web/src/features/widgets/components/SelectWidgetDialog.tsxindex d1dc2cee65..a34b953953 100644--- a/web/src/features/widgets/components/SelectWidgetDialog.tsx+++ b/web/src/features/widgets/components/SelectWidgetDialog.tsx@@ -1,6 +1,7 @@-import React, { useState } from "react";+import React, { useEffect, useRef } from "react";import { useRouter } from "next/router";import { api } from "@/src/utils/api";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import {Dialog,DialogContent,@@ -10,17 +11,20 @@ import {DialogBody,} 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";+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@/src/components/ui/tabs";import startCase from "lodash/startCase";import { getChartTypeDisplayName } from "@/src/features/widgets/chart-library/utils";+import { ChartTypeIllustration } from "@/src/features/widgets/components/ChartTypeIllustration";+import {+ HOME_DASHBOARD_PRESET_IDS,+ type HomeDashboardPresetId,+} from "@langfuse/shared";+import { HOME_PRESET_METADATA } from "@/src/features/dashboard/components/home-preset-registry";import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";export type WidgetItem = {@@ -33,11 +37,60 @@ export type WidgetItem = {updatedAt: Date;};+const rowClassName =+ "flex w-full items-center gap-4 rounded-lg border p-3 text-left hover:bg-accent/50 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring";++function RowIllustration({ type }: { type: string }) {+ return (+ <div className="bg-muted/40 flex h-14 w-[5.5rem] shrink-0 items-center justify-center rounded-md">+ <ChartTypeIllustration+ type={type as DashboardWidgetChartType | "CUSTOM"}+ className="h-11 w-16"+ />+ </div>+ );+}++function WidgetRow({+ widget,+ onClick,+}: {+ widget: WidgetItem;+ onClick: () => void;+}) {+ return (+ <button type="button" onClick={onClick} className={rowClassName}>+ <RowIllustration type={widget.chartType} />+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium" title={widget.name}>+ {widget.name}+ </div>+ {widget.description ? (+ <div+ className="text-muted-foreground truncate text-xs"+ title={widget.description}+ >+ {widget.description}+ </div>+ ) : null}+ <div className="text-muted-foreground/80 mt-0.5 text-xs">+ {getChartTypeDisplayName(+ widget.chartType as DashboardWidgetChartType,+ )}{" "}+ Β· {startCase(widget.view.toLowerCase())}+ </div>+ </div>+ </button>+ );+}+interface SelectWidgetDialogProps {open: boolean;onOpenChange: (open: boolean) => void;projectId: string;onSelectWidget: (widget: WidgetItem) => void;+ /** Adds a Langfuse Home card as a preset placement. */+ onSelectPreset?: (presetId: HomeDashboardPresetId) => void;dashboardId: string;}@@ -46,12 +99,23 @@ export function SelectWidgetDialog({onOpenChange,projectId,onSelectWidget,+ onSelectPreset,dashboardId,}: SelectWidgetDialogProps) {const router = useRouter();- const [selectedWidgetId, setSelectedWidgetId] = useState<string | null>(null);+ const capture = usePostHogClientCapture();- // Fetch widgets+ const openCapturedRef = useRef(false);+ useEffect(() => {+ if (open && !openCapturedRef.current) {+ capture("dashboard:add_widget_dialog_open", {+ dashboard_id: dashboardId,+ });+ }+ openCapturedRef.current = open;+ }, [open, dashboardId, capture]);++ // Fetch widgets (project-owned and Langfuse-maintained)const widgets = api.dashboardWidgets.all.useQuery({projectId,@@ -65,99 +129,142 @@ export function SelectWidgetDialog({},);- const handleNavigateToNewWidget = () => {- router.push(`/project/${projectId}/widgets/new?dashboardId=${dashboardId}`);- };+ const projectWidgets = widgets.data?.widgets ?? [];- const handleAddWidget = () => {- if (selectedWidgetId) {- const selectedWidget = widgets.data?.widgets.find(- (widget) => widget.id === selectedWidgetId,- );- if (selectedWidget) {- onSelectWidget(selectedWidget as WidgetItem);- onOpenChange(false);- }- }+ const selectWidget = (widget: WidgetItem) => {+ capture("dashboard:widget_added", {+ kind: "project_widget",+ widget_id: widget.id,+ chart_type: widget.chartType,+ view: widget.view,+ dashboard_id: dashboardId,+ });+ onSelectWidget(widget);+ onOpenChange(false);};return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-[800px]">+ <DialogContent className="sm:max-w-[640px]"><DialogHeader>- <DialogTitle>Select widget to add</DialogTitle>+ <DialogTitle>Add widget</DialogTitle></DialogHeader><DialogBody>- <div className="max-h-[400px] overflow-y-auto">- {widgets.isPending ? (- <div className="py-8 text-center">Loading widgets...</div>- ) : widgets.isError ? (- <div className="text-destructive py-8 text-center">- Error: {widgets.error.message}- </div>- ) : widgets.data?.widgets.length === 0 ? (- <div className="text-muted-foreground py-8 text-center">- 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={`hover:bg-muted cursor-pointer ${- selectedWidgetId === widget.id ? "bg-muted" : ""- }`}- >- <TableCell density="comfortable" className="font-medium">- {widget.name}- </TableCell>- <TableCell- density="comfortable"- className="truncate"- title={widget.description}- >- {widget.description}- </TableCell>- <TableCell density="comfortable">- {startCase(widget.view.toLowerCase())}- </TableCell>- <TableCell density="comfortable">- {getChartTypeDisplayName(- widget.chartType as DashboardWidgetChartType,- )}- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- )}- </div>+ {widgets.isPending ? (+ <div className="py-8 text-center">Loading widgets...</div>+ ) : widgets.isError ? (+ <div className="text-destructive py-8 text-center">+ Error: {widgets.error.message}+ </div>+ ) : (+ <div className="flex flex-col gap-3 p-1">+ <button+ type="button"+ onClick={() => {+ capture("dashboard:new_widget_form_open", {+ source: "add_widget_dialog",+ dashboard_id: dashboardId,+ });+ router.push(+ `/project/${projectId}/widgets/new?dashboardId=${dashboardId}`,+ );+ }}+ className={`${rowClassName} border-dashed`}+ >+ <RowIllustration type="CUSTOM" />+ <div className="min-w-0 flex-1">+ <div className="font-medium">Custom Chart</div>+ <div className="text-muted-foreground text-xs">+ Pick a data view, metrics, and chart type from scratch+ </div>+ </div>+ </button>++ <Tabs+ defaultValue={+ projectWidgets.length > 0 ? "project" : "home-cards"+ }+ onValueChange={(tab) =>+ capture("dashboard:add_widget_tab_switch", { tab })+ }+ >+ <TabsList>+ <TabsTrigger value="project">+ Your widgets ({projectWidgets.length})+ </TabsTrigger>+ {onSelectPreset && (+ <TabsTrigger value="home-cards">+ Home cards ({HOME_DASHBOARD_PRESET_IDS.length})+ </TabsTrigger>+ )}+ </TabsList>+ <TabsContent value="project">+ <div className="flex max-h-[360px] flex-col gap-2 overflow-y-auto p-1">+ {projectWidgets.length === 0 ? (+ <div className="text-muted-foreground py-8 text-center text-sm">+ No saved widgets in this project yet β build one with+ Custom Chart.+ </div>+ ) : (+ projectWidgets.map((widget) => (+ <WidgetRow+ key={widget.id}+ widget={widget as WidgetItem}+ onClick={() => selectWidget(widget as WidgetItem)}+ />+ ))+ )}+ </div>+ </TabsContent>+ {onSelectPreset && (+ <TabsContent value="home-cards">+ <div className="flex max-h-[360px] flex-col gap-2 overflow-y-auto p-1">+ {HOME_DASHBOARD_PRESET_IDS.map((presetId) => {+ const meta = HOME_PRESET_METADATA[presetId];+ return (+ <button+ key={presetId}+ type="button"+ onClick={() => {+ onSelectPreset(presetId);+ onOpenChange(false);+ }}+ className={rowClassName}+ >+ <RowIllustration type={meta.illustration} />+ <div className="min-w-0 flex-1">+ <div+ className="truncate font-medium"+ title={meta.name}+ >+ {meta.name}+ </div>+ <div+ className="text-muted-foreground truncate text-xs"+ title={meta.description}+ >+ {meta.description}+ </div>+ <div className="text-muted-foreground/80 mt-0.5 text-xs">+ Home card Β· fixed configuration+ </div>+ </div>+ </button>+ );+ })}+ </div>+ </TabsContent>+ )}+ </Tabs>+ </div>+ )}</DialogBody>- <DialogFooter className="mt-4 flex justify-between">- <Button onClick={handleNavigateToNewWidget} variant="outline">- <PlusIcon className="mr-2 h-4 w-4" />- Create New Widget+ <DialogFooter className="mt-4">+ <Button onClick={() => onOpenChange(false)} variant="outline">+ Cancel</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/hooks/useDashboardFilterOptions.ts b/web/src/hooks/useDashboardFilterOptions.tsindex b966e5076b..5b1627d30d 100644--- a/web/src/hooks/useDashboardFilterOptions.ts+++ b/web/src/hooks/useDashboardFilterOptions.ts@@ -80,14 +80,17 @@ export function useDashboardFilterOptions({[absoluteTimeRange],);+ // Gate on projectId: on a direct URL load the first render happens before+ // the router query hydrates, and firing with projectId=undefined surfaces+ // a "Bad Request" toast.const traceFilterOptions = api.traces.filterOptions.useQuery({ projectId, timestampFilter: traceTimestampFilter },- { ...commonQueryOptions, enabled: !isBetaEnabled },+ { ...commonQueryOptions, enabled: Boolean(projectId) && !isBetaEnabled },);const eventsFilterOptions = api.events.filterOptions.useQuery({ projectId, startTimeFilter },- { ...commonQueryOptions, enabled: isBetaEnabled },+ { ...commonQueryOptions, enabled: Boolean(projectId) && isBetaEnabled },);const nameOptions = useMemo(diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsxindex 6a143689b6..6bf969b914 100644--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx@@ -10,7 +10,6 @@ import { useEffect, useState, useMemo, useCallback } from "react";import type { ColumnDefinition, FilterState } from "@langfuse/shared";import { Button } from "@/src/components/ui/button";import { PlusIcon, Copy } from "lucide-react";-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import {SelectWidgetDialog,@@ -20,7 +19,25 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { v4 as uuidv4 } from "uuid";import { useDebounce } from "@/src/hooks/useDebounce";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { DashboardGrid } from "@/src/features/widgets/components/DashboardGrid";+import {+ DashboardGrid,+ type DashboardPlacement,+} from "@/src/features/widgets/components/DashboardGrid";+import { CloneFirstDialog } from "@/src/features/dashboard/components/CloneFirstDialog";+import { InlineEditText } from "@/src/components/design-system/InlineEditText/InlineEditText";+import { PageHeaderControlsPortal } from "@/src/components/layouts/page-header-controls-slot";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { EditDashboardDialog } from "@/src/features/dashboard/components/EditDashboardDialog";+import {+ LANGFUSE_HOME_DASHBOARD_ID,+ type HomeDashboardPresetId,+} from "@langfuse/shared";+import { HomeIcon, Loader2, MoreVertical, PencilIcon } from "lucide-react";import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";import {DASHBOARD_AGGREGATION_OPTIONS,@@ -28,22 +45,17 @@ import {} from "@/src/utils/date-range-utils";import { useEntitlementLimit } from "@/src/features/entitlements/hooks";import { useEnvironmentFilterOptionsCache } from "@/src/hooks/use-environment-filter-options-cache";+import { MultiSelect } from "@/src/features/filters/components/multi-select";+import {+ convertSelectedEnvironmentsToFilter,+ useEnvironmentFilter,+} from "@/src/hooks/useEnvironmentFilter";import {DashboardQuerySchedulerProvider,getDashboardQuerySchedulerMaxConcurrent,useDashboardQueryScheduler,} from "@/src/hooks/useDashboardQueryScheduler";-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 utils = api.useUtils();@@ -64,18 +76,50 @@ export default function DashboardDetail() {dashboardId,});- const hasCUDAccess =- useHasProjectAccess({- projectId,- scope: "dashboards:CUD",- }) && dashboard.data?.owner !== "LANGFUSE";+ const hasRbacCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });+ const isLockedDashboard = dashboard.data?.owner === "LANGFUSE";+ const hasCUDAccess = hasRbacCUDAccess && !isLockedDashboard;++ // Langfuse-managed dashboards keep full edit affordances; edit attempts+ // route through the clone-first flow instead of mutating.+ const isLockedEditable = hasRbacCUDAccess && isLockedDashboard;// Access for cloning (independent of dashboard owner)- const hasCloneAccess =- useHasProjectAccess({- projectId,- scope: "dashboards:CUD",- }) && dashboard.data?.owner === "LANGFUSE";+ const hasCloneAccess = hasRbacCUDAccess && isLockedDashboard;++ // Clone-first dialog state: open + the attempted change (if any) to carry+ // into the clone. gridResetKey remounts the grid to revert an attempted+ // drag/resize when the user cancels.+ const [cloneFirstState, setCloneFirstState] = useState<{+ open: boolean;+ pendingDefinition: { widgets: DashboardPlacement[] } | null;+ }>({ open: false, pendingDefinition: null });+ const [gridResetKey, setGridResetKey] = useState(0);++ const openCloneFirst = useCallback(+ (+ attempt:+ | "layout_change"+ | "delete_widget"+ | "add_widget"+ | "widget_pencil",+ pendingDefinition?: { widgets: DashboardPlacement[] },+ ) => {+ capture("dashboard:locked_edit_attempt", {+ dashboard_id: dashboardId,+ attempt,+ surface: "detail",+ });+ setCloneFirstState({+ open: true,+ pendingDefinition: pendingDefinition ?? null,+ });+ },+ [capture, dashboardId],+ );// Filter state - use persistent filters from dashboardconst [savedFilters, setSavedFilters] = useState<FilterState>([]);@@ -95,7 +139,7 @@ export default function DashboardDetail() {// State for handling widget deletion and additionconst [localDashboardDefinition, setLocalDashboardDefinition] = useState<{- widgets: WidgetPlacement[];+ widgets: DashboardPlacement[];} | null>(null);// State for the widget selection dialog@@ -104,12 +148,8 @@ export default function DashboardDetail() {// Mutation for updating dashboard definitionconst updateDashboardDefinition =api.dashboard.updateDashboardDefinition.useMutation({+ // Saves are silent; the header shows a spinner while in flight.onSuccess: () => {- showSuccessToast({- title: "Dashboard updated",- description: "Your changes have been saved automatically",- duration: 2000,- });// Invalidate the dashboard query to refetch the datadashboard.refetch();},@@ -118,15 +158,42 @@ export default function DashboardDetail() {},});+ // Which dashboard is shown on this project's Home (for the "Use as Home" action)+ const homePointer = api.dashboard.getHomeDashboard.useQuery(+ { projectId },+ { enabled: Boolean(projectId), retry: false },+ );+ const isCurrentHome =+ (homePointer.data?.homeDashboardId ?? LANGFUSE_HOME_DASHBOARD_ID) ===+ dashboardId;++ const setHomeDashboard = api.dashboard.setHomeDashboard.useMutation({+ onSuccess: () => {+ utils.dashboard.getHomeDashboard.invalidate();+ },+ onError: (error) => {+ showErrorToast("Failed to update home dashboard", error.message);+ },+ });++ // Dialog for editing name + description from the ... menu+ const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);++ // Mutation for renaming the dashboard inline from the page header+ const updateDashboardMetadata =+ api.dashboard.updateDashboardMetadata.useMutation({+ onSuccess: () => {+ utils.dashboard.invalidate();+ },+ onError: (error) => {+ showErrorToast("Error renaming dashboard", error.message);+ },+ });+// Mutation for updating dashboard filtersconst updateDashboardFilters =api.dashboard.updateDashboardFilters.useMutation({onSuccess: () => {- showSuccessToast({- title: "Filters saved",- description: "Dashboard filters have been saved successfully",- duration: 2000,- });// Update saved state to match current statesetSavedFilters(currentFilters);},@@ -136,7 +203,7 @@ export default function DashboardDetail() {});const saveDashboardChanges = useDebounce(- (definition: { widgets: WidgetPlacement[] }) => {+ (definition: { widgets: DashboardPlacement[] }) => {if (!hasCUDAccess) return;updateDashboardDefinition.mutate({projectId,@@ -173,7 +240,7 @@ export default function DashboardDetail() {: 0;// Create a new widget placement- const newWidgetPlacement: WidgetPlacement = {+ const newWidgetPlacement: DashboardPlacement = {id: uuidv4(),widgetId: widget.id,x: 0, // Start at left@@ -190,6 +257,13 @@ export default function DashboardDetail() {};setLocalDashboardDefinition(updatedDefinition);saveDashboardChanges(updatedDefinition);++ // The new widget lands at the bottom of the grid β bring it into view.+ setTimeout(() => {+ document+ .querySelector(`[data-placement-id="${newWidgetPlacement.id}"]`)+ ?.scrollIntoView({ behavior: "smooth", block: "center" });+ }, 150);},[localDashboardDefinition,@@ -198,6 +272,44 @@ export default function DashboardDetail() {],);+ // Add a Langfuse Home card as a preset placement (no widget row involved)+ const addPresetToDashboard = useCallback(+ (presetId: HomeDashboardPresetId) => {+ if (!localDashboardDefinition) return;++ const maxY =+ localDashboardDefinition.widgets.length > 0+ ? Math.max(+ ...localDashboardDefinition.widgets.map((w) => w.y + w.y_size),+ )+ : 0;++ const newPresetPlacement: DashboardPlacement = {+ id: uuidv4(),+ presetId,+ type: "preset",+ x: 0,+ y: maxY,+ x_size: 6,+ y_size: 6,+ };++ const updatedDefinition = {+ ...localDashboardDefinition,+ widgets: [...localDashboardDefinition.widgets, newPresetPlacement],+ };+ setLocalDashboardDefinition(updatedDefinition);+ saveDashboardChanges(updatedDefinition);++ setTimeout(() => {+ document+ .querySelector(`[data-placement-id="${newPresetPlacement.id}"]`)+ ?.scrollIntoView({ behavior: "smooth", block: "center" });+ }, 150);+ },+ [localDashboardDefinition, saveDashboardChanges],+ );+const { nameOptions, tagsOptions } = useDashboardFilterOptions({projectId,isBetaEnabled,@@ -213,6 +325,24 @@ export default function DashboardDetail() {value,}),);++ // Dedicated environment selector, same as Home. The selection is a view+ // setting (persisted per project for this user), merged into the widget+ // filters but never written into the dashboard's saved filters.+ const { selectedEnvironments, setSelectedEnvironments } =+ useEnvironmentFilter(environmentOptionsState.environmentOptions, projectId);+ const environmentFilter = useMemo(+ () =>+ convertSelectedEnvironmentsToFilter(+ ["environment"],+ selectedEnvironments,+ ),+ [selectedEnvironments],+ );+ const gridFilterState: FilterState = useMemo(+ () => [...currentFilters, ...environmentFilter],+ [currentFilters, environmentFilter],+ );// Filter columns for PopoverFilterBuilderconst filterColumns: ColumnDefinition[] = [{@@ -306,7 +436,7 @@ export default function DashboardDetail() {if (localDashboardDefinition && widgetToAdd.data && addWidgetId) {if (!localDashboardDefinition.widgets.some(- (w) => w.widgetId === addWidgetId,+ (w) => w.type === "widget" && w.widgetId === addWidgetId,)) {addWidgetToDashboard(widgetToAdd.data);@@ -338,6 +468,13 @@ export default function DashboardDetail() {...localDashboardDefinition,widgets: updatedWidgets,};++ if (isLockedEditable) {+ // Carry the removal into the clone instead of mutating.+ openCloneFirst("delete_widget", updatedDefinition);+ return;+ }+setLocalDashboardDefinition(updatedDefinition);saveDashboardChanges(updatedDefinition);}@@ -345,6 +482,10 @@ export default function DashboardDetail() {// Handle adding a widgetconst handleAddWidget = () => {+ if (isLockedEditable) {+ openCloneFirst("add_widget");+ return;+ }setIsWidgetDialogOpen(true);};@@ -356,7 +497,7 @@ export default function DashboardDetail() {const mutateCloneDashboard = api.dashboard.cloneDashboard.useMutation({onSuccess: (data) => {utils.dashboard.invalidate();- capture("dashboard:clone_dashboard");+ capture("dashboard:clone_dashboard", { source: "detail_clone_button" });// Redirect to new dashboardif (data?.id) {router.replace(@@ -394,6 +535,7 @@ export default function DashboardDetail() {absoluteTimeRange?.from?.toISOString() ?? "",absoluteTimeRange?.to?.toISOString() ?? "",JSON.stringify(currentFilters),+ selectedEnvironments.join(","),widgetPlacements.map((widget) => widget.id).join(","),].join("|");}, [@@ -402,6 +544,7 @@ export default function DashboardDetail() {currentFilters,dashboardId,projectId,+ selectedEnvironments,widgetPlacements,]);@@ -424,6 +567,25 @@ export default function DashboardDetail() {(dashboard.data?.owner === "LANGFUSE"? " (Langfuse Maintained)": ""),+ titleContent:+ hasCUDAccess && dashboard.data ? (+ <InlineEditText+ value={dashboard.data.name}+ required+ aria-label="Rename dashboard"+ onSave={(name) => {+ capture("dashboard:dashboard_renamed_inline", {+ dashboard_id: dashboardId,+ });+ updateDashboardMetadata.mutate({+ projectId,+ dashboardId,+ name,+ description: dashboard.data?.description ?? "",+ });+ }}+ />+ ) : undefined,breadcrumb: [{name: "Dashboards",@@ -434,8 +596,38 @@ export default function DashboardDetail() {description:dashboard.data?.description || "No description available",},+ actionButtonsLeft: (+ <>+ <MultiSelect+ title="Environment"+ label="Env"+ values={selectedEnvironments}+ onValueChange={useDebounce(setSelectedEnvironments)}+ options={environmentOptions}+ className="my-0 w-auto overflow-hidden"+ />+ <PopoverFilterBuilder+ columns={filterColumns}+ filterState={currentFilters}+ onChange={setCurrentFilters}+ />+ </>+ ),actionButtonsRight: (<>+ {(updateDashboardDefinition.isPending ||+ updateDashboardMetadata.isPending ||+ updateDashboardFilters.isPending ||+ setHomeDashboard.isPending) && (+ <span+ className="flex items-center"+ title="Saving..."+ role="status"+ aria-label="Saving"+ >+ <Loader2 className="text-muted-foreground h-4 w-4 animate-spin" />+ </span>+ )}{hasCUDAccess && hasUnsavedFilterChanges && (<ButtononClick={handleSaveFilters}@@ -447,7 +639,7 @@ export default function DashboardDetail() {: "Save Filters"}</Button>)}- {hasCUDAccess && (+ {hasRbacCUDAccess && (<Button onClick={handleAddWidget}><PlusIcon size={16} className="mr-1 h-4 w-4" />Add Widget@@ -455,6 +647,7 @@ export default function DashboardDetail() {)}{hasCloneAccess && (<Button+ variant="outline"onClick={handleCloneDashboard}disabled={mutateCloneDashboard.isPending}>@@ -462,16 +655,104 @@ export default function DashboardDetail() {Clone</Button>)}+ {hasRbacCUDAccess && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ aria-label="More actions"+ >+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={isCurrentHome || setHomeDashboard.isPending}+ onClick={() => {+ capture("dashboard:home_dashboard_set_default", {+ dashboard_id: dashboardId,+ source: "detail_menu",+ });+ setHomeDashboard.mutate({+ projectId,+ dashboardId:+ dashboardId === LANGFUSE_HOME_DASHBOARD_ID+ ? null+ : dashboardId,+ });+ }}+ >+ <HomeIcon className="mr-2 h-4 w-4" />+ {isCurrentHome ? "Shown on Home" : "Use as Home"}+ </DropdownMenuItem>+ {hasCUDAccess && (+ <DropdownMenuItem+ onClick={() => setIsEditDialogOpen(true)}+ >+ <PencilIcon className="mr-2 h-4 w-4" />+ Edit name & description+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}</>),}}>+ <PageHeaderControlsPortal>+ <TimeRangePicker+ timeRange={timeRange}+ onTimeRangeChange={setTimeRange}+ timeRangePresets={dashboardTimeRangePresets}+ className="my-0 max-w-full overflow-x-auto"+ triggerClassName="px-2"+ disabled={+ lookbackLimit+ ? {+ before: new Date(+ new Date().getTime() -+ lookbackLimit * 24 * 60 * 60 * 1000,+ ),+ }+ : undefined+ }+ />+ </PageHeaderControlsPortal><SelectWidgetDialogopen={isWidgetDialogOpen}onOpenChange={setIsWidgetDialogOpen}projectId={projectId}onSelectWidget={handleSelectWidget}+ onSelectPreset={addPresetToDashboard}+ dashboardId={dashboardId}+ />+ {isEditDialogOpen && dashboard.data && (+ <EditDashboardDialog+ open={isEditDialogOpen}+ onOpenChange={setIsEditDialogOpen}+ projectId={projectId}+ dashboardId={dashboardId}+ initialName={dashboard.data.name}+ initialDescription={dashboard.data.description}+ />+ )}+ <CloneFirstDialog+ open={cloneFirstState.open}+ onOpenChange={(open) =>+ setCloneFirstState((prev) => ({ ...prev, open }))+ }+ projectId={projectId}dashboardId={dashboardId}+ dashboardName={dashboard.data?.name ?? "Dashboard"}+ pendingDefinition={cloneFirstState.pendingDefinition}+ onCancel={() => {+ // Revert the attempted drag/resize by remounting the grid with+ // the unchanged definition.+ setCloneFirstState({ open: false, pendingDefinition: null });+ setGridResetKey((key) => key + 1);+ }}/>{dashboard.isPending || !localDashboardDefinition ? (<NoDataOrLoading isLoading={true} />@@ -483,34 +764,18 @@ export default function DashboardDetail() {</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">- <TimeRangePicker- timeRange={timeRange}- onTimeRangeChange={setTimeRange}- timeRangePresets={dashboardTimeRangePresets}- className="my-0 max-w-full overflow-x-auto"- disabled={- lookbackLimit- ? {- before: new Date(- new Date().getTime() -- lookbackLimit * 24 * 60 * 60 * 1000,- ),- }- : undefined- }- />- <PopoverFilterBuilder- columns={filterColumns}- filterState={currentFilters}- onChange={setCurrentFilters}- />- </div>- </div><DashboardGrid+ key={gridResetKey}widgets={localDashboardDefinition.widgets}onChange={(updatedWidgets) => {+ if (isLockedEditable) {+ // Carry the attempted layout change into the clone.+ openCloneFirst("layout_change", {+ ...localDashboardDefinition,+ widgets: updatedWidgets,+ });+ return;+ }setLocalDashboardDefinition({...localDashboardDefinition,widgets: updatedWidgets,@@ -520,14 +785,19 @@ export default function DashboardDetail() {widgets: updatedWidgets,});}}- canEdit={hasCUDAccess}+ canEdit={hasRbacCUDAccess}dashboardId={dashboardId}projectId={projectId}dateRange={absoluteTimeRange}- filterState={currentFilters}+ filterState={gridFilterState}onDeleteWidget={handleDeleteWidget}dashboardOwner={dashboard.data?.owner}getWidgetSchedulerId={getWidgetSchedulerId}+ onLockedEditAttempt={+ isLockedEditable+ ? () => openCloneFirst("widget_pencil")+ : undefined+ }/></div>)}diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex d2ed814eb7..b1d9c3ce2d 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -1,29 +1,24 @@import { useRouter } from "next/router";-import { GenerationLatencyChart } from "@/src/features/dashboard/components/LatencyChart";-import { ChartScores } from "@/src/features/dashboard/components/ChartScores";-import { TracesBarListChart } from "@/src/features/dashboard/components/TracesBarListChart";-import { ModelCostTable } from "@/src/features/dashboard/components/ModelCostTable";-import { ScoresTable } from "@/src/features/dashboard/components/ScoresTable";-import { ModelUsageChart } from "@/src/features/dashboard/components/ModelUsageChart";-import { TracesAndObservationsTimeSeriesChart } from "@/src/features/dashboard/components/TracesTimeSeriesChart";-import { UserChart } from "@/src/features/dashboard/components/UserChart";+import { api } from "@/src/utils/api";import { TimeRangePicker } from "@/src/components/date-picker";import { PageHeaderControlsPortal } from "@/src/components/layouts/page-header-controls-slot";import { useDashboardFilterOptions } from "@/src/hooks/useDashboardFilterOptions";import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";-import { type ColumnDefinition, type FilterState } from "@langfuse/shared";+import {+ LANGFUSE_HOME_DASHBOARD_DEFINITION,+ LANGFUSE_HOME_DASHBOARD_ID,+ type ColumnDefinition,+ type FilterState,+} from "@langfuse/shared";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";-import { LatencyTables } from "@/src/features/dashboard/components/LatencyTables";-import { useMemo } from "react";+import { useCallback, useEffect, useMemo, useRef } from "react";+import { StringParam, useQueryParam } from "use-query-params";import {DASHBOARD_AGGREGATION_OPTIONS,- findClosestDashboardInterval,toAbsoluteTimeRange,- type DashboardDateRangeAggregationOption,} from "@/src/utils/date-range-utils";import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";import { useDebounce } from "@/src/hooks/useDebounce";-import { ScoreAnalytics } from "@/src/features/dashboard/components/score-analytics/ScoreAnalytics";import SetupTracingButton from "@/src/features/setup/components/SetupTracingButton";import { useEntitlementLimit } from "@/src/features/entitlements/hooks";import Page from "@/src/components/layouts/page";@@ -41,33 +36,26 @@ import {getDashboardQuerySchedulerMaxConcurrent,useDashboardQueryScheduler,} from "@/src/hooks/useDashboardQueryScheduler";--const HOME_DASHBOARD_CARD_IDS = {- traces: "home:traces",- modelCosts: "home:model-costs",- scoresTable: "home:scores-table",- tracesTimeSeries: "home:traces-time-series",- modelUsage: "home:model-usage",- users: "home:users",- chartScores: "home:chart-scores",- latencyTables: "home:latency-tables",- generationLatency: "home:generation-latency",- scoreAnalytics: "home:score-analytics",-} as const;--// Shared across the home time-series charts so hovering one moves the time-// crosshair on all of them (they share one time range + granularity). (LFE-10549)-const HOME_DASHBOARD_SYNC_ID = "home-dashboard-timeseries";+import Link from "next/link";+import { PencilIcon } from "lucide-react";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { Button } from "@/src/components/ui/button";+import { DashboardGrid } from "@/src/features/widgets/components/DashboardGrid";+import { HomeDashboardSelect } from "@/src/features/dashboard/components/HomeDashboardSelect";export default function Dashboard() {const router = useRouter();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();const projectId = router.query.projectId as string;const { timeRange, setTimeRange } = useDashboardDateRange();const { isBetaEnabled } = useV4Beta();const metricsVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";const absoluteTimeRange = useMemo(- () => toAbsoluteTimeRange(timeRange),+ () => toAbsoluteTimeRange(timeRange) ?? undefined,[timeRange],);@@ -132,48 +120,122 @@ export default function Dashboard() {const dashboardTimeRangePresets = DASHBOARD_AGGREGATION_OPTIONS;- const agg = useMemo(() => {- if ("range" in timeRange) {- return timeRange.range as DashboardDateRangeAggregationOption;- }+ const environmentFilter = useMemo(+ () =>+ convertSelectedEnvironmentsToFilter(+ ["environment"],+ selectedEnvironments,+ ),+ [selectedEnvironments],+ );++ const isDashboardDataReady = environmentOptionsState.isReady;- return findClosestDashboardInterval(timeRange) ?? "last7Days";- }, [timeRange]);+ // Home renders the project's selected dashboard (Project.homeDashboardId);+ // unset/missing pointers resolve server-side to the Langfuse-curated+ // default. Fall back to the shared constant so Home still renders when the+ // curated row does not exist yet (e.g. worker has not run against this DB).+ const homeDashboard = api.dashboard.getHomeDashboard.useQuery(+ { projectId },+ { enabled: Boolean(projectId), retry: false },+ );+ const appliedDefaultId =+ homeDashboard.data?.homeDashboardId ?? LANGFUSE_HOME_DASHBOARD_ID;- const fromTimestamp = absoluteTimeRange?.from- ? absoluteTimeRange.from- : new Date(new Date().getTime() - 1000);- const toTimestamp = absoluteTimeRange?.to ? absoluteTimeRange.to : new Date();- const timeFilter = [- {- type: "datetime" as const,- column: "startTime",- operator: ">" as const,- value: fromTimestamp,+ // Selecting in the picker "peeks" a dashboard on Home β tracked in the URL+ // (?dashboard=...) so the state is explicit and linkable; the bare URL+ // always shows the project default. "Set default" persists for the project.+ const [peekParam, setPeekParam] = useQueryParam("dashboard", StringParam);+ const peekId = peekParam && peekParam !== appliedDefaultId ? peekParam : null;+ const setPeekId = useCallback(+ (id: string | null) => {+ // replaceIn: peeking is view state, not a navigation history entry+ setPeekParam(id ?? undefined, "replaceIn");},- {- type: "datetime" as const,- column: "startTime",- operator: "<" as const,- value: toTimestamp,+ [setPeekParam],+ );+ const peekQuery = api.dashboard.getDashboard.useQuery(+ { projectId, dashboardId: peekId ?? "" },+ { enabled: Boolean(projectId) && Boolean(peekId), retry: false },+ );++ const displayedDashboard = peekId+ ? (peekQuery.data ?? null)+ : (homeDashboard.data?.dashboard ?? null);+ const dashboardId =+ displayedDashboard?.id ?? peekId ?? LANGFUSE_HOME_DASHBOARD_ID;+ const dashboardName = displayedDashboard?.name ?? "Langfuse Home";+ const dashboardOwner = displayedDashboard?.owner ?? "LANGFUSE";+ // Show a loading state until the home resolution (or peek fetch) settles β+ // rendering the curated fallback early would flash the wrong layout and+ // fire its widget queries whenever the project default is a different+ // dashboard. The constant fallback only renders once the query has settled+ // without a dashboard (curated row missing / no read access).+ const isResolvingDashboard = peekId+ ? peekQuery.isPending+ : homeDashboard.isPending;++ const hasRbacCUDAccess = useHasProjectAccess({+ projectId,+ scope: "dashboards:CUD",+ });++ // Silent on success: the "Set default" button disappearing is the feedback.+ const setHomeDashboard = api.dashboard.setHomeDashboard.useMutation({+ onSuccess: () => {+ utils.dashboard.getHomeDashboard.invalidate();+ setPeekId(null);},- ];+ onError: (e) => {+ showErrorToast("Failed to set the default Home dashboard", e.message);+ },+ });- const environmentFilter = convertSelectedEnvironmentsToFilter(- ["environment"],- selectedEnvironments,+ // Usage analytics: which dashboard Home actually shows (default vs peek)+ const viewedRef = useRef<string | null>(null);+ useEffect(() => {+ if (!displayedDashboard || viewedRef.current === displayedDashboard.id)+ return;+ viewedRef.current = displayedDashboard.id;+ capture("dashboard:home_dashboard_viewed", {+ dashboard_id: displayedDashboard.id,+ dashboard_owner: displayedDashboard.owner,+ is_peek: Boolean(peekId),+ is_curated_default: !peekId && !homeDashboard.data?.homeDashboardId,+ });+ }, [+ displayedDashboard,+ peekId,+ homeDashboard.data?.homeDashboardId,+ capture,+ ]);++ // Home is a viewing surface: no in-place editing (that lives in the+ // Dashboards section, one pencil click away).+ const definition =+ displayedDashboard?.definition ?? LANGFUSE_HOME_DASHBOARD_DEFINITION;++ // The dashboard's saved filters apply as the base (like the detail page),+ // with Home's own user/environment filters on top.+ const gridFilterState: FilterState = useMemo(+ () => [+ ...(displayedDashboard?.filters ?? []),+ ...userFilterState,+ ...environmentFilter,+ ],+ [displayedDashboard?.filters, userFilterState, environmentFilter],);- const mergedFilterState: FilterState = [- ...userFilterState,- ...timeFilter,- ...environmentFilter,- ];- const isDashboardDataReady = environmentOptionsState.isReady;+ const getWidgetSchedulerId = useCallback(+ (widgetPlacementId: string) =>+ `${projectId}:${dashboardId}:${widgetPlacementId}`,+ [projectId, dashboardId],+ );const schedulerResetKey = useMemo(() => {return [projectId,+ dashboardId,metricsVersion,absoluteTimeRange?.from?.toISOString() ?? "",absoluteTimeRange?.to?.toISOString() ?? "",@@ -183,6 +245,7 @@ export default function Dashboard() {}, [absoluteTimeRange?.from,absoluteTimeRange?.to,+ dashboardId,metricsVersion,projectId,selectedEnvironments,@@ -193,7 +256,6 @@ export default function Dashboard() {maxConcurrent: getDashboardQuerySchedulerMaxConcurrent(timeRange),resetKey: schedulerResetKey,});- const homeSchedulerIdPrefix = `${projectId}:`;return (<DashboardQuerySchedulerProvider@@ -226,6 +288,62 @@ export default function Dashboard() {),actionButtonsRight: (<>+ <HomeDashboardSelect+ projectId={projectId}+ value={dashboardId}+ defaultDashboardId={appliedDefaultId}+ onValueChange={(id) => {+ capture("dashboard:home_dashboard_peeked", {+ dashboard_id: id,+ is_default: id === appliedDefaultId,+ });+ setPeekId(id === appliedDefaultId ? null : id);+ }}+ currentDashboardName={dashboardName}+ />+ {Boolean(peekId) && hasRbacCUDAccess && (+ <Button+ variant="outline"+ loading={setHomeDashboard.isPending}+ title="Show this dashboard on Home for everyone in this project"+ onClick={() => {+ capture("dashboard:home_dashboard_set_default", {+ dashboard_id: dashboardId,+ source: "home_selector",+ });+ setHomeDashboard.mutate({+ projectId,+ dashboardId:+ dashboardId === LANGFUSE_HOME_DASHBOARD_ID+ ? null+ : dashboardId,+ });+ }}+ >+ Set default+ </Button>+ )}+ <Button+ variant="outline"+ size="icon"+ title="Edit this dashboard in Dashboards"+ asChild+ >+ <Link+ href={`/project/${projectId}/dashboards/${encodeURIComponent(dashboardId)}`}+ onClick={() =>+ capture("dashboard:home_edit_pencil_click", {+ dashboard_id: dashboardId,+ dashboard_owner: dashboardOwner,+ })+ }+ >+ <PencilIcon className="h-4 w-4" />+ <span className="sr-only">+ Edit this dashboard in Dashboards+ </span>+ </Link>+ </Button><SetupTracingButton /></>),@@ -250,118 +368,22 @@ export default function Dashboard() {}/></PageHeaderControlsPortal>- {!isDashboardDataReady ? (+ {!isDashboardDataReady || isResolvingDashboard ? (<NoDataOrLoading isLoading />) : (- <div className="grid w-full grid-cols-1 gap-3 overflow-hidden lg:grid-cols-2 xl:grid-cols-6">- <TracesBarListChart- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.traces}`}- />- <ModelCostTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.modelCosts}`}- />- <ScoresTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <TracesAndObservationsTimeSeriesChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- agg={agg}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.tracesTimeSeries}`}- syncId={HOME_DASHBOARD_SYNC_ID}- />- <ModelUsageChart- className="col-span-1 min-h-24 xl:col-span-3"- projectId={projectId}- globalFilterState={mergedFilterState}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- userAndEnvFilterState={[...userFilterState, ...environmentFilter]}- agg={agg}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.modelUsage}`}- syncId={HOME_DASHBOARD_SYNC_ID}- />- <UserChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.users}`}- />- <ChartScores- className="col-span-1 xl:col-span-3"- agg={agg}- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.chartScores}`}- syncId={HOME_DASHBOARD_SYNC_ID}- />- <LatencyTables- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.latencyTables}`}- />- <GenerationLatencyChart- className="col-span-1 flex-auto justify-between lg:col-span-full"- projectId={projectId}- agg={agg}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.generationLatency}`}- syncId={HOME_DASHBOARD_SYNC_ID}- />- <ScoreAnalytics- className="col-span-1 flex-auto justify-between lg:col-span-full"- agg={agg}- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.scoreAnalytics}`}- syncId={HOME_DASHBOARD_SYNC_ID}- />- </div>+ <DashboardGrid+ widgets={definition.widgets}+ onChange={() => undefined}+ canEdit={false}+ dashboardId={dashboardId}+ projectId={projectId}+ dateRange={absoluteTimeRange}+ filterState={gridFilterState}+ onDeleteWidget={() => undefined}+ dashboardOwner={dashboardOwner}+ getWidgetSchedulerId={getWidgetSchedulerId}+ readOnly+ />)}</Page></DashboardQuerySchedulerProvider>diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex a1f8e4d583..c2ca054caf 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -518,6 +518,14 @@}@layer utilities {+ /* react-grid-layout: no tile/container transitions at all β layout+ changes snap into place. The animations added no value and burned CPU+ on window resizes and dashboard switches. */+ .react-grid-layout,+ .react-grid-item {+ transition: none !important;+ }+/* Custom styles for react-grid-layout resize handle */.react-resizable-handle {position: absolute;diff --git a/worker/src/scripts/upsertLangfuseDashboards.ts b/worker/src/scripts/upsertLangfuseDashboards.tsindex 2f308c8155..7de390e153 100644--- a/worker/src/scripts/upsertLangfuseDashboards.ts+++ b/worker/src/scripts/upsertLangfuseDashboards.ts@@ -1,6 +1,7 @@import { z } from "zod";import { prisma } from "@langfuse/shared/src/db";import langfuseDashboards from "../constants/langfuse-dashboards.json";+import { LANGFUSE_HOME_DASHBOARD } from "@langfuse/shared";import {logger,WidgetDomainSchema,@@ -58,8 +59,19 @@ export const upsertLangfuseDashboards = async (force = false) => {const parsed = FileSchema.parse(langfuseDashboards);+ // The curated Home dashboard lives in @langfuse/shared (the web app falls+ // back to the same constant when this row does not exist yet). Its+ // placements are presets, so it brings no widgets of its own.+ const homeDashboard = RawDashboardSchema.parse({+ ...LANGFUSE_HOME_DASHBOARD,+ projectId: null,+ createdBy: null,+ updatedBy: null,+ owner: "LANGFUSE",+ });+await upsertWidgets(parsed.widgets, force);- await upsertDashboards(parsed.dashboards, force);+ await upsertDashboards([...parsed.dashboards, homeDashboard], force);logger.info(`Finished upserting Langfuse dashboards and widgets in ${Date.now() - startTime}ms`,