🪢 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(v4): add organization migration surface (#14578)
Max Deichmann8405149ccf70
diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.tsindex 37a0e40379..9373d492f4 100644--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts@@ -21,13 +21,31 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {const mockedQueryClickhouse = vi.mocked(queryClickhouse);const projectId = "project-v4-transition";+const orgId = "org-v4-transition";+const secondProjectId = "project-v4-transition-second";-const createCaller = (prisma?: Partial<PrismaClient>) =>+const createCaller = (+ prisma?: Partial<PrismaClient>,+ callerSession: Session = session,+) =>v4TransitionRouter.createCaller({- ...createInnerTRPCContext({ session, headers: {} }),+ ...createInnerTRPCContext({ session: callerSession, headers: {} }),...(prisma ? { prisma: prisma as PrismaClient } : {}),});+type OrganizationRole = Session["user"]["organizations"][number]["role"];++const createSessionWithOrgRole = (role: OrganizationRole): Session => ({+ ...session,+ user: {+ ...session.user,+ organizations: session.user.organizations.map((organization) => ({+ ...organization,+ role,+ })),+ },+});+const session: Session = {expires: "1",user: {@@ -37,7 +55,7 @@ const session: Session = {canCreateOrganizations: true,organizations: [{- id: "org-v4-transition",+ id: orgId,name: "V4 Transition Org",role: "OWNER",plan: "cloud:hobby",@@ -517,6 +535,169 @@ describe("v4TransitionRouter", () => {});});+ it("summarizes v4 migration data by active organization project", async () => {+ const mockPrisma = {+ project: {+ findMany: vi.fn().mockResolvedValue([+ { id: projectId, name: "V4 Transition Project" },+ { id: secondProjectId, name: "Second Project" },+ ]),+ },+ jobConfiguration: {+ groupBy: vi.fn().mockResolvedValue([+ {+ projectId,+ _count: { _all: 3 },+ },+ ]),+ },+ posthogIntegration: {+ findMany: vi.fn().mockResolvedValue([+ {+ projectId,+ enabled: true,+ exportSource: "TRACES_OBSERVATIONS",+ },+ ]),+ },+ mixpanelIntegration: {+ findMany: vi.fn().mockResolvedValue([+ {+ projectId: secondProjectId,+ enabled: true,+ exportSource: "TRACES_OBSERVATIONS_EVENTS",+ },+ ]),+ },+ blobStorageIntegration: {+ findMany: vi.fn().mockResolvedValue([+ {+ projectId,+ enabled: true,+ exportSource: "EVENTS",+ },+ {+ projectId: secondProjectId,+ enabled: false,+ exportSource: "TRACES_OBSERVATIONS",+ },+ ]),+ },+ };+ const caller = createCaller(mockPrisma);++ await expect(caller.summaryByProject({ orgId })).resolves.toEqual({+ projects: [+ {+ projectId,+ projectName: "V4 Transition Project",+ traceLevelEvalCount: 3,+ legacyIntegrationCount: 1,+ legacyIntegrations: {+ posthog: true,+ mixpanel: false,+ blobStorage: false,+ },+ },+ {+ projectId: secondProjectId,+ projectName: "Second Project",+ traceLevelEvalCount: 0,+ legacyIntegrationCount: 1,+ legacyIntegrations: {+ posthog: false,+ mixpanel: true,+ blobStorage: false,+ },+ },+ ],+ });++ expect(mockPrisma.project.findMany).toHaveBeenCalledWith({+ where: {+ orgId,+ deletedAt: null,+ },+ select: {+ id: true,+ name: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ });+ expect(mockPrisma.jobConfiguration.groupBy).toHaveBeenCalledWith({+ by: ["projectId"],+ where: {+ projectId: { in: [projectId, secondProjectId] },+ jobType: "EVAL",+ targetObject: "trace",+ },+ _count: { _all: true },+ });+ });++ it("allows organization admins and owners to access org-level v4 data", async () => {+ const mockPrisma = {+ project: {+ findMany: vi.fn().mockResolvedValue([]),+ },+ };++ await expect(+ createCaller(+ mockPrisma,+ createSessionWithOrgRole("OWNER"),+ ).summaryByProject({+ orgId,+ }),+ ).resolves.toEqual({ projects: [] });++ await expect(+ createCaller(+ mockPrisma,+ createSessionWithOrgRole("ADMIN"),+ ).summaryByProject({+ orgId,+ }),+ ).resolves.toEqual({ projects: [] });+ });++ it("forbids organization members from accessing org-level v4 data", async () => {+ const caller = createCaller(+ {+ project: {+ findMany: vi.fn(),+ },+ },+ createSessionWithOrgRole("MEMBER"),+ );++ await expect(caller.summaryByProject({ orgId })).rejects.toMatchObject({+ code: "FORBIDDEN",+ });+ await expect(+ caller.traceLevelEvalExecutionsTimeSeriesByProject({+ orgId,+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),+ toTimestamp: new Date("2026-06-25T13:00:00Z"),+ granularity: "auto",+ }),+ ).rejects.toMatchObject({+ code: "FORBIDDEN",+ });+ await expect(+ caller.timeSeriesByEntrypointByProject({+ orgId,+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),+ toTimestamp: new Date("2026-06-25T00:00:00Z"),+ granularity: "auto",+ }),+ ).rejects.toMatchObject({+ code: "FORBIDDEN",+ });+ });+it("queries trace-level eval execution counts with the same 2 minute buckets as the legacy API timeline", async () => {const mockPrisma = {$queryRaw: vi.fn().mockResolvedValue([@@ -632,4 +813,155 @@ describe("v4TransitionRouter", () => {| undefined;expect(query?.values?.[0]).toBe("1 minute");});++ it("queries trace-level eval execution counts by organization project", async () => {+ const mockPrisma = {+ project: {+ findMany: vi+ .fn()+ .mockResolvedValue([{ id: projectId }, { id: secondProjectId }]),+ },+ $queryRaw: vi.fn().mockResolvedValue([+ {+ projectId,+ time: "2026-06-25T12:00:00Z",+ scoreName: "toxicity",+ count: 4n,+ },+ {+ projectId: secondProjectId,+ time: "2026-06-25T12:04:00Z",+ scoreName: "helpfulness",+ count: 2,+ },+ ]),+ };+ const caller = createCaller(mockPrisma);++ const rows = await caller.traceLevelEvalExecutionsTimeSeriesByProject({+ orgId,+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),+ toTimestamp: new Date("2026-06-25T13:00:00Z"),+ granularity: "auto",+ });++ expect(rows).toContainEqual({+ projectId,+ time: "2026-06-25T12:00:00Z",+ scoreName: "toxicity",+ count: 4,+ });+ expect(rows).toContainEqual({+ projectId: secondProjectId,+ time: "2026-06-25T12:04:00Z",+ scoreName: "helpfulness",+ count: 2,+ });+ expect(rows.every((row) => Boolean(row.projectId))).toBe(true);++ expect(mockPrisma.project.findMany).toHaveBeenCalledWith({+ where: {+ orgId,+ deletedAt: null,+ },+ select: {+ id: true,+ },+ });+ const query = mockPrisma.$queryRaw.mock.calls[0]?.[0] as+ | { sql?: string; text?: string; values?: unknown[] }+ | undefined;+ const queryText = query?.sql ?? query?.text ?? "";++ expect(queryText).toContain('project_id AS "projectId"');+ expect(queryText).toContain("je.project_id IN (?,?)");+ expect(queryText).toContain("bucket_time AT TIME ZONE 'UTC'");+ expect(queryText).toContain("GROUP BY project_id, bucket_time, score_name");+ expect(query?.values).toEqual([+ "2 minutes",+ projectId,+ secondProjectId,+ "trace",+ new Date("2026-06-25T12:00:00Z"),+ new Date("2026-06-25T13:00:00Z"),+ ]);+ });++ it("queries legacy public API usage by organization project", async () => {+ mockedQueryClickhouse.mockResolvedValue([+ {+ projectId,+ time: "2026-06-24T12:00:00Z",+ entrypoint: "publicapi: GET /api/public/traces/{id}",+ count: "0.6666666666666666",+ },+ {+ projectId: secondProjectId,+ time: "2026-06-24T13:00:00Z",+ entrypoint: "publicapi: GET /api/public/metrics",+ count: 3,+ },+ ]);+ const mockPrisma = {+ project: {+ findMany: vi+ .fn()+ .mockResolvedValue([{ id: projectId }, { id: secondProjectId }]),+ },+ };+ const caller = createCaller(mockPrisma);++ const rows = await caller.timeSeriesByEntrypointByProject({+ orgId,+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),+ toTimestamp: new Date("2026-06-25T00:00:00Z"),+ granularity: "auto",+ });++ expect(rows).toHaveLength(50);+ expect(+ rows.filter(+ (row) => row.projectId === projectId && row.entrypoint === "",+ ),+ ).toHaveLength(24);+ expect(+ rows.filter(+ (row) => row.projectId === secondProjectId && row.entrypoint === "",+ ),+ ).toHaveLength(24);+ expect(rows).toContainEqual({+ projectId,+ time: "2026-06-24T12:00:00Z",+ entrypoint: "publicapi: GET /api/public/traces/{id}",+ count: 0.6666666666666666,+ });+ expect(rows).toContainEqual({+ projectId: secondProjectId,+ time: "2026-06-24T13:00:00Z",+ entrypoint: "publicapi: GET /api/public/metrics",+ count: 3,+ });++ expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];+ expect(clickhouseQuery?.query).toContain(+ "toStartOfInterval(event_time_microseconds, INTERVAL 1 HOUR, 'UTC') AS bucket_time",+ );+ expect(clickhouseQuery?.query).toContain(+ "JSONExtractString(log_comment, 'projectId') AS project_id",+ );+ expect(clickhouseQuery?.query).toContain(+ "JSONExtractString(log_comment, 'projectId') IN {projectIds: Array(String)}",+ );+ expect(clickhouseQuery?.query).toContain("project_id AS projectId");+ expect(clickhouseQuery?.query).toContain(+ "GROUP BY project_id, bucket_time, legacy_route",+ );+ expect(clickhouseQuery?.params).toMatchObject({+ projectIds: [projectId, secondProjectId],+ });+ expect(clickhouseQuery?.tags).toEqual({+ route: "v4-org-legacy-api-usage",+ });+ });});diff --git a/web/src/components/date-picker.clienttest.tsx b/web/src/components/date-picker.clienttest.tsxindex bbe45f7cfc..f07ebb65b9 100644--- a/web/src/components/date-picker.clienttest.tsx+++ b/web/src/components/date-picker.clienttest.tsx@@ -2,7 +2,11 @@ import { fireEvent, render, screen } from "@testing-library/react";import { useState } from "react";import { type DateRange } from "react-day-picker";import { Calendar } from "@/src/components/ui/calendar";-import { nextRangeForDayClick } from "@/src/components/date-picker";+import {+ isRangeWithinMaxDuration,+ nextRangeForDayClick,+} from "@/src/components/date-picker";+import { setBeginningOfDay, setEndOfDay } from "@/src/utils/dates";/*** Regression coverage for LFE-8156. The range calendar used to feel "sticky":@@ -51,6 +55,34 @@ describe("nextRangeForDayClick (LFE-8156)", () => {});});+describe("isRangeWithinMaxDuration", () => {+ const maxThirtyDaysMs = 30 * 24 * 60 * 60 * 1000;++ it("allows a range up to the configured maximum duration", () => {+ expect(+ isRangeWithinMaxDuration(+ {+ from: setBeginningOfDay(new Date(2026, 5, 1)),+ to: setEndOfDay(new Date(2026, 5, 30)),+ },+ maxThirtyDaysMs,+ ),+ ).toBe(true);+ });++ it("rejects a range longer than the configured maximum duration", () => {+ expect(+ isRangeWithinMaxDuration(+ {+ from: setBeginningOfDay(new Date(2026, 5, 1)),+ to: setEndOfDay(new Date(2026, 6, 1)),+ },+ maxThirtyDaysMs,+ ),+ ).toBe(false);+ });+});+/*** Integration: drive the real calendar exactly as the pickers do — compute the* next range from the clicked day and "commit" (write URL / form) only oncediff --git a/web/src/components/date-picker.tsx b/web/src/components/date-picker.tsxindex a3bfb41dc9..39ff4e14dc 100644--- a/web/src/components/date-picker.tsx+++ b/web/src/components/date-picker.tsx@@ -124,6 +124,14 @@ export function nextRangeForDayClick(return { from: clickedDay, to: undefined };}+export function isRangeWithinMaxDuration(+ range: RDPDateRange | undefined,+ maxDurationMs: number | undefined,+): boolean {+ if (!range?.from || !range.to || maxDurationMs === undefined) return true;+ return range.to.getTime() - range.from.getTime() <= maxDurationMs;+}+export function DatePickerWithRange({className,dateRange,@@ -302,6 +310,7 @@ export type TimeRangePickerProps = {timeRangePresets: readonly string[];className?: string;disabled?: boolean | { before?: Date; after?: Date } | Date | Date[];+ maxRangeMs?: number;};export function TimeRangePicker({@@ -310,6 +319,7 @@ export function TimeRangePicker({timeRangePresets,onTimeRangeChange,disabled,+ maxRangeMs,}: TimeRangePickerProps) {// Determine the range typeconst rangeType: "named" | "custom" | null = timeRange@@ -318,19 +328,6 @@ export function TimeRangePicker({: "named": null;- // Disable future dates by default, plus any additional disabled prop- const calendarDisabled = React.useMemo(() => {- const futureDisabled = { after: new Date() };-- if (!disabled) return futureDisabled;- if (typeof disabled === "boolean") return disabled;-- // Always return an array when combining with additional restrictions- const disabledArray = Array.isArray(disabled) ? disabled : [disabled];- return [...disabledArray, futureDisabled] as React.ComponentProps<- typeof Calendar- >["disabled"];- }, [disabled]);const namedRangeValue =rangeType === "named" && timeRange && "range" in timeRange? timeRange.range@@ -366,6 +363,46 @@ export function TimeRangePicker({setInternalDateRange(committedDateRange);}, [committedDateRange]);+ // Disable future dates by default, plus any additional disabled prop.+ // When a custom range is mid-selection, also disable days that would complete+ // a range longer than the caller's maximum duration.+ const calendarDisabled = React.useMemo(() => {+ const futureDisabled = { after: new Date() };++ if (typeof disabled === "boolean") return disabled;++ const disabledArray = disabled+ ? Array.isArray(disabled)+ ? disabled+ : [disabled]+ : [];+ const maxRangeDisabled =+ maxRangeMs !== undefined &&+ internalDateRange?.from &&+ !internalDateRange.to+ ? [+ {+ before: new Date(+ setEndOfDay(internalDateRange.from).getTime() - maxRangeMs + 1,+ ),+ },+ {+ after: new Date(+ setBeginningOfDay(internalDateRange.from).getTime() ++ maxRangeMs -+ 1,+ ),+ },+ ]+ : [];++ return [+ ...disabledArray,+ futureDisabled,+ ...maxRangeDisabled,+ ] as React.ComponentProps<typeof Calendar>["disabled"];+ }, [disabled, internalDateRange, maxRangeMs]);+const setNewDateRange = (internalDateRange: RDPDateRange | undefined,newFromDate: Date | undefined,@@ -381,6 +418,8 @@ export function TimeRangePicker({const updateDateRange = (newRange: RDPDateRange | undefined) => {if (newRange && newRange.from && newRange.to) {+ if (!isRangeWithinMaxDuration(newRange, maxRangeMs)) return;+onTimeRangeChange({from: newRange.from,to: newRange.to,@@ -395,6 +434,8 @@ export function TimeRangePicker({from: setBeginningOfDay(next.from),to: next.to ? setEndOfDay(next.to) : undefined,};+ if (!isRangeWithinMaxDuration(newRange, maxRangeMs)) return;+setInternalDateRange(newRange);updateDateRange(newRange);};@@ -406,6 +447,8 @@ export function TimeRangePicker({newDateTime,internalDateRange?.to,);+ if (!isRangeWithinMaxDuration(newRange, maxRangeMs)) return;+setInternalDateRange(newRange);updateDateRange(newRange);};@@ -417,6 +460,8 @@ export function TimeRangePicker({internalDateRange?.from,newDateTime,);+ if (!isRangeWithinMaxDuration(newRange, maxRangeMs)) return;+setInternalDateRange(newRange);updateDateRange(newRange);};diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/web/src/features/rbac/constants/organizationAccessRights.tsindex 2b3f27b11c..0477eb3701 100644--- a/web/src/features/rbac/constants/organizationAccessRights.ts+++ b/web/src/features/rbac/constants/organizationAccessRights.ts@@ -12,11 +12,15 @@ export const organizationScopes = ["organizationMembers:CUD","langfuseCloudBilling:CRUD","auditLogs:read",+ "v4Migration:read",] as const;// type string of all Resource:Action, e.g. "organizationMembers:read"export type OrganizationScope = (typeof organizationScopes)[number];+export const v4MigrationOrgScope =+ "v4Migration:read" satisfies OrganizationScope;+export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {OWNER: ["projects:create",@@ -28,6 +32,7 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {"organizationMembers:read","langfuseCloudBilling:CRUD","auditLogs:read",+ v4MigrationOrgScope,],ADMIN: ["projects:create",@@ -36,6 +41,7 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {"organizationMembers:CUD","organizationMembers:read","auditLogs:read",+ v4MigrationOrgScope,],MEMBER: ["organizationMembers:read"],VIEWER: [],diff --git a/web/src/features/v4/components/V4MigrationProjectCards.tsx b/web/src/features/v4/components/V4MigrationProjectCards.tsxnew file mode 100644index 0000000000..0509d65511--- /dev/null+++ b/web/src/features/v4/components/V4MigrationProjectCards.tsx@@ -0,0 +1,321 @@+import { useMemo, type ReactNode } from "react";+import Link from "next/link";+import { ArrowRight, ExternalLink } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { encodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";+import { numberFormatter } from "@/src/utils/numbers";++export type V4LegacyIntegrations = {+ posthog: boolean;+ mixpanel: boolean;+ blobStorage: boolean;+};++export type V4MigrationSummary = {+ traceLevelEvalCount: number;+ legacyIntegrationCount: number;+ legacyIntegrations: V4LegacyIntegrations;+};++export type V4LegacyApiUsagePoint = {+ time: string;+ entrypoint: string;+ count: number;+};++export type V4TraceLevelEvalExecutionPoint = {+ time: string;+ scoreName: string;+ count: number;+};++export const PUBLIC_API_DOCS = [+ {+ label: "V4 upgrade guide",+ href: "https://langfuse.com/docs/v4",+ },+ {+ label: "Observations API v2",+ href: "https://langfuse.com/docs/api-and-data-platform/features/observations-api#v2",+ },+ {+ label: "Metrics API v2",+ href: "https://langfuse.com/docs/metrics/features/metrics-api#v2",+ },+] as const;++export const INTEGRATION_LINKS = [+ {+ key: "posthog",+ label: "PostHog",+ path: "posthog",+ },+ {+ key: "mixpanel",+ label: "Mixpanel",+ path: "mixpanel",+ },+ {+ key: "blobStorage",+ label: "Blob Storage",+ path: "blobstorage",+ },+] as const satisfies ReadonlyArray<{+ key: keyof V4LegacyIntegrations;+ label: string;+ path: string;+}>;++export const getTraceLevelEvalsHref = (projectId: string) => ({+ pathname: `/project/${projectId}/evals`,+ query: {+ filter: encodeFiltersGeneric([+ {+ column: "target",+ type: "stringOptions",+ operator: "any of",+ value: ["trace"],+ },+ ]),+ },+});++const CardError = ({ children }: { children: string }) => (+ <div className="border-destructive/30 bg-destructive/10 text-destructive flex min-h-28 items-center rounded-md border p-4 text-sm">+ {children}+ </div>+);++export const ProductLinkButton = ({+ href,+ children,+}: {+ href: string | { pathname: string; query: Record<string, string> };+ children: ReactNode;+}) => (+ <Button asChild variant="outline" size="sm">+ <Link href={href}>+ {children}+ <ArrowRight className="ml-1 h-3.5 w-3.5" />+ </Link>+ </Button>+);++const ExternalDocButton = ({+ href,+ children,+}: {+ href: string;+ children: ReactNode;+}) => (+ <Button asChild variant="outline" size="sm">+ <a href={href} target="_blank" rel="noopener noreferrer">+ {children}+ <ExternalLink className="ml-1 h-3.5 w-3.5" />+ </a>+ </Button>+);++export const V4MigrationProjectCards = ({+ projectId,+ summary,+ legacyApiUsage,+ traceLevelEvalExecutions,+ isSummaryLoading,+ isLegacyApiUsageLoading,+ isTraceLevelEvalExecutionsLoading,+ hasSummaryError,+ hasLegacyApiUsageError,+ hasTraceLevelEvalExecutionsError,+}: {+ projectId: string;+ summary: V4MigrationSummary | undefined;+ legacyApiUsage: V4LegacyApiUsagePoint[] | undefined;+ traceLevelEvalExecutions: V4TraceLevelEvalExecutionPoint[] | undefined;+ isSummaryLoading: boolean;+ isLegacyApiUsageLoading: boolean;+ isTraceLevelEvalExecutionsLoading: boolean;+ hasSummaryError: boolean;+ hasLegacyApiUsageError: boolean;+ hasTraceLevelEvalExecutionsError: boolean;+}) => {+ const traceLevelEvalsHref = useMemo(+ () => getTraceLevelEvalsHref(projectId),+ [projectId],+ );++ const legacyIntegrationLinks = useMemo(+ () =>+ INTEGRATION_LINKS.filter(+ (link) => summary?.legacyIntegrations[link.key] === true,+ ).map((link) => ({+ ...link,+ href: `/project/${projectId}/settings/integrations/${link.path}`,+ })),+ [projectId, summary?.legacyIntegrations],+ );++ const integrationsHref = `/project/${projectId}/settings/integrations`;++ const chartData = useMemo(+ () =>+ legacyApiUsage?.map((row) => ({+ time_dimension: row.time,+ dimension: row.entrypoint,+ metric: row.count,+ })) ?? [],+ [legacyApiUsage],+ );++ const evalExecutionChartData = useMemo(+ () =>+ traceLevelEvalExecutions?.map((row) => ({+ time_dimension: row.time,+ dimension: row.scoreName,+ metric: row.count,+ })) ?? [],+ [traceLevelEvalExecutions],+ );++ return (+ <>+ <div className="grid grid-cols-1 items-stretch gap-3 lg:grid-cols-[minmax(0,2fr)_minmax(20rem,1fr)]">+ <DashboardCard+ title="Trace-level evals"+ description="Trace-targeting evaluator configs and non-cancelled execution jobs by generated score name."+ isLoading={isSummaryLoading || isTraceLevelEvalExecutionsLoading}+ cardContentClassName="min-h-[30rem]"+ headerClassName="pr-12"+ headerRight={+ <ProductLinkButton href={traceLevelEvalsHref}>+ View evals+ </ProductLinkButton>+ }+ >+ <div className="flex flex-col gap-4">+ {hasSummaryError ? (+ <CardError>Failed to load trace-level evals.</CardError>+ ) : (+ <div>+ <p className="text-muted-foreground text-sm">+ Configured trace-level evals+ </p>+ <div className="text-4xl font-semibold">+ {numberFormatter(summary?.traceLevelEvalCount ?? 0, 0)}+ </div>+ </div>+ )}++ {hasTraceLevelEvalExecutionsError ? (+ <CardError>Failed to load trace-level eval executions.</CardError>+ ) : evalExecutionChartData.length > 0 ? (+ <div className="h-[22rem] w-full">+ <Chart+ chartType="BAR_TIME_SERIES"+ data={evalExecutionChartData}+ rowLimit={1_000}+ chartConfig={{+ type: "BAR_TIME_SERIES",+ unit: "short",+ }}+ overrideWarning+ />+ </div>+ ) : (+ <NoDataOrLoading+ isLoading={isTraceLevelEvalExecutionsLoading}+ description="No trace-level eval executions were found for this project in the selected time range."+ className="min-h-[22rem]"+ />+ )}+ </div>+ </DashboardCard>++ <DashboardCard+ title="Integrations"+ description="PostHog, Mixpanel, and Blob Storage exports that need review for V4."+ isLoading={isSummaryLoading}+ >+ {hasSummaryError ? (+ <CardError>Failed to load integrations.</CardError>+ ) : (+ <div className="flex min-h-32 flex-col gap-4">+ <div>+ <p className="text-muted-foreground text-sm">+ Configured integrations to review+ </p>+ <div className="text-4xl font-semibold">+ {numberFormatter(summary?.legacyIntegrationCount ?? 0, 0)}+ </div>+ </div>++ <div className="flex flex-wrap gap-2">+ <ProductLinkButton href={integrationsHref}>+ View integrations+ </ProductLinkButton>+ {legacyIntegrationLinks.length > 0+ ? legacyIntegrationLinks.map((link) => (+ <ProductLinkButton key={link.key} href={link.href}>+ {link.label}+ </ProductLinkButton>+ ))+ : null}+ </div>+ </div>+ )}+ </DashboardCard>+ </div>++ <DashboardCard+ title="Public API calls to review"+ description="ClickHouse-backed public API calls that may need changes for V4."+ isLoading={isLegacyApiUsageLoading}+ cardContentClassName="min-h-[32rem]"+ headerClassName="pr-12"+ >+ {hasLegacyApiUsageError ? (+ <div className="border-destructive/30 bg-destructive/10 text-destructive flex min-h-36 items-center rounded-md border p-4 text-sm">+ Failed to load public API usage.+ </div>+ ) : (+ <>+ <div className="flex flex-wrap gap-2">+ {PUBLIC_API_DOCS.map((doc) => (+ <ExternalDocButton key={doc.href} href={doc.href}>+ {doc.label}+ </ExternalDocButton>+ ))}+ </div>+ <p className="text-muted-foreground text-sm">+ We do not have query-log data for GET /api/public/sessions.+ </p>++ {chartData.length > 0 ? (+ <div className="h-[30rem] w-full">+ <Chart+ chartType="BAR_TIME_SERIES"+ data={chartData}+ rowLimit={1_000}+ chartConfig={{+ type: "BAR_TIME_SERIES",+ unit: "short",+ }}+ overrideWarning+ />+ </div>+ ) : (+ <NoDataOrLoading+ isLoading={isLegacyApiUsageLoading}+ description="No ClickHouse-backed public API usage was found for this project in the selected time range."+ className="min-h-[30rem]"+ />+ )}+ </>+ )}+ </DashboardCard>+ </>+ );+};diff --git a/web/src/features/v4/server/v4TransitionRouter.ts b/web/src/features/v4/server/v4TransitionRouter.tsindex 20c578a130..8c8d2b3d38 100644--- a/web/src/features/v4/server/v4TransitionRouter.ts+++ b/web/src/features/v4/server/v4TransitionRouter.ts@@ -1,8 +1,11 @@import { z } from "zod/v4";import {createTRPCRouter,+ protectedOrganizationProcedure,protectedProjectProcedure,} from "@/src/server/api/trpc";+import { v4MigrationOrgScope } from "@/src/features/rbac/constants/organizationAccessRights";+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import {AnalyticsIntegrationExportSource,Prisma,@@ -106,6 +109,24 @@ const timelineInputSchema = z{ message: "V4 timeline ranges cannot exceed 30 days" },);+const organizationTimelineInputSchema = z+ .object({+ orgId: z.string(),+ fromTimestamp: z.date(),+ toTimestamp: z.date(),+ granularity: timelineGranularity.default("auto"),+ })+ .refine(+ ({ fromTimestamp, toTimestamp }) =>+ toTimestamp.getTime() > fromTimestamp.getTime(),+ { message: "fromTimestamp must be before toTimestamp" },+ )+ .refine(+ ({ fromTimestamp, toTimestamp }) =>+ toTimestamp.getTime() - fromTimestamp.getTime() <= MAX_TIMELINE_RANGE_MS,+ { message: "V4 timeline ranges cannot exceed 30 days" },+ );+type LegacyApiUsageRow = {time: string;entrypoint: string;@@ -118,6 +139,14 @@ type LegacyApiUsageResultRow = {count: number;};+type LegacyApiUsageByProjectRow = LegacyApiUsageRow & {+ projectId: string;+};++type LegacyApiUsageByProjectResultRow = LegacyApiUsageResultRow & {+ projectId: string;+};+const floorTimelineBucket = (timestamp: Date,granularity: ResolvedTimelineGranularity,@@ -213,6 +242,15 @@ const compareTimelineRows = (return left.entrypoint.localeCompare(right.entrypoint);};+const compareTimelineRowsByProject = (+ left: LegacyApiUsageByProjectResultRow,+ right: LegacyApiUsageByProjectResultRow,+): number => {+ if (left.projectId < right.projectId) return -1;+ if (left.projectId > right.projectId) return 1;+ return compareTimelineRows(left, right);+};+type TraceLevelEvalExecutionTimeSeriesRow = {time: string;scoreName: string;@@ -225,6 +263,22 @@ type TraceLevelEvalExecutionTimeSeriesPoint = {count: number;};+type TraceLevelEvalExecutionTimeSeriesByProjectRow =+ TraceLevelEvalExecutionTimeSeriesRow & {+ projectId: string;+ };++type TraceLevelEvalExecutionTimeSeriesByProjectPoint =+ TraceLevelEvalExecutionTimeSeriesPoint & {+ projectId: string;+ };++type LegacyIntegrations = {+ posthog: boolean;+ mixpanel: boolean;+ blobStorage: boolean;+};+const fillTraceLevelEvalExecutionBuckets = ({rows,fromTimestamp,@@ -267,6 +321,79 @@ const fillTraceLevelEvalExecutionBuckets = ({return filledRows;};+const fillTraceLevelEvalExecutionBucketsByProject = ({+ rows,+ fromTimestamp,+ toTimestamp,+ granularity,+}: {+ rows: TraceLevelEvalExecutionTimeSeriesByProjectPoint[];+ fromTimestamp: Date;+ toTimestamp: Date;+ granularity: ResolvedTimelineGranularity;+}): TraceLevelEvalExecutionTimeSeriesByProjectPoint[] => {+ const rowsByProject = new Map<+ string,+ TraceLevelEvalExecutionTimeSeriesPoint[]+ >();++ for (const row of rows) {+ const projectRows = rowsByProject.get(row.projectId) ?? [];+ projectRows.push({+ time: row.time,+ scoreName: row.scoreName,+ count: row.count,+ });+ rowsByProject.set(row.projectId, projectRows);+ }++ return Array.from(rowsByProject.entries()).flatMap(+ ([projectId, projectRows]) =>+ fillTraceLevelEvalExecutionBuckets({+ rows: projectRows,+ fromTimestamp,+ toTimestamp,+ granularity,+ }).map((row) => ({+ projectId,+ ...row,+ })),+ );+};++const protectedV4MigrationOrgProcedure = protectedOrganizationProcedure.use(+ ({ ctx, next }) => {+ throwIfNoOrganizationAccess({+ role: ctx.session.orgRole,+ scope: v4MigrationOrgScope,+ });+ return next();+ },+);++const getLegacyIntegrations = ({+ posthogIntegration,+ mixpanelIntegration,+ blobStorageIntegration,+}: {+ posthogIntegration:+ | { enabled: boolean; exportSource: AnalyticsIntegrationExportSource }+ | null+ | undefined;+ mixpanelIntegration:+ | { enabled: boolean; exportSource: AnalyticsIntegrationExportSource }+ | null+ | undefined;+ blobStorageIntegration:+ | { enabled: boolean; exportSource: AnalyticsIntegrationExportSource }+ | null+ | undefined;+}): LegacyIntegrations => ({+ posthog: isEnabledLegacyIntegration(posthogIntegration),+ mixpanel: isEnabledLegacyIntegration(mixpanelIntegration),+ blobStorage: isEnabledLegacyIntegration(blobStorageIntegration),+});+export const v4TransitionRouter = createTRPCRouter({summary: protectedProjectProcedure.input(z.object({ projectId: z.string() }))@@ -298,11 +425,11 @@ export const v4TransitionRouter = createTRPCRouter({}),]);- const legacyIntegrations = {- posthog: isEnabledLegacyIntegration(posthogIntegration),- mixpanel: isEnabledLegacyIntegration(mixpanelIntegration),- blobStorage: isEnabledLegacyIntegration(blobStorageIntegration),- };+ const legacyIntegrations = getLegacyIntegrations({+ posthogIntegration,+ mixpanelIntegration,+ blobStorageIntegration,+ });return {traceLevelEvalCount,@@ -312,6 +439,104 @@ export const v4TransitionRouter = createTRPCRouter({};}),+ summaryByProject: protectedV4MigrationOrgProcedure+ .input(z.object({ orgId: z.string() }))+ .query(async ({ input, ctx }) => {+ const projects = await ctx.prisma.project.findMany({+ where: {+ orgId: input.orgId,+ deletedAt: null,+ },+ select: {+ id: true,+ name: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ });+ const projectIds = projects.map((project) => project.id);++ if (projectIds.length === 0) {+ return { projects: [] };+ }++ const [+ traceLevelEvalCounts,+ posthogIntegrations,+ mixpanelIntegrations,+ blobStorageIntegrations,+ ] = await Promise.all([+ ctx.prisma.jobConfiguration.groupBy({+ by: ["projectId"],+ where: {+ projectId: { in: projectIds },+ jobType: "EVAL",+ targetObject: TRACE_EVAL_TARGET,+ },+ _count: { _all: true },+ }),+ ctx.prisma.posthogIntegration.findMany({+ where: { projectId: { in: projectIds } },+ select: { projectId: true, enabled: true, exportSource: true },+ }),+ ctx.prisma.mixpanelIntegration.findMany({+ where: { projectId: { in: projectIds } },+ select: { projectId: true, enabled: true, exportSource: true },+ }),+ ctx.prisma.blobStorageIntegration.findMany({+ where: { projectId: { in: projectIds } },+ select: { projectId: true, enabled: true, exportSource: true },+ }),+ ]);++ const traceLevelEvalCountsByProjectId = new Map(+ traceLevelEvalCounts.map((row) => [row.projectId, row._count._all]),+ );+ const posthogIntegrationsByProjectId = new Map(+ posthogIntegrations.map((integration) => [+ integration.projectId,+ integration,+ ]),+ );+ const mixpanelIntegrationsByProjectId = new Map(+ mixpanelIntegrations.map((integration) => [+ integration.projectId,+ integration,+ ]),+ );+ const blobStorageIntegrationsByProjectId = new Map(+ blobStorageIntegrations.map((integration) => [+ integration.projectId,+ integration,+ ]),+ );++ return {+ projects: projects.map((project) => {+ const legacyIntegrations = getLegacyIntegrations({+ posthogIntegration: posthogIntegrationsByProjectId.get(project.id),+ mixpanelIntegration: mixpanelIntegrationsByProjectId.get(+ project.id,+ ),+ blobStorageIntegration: blobStorageIntegrationsByProjectId.get(+ project.id,+ ),+ });++ return {+ projectId: project.id,+ projectName: project.name,+ traceLevelEvalCount:+ traceLevelEvalCountsByProjectId.get(project.id) ?? 0,+ legacyIntegrationCount:+ Object.values(legacyIntegrations).filter(Boolean).length,+ legacyIntegrations,+ };+ }),+ };+ }),+traceLevelEvalExecutionsTimeSeries: protectedProjectProcedure.input(timelineInputSchema).query(async ({ input, ctx }) => {@@ -361,6 +586,71 @@ ORDER BY bucket_time ASC, score_name ASC});}),+ traceLevelEvalExecutionsTimeSeriesByProject: protectedV4MigrationOrgProcedure+ .input(organizationTimelineInputSchema)+ .query(async ({ input, ctx }) => {+ const projects = await ctx.prisma.project.findMany({+ where: {+ orgId: input.orgId,+ deletedAt: null,+ },+ select: {+ id: true,+ },+ });+ const projectIds = projects.map((project) => project.id);++ if (projectIds.length === 0) return [];++ const granularity = resolveTimelineGranularity(+ input.fromTimestamp,+ input.toTimestamp,+ );+ const bucketExpression = getPostgresTimelineBucketExpression(granularity);++ const rows = await ctx.prisma.$queryRaw<+ TraceLevelEvalExecutionTimeSeriesByProjectRow[]+ >(Prisma.sql`+WITH selected AS (+ SELECT+ je.project_id AS project_id,+ ${bucketExpression} AS bucket_time,+ jc.score_name AS score_name+ FROM job_executions je+ INNER JOIN job_configurations jc ON jc.id = je.job_configuration_id+ AND jc.project_id = je.project_id+ WHERE je.project_id IN (${Prisma.join(projectIds)})+ AND jc.project_id = je.project_id+ AND jc.job_type = 'EVAL'+ AND jc.target_object = ${TRACE_EVAL_TARGET}+ AND je.status != 'CANCELLED'+ AND je.created_at >= ${input.fromTimestamp}+ AND je.created_at <= ${input.toTimestamp}+)++SELECT+ project_id AS "projectId",+ to_char(bucket_time AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS time,+ score_name AS "scoreName",+ COUNT(*)::bigint AS count+FROM selected+GROUP BY project_id, bucket_time, score_name+ORDER BY project_id ASC, bucket_time ASC, score_name ASC+ `);++ return fillTraceLevelEvalExecutionBucketsByProject({+ rows: rows.map((row) => ({+ projectId: row.projectId,+ time: row.time,+ scoreName: row.scoreName,+ count: Number(row.count),+ })),+ fromTimestamp: input.fromTimestamp,+ toTimestamp: input.toTimestamp,+ granularity,+ });+ }),+timeSeriesByEntrypoint: protectedProjectProcedure.input(timelineInputSchema).query(async ({ input }) => {@@ -478,4 +768,144 @@ SETTINGS skip_unavailable_shards = 1.concat(dataRows).sort(compareTimelineRows);}),++ timeSeriesByEntrypointByProject: protectedV4MigrationOrgProcedure+ .input(organizationTimelineInputSchema)+ .query(async ({ input, ctx }) => {+ const projects = await ctx.prisma.project.findMany({+ where: {+ orgId: input.orgId,+ deletedAt: null,+ },+ select: {+ id: true,+ },+ });+ const projectIds = projects.map((project) => project.id);++ if (projectIds.length === 0) return [];++ const granularity = resolveTimelineGranularity(+ input.fromTimestamp,+ input.toTimestamp,+ );+ const bucketTimeSql = getTimelineBucketSql(+ "event_time_microseconds",+ granularity,+ );++ const rows = await queryClickhouse<LegacyApiUsageByProjectRow>({+ query: `+WITH selected AS (+ SELECT+ ${bucketTimeSql} AS bucket_time,+ JSONExtractString(log_comment, 'projectId') AS project_id,+ splitByChar('?', JSONExtractString(log_comment, 'route'))[1] AS route_path+ FROM ${systemTableRef("system.query_log")}+ WHERE+ event_time >= {fromTimestamp: DateTime64(3)}+ AND event_time <= {toTimestamp: DateTime64(3)}+ AND event_date >= toDate({fromTimestamp: DateTime64(3)})+ AND event_date <= toDate({toTimestamp: DateTime64(3)})+ AND type = 'QueryFinish'+ AND JSONExtractString(log_comment, 'tag_schema_version') = '1'+ AND JSONExtractString(log_comment, 'surface') = 'publicapi'+ AND JSONExtractString(log_comment, 'projectId') IN {projectIds: Array(String)}+),+classified AS (+ SELECT+ project_id,+ bucket_time,+ multiIf(+ route_path IN (+ 'GET /api/public/spans',+ 'GET /api/public/generations',+ 'GET /api/public/traces',+ 'GET /api/public/sessions',+ 'GET /api/public/observations',+ 'GET /api/public/scores',+ 'GET /api/public/v2/scores',+ 'GET /api/public/metrics',+ 'GET /api/public/metrics/daily'+ ), route_path,+ match(route_path, '^GET /api/public/traces/[^/?#]+$'), 'GET /api/public/traces/{id}',+ match(route_path, '^GET /api/public/sessions/[^/?#]+$'), 'GET /api/public/sessions/{id}',+ match(route_path, '^GET /api/public/observations/[^/?#]+$'), 'GET /api/public/observations/{id}',+ match(route_path, '^GET /api/public/scores/[^/?#]+$'), 'GET /api/public/scores/{id}',+ match(route_path, '^GET /api/public/v2/scores/[^/?#]+$'), 'GET /api/public/v2/scores/{id}',+ NULL+ ) AS legacy_route,+ multiIf(+ route_path IN (+ 'GET /api/public/spans',+ 'GET /api/public/generations',+ 'GET /api/public/traces',+ 'GET /api/public/observations',+ 'GET /api/public/scores',+ 'GET /api/public/v2/scores',+ 'GET /api/public/metrics/daily'+ ), 2,+ route_path IN (+ 'GET /api/public/sessions',+ 'GET /api/public/metrics'+ ), 1,+ match(route_path, '^GET /api/public/traces/[^/?#]+$'), 3,+ match(route_path, '^GET /api/public/sessions/[^/?#]+$'), 1,+ match(route_path, '^GET /api/public/observations/[^/?#]+$'), 1,+ match(route_path, '^GET /api/public/scores/[^/?#]+$'), 1,+ match(route_path, '^GET /api/public/v2/scores/[^/?#]+$'), 1,+ NULL+ ) AS clickhouse_queries_per_api_call+ FROM selected+)++SELECT+ project_id AS projectId,+ formatDateTime(bucket_time, '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS time,+ concat('publicapi: ', legacy_route) AS entrypoint,+ sum(1.0 / clickhouse_queries_per_api_call) AS count+FROM classified+WHERE legacy_route IS NOT NULL+ AND clickhouse_queries_per_api_call IS NOT NULL+GROUP BY project_id, bucket_time, legacy_route+ORDER BY project_id ASC, bucket_time ASC, legacy_route ASC+SETTINGS skip_unavailable_shards = 1+ `,+ params: {+ projectIds,+ fromTimestamp: convertDateToClickhouseDateTime(input.fromTimestamp),+ toTimestamp: convertDateToClickhouseDateTime(input.toTimestamp),+ },+ tags: {+ route: "v4-org-legacy-api-usage",+ },+ preferredClickhouseService: "ReadOnly",+ clickhouseSettings: {+ skip_unavailable_shards: 1,+ },+ });++ const dataRows = rows.map((row) => ({+ projectId: row.projectId,+ time: row.time,+ entrypoint: row.entrypoint,+ count: Number(row.count),+ }));++ return dataRows.length === 0+ ? dataRows+ : Array.from(new Set(dataRows.map((row) => row.projectId)))+ .flatMap((projectId) =>+ getEmptyTimelineBuckets(+ input.fromTimestamp,+ input.toTimestamp,+ granularity,+ ).map((row) => ({+ projectId,+ ...row,+ })),+ )+ .concat(dataRows)+ .sort(compareTimelineRowsByProject);+ }),});diff --git a/web/src/pages/organization/[organizationId]/v4/index.tsx b/web/src/pages/organization/[organizationId]/v4/index.tsxnew file mode 100644index 0000000000..7b52860bab--- /dev/null+++ b/web/src/pages/organization/[organizationId]/v4/index.tsx@@ -0,0 +1,365 @@+import { useMemo } from "react";+import Link from "next/link";+import { useRouter } from "next/router";+import { useSession } from "next-auth/react";+import { v4MigrationOrgScope } from "@/src/features/rbac/constants/organizationAccessRights";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import Page from "@/src/components/layouts/page";+import { ErrorPage } from "@/src/components/error-page";+import { TimeRangePicker } from "@/src/components/date-picker";+import {+ DEFAULT_DASHBOARD_AGGREGATION_SELECTION,+ toAbsoluteTimeRange,+ type AbsoluteTimeRange,+ type TimeRange,+} from "@/src/utils/date-range-utils";+import { useGlobalDateRange } from "@/src/features/global-time-range/useGlobalDateRange";+import { api } from "@/src/utils/api";+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/src/components/ui/table";+import { numberFormatter } from "@/src/utils/numbers";+import {+ getTraceLevelEvalsHref,+ ProductLinkButton,+ V4MigrationProjectCards,+ type V4LegacyApiUsagePoint,+ type V4MigrationSummary,+ type V4TraceLevelEvalExecutionPoint,+} from "@/src/features/v4/components/V4MigrationProjectCards";++type ProjectSummary = V4MigrationSummary & {+ projectId: string;+ projectName: string;+};++type ProjectScopedLegacyApiUsagePoint = V4LegacyApiUsagePoint & {+ projectId: string;+};++type ProjectScopedEvalExecutionPoint = V4TraceLevelEvalExecutionPoint & {+ projectId: string;+};++const V4_TIME_RANGE_PRESETS = [+ "last5Minutes",+ "last30Minutes",+ "last1Hour",+ "last3Hours",+ "last1Day",+ "last7Days",+ "last30Days",+] as const;++const MAX_V4_TIMELINE_RANGE_MS = 30 * 24 * 60 * 60 * 1000;++const getCappedAbsoluteTimeRange = (+ timeRange: TimeRange,+): AbsoluteTimeRange => {+ const absoluteRange =+ toAbsoluteTimeRange(timeRange) ??+ ({+ from: new Date(Date.now() - 24 * 60 * 60 * 1000),+ to: new Date(),+ } satisfies AbsoluteTimeRange);++ if (+ absoluteRange.to.getTime() - absoluteRange.from.getTime() <=+ MAX_V4_TIMELINE_RANGE_MS+ ) {+ return absoluteRange;+ }++ return {+ from: new Date(absoluteRange.to.getTime() - MAX_V4_TIMELINE_RANGE_MS),+ to: absoluteRange.to,+ };+};++const groupByProjectId = <T extends { projectId: string }>(+ rows: T[] | undefined,+): Map<string, T[]> => {+ const grouped = new Map<string, T[]>();++ for (const row of rows ?? []) {+ const projectRows = grouped.get(row.projectId) ?? [];+ projectRows.push(row);+ grouped.set(row.projectId, projectRows);+ }++ return grouped;+};++const sumLegacyApiUsage = (+ rows: ProjectScopedLegacyApiUsagePoint[] | undefined,+): number => rows?.reduce((total, row) => total + row.count, 0) ?? 0;++const getProjectActionCount = (+ project: ProjectSummary,+ legacyApiUsageCount: number,+): number =>+ project.traceLevelEvalCount ++ project.legacyIntegrationCount ++ legacyApiUsageCount;++export default function OrganizationV4Page() {+ const router = useRouter();+ const session = useSession();+ const organizationId = router.query.organizationId as string | undefined;+ const { timeRange, setTimeRange } = useGlobalDateRange({+ allowedRanges: V4_TIME_RANGE_PRESETS,+ fallback: DEFAULT_DASHBOARD_AGGREGATION_SELECTION,+ });+ const canViewOrgV4Page = useHasOrganizationAccess({+ organizationId,+ scope: v4MigrationOrgScope,+ });++ const absoluteTimeRange = useMemo(() => {+ return getCappedAbsoluteTimeRange(timeRange);+ }, [timeRange]);++ const earliestSelectableDate = useMemo(+ () => new Date(Date.now() - MAX_V4_TIMELINE_RANGE_MS),+ [],+ );++ const summaryByProject = api.v4Transition.summaryByProject.useQuery(+ {+ orgId: organizationId ?? "",+ },+ {+ enabled: Boolean(organizationId) && canViewOrgV4Page,+ },+ );++ const legacyApiUsageByProject =+ api.v4Transition.timeSeriesByEntrypointByProject.useQuery(+ {+ orgId: organizationId ?? "",+ fromTimestamp: absoluteTimeRange.from,+ toTimestamp: absoluteTimeRange.to,+ granularity: "auto",+ },+ {+ enabled: Boolean(organizationId) && canViewOrgV4Page,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );++ const traceLevelEvalExecutionsByProject =+ api.v4Transition.traceLevelEvalExecutionsTimeSeriesByProject.useQuery(+ {+ orgId: organizationId ?? "",+ fromTimestamp: absoluteTimeRange.from,+ toTimestamp: absoluteTimeRange.to,+ granularity: "auto",+ },+ {+ enabled: Boolean(organizationId) && canViewOrgV4Page,+ },+ );++ const legacyApiUsageRowsByProjectId = useMemo(+ () =>+ groupByProjectId<ProjectScopedLegacyApiUsagePoint>(+ legacyApiUsageByProject.data,+ ),+ [legacyApiUsageByProject.data],+ );+ const evalExecutionRowsByProjectId = useMemo(+ () =>+ groupByProjectId<ProjectScopedEvalExecutionPoint>(+ traceLevelEvalExecutionsByProject.data,+ ),+ [traceLevelEvalExecutionsByProject.data],+ );++ const projects = useMemo(+ () =>+ [...(summaryByProject.data?.projects ?? [])].sort((a, b) => {+ const bActionCount = getProjectActionCount(+ b,+ sumLegacyApiUsage(legacyApiUsageRowsByProjectId.get(b.projectId)),+ );+ const aActionCount = getProjectActionCount(+ a,+ sumLegacyApiUsage(legacyApiUsageRowsByProjectId.get(a.projectId)),+ );++ if (bActionCount !== aActionCount) return bActionCount - aActionCount;+ return a.projectName.localeCompare(b.projectName);+ }),+ [summaryByProject.data?.projects, legacyApiUsageRowsByProjectId],+ );++ if (!organizationId || session.status === "loading") return null;++ if (!canViewOrgV4Page) {+ return <ErrorPage title="Not found" message="This page does not exist." />;+ }++ return (+ <Page+ withPadding+ scrollable+ headerProps={{+ title: "V4",+ breadcrumb: [+ { name: "Projects", href: `/organization/${organizationId}` },+ ],+ actionButtonsLeft: (+ <TimeRangePicker+ timeRange={timeRange}+ onTimeRangeChange={setTimeRange}+ timeRangePresets={V4_TIME_RANGE_PRESETS}+ disabled={{ before: earliestSelectableDate }}+ maxRangeMs={MAX_V4_TIMELINE_RANGE_MS}+ className="my-0 max-w-full overflow-x-auto"+ />+ ),+ }}+ >+ <div className="mx-auto flex w-full max-w-screen-xl flex-col gap-6">+ <DashboardCard+ title="Projects"+ description="V4 migration signals split by project."+ isLoading={+ summaryByProject.isPending || legacyApiUsageByProject.isPending+ }+ >+ {summaryByProject.error ? (+ <div className="border-destructive/30 bg-destructive/10 text-destructive flex min-h-28 items-center rounded-md border p-4 text-sm">+ Failed to load projects.+ </div>+ ) : projects.length > 0 ? (+ <div className="overflow-x-auto">+ <Table className="min-w-[56rem] table-auto">+ <TableHeader>+ <TableRow>+ <TableHead>Project</TableHead>+ <TableHead className="w-36 text-right">+ Trace evals+ </TableHead>+ <TableHead className="w-36 text-right">+ Integrations+ </TableHead>+ <TableHead className="w-36 text-right">+ Public API+ </TableHead>+ <TableHead className="w-[24rem]">Links</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {projects.map((project) => {+ const legacyApiUsageCount = sumLegacyApiUsage(+ legacyApiUsageRowsByProjectId.get(project.projectId),+ );++ return (+ <TableRow key={project.projectId}>+ <TableCell density="comfortable">+ <Link+ href={`/project/${project.projectId}`}+ className="font-medium hover:underline"+ >+ {project.projectName}+ </Link>+ </TableCell>+ <TableCell density="comfortable" className="text-right">+ {numberFormatter(project.traceLevelEvalCount, 0)}+ </TableCell>+ <TableCell density="comfortable" className="text-right">+ {numberFormatter(project.legacyIntegrationCount, 0)}+ </TableCell>+ <TableCell density="comfortable" className="text-right">+ {legacyApiUsageByProject.error+ ? "Failed"+ : numberFormatter(legacyApiUsageCount, 0, 2)}+ </TableCell>+ <TableCell density="comfortable">+ <div className="flex flex-wrap gap-2">+ <ProductLinkButton+ href={`/project/${project.projectId}/v4`}+ >+ V4 page+ </ProductLinkButton>+ <ProductLinkButton+ href={getTraceLevelEvalsHref(project.projectId)}+ >+ Evals+ </ProductLinkButton>+ <ProductLinkButton+ href={`/project/${project.projectId}/settings/integrations`}+ >+ Integrations+ </ProductLinkButton>+ </div>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ ) : (+ <NoDataOrLoading+ isLoading={summaryByProject.isPending}+ description="No active projects were found in this organization."+ className="min-h-40"+ />+ )}+ </DashboardCard>++ {projects.map((project) => (+ <section key={project.projectId} className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="min-w-0">+ <h2 className="truncate text-xl font-semibold">+ {project.projectName}+ </h2>+ </div>+ <div className="flex flex-wrap gap-2">+ <ProductLinkButton href={`/project/${project.projectId}/v4`}>+ Project V4 page+ </ProductLinkButton>+ </div>+ </div>++ <V4MigrationProjectCards+ projectId={project.projectId}+ summary={project}+ legacyApiUsage={legacyApiUsageRowsByProjectId.get(+ project.projectId,+ )}+ traceLevelEvalExecutions={evalExecutionRowsByProjectId.get(+ project.projectId,+ )}+ isSummaryLoading={summaryByProject.isPending}+ isLegacyApiUsageLoading={legacyApiUsageByProject.isPending}+ isTraceLevelEvalExecutionsLoading={+ traceLevelEvalExecutionsByProject.isPending+ }+ hasSummaryError={Boolean(summaryByProject.error)}+ hasLegacyApiUsageError={Boolean(legacyApiUsageByProject.error)}+ hasTraceLevelEvalExecutionsError={Boolean(+ traceLevelEvalExecutionsByProject.error,+ )}+ />+ </section>+ ))}+ </div>+ </Page>+ );+}diff --git a/web/src/pages/project/[projectId]/v4/index.tsx b/web/src/pages/project/[projectId]/v4/index.tsxindex e0aec63366..2dd4266625 100644--- a/web/src/pages/project/[projectId]/v4/index.tsx+++ b/web/src/pages/project/[projectId]/v4/index.tsx@@ -1,14 +1,7 @@import { useMemo } from "react";-import type { ReactNode } from "react";import { useRouter } from "next/router";-import Link from "next/link";-import { ArrowRight, ExternalLink } from "lucide-react";import Page from "@/src/components/layouts/page";import { TimeRangePicker } from "@/src/components/date-picker";-import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";-import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";-import { Chart } from "@/src/features/widgets/chart-library/Chart";-import { Button } from "@/src/components/ui/button";import {DEFAULT_DASHBOARD_AGGREGATION_SELECTION,toAbsoluteTimeRange,@@ -17,8 +10,7 @@ import {} from "@/src/utils/date-range-utils";import { useGlobalDateRange } from "@/src/features/global-time-range/useGlobalDateRange";import { api } from "@/src/utils/api";-import { encodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";-import { numberFormatter } from "@/src/utils/numbers";+import { V4MigrationProjectCards } from "@/src/features/v4/components/V4MigrationProjectCards";const V4_TIME_RANGE_PRESETS = ["last5Minutes",@@ -55,75 +47,6 @@ const getCappedAbsoluteTimeRange = (};};-const PUBLIC_API_DOCS = [- {- label: "V4 upgrade guide",- href: "https://langfuse.com/docs/v4",- },- {- label: "Observations API v2",- href: "https://langfuse.com/docs/api-and-data-platform/features/observations-api#v2",- },- {- label: "Metrics API v2",- href: "https://langfuse.com/docs/metrics/features/metrics-api#v2",- },-] as const;--const INTEGRATION_LINKS = [- {- key: "posthog",- label: "PostHog",- path: "posthog",- },- {- key: "mixpanel",- label: "Mixpanel",- path: "mixpanel",- },- {- key: "blobStorage",- label: "Blob Storage",- path: "blobstorage",- },-] as const;--const CardError = ({ children }: { children: string }) => (- <div className="border-destructive/30 bg-destructive/10 text-destructive flex min-h-28 items-center rounded-md border p-4 text-sm">- {children}- </div>-);--const ProductLinkButton = ({- href,- children,-}: {- href: string | { pathname: string; query: Record<string, string> };- children: ReactNode;-}) => (- <Button asChild variant="outline" size="sm">- <Link href={href}>- {children}- <ArrowRight className="ml-1 h-3.5 w-3.5" />- </Link>- </Button>-);--const ExternalDocButton = ({- href,- children,-}: {- href: string;- children: ReactNode;-}) => (- <Button asChild variant="outline" size="sm">- <a href={href} target="_blank" rel="noopener noreferrer">- {children}- <ExternalLink className="ml-1 h-3.5 w-3.5" />- </a>- </Button>-);-export default function V4Page() {const router = useRouter();const projectId = router.query.projectId as string | undefined;@@ -180,58 +103,6 @@ export default function V4Page() {},);- const traceLevelEvalsHref = useMemo(- () => ({- pathname: `/project/${projectId}/evals`,- query: {- filter: encodeFiltersGeneric([- {- column: "target",- type: "stringOptions",- operator: "any of",- value: ["trace"],- },- ]),- },- }),- [projectId],- );-- const legacyIntegrationLinks = useMemo(- () =>- INTEGRATION_LINKS.filter(- (link) =>- summary.data?.legacyIntegrations[link.key] === true &&- Boolean(projectId),- ).map((link) => ({- ...link,- href: `/project/${projectId}/settings/integrations/${link.path}`,- })),- [projectId, summary.data?.legacyIntegrations],- );-- const integrationsHref = `/project/${projectId}/settings/integrations`;-- const chartData = useMemo(- () =>- legacyApiUsage.data?.map((row) => ({- time_dimension: row.time,- dimension: row.entrypoint,- metric: row.count,- })) ?? [],- [legacyApiUsage.data],- );-- const evalExecutionChartData = useMemo(- () =>- traceLevelEvalExecutions.data?.map((row) => ({- time_dimension: row.time,- dimension: row.scoreName,- metric: row.count,- })) ?? [],- [traceLevelEvalExecutions.data],- );-return (<PagewithPadding@@ -245,151 +116,27 @@ export default function V4Page() {onTimeRangeChange={setTimeRange}timeRangePresets={V4_TIME_RANGE_PRESETS}disabled={{ before: earliestSelectableDate }}+ maxRangeMs={MAX_V4_TIMELINE_RANGE_MS}className="my-0 max-w-full overflow-x-auto"/>),}}><div className="mx-auto flex w-full max-w-screen-xl flex-col gap-3">- <div className="grid grid-cols-1 items-stretch gap-3 lg:grid-cols-[minmax(0,2fr)_minmax(20rem,1fr)]">- <DashboardCard- title="Trace-level evals"- description="Trace-targeting evaluator configs and non-cancelled execution jobs by generated score name."- isLoading={summary.isPending || traceLevelEvalExecutions.isPending}- cardContentClassName="min-h-[30rem]"- headerClassName="pr-12"- headerRight={- <ProductLinkButton href={traceLevelEvalsHref}>- View evals- </ProductLinkButton>- }- >- <div className="flex flex-col gap-4">- {summary.error ? (- <CardError>Failed to load trace-level evals.</CardError>- ) : (- <div>- <p className="text-muted-foreground text-sm">- Configured trace-level evals- </p>- <div className="text-4xl font-semibold">- {numberFormatter(summary.data?.traceLevelEvalCount ?? 0, 0)}- </div>- </div>- )}-- {traceLevelEvalExecutions.error ? (- <CardError>- Failed to load trace-level eval executions.- </CardError>- ) : evalExecutionChartData.length > 0 ? (- <div className="h-[22rem] w-full">- <Chart- chartType="BAR_TIME_SERIES"- data={evalExecutionChartData}- rowLimit={1_000}- chartConfig={{- type: "BAR_TIME_SERIES",- unit: "short",- }}- overrideWarning- />- </div>- ) : (- <NoDataOrLoading- isLoading={traceLevelEvalExecutions.isPending}- description="No trace-level eval executions were found for this project in the selected time range."- className="min-h-[22rem]"- />- )}- </div>- </DashboardCard>-- <DashboardCard- title="Integrations"- description="PostHog, Mixpanel, and Blob Storage exports that need review for V4."- isLoading={summary.isPending}- >- {summary.error ? (- <CardError>Failed to load integrations.</CardError>- ) : (- <div className="flex min-h-32 flex-col gap-4">- <div>- <p className="text-muted-foreground text-sm">- Configured integrations to review- </p>- <div className="text-4xl font-semibold">- {numberFormatter(- summary.data?.legacyIntegrationCount ?? 0,- 0,- )}- </div>- </div>-- <div className="flex flex-wrap gap-2">- <ProductLinkButton href={integrationsHref}>- View integrations- </ProductLinkButton>- {legacyIntegrationLinks.length > 0- ? legacyIntegrationLinks.map((link) => (- <ProductLinkButton key={link.key} href={link.href}>- {link.label}- </ProductLinkButton>- ))- : null}- </div>- </div>- )}- </DashboardCard>- </div>-- <DashboardCard- title="Public API calls to review"- description="ClickHouse-backed public API calls that may need changes for V4."- isLoading={legacyApiUsage.isPending}- cardContentClassName="min-h-[32rem]"- headerClassName="pr-12"- >- {legacyApiUsage.error ? (- <div className="border-destructive/30 bg-destructive/10 text-destructive flex min-h-36 items-center rounded-md border p-4 text-sm">- Failed to load public API usage.- </div>- ) : (- <>- <div className="flex flex-wrap gap-2">- {PUBLIC_API_DOCS.map((doc) => (- <ExternalDocButton key={doc.href} href={doc.href}>- {doc.label}- </ExternalDocButton>- ))}- </div>- <p className="text-muted-foreground text-sm">- We do not have query-log data for GET /api/public/sessions.- </p>-- {chartData.length > 0 ? (- <div className="h-[30rem] w-full">- <Chart- chartType="BAR_TIME_SERIES"- data={chartData}- rowLimit={1_000}- chartConfig={{- type: "BAR_TIME_SERIES",- unit: "short",- }}- overrideWarning- />- </div>- ) : (- <NoDataOrLoading- isLoading={legacyApiUsage.isPending}- description="No ClickHouse-backed public API usage was found for this project in the selected time range."- className="min-h-[30rem]"- />- )}- </>+ <V4MigrationProjectCards+ projectId={projectId ?? ""}+ summary={summary.data}+ legacyApiUsage={legacyApiUsage.data}+ traceLevelEvalExecutions={traceLevelEvalExecutions.data}+ isSummaryLoading={summary.isPending}+ isLegacyApiUsageLoading={legacyApiUsage.isPending}+ isTraceLevelEvalExecutionsLoading={traceLevelEvalExecutions.isPending}+ hasSummaryError={Boolean(summary.error)}+ hasLegacyApiUsageError={Boolean(legacyApiUsage.error)}+ hasTraceLevelEvalExecutionsError={Boolean(+ traceLevelEvalExecutions.error,)}- </DashboardCard>+ /></div></Page>);