🪢 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(web): v4 migration entry point — sidebar card + migration side panel (#15086)
Trang Nguyen88c2e90146a1
diff --git a/.prettierignore b/.prettierignoreindex 173af102d4..05f658f671 100644--- a/.prettierignore+++ b/.prettierignore@@ -1,2 +1,5 @@# Generated codepackages/shared/prisma/generated++# Local, untracked screenshot/review archives+.screenshots-reviewdiff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 94a37e96fc..bc141ff810 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -23,6 +23,7 @@ import {convertClickhouseTracesListToDomain,} from "./traces_converters";import {+ getLastTraceTimestampsByProjectsFromTracesTable,getTraceByIdFromTracesTable,getTracesIdentifierForSessionFromTracesTable,hasAnyTrace,@@ -1267,6 +1268,58 @@ export const hasAnyTracingData = async (projectId: string) => {return result;};+/**+ * Last event start_time per project from the events table, capped to the last+ * 30 days (matches the traces-table variant's window).+ */+export const getLastTraceTimestampsByProjectsFromEventsTable = async ({+ projectIds,+}: {+ projectIds: string[];+}) => {+ if (projectIds.length === 0) return [];++ const query = `+ SELECT+ project_id,+ max(start_time) as last_trace_at+ FROM events_core+ WHERE project_id IN ({projectIds: Array(String)})+ AND start_time >= now() - INTERVAL 30 DAY+ AND is_deleted = 0+ GROUP BY project_id+ `;++ const rows = await queryClickhouse<{+ project_id: string;+ last_trace_at: string;+ }>({+ query,+ params: { projectIds },+ preferredClickhouseService: "EventsReadOnly",+ });++ return rows.map((row) => ({+ projectId: row.project_id,+ lastTraceAt: parseClickhouseUTCDateTimeFormat(row.last_trace_at),+ }));+};++/**+ * Routing wrapper for "last trace timestamp per project" reads.+ *+ * If data is only written into the events tables, we look there and go to the+ * legacy traces table otherwise.+ */+export const getLastTraceTimestampsByProjects = async (+ params: Parameters<typeof getLastTraceTimestampsByProjectsFromTracesTable>[0],+) => {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {+ return getLastTraceTimestampsByProjectsFromTracesTable(params);+ }+ return getLastTraceTimestampsByProjectsFromEventsTable(params);+};+type PublicApiObservationsQuery = {projectId: string;page: number;diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex e5793ec531..c239f8578d 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -448,6 +448,38 @@ export const getTraceCountsByProjectInCreationInterval = async ({});};+export const getLastTraceTimestampsByProjectsFromTracesTable = async ({+ projectIds,+}: {+ projectIds: string[];+}) => {+ if (projectIds.length === 0) return [];++ const query = `+ SELECT+ project_id,+ max(timestamp) as last_trace_at+ FROM traces+ WHERE project_id IN ({projectIds: Array(String)})+ AND timestamp >= now() - INTERVAL 30 DAY+ GROUP BY project_id+ `;++ const rows = await queryClickhouse<{+ project_id: string;+ last_trace_at: string;+ }>({+ query,+ params: { projectIds },+ preferredClickhouseService: "ReadOnly",+ });++ return rows.map((row) => ({+ projectId: row.project_id,+ lastTraceAt: parseClickhouseUTCDateTimeFormat(row.last_trace_at),+ }));+};+export const getTraceCountOfProjectsSinceCreationDate = async ({projectIds,start,diff --git a/web/src/__tests__/server/admin-org-context-trpc.servertest.ts b/web/src/__tests__/server/admin-org-context-trpc.servertest.tsindex d8dcda0fd1..84ea1aff30 100644--- a/web/src/__tests__/server/admin-org-context-trpc.servertest.ts+++ b/web/src/__tests__/server/admin-org-context-trpc.servertest.ts@@ -9,12 +9,23 @@ import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { randomUUID } from "crypto";+import {+ createTrace,+ createTracesCh,+ deleteTraces,+} from "@langfuse/shared/src/server";const orgId = `org-${randomUUID()}`;const projectId = `project-${randomUUID()}`;const siblingProjectId = `project-${randomUUID()}`;+const projectTraceId = `trace-${randomUUID()}`;+const siblingProjectTraceId = `trace-${randomUUID()}`;-const createSession = (opts: { admin: boolean; member: boolean }): Session => ({+const createSession = (opts: {+ admin: boolean;+ member: boolean;+ orgRole?: "MEMBER" | "NONE";+}): Session => ({expires: "1",user: {id: "user-admin-org-context-test",@@ -25,7 +36,7 @@ const createSession = (opts: { admin: boolean; member: boolean }): Session => ({{id: orgId,name: "Admin Org Context Test Org",- role: "MEMBER",+ role: opts.orgRole ?? "MEMBER",plan: "cloud:hobby",cloudConfig: undefined,projects: [@@ -49,7 +60,11 @@ const createSession = (opts: { admin: boolean; member: boolean }): Session => ({environment: {} as any,});-const createCaller = (opts: { admin: boolean; member: boolean }) => {+const createCaller = (opts: {+ admin: boolean;+ member: boolean;+ orgRole?: "MEMBER" | "NONE";+}) => {const ctx = createInnerTRPCContext({session: createSession(opts),headers: {},@@ -70,13 +85,45 @@ beforeAll(async () => {},},});+ await createTracesCh([+ createTrace({ id: projectTraceId, project_id: projectId }),+ createTrace({ id: siblingProjectTraceId, project_id: siblingProjectId }),+ ]);});afterAll(async () => {+ await Promise.all([+ deleteTraces(projectId, [projectTraceId]),+ deleteTraces(siblingProjectId, [siblingProjectTraceId]),+ ]);await prisma.project.deleteMany({ where: { orgId } });await prisma.organization.delete({ where: { id: orgId } });});+describe("organizations.lastTraceByProject", () => {+ it("returns timestamps only for projects readable by a project-only member", async () => {+ const caller = createCaller({+ admin: false,+ member: true,+ orgRole: "NONE",+ });++ const result = await caller.organizations.lastTraceByProject({ orgId });++ expect(result.map(({ projectId }) => projectId)).toEqual([projectId]);+ });++ it("returns timestamps for all projects to a Langfuse admin", async () => {+ const caller = createCaller({ admin: true, member: false });++ const result = await caller.organizations.lastTraceByProject({ orgId });++ expect(result.map(({ projectId }) => projectId).sort()).toEqual(+ [projectId, siblingProjectId].sort(),+ );+ });+});+describe("organizations.byId", () => {it("returns the session-shaped org for an admin who is not a member", async () => {const caller = createCaller({ admin: true, member: false });diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.tsindex 8a2aa66076..1b41cdf676 100644--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts@@ -112,6 +112,7 @@ const mockedQueryClickhouse = vi.mocked(queryClickhouse);const projectId = "project-v4-transition";const orgId = "org-v4-transition";const secondProjectId = "project-v4-transition-second";+const outsideProjectId = "project-v4-transition-outside";// Mocked Prisma delegates only implement the methods a test exercises, so// accept any subset of PrismaClient keys with loosely typed values.@@ -138,6 +139,10 @@ const createSessionWithOrgRole = (role: OrganizationRole): Session => ({organizations: session.user!.organizations.map((organization) => ({...organization,role,+ projects:+ role === "NONE"+ ? organization.projects.filter((project) => project.id === projectId)+ : organization.projects,})),},});@@ -184,6 +189,16 @@ const session: Session = {metadata: {},createdAt: new Date(0).toISOString(),},+ {+ id: secondProjectId,+ name: "Second Project",+ role: "ADMIN",+ deletedAt: null,+ retentionDays: null,+ hasTraces: false,+ metadata: {},+ createdAt: new Date(0).toISOString(),+ },],},],@@ -732,6 +747,7 @@ describe("v4TransitionRouter", () => {where: {orgId,deletedAt: null,+ id: { in: [projectId, secondProjectId] },},select: {id: true,@@ -778,6 +794,7 @@ describe("v4TransitionRouter", () => {where: {orgId,deletedAt: null,+ id: { in: [projectId, secondProjectId] },},select: {id: true,@@ -856,44 +873,54 @@ describe("v4TransitionRouter", () => {).resolves.toEqual([]);});- it("forbids organization members from accessing org-level v4 data", async () => {+ it("allows project-only members to access org-level v4 data for their readable projects", async () => {+ const findManyProjects = vi.fn().mockResolvedValue([+ {+ id: projectId,+ name: "V4 Transition Project",+ },+ ]);const caller = createCaller({project: {- findMany: vi.fn(),+ findMany: findManyProjects,+ },+ posthogIntegration: {+ findMany: vi.fn().mockResolvedValue([]),+ },+ mixpanelIntegration: {+ findMany: vi.fn().mockResolvedValue([]),+ },+ blobStorageIntegration: {+ findMany: vi.fn().mockResolvedValue([]),},},- createSessionWithOrgRole("MEMBER"),+ createSessionWithOrgRole("NONE"),);- await expect(caller.summaryByProject({ orgId })).rejects.toMatchObject({- code: "FORBIDDEN",- });- await expect(- caller.traceLevelEvalSummaryByProject({- orgId,- }),- ).rejects.toMatchObject({- code: "FORBIDDEN",- });- await expect(- caller.legacyApiUsageSummaryByProject({- orgId,- fromTimestamp: new Date("2026-06-24T00:00:00Z"),- toTimestamp: new Date("2026-06-25T00:00:00Z"),- }),- ).rejects.toMatchObject({- code: "FORBIDDEN",+ await expect(caller.summaryByProject({ orgId })).resolves.toEqual({+ projects: [+ {+ projectId,+ projectName: "V4 Transition Project",+ legacyIntegrationCount: 0,+ legacyIntegrations: {+ posthog: false,+ mixpanel: false,+ blobStorage: false,+ },+ },+ ],});- await expect(- caller.sdkUsageSummaryByProject({- orgId,- fromTimestamp: new Date("2026-06-24T00:00:00Z"),- toTimestamp: new Date("2026-06-25T00:00:00Z"),+ expect(findManyProjects).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ orgId,+ deletedAt: null,+ id: { in: [projectId] },+ },}),- ).rejects.toMatchObject({- code: "FORBIDDEN",- });+ );});it("queries trace-level eval execution counts with the same 2 minute buckets as the legacy API timeline", async () => {@@ -1133,76 +1160,36 @@ describe("v4TransitionRouter", () => {expect(clickhouseQuery?.preferredClickhouseService).toBe("EventsReadOnly");});- it("forbids project members and viewers from accessing project-level v4 data", async () => {- const mockPrisma = {- posthogIntegration: {- findUnique: vi.fn(),- },- mixpanelIntegration: {- findUnique: vi.fn(),- },- blobStorageIntegration: {- findUnique: vi.fn(),- },- jobConfiguration: {- count: vi.fn(),- },- $queryRaw: vi.fn(),- };+ it.each(["MEMBER", "VIEWER"] as const)(+ "allows project %s roles to access project-level v4 data",+ async (role) => {+ const mockPrisma = {+ posthogIntegration: {+ findUnique: vi.fn().mockResolvedValue(null),+ },+ mixpanelIntegration: {+ findUnique: vi.fn().mockResolvedValue(null),+ },+ blobStorageIntegration: {+ findUnique: vi.fn().mockResolvedValue(null),+ },+ };- for (const role of ["MEMBER", "VIEWER"] as const) {const caller = createCaller(mockPrisma,createSessionWithProjectRole(role),);- await expect(caller.summary({ projectId })).rejects.toMatchObject({- code: "FORBIDDEN",- });- await expect(- caller.traceLevelEvalSummary({ projectId }),- ).rejects.toMatchObject({- code: "FORBIDDEN",- });- await expect(- caller.timeSeriesByEntrypoint({- projectId,- 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.traceLevelEvalExecutionsTimeSeries({- projectId,- 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.sdkUsageTimeSeries({- projectId,- 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.summary({ projectId })).resolves.toEqual({+ legacyIntegrationCount: 0,+ legacyIntegrations: {+ posthog: false,+ mixpanel: false,+ blobStorage: false,+ },});- }-- expect(mockedQueryClickhouse).not.toHaveBeenCalled();- expect(mockPrisma.posthogIntegration.findUnique).not.toHaveBeenCalled();- expect(mockPrisma.mixpanelIntegration.findUnique).not.toHaveBeenCalled();- expect(mockPrisma.blobStorageIntegration.findUnique).not.toHaveBeenCalled();- expect(mockPrisma.jobConfiguration.count).not.toHaveBeenCalled();- expect(mockPrisma.$queryRaw).not.toHaveBeenCalled();- });+ },+ );it("queries SDK usage without a ClickHouse metadata preflight", async () => {mockedQueryClickhouse.mockResolvedValueOnce([@@ -1243,7 +1230,7 @@ describe("v4TransitionRouter", () => {await expect(caller.sdkUsageTimeSeries({- projectId: secondProjectId,+ projectId: outsideProjectId,fromTimestamp: new Date("2026-06-25T12:00:00Z"),toTimestamp: new Date("2026-06-25T13:00:00Z"),granularity: "auto",@@ -1307,6 +1294,7 @@ describe("v4TransitionRouter", () => {where: {orgId,deletedAt: null,+ id: { in: [projectId, secondProjectId] },},select: {id: true,diff --git a/web/src/components/editor/shared-theme.ts b/web/src/components/editor/shared-theme.tsindex 9658ec9f89..9885132004 100644--- a/web/src/components/editor/shared-theme.ts+++ b/web/src/components/editor/shared-theme.ts@@ -19,7 +19,7 @@ export const defaultSettingsBothThemes: CreateThemeOptions["settings"] = {};export const bothThemeStyles: CreateThemeOptions["styles"] = [- { tag: t.invalid, color: "hsl(var(--dark-red))" },+ { tag: t.invalid, color: "var(--dark-red)" },{tag: [t.name,diff --git a/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx b/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsxindex 3ebd994d45..155bbf2494 100644--- a/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx+++ b/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx@@ -1,4 +1,5 @@import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanelProvider";import { type PropsWithChildren } from "react";import { useMediaQuery } from "react-responsive";import dynamic from "next/dynamic";@@ -26,6 +27,17 @@ const DynamicSupportDrawer = dynamic(},);+const DynamicV4MigrationPanel = dynamic(+ () =>+ import("@/src/features/v4-migration/V4MigrationPanel").then((mod) => ({+ default: mod.V4MigrationPanel,+ })),+ {+ ssr: false,+ loading: () => <RightDrawerLoadingFallback />,+ },+);+function RightDrawerLoadingFallback() {return (<div className="flex h-full w-full items-center justify-center">@@ -43,18 +55,23 @@ function RightDrawerLoadingFallback() {export function AppContentWithRightDrawer({ children }: PropsWithChildren) {const isDesktop = useMediaQuery({ query: "(min-width: 768px)" });const { open: supportOpen } = useSupportDrawer();+ const { open: migrationOpen } = useV4MigrationPanel();if (!isDesktop) {return <DynamicMobileRightDrawer>{children}</DynamicMobileRightDrawer>;}- const rightDrawerContent = supportOpen ? <DynamicSupportDrawer /> : null;+ const rightDrawerContent = supportOpen ? (+ <DynamicSupportDrawer />+ ) : migrationOpen ? (+ <DynamicV4MigrationPanel />+ ) : null;return (<ResizableSplitLayoutprimaryContent={children}secondaryContent={rightDrawerContent}- open={supportOpen}+ open={supportOpen || migrationOpen}defaultPrimarySize={70}defaultSecondarySize={30}minPrimarySize={30}diff --git a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsxindex ca0517997c..8c0935f838 100644--- a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx+++ b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx@@ -8,9 +8,13 @@ import {} from "@/src/components/ui/drawer";import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";import { SupportDrawer } from "@/src/features/support-chat/SupportDrawer";+import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanelProvider";+import { V4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanel";export function MobileRightDrawer({ children }: PropsWithChildren) {const { open: supportOpen, setOpen: setSupportOpen } = useSupportDrawer();+ const { open: migrationOpen, setOpen: setMigrationOpen } =+ useV4MigrationPanel();return (<>@@ -47,6 +51,40 @@ export function MobileRightDrawer({ children }: PropsWithChildren) {</div></DrawerContent></Drawer>++ <Drawer+ open={migrationOpen}+ onOpenChange={(open) => {+ if (!open) {+ setMigrationOpen(false);+ }+ }}+ forceDirection="bottom"+ >+ <DrawerContent+ id="v4-migration-drawer"+ className="min-h-screen-with-banner inset-x-0 top-[calc(var(--banner-offset)+10px)] bottom-0"+ size="full"+ >+ <DrawerHeader className="absolute inset-x-0 top-0 p-0 text-left">+ <div className="flex w-full items-center justify-center pt-3">+ <div className="bg-muted h-2 w-20 rounded-full" />+ </div>+ {/* sr-only for screen readers and accessibility */}+ <DrawerTitle className="sr-only">Migrate to v4</DrawerTitle>+ <DrawerDescription className="sr-only">+ Information about migrating to Langfuse v4 and upcoming+ deprecations.+ </DrawerDescription>+ </DrawerHeader>+ <div className="mt-4 max-h-full">+ <V4MigrationPanel+ showCloseButton={false}+ className="h-full pb-20"+ />+ </div>+ </DrawerContent>+ </Drawer></>);}diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.tsindex b13f98261f..432cbb5414 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts@@ -83,6 +83,12 @@ export const filters = {return ctx.session?.user?.canToggleV4 === true ? route : null;}+ if (route.featureFlag === "v4UpgradeUi") {+ return ctx.session?.user?.featureFlags.v4UpgradeUi === true+ ? route+ : null;+ }+const hasFlag =ctx.enableExperimentalFeatures ||ctx.cloudAdmin ||diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex 5c7139cec5..1dbd46b86b 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -26,6 +26,7 @@ import { type Entitlement } from "@/src/features/entitlements/constants/entitlemimport { type Session } from "next-auth";import { type OrganizationScope } from "@/src/features/rbac/constants/organizationAccessRights";import { SupportButton } from "@/src/components/nav/support-button";+import { V4MigrationNavItem } from "@/src/features/v4-migration/V4MigrationNavItem";import { BookACallButton } from "@/src/components/nav/book-a-call-button";import { V4SidebarToggle } from "@/src/features/events/components/V4SidebarToggle";import { SidebarMenuButton } from "@/src/components/ui/sidebar";@@ -227,6 +228,14 @@ export const ROUTES: Route[] = [featureFlag: "v4BetaToggleVisible",menuNode: <V4SidebarToggle />,},+ {+ title: "Update",+ pathname: "",+ section: RouteSection.Secondary,+ featureFlag: "v4UpgradeUi",+ show: ({ projectId }) => projectId !== undefined,+ menuNode: <V4MigrationNavItem />,+ },{title: "Settings",pathname: "/project/[projectId]/settings",diff --git a/web/src/components/nav/app-sidebar.tsx b/web/src/components/nav/app-sidebar.tsxindex 819a9e288d..eb6c152a39 100644--- a/web/src/components/nav/app-sidebar.tsx+++ b/web/src/components/nav/app-sidebar.tsx@@ -29,6 +29,7 @@ import { SidebarNotifications } from "@/src/components/nav/sidebar-notificationsimport { type RouteGroup } from "@/src/components/layouts/routes";import { ExternalLink, Grid2X2 } from "lucide-react";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";type AppSidebarProps = {navItems: {@@ -49,6 +50,7 @@ export function AppSidebar({...props}: AppSidebarProps) {const { isMobile } = useSidebar();+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();return (<Sidebar collapsible="icon" variant="sidebar" {...props}>@@ -63,9 +65,13 @@ export function AppSidebar({{isMobile && <MobileNavSwitcher />}<NavMain items={navItems} /><div className="flex-1" />- <div className="flex flex-col gap-2 p-2">- <SidebarNotifications />- </div>+ {/* Hidden for v4-upgrade users only: the "Update" nav entry is trialled+ in this slot. Everyone else keeps the notifications stack. */}+ {!v4UpgradeUiEnabled && (+ <div className="flex flex-col gap-2 p-2">+ <SidebarNotifications />+ </div>+ )}<NavMain items={secondaryNavItems} /></SidebarContent><SidebarFooter>diff --git a/web/src/components/nav/support-button.tsx b/web/src/components/nav/support-button.tsxindex 9b92d8349a..d78853a6d2 100644--- a/web/src/components/nav/support-button.tsx+++ b/web/src/components/nav/support-button.tsx@@ -1,10 +1,12 @@import { LifeBuoy } from "lucide-react";import { SidebarMenuButton, useSidebar } from "@/src/components/ui/sidebar";import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanelProvider";import { useInAppAiAgent } from "@/src/ee/features/in-app-agent/components/InAppAiAgentProvider";export const SupportButton = () => {const { setOpen: setSupportDrawerOpen } = useSupportDrawer();+ const { setOpen: setMigrationPanelOpen } = useV4MigrationPanel();const { setOpen: setAiAgentOpen } = useInAppAiAgent();const { isMobile, setOpenMobile: setOpenMobileSidebar } = useSidebar();@@ -17,6 +19,7 @@ export const SupportButton = () => {setTimeout(() => {// push to next tick to avoid flickering when hiding sidebar on mobilesetAiAgentOpen(false);+ setMigrationPanelOpen(false);setSupportDrawerOpen(true);}, 1);}}diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsxindex 7787edcd58..141adc4cd6 100644--- a/web/src/components/ui/dialog.tsx+++ b/web/src/components/ui/dialog.tsx@@ -83,6 +83,7 @@ const DialogContent = React.forwardRef<closeOnInteractionOutside?: boolean;confirmCloseOnEscape?: string;overlayMode?: DialogOverlayMode;+ overlayClassName?: string;stopPropagationOnEnterSpace?: boolean;} & VariantProps<typeof dialogContentVariants>,"onPointerDownOutside" | "onInteractOutside"@@ -95,6 +96,7 @@ const DialogContent = React.forwardRef<closeOnInteractionOutside = false,confirmCloseOnEscape,overlayMode = "subtle",+ overlayClassName,stopPropagationOnEnterSpace = true,onEscapeKeyDown,onClick,@@ -126,7 +128,7 @@ const DialogContent = React.forwardRef<return (<DialogPortal>- <DialogOverlay overlayMode={overlayMode} />+ <DialogOverlay overlayMode={overlayMode} className={overlayClassName} /><DialogPrimitive.Contentref={ref}className={cn(diff --git a/web/src/ee/features/billing/components/BillingActionButtons.tsx b/web/src/ee/features/billing/components/BillingActionButtons.tsxindex 5f911ec0e7..906d444b76 100644--- a/web/src/ee/features/billing/components/BillingActionButtons.tsx+++ b/web/src/ee/features/billing/components/BillingActionButtons.tsx@@ -4,6 +4,7 @@ import { Button } from "@/src/components/ui/button";import Link from "next/link";import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanelProvider";import { StripeCustomerPortalButton } from "./StripeCustomerPortalButton";import { BillingSwitchPlanDialog } from "./BillingSwitchPlanDialog";import { useBillingInformation } from "./useBillingInformation";@@ -13,6 +14,7 @@ export const BillingActionButtons = () => {const { organization, hasValidPaymentMethod, isLoading } =useBillingInformation();const { setOpen } = useSupportDrawer();+ const { setOpen: setMigrationPanelOpen } = useV4MigrationPanel();// Show pricing page buttonconst shouldDisableChangePlan = useMemo(() => {@@ -29,7 +31,13 @@ export const BillingActionButtons = () => {if (organization?.cloudConfig?.plan) {return (<div className="mt-4 flex flex-row items-center gap-2">- <Button variant="secondary" onClick={() => setOpen(true)}>+ <Button+ variant="secondary"+ onClick={() => {+ setMigrationPanelOpen(false);+ setOpen(true);+ }}+ >Change plan (via support)</Button><Button variant="secondary" asChild>diff --git a/web/src/features/evals/pages/evaluators.tsx b/web/src/features/evals/pages/evaluators.tsxindex fc95787e3f..d7789962f6 100644--- a/web/src/features/evals/pages/evaluators.tsx+++ b/web/src/features/evals/pages/evaluators.tsx@@ -14,6 +14,7 @@ import { useEntitlementLimit } from "@/src/features/entitlements/hooks";import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";import { EvaluatorsOnboarding } from "@/src/components/onboarding/EvaluatorsOnboarding";import { ManageDefaultEvalModel } from "@/src/features/evals/components/manage-default-eval-model";+import { V4MigrationModal } from "@/src/features/v4-migration/V4MigrationModal";export default function EvaluatorsPage() {const router = useRouter();@@ -76,6 +77,7 @@ export default function EvaluatorsPage() {return (<>+ <V4MigrationModal /><PageheaderProps={{title: "Evaluators",diff --git a/web/src/features/events/hooks/useAppRootDefault.ts b/web/src/features/events/hooks/useAppRootDefault.tsindex da9f062c67..fb2059c3f5 100644--- a/web/src/features/events/hooks/useAppRootDefault.ts+++ b/web/src/features/events/hooks/useAppRootDefault.ts@@ -8,7 +8,6 @@ import {getAppRootDefaultPolicy,getAppRootFallbackDecision,getAppRootSuppressionToPersist,- shouldQuerySdkVersion,storedViewOwnsEventsTableState,urlOwnsEventsTableState,viewOwnsEventsTableState,@@ -20,11 +19,9 @@ import {useBrowserStorageValue,writeStorage,} from "@/src/features/events/lib/appRootDefaultStorage";-import {- getSdkVersionCapability,- sdkVersionStorageKeys,- toSdkVersionInfo,-} from "@/src/features/sdk-version/lib/sdkVersionCapabilities";+import { getSdkVersionCapability } from "@/src/features/sdk-version/lib/sdkVersionCapabilities";+import { useProjectSdkVersionInfo } from "@/src/features/sdk-version/hooks/useProjectSdkVersionInfo";+import { clearProjectSdkVersionInfo } from "@/src/features/sdk-version/lib/sdkVersionStorage";export function useAppRootDefault(params: {enabled: boolean;@@ -70,16 +67,8 @@ export function useAppRootDefault(params: {);}, [projectId]);- const {- language: sdkLanguageKey,- version: sdkVersionKey,- checkedAt: sdkCheckedAtKey,- } = sdkVersionStorageKeys(projectId);const preferenceKey = appRootPreferenceStorageKey(projectId);const savedViewKey = appRootSavedViewSessionStorageKey(projectId);- const sdkLanguage = useBrowserStorageValue("localStorage", sdkLanguageKey);- const sdkVersion = useBrowserStorageValue("localStorage", sdkVersionKey);- const sdkCheckedAt = useBrowserStorageValue("localStorage", sdkCheckedAtKey);const preference = useBrowserStorageValue("localStorage", preferenceKey);const restoredSavedViewId = useBrowserStorageValue("sessionStorage",@@ -88,20 +77,11 @@ export function useAppRootDefault(params: {const currentViewOwnsState = viewOwnsEventsTableState(router.query);const now = Date.now();- const sdkQuery = api.events.getSdkVersionInfo.useQuery(- { projectId },- {- enabled: shouldQuerySdkVersion({- enabled,- routerReady: router.isReady,- sdkCheckedAt,- dismissed,- now,- }),- refetchOnWindowFocus: false,- retry: false,- },- );+ const sdkVersionState = useProjectSdkVersionInfo({+ projectId,+ enabled: enabled && router.isReady && !dismissed,+ refreshMode: "if-stale",+ });const defaultViewQuery = api.TableViewPresets.getDefault.useQuery({ projectId, viewName: TableViewPresetTableName.ObservationsEvents },@@ -115,23 +95,16 @@ export function useAppRootDefault(params: {currentViewOwnsState ||storedViewOwnsEventsTableState(restoredSavedViewId) ||Boolean(defaultViewQuery.data?.viewId);- const sdkCheckSettled = sdkQuery.isSuccess && !sdkQuery.isFetching;- const checkedSdkVersion = toSdkVersionInfo(- sdkCheckSettled ? sdkQuery.data : undefined,- );const appRootSupported = getSdkVersionCapability(- checkedSdkVersion ??- (sdkCheckedAt- ? { language: sdkLanguage, version: sdkVersion }- : undefined),+ sdkVersionState.sdkVersion,"appRootObservations",);const policy = getAppRootDefaultPolicy({enabled,routerReady: router.isReady,appRootSupported,- sdkCheckedAt,- sdkCheckSettled,+ sdkCheckedAt: sdkVersionState.checkedAt,+ sdkCheckSettled: sdkVersionState.querySettled,preference,defaultViewSettled: !defaultViewQuery.isLoading,savedViewOwnsState,@@ -140,32 +113,10 @@ export function useAppRootDefault(params: {});useEffect(() => {- if (policy.shouldPersistSdkVersion) {- writeStorage(- "localStorage",- sdkLanguageKey,- checkedSdkVersion?.language ?? null,- );- writeStorage(- "localStorage",- sdkVersionKey,- checkedSdkVersion?.version ?? null,- );- writeStorage("localStorage", sdkCheckedAtKey, new Date().toISOString());- }if (policy.shouldPersistAuto) {writeStorage("localStorage", preferenceKey, "auto");}- }, [- checkedSdkVersion?.language,- checkedSdkVersion?.version,- policy.shouldPersistSdkVersion,- policy.shouldPersistAuto,- preferenceKey,- sdkCheckedAtKey,- sdkLanguageKey,- sdkVersionKey,- ]);+ }, [policy.shouldPersistAuto, preferenceKey]);const autoProvenanceKnown = preference === "auto" && !savedViewOwnsState;const onExplicitFilterStateChange = useCallback(@@ -195,17 +146,9 @@ export function useAppRootDefault(params: {);const removeSdkVersionCache = useCallback(() => {- writeStorage("localStorage", sdkCheckedAtKey, null);- writeStorage("localStorage", sdkLanguageKey, null);- writeStorage("localStorage", sdkVersionKey, null);+ clearProjectSdkVersionInfo(projectId);utils.events.getSdkVersionInfo.reset({ projectId }).catch(() => undefined);- }, [- projectId,- sdkCheckedAtKey,- sdkLanguageKey,- sdkVersionKey,- utils.events.getSdkVersionInfo,- ]);+ }, [projectId, utils.events.getSdkVersionInfo]);return {defaultExplicitFilterState: policy.shouldApplyFilterdiff --git a/web/src/features/events/lib/appRootDefault.clienttest.ts b/web/src/features/events/lib/appRootDefault.clienttest.tsindex 09a6b1624d..76ede65905 100644--- a/web/src/features/events/lib/appRootDefault.clienttest.ts+++ b/web/src/features/events/lib/appRootDefault.clienttest.ts@@ -7,7 +7,6 @@ import {getAppRootSavedViewComparisonFilters,getAppRootSuppressionToPersist,removeAppRootDefaultFilter,- shouldQuerySdkVersion,storedViewOwnsEventsTableState,urlOwnsEventsTableState,} from "./appRootDefaultFilterPolicy";@@ -68,39 +67,6 @@ describe("app-root default policy", () => {).toBe(apply);});- it("queries the SDK version only when a refresh could matter", () => {- const base = {- enabled: true,- routerReady: true,- sdkCheckedAt: null,- dismissed: false,- now,- };- expect(shouldQuerySdkVersion(base)).toBe(true);- expect(- shouldQuerySdkVersion({- ...base,- sdkCheckedAt: "2026-07-14T12:00:00.000Z",- }),- ).toBe(false);- expect(- shouldQuerySdkVersion({- ...base,- sdkCheckedAt: "2026-05-01T12:00:00.000Z",- }),- ).toBe(true);- expect(shouldQuerySdkVersion({ ...base, dismissed: true })).toBe(false);- });-- it("persists the SDK check only after it settles", () => {- const stale = { ...basePolicy, sdkCheckedAt: null };- expect(getAppRootDefaultPolicy(stale).shouldPersistSdkVersion).toBe(false);- expect(- getAppRootDefaultPolicy({ ...stale, sdkCheckSettled: true })- .shouldPersistSdkVersion,- ).toBe(true);- });-it("URL table-state params own the table on arrival", () => {expect(urlOwnsEventsTableState({})).toBe(false);expect(urlOwnsEventsTableState({ peek: "obs-1" })).toBe(false);diff --git a/web/src/features/events/lib/appRootDefaultFilterPolicy.ts b/web/src/features/events/lib/appRootDefaultFilterPolicy.tsindex 0f8588f570..9d4d0b9bc5 100644--- a/web/src/features/events/lib/appRootDefaultFilterPolicy.ts+++ b/web/src/features/events/lib/appRootDefaultFilterPolicy.ts@@ -1,6 +1,4 @@import type { FilterState } from "@langfuse/shared";-import { sdkVersionNeedsRefresh } from "@/src/features/sdk-version/lib/sdkVersionCapabilities";-const URL_STATE_PARAMS = ["filter", "search", "searchType", "orderBy"];export const APP_ROOT_OBSERVATION_FILTER = {@@ -31,18 +29,6 @@ export const urlOwnsEventsTableState = (export const storedViewOwnsEventsTableState = (value: string | null) =>Boolean(value) && value !== "null";-export const shouldQuerySdkVersion = (params: {- enabled: boolean;- routerReady: boolean;- sdkCheckedAt: string | null;- dismissed: boolean;- now: number;-}) =>- params.enabled &&- params.routerReady &&- !params.dismissed &&- sdkVersionNeedsRefresh(params.sdkCheckedAt, params.now);-export const getAppRootDefaultPolicy = (params: {enabled: boolean;routerReady: boolean;@@ -70,8 +56,6 @@ export const getAppRootDefaultPolicy = (params: {return {shouldApplyFilter,shouldPersistAuto: shouldApplyFilter && params.preference === null,- shouldPersistSdkVersion:- shouldQuerySdkVersion(params) && params.sdkCheckSettled,};};diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.tsindex 02a2ce0303..a4913eb85b 100644--- a/web/src/features/feature-flags/available-flags.ts+++ b/web/src/features/feature-flags/available-flags.ts@@ -8,6 +8,7 @@ export const availableFlags = ["templateFlag","excludeClickhouseRead","v4BetaToggleVisible",+ "v4UpgradeUi","observationEvals","experimentsV4Enabled",] as const;diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.tsindex 4416608325..464f94a4a0 100644--- a/web/src/features/feature-flags/types.ts+++ b/web/src/features/feature-flags/types.ts@@ -2,8 +2,9 @@ import { type availableFlags } from "./available-flags";export type Flag = (typeof availableFlags)[number];export type Flags = {- [key in Exclude<Flag, "modernSession">]: boolean;+ [key in Exclude<Flag, "modernSession" | "v4UpgradeUi">]: boolean;} & {- // Optional while older sessions and test fixtures roll across the new flag.+ // Optional while older sessions and test fixtures roll across new flags.modernSession?: boolean;+ v4UpgradeUi?: boolean;};diff --git a/web/src/features/notifications/ErrorNotification.tsx b/web/src/features/notifications/ErrorNotification.tsxindex 78b1d6e9c2..ba30202815 100644--- a/web/src/features/notifications/ErrorNotification.tsx+++ b/web/src/features/notifications/ErrorNotification.tsx@@ -1,6 +1,7 @@import { Button } from "@/src/components/ui/button";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanelProvider";import { AlertTriangle, X } from "lucide-react";interface ErrorNotificationProps {@@ -21,6 +22,7 @@ export const ErrorNotification: React.FC<ErrorNotificationProps> = ({path,}) => {const { setOpen } = useSupportDrawer();+ const { setOpen: setMigrationPanelOpen } = useV4MigrationPanel();const capture = usePostHogClientCapture();const isError = type === "ERROR";const textColor = isError@@ -67,6 +69,7 @@ export const ErrorNotification: React.FC<ErrorNotificationProps> = ({toast_type: type,path,});+ setMigrationPanelOpen(false);setOpen(true);}}>diff --git a/web/src/features/notifications/showErrorToast.tsx b/web/src/features/notifications/showErrorToast.tsxindex 34f58074fd..1db1bb2536 100644--- a/web/src/features/notifications/showErrorToast.tsx+++ b/web/src/features/notifications/showErrorToast.tsx@@ -7,8 +7,8 @@ const toastErrorStyleProps = {};const toastWarningStyleProps = {- border: "1px solid hsl(var(--light-yellow))",- backgroundColor: "hsl(var(--light-yellow))",+ border: "1px solid var(--light-yellow)",+ backgroundColor: "var(--light-yellow)",};export const showErrorToast = (diff --git a/web/src/features/notifications/showSuccessToast.tsx b/web/src/features/notifications/showSuccessToast.tsxindex 7c4267ba77..abd2292051 100644--- a/web/src/features/notifications/showSuccessToast.tsx+++ b/web/src/features/notifications/showSuccessToast.tsx@@ -16,9 +16,9 @@ export const showSuccessToast = ({duration,style: {padding: "1rem",- border: "1px solid hsl(var(--dark-green))",+ border: "1px solid var(--dark-green)",borderRadius: "0.5rem",- backgroundColor: "hsl(var(--dark-green))",+ backgroundColor: "var(--dark-green)",},},);diff --git a/web/src/features/organizations/components/ProjectOverview.tsx b/web/src/features/organizations/components/ProjectOverview.tsxindex 86e17af23b..3343da77da 100644--- a/web/src/features/organizations/components/ProjectOverview.tsx+++ b/web/src/features/organizations/components/ProjectOverview.tsx@@ -34,6 +34,11 @@ import ContainerPage from "@/src/components/layouts/container-page";import { type Session } from "next-auth";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { AgentToolsBanner } from "@/src/features/developer-tools/components/AgentToolsBanner";+import { V4MigrationProjectChip } from "@/src/features/v4-migration/V4MigrationProjectChip";+import { api } from "@/src/utils/api";+import { formatCompactRelativeTime } from "@/src/utils/dates";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";+import { useAccountV4MigrationData } from "@/src/features/v4-migration/hooks/useV4MigrationData";const OrganizationProjectTiles = ({org,@@ -42,37 +47,105 @@ const OrganizationProjectTiles = ({org: NonNullable<Session["user"]>["organizations"][number];search?: string;}) => {+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();+ const { data: lastTraceTimes } =+ api.organizations.lastTraceByProject.useQuery(+ { orgId: org.id },+ { enabled: v4UpgradeUiEnabled },+ );+ const migrationStatusByProjectId = useAccountV4MigrationData({+ organizations: [+ {+ id: org.id,+ name: org.name,+ projects: org.projects+ .filter((project) => !project.deletedAt)+ .map((project) => ({ id: project.id, name: project.name })),+ },+ ],+ enabled: v4UpgradeUiEnabled,+ });return (<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">{org.projects.filter((p) => !search || p.name.toLowerCase().includes(search.toLowerCase()),)- .map((project) => (- <Card key={project.id}>- <CardHeader>- <CardTitle className="truncate text-base" title={project.name}>- {project.name}- </CardTitle>- </CardHeader>- {!project.deletedAt ? (- <CardFooter className="gap-2">- <Button asChild variant="secondary">- <Link href={`/project/${project.id}`}>Go to project</Link>- </Button>- <Button asChild variant="ghost">- <Link href={`/project/${project.id}/settings`}>- <Settings size={16} />- </Link>- </Button>- </CardFooter>- ) : (- <CardContent>- <CardDescription>Project is being deleted</CardDescription>- </CardContent>- )}- </Card>- ))}+ .map((project) =>+ v4UpgradeUiEnabled ? (+ <Card+ key={project.id}+ className="group hover:bg-muted/50 relative transition-colors"+ >+ {!project.deletedAt && (+ <Link+ href={`/project/${project.id}`}+ className="absolute inset-0"+ aria-label={`Go to project ${project.name}`}+ />+ )}+ <CardHeader>+ <div className="flex items-start justify-between gap-2">+ <CardTitle+ className="truncate text-base"+ title={project.name}+ >+ {project.name}+ </CardTitle>+ {!project.deletedAt && (+ <V4MigrationProjectChip+ project={{ id: project.id, name: project.name }}+ status={migrationStatusByProjectId.get(project.id)}+ />+ )}+ </div>+ </CardHeader>+ {!project.deletedAt && lastTraceTimes && (+ <CardContent className="pb-3">+ <p className="text-muted-foreground text-xs">+ {(() => {+ const lastTraceAt = lastTraceTimes.find(+ (t) => t.projectId === project.id,+ )?.lastTraceAt;+ return lastTraceAt+ ? `Last trace ${formatCompactRelativeTime(new Date(lastTraceAt))}`+ : "No traces in the last 30d";+ })()}+ </p>+ </CardContent>+ )}+ {project.deletedAt && (+ <CardContent>+ <CardDescription>Project is being deleted</CardDescription>+ </CardContent>+ )}+ </Card>+ ) : (+ <Card key={project.id}>+ <CardHeader>+ <CardTitle className="truncate text-base" title={project.name}>+ {project.name}+ </CardTitle>+ </CardHeader>+ {!project.deletedAt ? (+ <CardFooter className="gap-2">+ <Button asChild variant="secondary">+ <Link href={`/project/${project.id}`}>Go to project</Link>+ </Button>+ <Button asChild variant="ghost">+ <Link href={`/project/${project.id}/settings`}>+ <Settings size={16} />+ </Link>+ </Button>+ </CardFooter>+ ) : (+ <CardContent>+ <CardDescription>Project is being deleted</CardDescription>+ </CardContent>+ )}+ </Card>+ ),+ )}</div>);};diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex a028e1bd38..e39a93a8d6 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -12,7 +12,10 @@ import * as z from "zod";import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { TRPCError } from "@trpc/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";-import { redis } from "@langfuse/shared/src/server";+import {+ getLastTraceTimestampsByProjects,+ redis,+} from "@langfuse/shared/src/server";import { createBillingServiceFromContext } from "@/src/ee/features/billing/server/stripeBillingService";import { isCloudBillingEnabled } from "@/src/ee/features/billing/utils/isCloudBilling";import { shouldAutoEnableV4 } from "@/src/features/events/lib/v4Rollout";@@ -37,6 +40,20 @@ export const organizationsRouter = createTRPCRouter({}return organization;}),+ lastTraceByProject: protectedOrganizationProcedure+ .input(z.object({ orgId: z.string() }))+ .query(async ({ ctx }) => {+ const organization =+ ctx.session.user.admin === true+ ? await buildAdminOrgContext(ctx)+ : ctx.session.user.organizations.find(+ (org) => org.id === ctx.session.orgId,+ );++ return getLastTraceTimestampsByProjects({+ projectIds: organization?.projects.map((project) => project.id) ?? [],+ });+ }),create: authenticatedProcedure.input(organizationNameSchema).mutation(async ({ input, ctx }) => {diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex c843b0ff20..18389e3905 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -295,7 +295,20 @@ export const events = {],cmd_k_menu: ["opened", "search_entered", "navigated"],spend_alert: ["created", "updated", "deleted"],- sidebar: ["book_a_call_clicked", "v4_beta_toggled"],+ sidebar: [+ "book_a_call_clicked",+ "v4_beta_toggled",+ "v4_migration_card_clicked",+ ],+ v4_migration: [+ "in_app_agent_opened",+ "coding_agent_prompt_copied",+ "delay_badge_clicked",+ "project_chip_clicked",+ "contact_book_call_clicked",+ "contact_support_clicked",+ "status_row_clicked",+ ],// Filter/search-bar usage analytics (LFE-10781). METADATA ONLY — payloads// never carry a raw filter value, search text, or AI prompt (PII). Only// type/column/operator/key(field-name)/counts/lengths/booleans/enums.diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/web/src/features/rbac/constants/organizationAccessRights.tsindex 0477eb3701..2b3f27b11c 100644--- a/web/src/features/rbac/constants/organizationAccessRights.ts+++ b/web/src/features/rbac/constants/organizationAccessRights.ts@@ -12,15 +12,11 @@ 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",@@ -32,7 +28,6 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {"organizationMembers:read","langfuseCloudBilling:CRUD","auditLogs:read",- v4MigrationOrgScope,],ADMIN: ["projects:create",@@ -41,7 +36,6 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {"organizationMembers:CUD","organizationMembers:read","auditLogs:read",- v4MigrationOrgScope,],MEMBER: ["organizationMembers:read"],VIEWER: [],diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 933ab3b9e1..c0390cd342 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -83,16 +83,11 @@ export const projectScopes = ["monitors:read","monitors:CUD",-- "v4Migration:read",] as const;// type string of all Resource:Action, e.g. "members:read"export type ProjectScope = (typeof projectScopes)[number];-export const v4MigrationProjectScope =- "v4Migration:read" satisfies ProjectScope;-export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {OWNER: ["project:read",@@ -151,7 +146,6 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"automations:read","monitors:read","monitors:CUD",- v4MigrationProjectScope,],ADMIN: ["project:read",@@ -209,7 +203,6 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"automations:read","monitors:read","monitors:CUD",- v4MigrationProjectScope,],MEMBER: ["project:read",diff --git a/web/src/features/sdk-version/hooks/useProjectSdkVersionInfo.clienttest.ts b/web/src/features/sdk-version/hooks/useProjectSdkVersionInfo.clienttest.tsnew file mode 100644index 0000000000..9afd8a413a--- /dev/null+++ b/web/src/features/sdk-version/hooks/useProjectSdkVersionInfo.clienttest.ts@@ -0,0 +1,188 @@+import { renderHook, waitFor } from "@testing-library/react";+import { vi } from "vitest";++import {+ useProjectSdkVersionInfo,+ useProjectsSdkVersionInfo,+} from "@/src/features/sdk-version/hooks/useProjectSdkVersionInfo";+import { persistProjectSdkVersionInfo } from "@/src/features/sdk-version/lib/sdkVersionStorage";+import { sdkVersionStorageKeys } from "@/src/features/sdk-version/lib/sdkVersionCapabilities";++const apiMocks = vi.hoisted(() => ({+ getSdkVersionInfo: vi.fn(),+ queryResults: [] as unknown[],+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ useQueries: (+ buildQueries: (router: {+ events: { getSdkVersionInfo: typeof apiMocks.getSdkVersionInfo };+ }) => unknown,+ ) => {+ buildQueries({+ events: { getSdkVersionInfo: apiMocks.getSdkVersionInfo },+ });+ return apiMocks.queryResults;+ },+ },+}));++const storageValues = new Map<string, string>();+const localStorageMock: Storage = {+ get length() {+ return storageValues.size;+ },+ clear: () => storageValues.clear(),+ getItem: (key) => storageValues.get(key) ?? null,+ key: (index) => Array.from(storageValues.keys())[index] ?? null,+ removeItem: (key) => {+ storageValues.delete(key);+ },+ setItem: (key, value) => {+ storageValues.set(key, value);+ },+};++const pendingQuery = {+ data: undefined,+ dataUpdatedAt: 0,+ isFetching: true,+ isSuccess: false,+ isError: false,+};++describe("project SDK version hook", () => {+ beforeAll(() => {+ Object.defineProperty(window, "localStorage", {+ configurable: true,+ value: localStorageMock,+ });+ });++ beforeEach(() => {+ window.localStorage.clear();+ apiMocks.getSdkVersionInfo.mockReset();+ apiMocks.queryResults = [];+ });++ it("returns cached data immediately while refreshing in the background", () => {+ persistProjectSdkVersionInfo(+ "project-1",+ { language: "javascript", version: "5.4.0" },+ "2026-07-23T10:00:00.000Z",+ );+ apiMocks.queryResults = [pendingQuery];++ const { result } = renderHook(() =>+ useProjectSdkVersionInfo({+ projectId: "project-1",+ enabled: true,+ refreshMode: "always",+ }),+ );++ expect(result.current).toMatchObject({+ sdkVersion: { language: "javascript", version: "5.4.0" },+ isRefreshing: true,+ });+ expect(apiMocks.getSdkVersionInfo).toHaveBeenCalledWith(+ { projectId: "project-1" },+ expect.objectContaining({ enabled: true }),+ );+ });++ it("creates one non-blocking query per project", () => {+ apiMocks.queryResults = [pendingQuery, pendingQuery];++ renderHook(() =>+ useProjectsSdkVersionInfo({+ projectIds: ["project-1", "project-2"],+ enabled: true,+ refreshMode: "always",+ }),+ );++ expect(apiMocks.getSdkVersionInfo).toHaveBeenCalledTimes(2);+ expect(apiMocks.getSdkVersionInfo).toHaveBeenNthCalledWith(+ 1,+ { projectId: "project-1" },+ expect.objectContaining({+ enabled: true,+ refetchOnWindowFocus: false,+ retry: false,+ }),+ );+ expect(apiMocks.getSdkVersionInfo).toHaveBeenNthCalledWith(+ 2,+ { projectId: "project-2" },+ expect.objectContaining({ enabled: true }),+ );+ });++ it.each([+ ["fresh", new Date().toISOString(), false],+ ["stale", new Date(Date.now() - 31 * 86_400_000).toISOString(), true],+ ] as const)(+ "sets the app-root query enabled state for a %s cache",+ (_cacheState, checkedAt, enabled) => {+ persistProjectSdkVersionInfo(+ "project-1",+ { language: "python", version: "4.7.0" },+ checkedAt,+ );+ apiMocks.queryResults = [+ enabled ? pendingQuery : { ...pendingQuery, isFetching: false },+ ];++ renderHook(() =>+ useProjectSdkVersionInfo({+ projectId: "project-1",+ enabled: true,+ refreshMode: "if-stale",+ }),+ );++ expect(apiMocks.getSdkVersionInfo).toHaveBeenCalledWith(+ { projectId: "project-1" },+ expect.objectContaining({ enabled }),+ );+ },+ );++ it("persists a settled query in the shared app-root cache", async () => {+ const checkedAt = new Date("2026-07-23T10:00:00.000Z").getTime();+ apiMocks.queryResults = [+ {+ data: { isOtel: true, name: "python", version: "4.7.1" },+ dataUpdatedAt: checkedAt,+ isFetching: false,+ isSuccess: true,+ isError: false,+ },+ ];++ const { result } = renderHook(() =>+ useProjectSdkVersionInfo({+ projectId: "project-1",+ enabled: true,+ refreshMode: "always",+ }),+ );++ expect(result.current).toMatchObject({+ sdkVersion: { language: "python", version: "4.7.1" },+ checkedAt: new Date(checkedAt).toISOString(),+ querySettled: true,+ });++ const keys = sdkVersionStorageKeys("project-1");+ await waitFor(() => {+ expect(window.localStorage.getItem(keys.language)).toBe("python");+ expect(window.localStorage.getItem(keys.version)).toBe("4.7.1");+ expect(window.localStorage.getItem(keys.checkedAt)).toBe(+ new Date(checkedAt).toISOString(),+ );+ });+ });+});diff --git a/web/src/features/sdk-version/hooks/useProjectSdkVersionInfo.ts b/web/src/features/sdk-version/hooks/useProjectSdkVersionInfo.tsnew file mode 100644index 0000000000..496cc964a3--- /dev/null+++ b/web/src/features/sdk-version/hooks/useProjectSdkVersionInfo.ts@@ -0,0 +1,141 @@+import { useEffect } from "react";++import { api } from "@/src/utils/api";+import {+ sdkVersionNeedsRefresh,+ sdkVersionStorageKeys,+ toSdkVersionInfo,+ type SdkVersionInfo,+} from "@/src/features/sdk-version/lib/sdkVersionCapabilities";+import { persistProjectSdkVersionInfo } from "@/src/features/sdk-version/lib/sdkVersionStorage";++type ProjectSdkVersionRefreshMode = "if-stale" | "always";++export type ProjectSdkVersionState = {+ sdkVersion: SdkVersionInfo | undefined;+ checkedAt: string | null;+ isRefreshing: boolean;+ querySettled: boolean;+ isError: boolean;+};++const MIGRATION_QUERY_STALE_TIME_MS = 5 * 60 * 1000;++const readCachedSdkVersion = (+ projectId: string,+): Pick<ProjectSdkVersionState, "sdkVersion" | "checkedAt"> => {+ if (typeof window === "undefined") {+ return { sdkVersion: undefined, checkedAt: null };+ }++ try {+ const keys = sdkVersionStorageKeys(projectId);+ const checkedAt = window.localStorage.getItem(keys.checkedAt);+ return {+ sdkVersion: checkedAt+ ? {+ language: window.localStorage.getItem(keys.language),+ version: window.localStorage.getItem(keys.version),+ }+ : undefined,+ checkedAt,+ };+ } catch {+ return { sdkVersion: undefined, checkedAt: null };+ }+};++export function useProjectsSdkVersionInfo(params: {+ projectIds: readonly string[];+ enabled: boolean;+ refreshMode: ProjectSdkVersionRefreshMode;+}): Map<string, ProjectSdkVersionState> {+ const { projectIds, enabled, refreshMode } = params;+ const cachedSdkVersions = projectIds.map(readCachedSdkVersion);+ const now = Date.now();+ const shouldQuery = cachedSdkVersions.map(({ checkedAt }) => {+ return (+ enabled &&+ (refreshMode === "always" || sdkVersionNeedsRefresh(checkedAt, now))+ );+ });++ const queries = api.useQueries((t) =>+ projectIds.map((projectId, index) =>+ t.events.getSdkVersionInfo(+ { projectId },+ {+ enabled: shouldQuery[index],+ refetchOnWindowFocus: false,+ retry: false,+ staleTime:+ refreshMode === "always"+ ? MIGRATION_QUERY_STALE_TIME_MS+ : undefined,+ },+ ),+ ),+ );++ useEffect(() => {+ queries.forEach((query, index) => {+ if (!query.isSuccess || query.isFetching || !query.data) return;++ const sdkVersion = toSdkVersionInfo(query.data);+ if (!sdkVersion) return;++ persistProjectSdkVersionInfo(+ projectIds[index]!,+ sdkVersion,+ new Date(query.dataUpdatedAt).toISOString(),+ );+ });+ }, [projectIds, queries]);++ return new Map(+ projectIds.map((projectId, index) => {+ const query = queries[index];+ const cachedSdkVersion = cachedSdkVersions[index]!;+ const querySettled = Boolean(+ query?.isSuccess && !query.isFetching && query.data,+ );+ const queryCheckedAt = querySettled+ ? new Date(query!.dataUpdatedAt).toISOString()+ : null;++ return [+ projectId,+ {+ sdkVersion:+ toSdkVersionInfo(query?.data) ?? cachedSdkVersion.sdkVersion,+ checkedAt: queryCheckedAt ?? cachedSdkVersion.checkedAt,+ isRefreshing: Boolean(shouldQuery[index] && query?.isFetching),+ querySettled,+ isError: Boolean(query?.isError && !cachedSdkVersion.sdkVersion),+ },+ ];+ }),+ );+}++export function useProjectSdkVersionInfo(params: {+ projectId: string;+ enabled: boolean;+ refreshMode: ProjectSdkVersionRefreshMode;+}): ProjectSdkVersionState {+ const sdkVersions = useProjectsSdkVersionInfo({+ projectIds: [params.projectId],+ enabled: params.enabled,+ refreshMode: params.refreshMode,+ });++ return (+ sdkVersions.get(params.projectId) ?? {+ sdkVersion: undefined,+ checkedAt: null,+ isRefreshing: false,+ querySettled: false,+ isError: false,+ }+ );+}diff --git a/web/src/features/sdk-version/lib/sdkVersionCapabilities.ts b/web/src/features/sdk-version/lib/sdkVersionCapabilities.tsindex 7cbdd58260..28ae6a743c 100644--- a/web/src/features/sdk-version/lib/sdkVersionCapabilities.ts+++ b/web/src/features/sdk-version/lib/sdkVersionCapabilities.ts@@ -1,6 +1,6 @@import { normalizeIngestionSdkName } from "@langfuse/shared";-export type SdkMetadata = {+type SdkMetadata = {isOtel: boolean;name?: string;version?: string;@@ -19,14 +19,14 @@ export const sdkVersionStorageKeys = (projectId: string) => ({checkedAt: `events-sdk-checkedAt:${projectId}`,});-export const SDK_VERSION_CAPABILITIES = {+const SDK_VERSION_CAPABILITIES = {appRootObservations: {javascript: [5, 4, 0],python: [4, 7, 0],},} as const;-export type SdkVersionCapability = keyof typeof SDK_VERSION_CAPABILITIES;+type SdkVersionCapability = keyof typeof SDK_VERSION_CAPABILITIES;export const toSdkVersionInfo = (sdk: SdkMetadata | undefined,diff --git a/web/src/features/sdk-version/lib/sdkVersionStorage.clienttest.ts b/web/src/features/sdk-version/lib/sdkVersionStorage.clienttest.tsnew file mode 100644index 0000000000..9f32bdb3de--- /dev/null+++ b/web/src/features/sdk-version/lib/sdkVersionStorage.clienttest.ts@@ -0,0 +1,77 @@+import {+ clearProjectSdkVersionInfo,+ persistProjectSdkVersionInfo,+} from "@/src/features/sdk-version/lib/sdkVersionStorage";+import { sdkVersionStorageKeys } from "@/src/features/sdk-version/lib/sdkVersionCapabilities";++const storageValues = new Map<string, string>();+const localStorageMock: Storage = {+ get length() {+ return storageValues.size;+ },+ clear: () => storageValues.clear(),+ getItem: (key) => storageValues.get(key) ?? null,+ key: (index) => Array.from(storageValues.keys())[index] ?? null,+ removeItem: (key) => {+ storageValues.delete(key);+ },+ setItem: (key, value) => {+ storageValues.set(key, value);+ },+};++describe("SDK version storage", () => {+ beforeAll(() => {+ Object.defineProperty(window, "localStorage", {+ configurable: true,+ value: localStorageMock,+ });+ });+ beforeEach(() => window.localStorage.clear());+ afterEach(() => vi.restoreAllMocks());++ it("caches an unknown result without stale language/version values", () => {+ const projectId = "project-1";+ const keys = sdkVersionStorageKeys(projectId);+ window.localStorage.setItem(keys.language, "javascript");+ window.localStorage.setItem(keys.version, "5.4.0");++ persistProjectSdkVersionInfo(+ projectId,+ { language: null, version: null },+ "2026-07-23T10:00:00.000Z",+ );++ expect(window.localStorage.getItem(keys.language)).toBeNull();+ expect(window.localStorage.getItem(keys.version)).toBeNull();+ expect(window.localStorage.getItem(keys.checkedAt)).toBe(+ "2026-07-23T10:00:00.000Z",+ );+ });++ it("clears all cached SDK detection values", () => {+ const keys = sdkVersionStorageKeys("project-1");+ persistProjectSdkVersionInfo(+ "project-1",+ { language: "javascript", version: "5.4.0" },+ "2026-07-23T10:00:00.000Z",+ );++ clearProjectSdkVersionInfo("project-1");++ expect(window.localStorage.getItem(keys.language)).toBeNull();+ expect(window.localStorage.getItem(keys.version)).toBeNull();+ expect(window.localStorage.getItem(keys.checkedAt)).toBeNull();+ });++ it("does not rewrite an unchanged SDK detection result", () => {+ const checkedAt = "2026-07-23T10:00:00.000Z";+ const sdkVersion = { language: "javascript", version: "5.4.0" };+ persistProjectSdkVersionInfo("project-1", sdkVersion, checkedAt);+ const setItem = vi.spyOn(window.localStorage, "setItem");++ persistProjectSdkVersionInfo("project-1", sdkVersion, checkedAt);++ expect(setItem).not.toHaveBeenCalled();+ });+});diff --git a/web/src/features/sdk-version/lib/sdkVersionStorage.ts b/web/src/features/sdk-version/lib/sdkVersionStorage.tsnew file mode 100644index 0000000000..4a34666183--- /dev/null+++ b/web/src/features/sdk-version/lib/sdkVersionStorage.ts@@ -0,0 +1,44 @@+import {+ sdkVersionStorageKeys,+ type SdkVersionInfo,+} from "@/src/features/sdk-version/lib/sdkVersionCapabilities";++const writeStorageValue = (key: string, value: string | null) => {+ if (value === null) {+ window.localStorage.removeItem(key);+ } else {+ window.localStorage.setItem(key, value);+ }+};++export const persistProjectSdkVersionInfo = (+ projectId: string,+ sdkVersion: SdkVersionInfo,+ checkedAt: string,+) => {+ if (typeof window === "undefined") return;++ const keys = sdkVersionStorageKeys(projectId);+ try {+ if (window.localStorage.getItem(keys.checkedAt) === checkedAt) return;++ writeStorageValue(keys.language, sdkVersion.language);+ writeStorageValue(keys.version, sdkVersion.version);+ writeStorageValue(keys.checkedAt, checkedAt);+ } catch {+ // Storage can be unavailable in hardened/private browser contexts.+ }+};++export const clearProjectSdkVersionInfo = (projectId: string) => {+ if (typeof window === "undefined") return;++ const keys = sdkVersionStorageKeys(projectId);+ try {+ writeStorageValue(keys.language, null);+ writeStorageValue(keys.version, null);+ writeStorageValue(keys.checkedAt, null);+ } catch {+ // Storage can be unavailable in hardened/private browser contexts.+ }+};diff --git a/web/src/features/support-chat/SupportDrawer.tsx b/web/src/features/support-chat/SupportDrawer.tsxindex 9cb5d803b3..179cdca8de 100644--- a/web/src/features/support-chat/SupportDrawer.tsx+++ b/web/src/features/support-chat/SupportDrawer.tsx@@ -15,21 +15,32 @@ import { SuccessSection } from "@/src/features/support-chat/SuccessSection";import { SupportFormSection } from "@/src/features/support-chat/SupportFormSection";import { cn } from "@/src/utils/tailwind";-export const SupportDrawer = ({+export const SupportDrawer = (props: {+ showCloseButton?: boolean;+ className?: string;+}) => {+ const { open, openEpoch } = useSupportDrawer();++ if (!open) return null;++ // Keyed by openEpoch so re-opening (openWithMode while already open)+ // remounts the content and re-seeds mode/topic from the provider.+ return <SupportDrawerContent key={openEpoch} {...props} />;+};++const SupportDrawerContent = ({showCloseButton = true,className,}: {showCloseButton?: boolean;className?: string;}) => {- const { open, setOpen } = useSupportDrawer();+ const { setOpen, initialMode } = useSupportDrawer();const [currentMode, setCurrentMode] = useState<"intro" | "form" | "success">(- "intro",+ initialMode,);const close = () => setOpen(false);- if (!open) return null;-return (<divclassName={cn([diff --git a/web/src/features/support-chat/SupportDrawerProvider.clienttest.tsx b/web/src/features/support-chat/SupportDrawerProvider.clienttest.tsxnew file mode 100644index 0000000000..34dde938b9--- /dev/null+++ b/web/src/features/support-chat/SupportDrawerProvider.clienttest.tsx@@ -0,0 +1,55 @@+// @vitest-environment jsdom++import { describe, it, expect } from "vitest";+import { act, renderHook } from "@testing-library/react";+import {+ SupportDrawerProvider,+ useSupportDrawer,+} from "@/src/features/support-chat/SupportDrawerProvider";++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <SupportDrawerProvider>{children}</SupportDrawerProvider>+);++describe("SupportDrawerProvider", () => {+ it("bumps openEpoch and reseeds on closed→open", () => {+ const { result } = renderHook(() => useSupportDrawer(), { wrapper });+ const epochBefore = result.current.openEpoch;++ act(() => result.current.openWithMode("form", { topic: "V4 Migration" }));+ act(() => result.current.setOpen(false));+ act(() => result.current.setOpen(true));++ expect(result.current.open).toBe(true);+ expect(result.current.openEpoch).toBe(epochBefore + 2);+ expect(result.current.initialMode).toBe("intro");+ expect(result.current.initialTopic).toBeNull();+ });++ it("does not reset a drawer that is already open", () => {+ const { result } = renderHook(() => useSupportDrawer(), { wrapper });++ act(() => result.current.openWithMode("form", { topic: "V4 Migration" }));+ const epochWhileOpen = result.current.openEpoch;++ // A redundant open (e.g. clicking the support button again) must not+ // remount the drawer and wipe an in-progress draft.+ act(() => result.current.setOpen(true));++ expect(result.current.openEpoch).toBe(epochWhileOpen);+ expect(result.current.initialMode).toBe("form");+ expect(result.current.initialTopic).toBe("V4 Migration");+ });++ it("openWithMode always reseeds, even while open", () => {+ const { result } = renderHook(() => useSupportDrawer(), { wrapper });++ act(() => result.current.setOpen(true));+ const epoch = result.current.openEpoch;++ act(() => result.current.openWithMode("form"));++ expect(result.current.openEpoch).toBe(epoch + 1);+ expect(result.current.initialMode).toBe("form");+ });+});diff --git a/web/src/features/support-chat/SupportDrawerProvider.tsx b/web/src/features/support-chat/SupportDrawerProvider.tsxindex 7958939037..50a866168b 100644--- a/web/src/features/support-chat/SupportDrawerProvider.tsx+++ b/web/src/features/support-chat/SupportDrawerProvider.tsx@@ -1,13 +1,28 @@import {createContext,+ useCallback,useContext,useState,type PropsWithChildren,} from "react";+import { type Topic } from "@/src/features/support-chat/formConstants";++export type SupportDrawerMode = "intro" | "form";type SupportDrawerContextType = {open: boolean;setOpen: (v: boolean) => void;+ /** Section the drawer shows when it opens; a closed→open resets to intro. */+ initialMode: SupportDrawerMode;+ /** Topic preselected in the support form; a closed→open resets it. */+ initialTopic: Topic | null;+ /**+ * Bumped on closed→open transitions and on every openWithMode so the+ * drawer can remount via key and re-seed mode/topic. A redundant+ * setOpen(true) while already open does NOT bump it.+ */+ openEpoch: number;+ openWithMode: (mode: SupportDrawerMode, options?: { topic?: Topic }) => void;};const SupportDrawerContext = createContext<SupportDrawerContextType | null>(@@ -23,9 +38,47 @@ export function SupportDrawerProvider({children,defaultOpen = false,}: SupportDrawerProviderProps) {- const [open, setOpen] = useState(defaultOpen);+ const [open, setOpenState] = useState(defaultOpen);+ const [initialMode, setInitialMode] = useState<SupportDrawerMode>("intro");+ const [initialTopic, setInitialTopic] = useState<Topic | null>(null);+ const [openEpoch, setOpenEpoch] = useState(0);++ const setOpen = useCallback(+ (v: boolean) => {+ // Reseed only on a closed→open transition: a redundant setOpen(true)+ // while open (support button, "Report issue") must not remount the+ // drawer and wipe an in-progress draft. openWithMode always reseeds.+ if (v && !open) {+ setInitialMode("intro");+ setInitialTopic(null);+ setOpenEpoch((e) => e + 1);+ }+ setOpenState(v);+ },+ [open],+ );++ const openWithMode = useCallback(+ (mode: SupportDrawerMode, options?: { topic?: Topic }) => {+ setInitialMode(mode);+ setInitialTopic(options?.topic ?? null);+ setOpenEpoch((e) => e + 1);+ setOpenState(true);+ },+ [],+ );+return (- <SupportDrawerContext.Provider value={{ open, setOpen }}>+ <SupportDrawerContext.Provider+ value={{+ open,+ setOpen,+ initialMode,+ initialTopic,+ openEpoch,+ openWithMode,+ }}+ >{children}</SupportDrawerContext.Provider>);diff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportFormSection.tsxindex 6c088ec534..76624922ae 100644--- a/web/src/features/support-chat/SupportFormSection.tsx+++ b/web/src/features/support-chat/SupportFormSection.tsx@@ -63,6 +63,8 @@ import { Paperclip, Trash2 } from "lucide-react";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { PYLON_MAX_FILE_SIZE_BYTES } from "./pylon/pylonConstants";import Spinner from "@/src/components/design-system/Spinner/Spinner";+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";/** Make RHF generics match the resolver (Zod defaults => input can be undefined) */type SupportFormInput = z.input<typeof SupportFormSchema>;@@ -203,12 +205,18 @@ export function SupportFormSection({// confirmation step.const [sev1ConfirmOpen, setSev1ConfirmOpen] = useState(false);+ const { initialTopic } = useSupportDrawer();+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();+ const productFeatureTopics = TopicGroups["Product Features"].filter(+ (topic) => topic !== "V4 Migration" || v4UpgradeUiEnabled,+ );+const form = useForm<SupportFormInput>({resolver: zodResolver(SupportFormSchema),defaultValues: {messageType: "Question" as MessageType,severity: SEVERITY_3,- topic: "",+ topic: initialTopic ?? "",message: "",integrationType: "",},@@ -496,7 +504,7 @@ export function SupportFormSection({<div className="text-muted-foreground mb-2 text-xs font-bold">Product Features</div>- {TopicGroups["Product Features"].map((t) => (+ {productFeatureTopics.map((t) => (<SelectItem key={t} value={t}>{t}</SelectItem>diff --git a/web/src/features/support-chat/formConstants.ts b/web/src/features/support-chat/formConstants.tsindex 946c55762d..a431f60a2b 100644--- a/web/src/features/support-chat/formConstants.ts+++ b/web/src/features/support-chat/formConstants.ts@@ -24,6 +24,7 @@ export const TopicGroups = {"Prompt Management","Evaluation","Platform",+ "V4 Migration","Other",],} as const;diff --git a/web/src/features/v4-migration/V4MigrationContent.tsx b/web/src/features/v4-migration/V4MigrationContent.tsxnew file mode 100644index 0000000000..30c99a4242--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationContent.tsx@@ -0,0 +1,506 @@+import { type ReactNode } from "react";+import { useRouter } from "next/router";+import Link from "next/link";+import {+ ChevronRight,+ Copy,+ LibraryBig,+ LifeBuoy,+ TriangleAlert,+} from "lucide-react";+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { Button } from "@/src/components/ui/button";+import { RainbowButton } from "@/src/components/magicui/rainbow-button";+import { Separator } from "@/src/components/ui/separator";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/src/components/ui/collapsible";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { cn } from "@/src/utils/tailwind";+import { type ProjectSdkVersionState } from "@/src/features/sdk-version/hooks/useProjectSdkVersionInfo";+import {+ formatSdkVersion,+ type V4MigrationSdkStatus,+} from "@/src/features/v4-migration/sdkVersionStatus";+import { useProjectV4MigrationData } from "@/src/features/v4-migration/hooks/useV4MigrationData";+import {+ V4_MIGRATION_LOOKBACK_DAYS,+ type MigrationCountState,+} from "@/src/features/v4-migration/migrationData";+import { numberFormatter } from "@/src/utils/numbers";++// Single source of truth for the v4-migration copy and content. Both surfaces+// (side panel and modal) render these components — edit copy here only.++const V4_DOCS_URL = "https://langfuse.com/docs/v4";+const SDK_UPGRADE_URL =+ "https://langfuse.com/docs/observability/sdk/upgrade-path";++const CODING_AGENT_PROMPT = `Migrate this project's Langfuse setup to v4:+1. Upgrade the Langfuse SDK to the latest major version. Upgrade guide: ${SDK_UPGRADE_URL}+2. Repoint evals that target trace input/output to observations instead.+3. Replace calls to deprecated APIs (GET /api/public/traces, GET /api/public/sessions, GET /api/public/metrics) with their v4 replacements.+Docs: ${V4_DOCS_URL}`;++// Copies the agent migration prompt to the clipboard with toast + analytics;+// shared by the panel/modal header CTA and the status page.+export function useCopyMigrationPrompt() {+ const capture = usePostHogClientCapture();++ return async () => {+ capture("v4_migration:coding_agent_prompt_copied");+ await navigator.clipboard.writeText(CODING_AGENT_PROMPT);+ showSuccessToast({+ title: "Prompt copied",+ description: "Paste it into Cursor, Codex, or another coding agent.",+ });+ };+}++function Chip({+ children,+ variant,+}: {+ children: ReactNode;+ variant: "warning" | "success";+}) {+ return (+ <span+ className={cn(+ "inline-flex w-fit shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-bold whitespace-nowrap",+ variant === "warning"+ ? "bg-light-yellow text-dark-yellow"+ : "bg-light-green text-dark-green",+ )}+ >+ {children}+ </span>+ );+}++function Section({+ title,+ chip,+ children,+}: {+ title: string;+ chip: ReactNode;+ children: ReactNode;+}) {+ return (+ <Collapsible>+ <CollapsibleTrigger className="group flex w-full items-center gap-2.5 py-1.5 text-left">+ <ChevronRight className="text-muted-foreground h-4 w-4 shrink-0 transition-transform group-data-[state=open]:rotate-90" />+ <span className="flex-1 text-sm">{title}</span>+ {chip}+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="pt-0.5 pb-3.5 pl-6.5">{children}</div>+ </CollapsibleContent>+ </Collapsible>+ );+}++function MonoValue({ children }: { children: ReactNode }) {+ return <span className="text-foreground font-bold">{children}</span>;+}++function ExternalLink({+ href,+ children,+ className,+}: {+ href: string;+ children: ReactNode;+ className?: string;+}) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ className={cn("text-dark-blue hover:underline", className)}+ >+ {children}+ </a>+ );+}++function MigrationCountChip({+ state,+ affectedLabel,+}: {+ state: MigrationCountState;+ affectedLabel: string;+}) {+ if (state.status === "loading") {+ return <Chip variant="warning">Checking</Chip>;+ }+ if (state.status === "error") {+ return <Chip variant="warning">Check failed</Chip>;+ }+ if (state.count === 0) {+ return <Chip variant="success">Up to date</Chip>;+ }+ return (+ <Chip variant="warning">+ {state.count} {affectedLabel}+ </Chip>+ );+}++function V4MigrationSdkSection({+ sdkVersionState,+ status,+}: {+ sdkVersionState: ProjectSdkVersionState;+ status: V4MigrationSdkStatus;+}) {+ const detectedSdk = formatSdkVersion(sdkVersionState.sdkVersion);++ const chip =+ status === "latest" ? (+ <Chip variant="success">Up to date</Chip>+ ) : status === "checking" ? (+ <Chip variant="warning">Checking</Chip>+ ) : status === "unknown" ? (+ <Chip variant="warning">Not detected</Chip>+ ) : status === "error" ? (+ <Chip variant="warning">Check failed</Chip>+ ) : (+ <Chip variant="warning">Legacy</Chip>+ );++ return (+ <Section title="Tracing Instrumentation" chip={chip}>+ <p className="text-muted-foreground text-sm leading-relaxed">+ {status === "checking" ? (+ "Checking the latest traces for this project…"+ ) : status === "unknown" ? (+ <>+ We could not detect an attributed Langfuse SDK in traces from the+ last 7 days. If this project uses one, verify that it is up to date.+ </>+ ) : status === "error" ? (+ "We could not check the latest traces for this project. Try again later."+ ) : status === "latest" ? (+ <>+ This project uses <MonoValue>{detectedSdk}</MonoValue>. Nothing to+ do.+ </>+ ) : (+ <>+ This project uses <MonoValue>{detectedSdk}</MonoValue>.{" "}+ <ExternalLink href={SDK_UPGRADE_URL}>Upgrade the SDK</ExternalLink>{" "}+ for real-time data and the latest tracing experience.+ </>+ )}+ </p>+ </Section>+ );+}++// Title, description, and the primary agent CTA.+export function V4MigrationHeaderContent({+ projectName,+}: {+ projectName?: string;+}) {+ const handleCopyPrompt = useCopyMigrationPrompt();++ return (+ <>+ <p className="mb-1.5 text-lg font-bold">+ {projectName ? (+ <>+ Review v4 migration for{" "}+ <span className="underline">{projectName}</span>+ </>+ ) : (+ "Review v4 migration"+ )}+ </p>+ <p className="text-muted-foreground mb-3 text-sm leading-relaxed">+ Review the items below and update anything still using the legacy data+ model.+ </p>+ <div className="flex flex-wrap items-center gap-2">+ <RainbowButton className="w-full" onClick={handleCopyPrompt}>+ <Copy className="mr-1.5 h-4 w-4 shrink-0" />+ <span className="min-w-0 truncate" title="Copy prompt for agents">+ Copy prompt for agents+ </span>+ </RainbowButton>+ </div>+ </>+ );+}++// The "Want to review first?" and "What happens if I don't update" groups.+// onNavigate fires when an internal link is followed so the hosting surface+// (panel or modal) can close itself.+export function V4MigrationDetailsContent({+ onNavigate,+ projectId: projectIdProp,+}: {+ onNavigate?: () => void;+ /** Project the content links point at; falls back to the route project. */+ projectId?: string;+}) {+ const router = useRouter();+ const capture = usePostHogClientCapture();+ const { openWithMode: openSupportDrawerWithMode } = useSupportDrawer();++ const routeProjectId = router.query.projectId;+ const projectId =+ projectIdProp ??+ (typeof routeProjectId === "string" ? routeProjectId : undefined);+ const migrationData = useProjectV4MigrationData({+ projectId,+ enabled: Boolean(projectId),+ });++ const handleEmailEngineer = () => {+ capture("v4_migration:contact_support_clicked");+ onNavigate?.();+ openSupportDrawerWithMode("form", { topic: "V4 Migration" });+ };+ const evalsUrl =+ typeof projectId === "string" ? `/project/${projectId}/evals` : undefined;+ const integrationsUrl =+ typeof projectId === "string"+ ? `/project/${projectId}/settings/integrations`+ : undefined;++ return (+ <>+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2 text-base font-bold">+ <LibraryBig className="h-4 w-4" /> Want to review first?+ </div>+ <div className="flex items-center gap-2">+ <Button variant="outline" asChild className="min-w-0 flex-1">+ <a href={V4_DOCS_URL} target="_blank" rel="noopener noreferrer">+ <span className="min-w-0 truncate" title="Documentation">+ Documentation+ </span>+ </a>+ </Button>+ <Button variant="outline" asChild className="min-w-0 flex-1">+ <Link href="/v4-migration" onClick={onNavigate}>+ <span className="min-w-0 truncate" title="Check migration status">+ Check migration status+ </span>+ </Link>+ </Button>+ </div>+ </div>++ <Separator />++ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2 text-base font-bold">+ <TriangleAlert className="h-4 w-4" /> What happens if I don't+ update?+ </div>+ <p className="text-muted-foreground text-sm">+ Some features will stop working after{" "}+ <span className="text-dark-yellow">Oct 1</span>.+ </p>+ <div>+ <V4MigrationSdkSection+ sdkVersionState={migrationData.sdkVersionState}+ status={migrationData.sdkStatus}+ />++ <Section+ title="Evals"+ chip={+ <MigrationCountChip+ state={migrationData.evals}+ affectedLabel="deprecated"+ />+ }+ >+ {migrationData.evals.status === "loading" ? (+ <p className="text-muted-foreground text-sm">+ Checking configured evals…+ </p>+ ) : migrationData.evals.status === "error" ? (+ <p className="text-muted-foreground text-sm">+ We could not check configured evals. Try again later.+ </p>+ ) : migrationData.evals.count > 0 ? (+ <>+ <p className="text-muted-foreground mb-2 text-sm">+ {migrationData.evals.count} configured{" "}+ {migrationData.evals.count === 1+ ? "eval targets"+ : "evals target"}{" "}+ trace input/output, which stops running{" "}+ <span className="text-dark-yellow">Oct 1</span>. Point{" "}+ {migrationData.evals.count === 1 ? "it" : "them"} at an+ observation instead.+ </p>+ {evalsUrl ? (+ <Link+ href={evalsUrl}+ onClick={onNavigate}+ className="text-dark-blue text-sm hover:underline"+ >+ Review trace-level evals+ </Link>+ ) : null}+ </>+ ) : (+ <p className="text-muted-foreground text-sm">+ No configured trace-level evals detected.+ </p>+ )}+ </Section>++ <Section+ title="Legacy APIs"+ chip={+ <MigrationCountChip+ state={migrationData.apis}+ affectedLabel="deprecated"+ />+ }+ >+ {migrationData.apis.status === "loading" ? (+ <p className="text-muted-foreground text-sm">+ Checking public API usage…+ </p>+ ) : migrationData.apis.status === "error" ? (+ <p className="text-muted-foreground text-sm">+ We could not check public API usage. Try again later.+ </p>+ ) : migrationData.apiUsage.length > 0 ? (+ <>+ <p className="text-muted-foreground mb-2 text-sm">+ You've called these deprecated endpoints in the last{" "}+ {V4_MIGRATION_LOOKBACK_DAYS} days. They stop working{" "}+ <span className="text-dark-yellow">Oct 1</span>; the{" "}+ <ExternalLink href="https://api.reference.langfuse.com">+ new APIs+ </ExternalLink>{" "}+ cover the same data.+ </p>+ <div className="flex flex-col">+ {migrationData.apiUsage.map((usage) => (+ <div+ key={usage.endpoint}+ className="flex items-center justify-between gap-2 py-0.5"+ >+ <ExternalLink+ href="https://api.reference.langfuse.com"+ className="text-sm"+ >+ {usage.endpoint}+ </ExternalLink>+ <span className="text-muted-foreground text-xs whitespace-nowrap">+ {numberFormatter(usage.count, 0, 2)} calls+ </span>+ </div>+ ))}+ </div>+ </>+ ) : (+ <p className="text-muted-foreground text-sm">+ No legacy public API usage detected in the last{" "}+ {V4_MIGRATION_LOOKBACK_DAYS} days.+ </p>+ )}+ </Section>++ <Section+ title="Legacy Integrations"+ chip={+ <MigrationCountChip+ state={migrationData.exports}+ affectedLabel="deprecated"+ />+ }+ >+ {migrationData.exports.status === "loading" ? (+ <p className="text-muted-foreground text-sm">+ Checking integrations…+ </p>+ ) : migrationData.exports.status === "error" ? (+ <p className="text-muted-foreground text-sm">+ We could not check integrations. Try again later.+ </p>+ ) : migrationData.legacyIntegrations.length > 0 ? (+ <>+ <p className="text-muted-foreground mb-2 text-sm">+ These exports still read from the old data source. Switching+ them over can change what downstream consumers receive, so+ worth a quick check.+ </p>+ <div className="flex flex-col">+ {migrationData.legacyIntegrations.map((name) => (+ <div key={name} className="flex items-center py-0.5">+ {integrationsUrl ? (+ <Link+ href={integrationsUrl}+ onClick={onNavigate}+ className="text-dark-blue text-sm hover:underline"+ >+ {name}+ </Link>+ ) : (+ <span className="text-sm">{name}</span>+ )}+ </div>+ ))}+ </div>+ </>+ ) : (+ <p className="text-muted-foreground text-sm">+ No legacy integration exports detected.+ </p>+ )}+ </Section>+ </div>+ </div>++ <Separator />++ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2 text-base font-bold">+ <LifeBuoy className="h-4 w-4" /> Contact us+ </div>+ <p className="text-muted-foreground text-sm">+ Need a hand with the update? We're here to help!+ </p>+ <div className="flex items-center gap-2">+ <Button variant="outline" asChild className="min-w-0 flex-1">+ <a+ href="https://cal.com/team/langfuse/welcome-to-langfuse"+ target="_blank"+ rel="noopener noreferrer"+ onClick={() => capture("v4_migration:contact_book_call_clicked")}+ >+ <span className="min-w-0 truncate" title="Book a call">+ Book a call+ </span>+ </a>+ </Button>+ <Button+ variant="outline"+ className="min-w-0 flex-1"+ onClick={handleEmailEngineer}+ >+ <span className="min-w-0 truncate" title="Email an Engineer">+ Email an Engineer+ </span>+ </Button>+ </div>+ </div>+ </>+ );+}diff --git a/web/src/features/v4-migration/V4MigrationDelayBadge.tsx b/web/src/features/v4-migration/V4MigrationDelayBadge.tsxnew file mode 100644index 0000000000..a31410eab0--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationDelayBadge.tsx@@ -0,0 +1,51 @@+import { ChevronRight } from "lucide-react";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useQueryProject } from "@/src/features/projects/hooks";+import { useProjectSdkVersionInfo } from "@/src/features/sdk-version/hooks/useProjectSdkVersionInfo";+import { getV4MigrationSdkStatus } from "@/src/features/v4-migration/sdkVersionStatus";+import { useOpenV4MigrationPanel } from "@/src/features/v4-migration/hooks/useOpenV4MigrationPanel";++export function V4MigrationDelayBadge() {+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();+ const openMigrationPanel = useOpenV4MigrationPanel();+ const { project } = useQueryProject();+ const capture = usePostHogClientCapture();+ const sdkVersionState = useProjectSdkVersionInfo({+ projectId: project?.id ?? "",+ enabled: v4UpgradeUiEnabled && Boolean(project),+ refreshMode: "always",+ });+ const sdkStatus = getV4MigrationSdkStatus(sdkVersionState);++ if (!v4UpgradeUiEnabled || !project || sdkStatus !== "legacy") {+ return null;+ }++ const handleClick = () => {+ capture("v4_migration:delay_badge_clicked");+ openMigrationPanel({ id: project.id, name: project.name });+ };++ return (+ <button+ type="button"+ onClick={handleClick}+ className="group ring-input hover:bg-muted/50 hover:text-foreground inline-flex w-fit flex-none shrink-0 items-center gap-1.5 rounded-full bg-transparent px-2 py-0.5 text-xs font-bold whitespace-nowrap ring"+ >+ <span+ aria-hidden+ className="size-1.75 shrink-0 rounded-full bg-orange-400 dark:bg-orange-400"+ ></span>+ <span className="flex items-center">+ New data in ~15 min+ <span className="flex max-w-0 items-center overflow-hidden transition-[max-width] duration-300 ease-out group-hover:max-w-96">+ <span className="whitespace-nowrap">+ . Update your SDK for real-time data.+ </span>+ </span>+ <ChevronRight className="ml-1 h-3 w-3 shrink-0" />+ </span>+ </button>+ );+}diff --git a/web/src/features/v4-migration/V4MigrationModal.tsx b/web/src/features/v4-migration/V4MigrationModal.tsxnew file mode 100644index 0000000000..46814549df--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationModal.tsx@@ -0,0 +1,74 @@+import { useState } from "react";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogTitle,+} from "@/src/components/ui/dialog";+import { Separator } from "@/src/components/ui/separator";+import {+ V4MigrationHeaderContent,+ V4MigrationDetailsContent,+} from "@/src/features/v4-migration/V4MigrationContent";+import { useQueryProject } from "@/src/features/projects/hooks";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";+import { api } from "@/src/utils/api";++// Modal variant of the migration panel (experiment): mounted on pages that+// use deprecated features (currently Evals) and opens on arrival.+export function V4MigrationModal() {+ const { project } = useQueryProject();+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();+ const traceLevelEvalSummary = api.v4Transition.traceLevelEvalSummary.useQuery(+ { projectId: project?.id ?? "" },+ {+ enabled: v4UpgradeUiEnabled && Boolean(project),+ refetchOnWindowFocus: false,+ staleTime: 5 * 60 * 1000,+ },+ );++ if (+ !v4UpgradeUiEnabled ||+ !project ||+ !traceLevelEvalSummary.data?.traceLevelEvalCount+ ) {+ return null;+ }++ // Keyed by project so a projectId-only navigation (which reuses the page+ // instance) re-opens the modal instead of inheriting the dismissal.+ return <V4MigrationModalContent key={project.id} project={project} />;+}++function V4MigrationModalContent({+ project,+}: {+ project: { id: string; name: string };+}) {+ const [open, setOpen] = useState(true);++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent+ overlayMode="blocking"+ overlayClassName="backdrop-blur-sm"+ closeOnInteractionOutside+ >+ <DialogTitle className="sr-only">+ {`Review v4 migration for ${project.name}`}+ </DialogTitle>+ <DialogBody className="gap-0 p-4">+ <V4MigrationHeaderContent projectName={project.name} />+ <Separator className="my-6" />+ <div className="flex flex-col gap-6">+ <V4MigrationDetailsContent+ onNavigate={() => setOpen(false)}+ projectId={project.id}+ />+ </div>+ </DialogBody>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/v4-migration/V4MigrationNavItem.tsx b/web/src/features/v4-migration/V4MigrationNavItem.tsxnew file mode 100644index 0000000000..d76a66c3c9--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationNavItem.tsx@@ -0,0 +1,71 @@+import { ChevronRight } from "lucide-react";+import { SidebarMenuButton, useSidebar } from "@/src/components/ui/sidebar";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useQueryProject } from "@/src/features/projects/hooks";+import { useProjectV4MigrationData } from "@/src/features/v4-migration/hooks/useV4MigrationData";+import { getProjectMigrationReadiness } from "@/src/features/v4-migration/migrationData";+import { useOpenV4MigrationPanel } from "@/src/features/v4-migration/hooks/useOpenV4MigrationPanel";++export function V4MigrationNavItem() {+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();+ const openMigrationPanel = useOpenV4MigrationPanel();+ const { isMobile, setOpenMobile: setOpenMobileSidebar } = useSidebar();+ const { project } = useQueryProject();+ const capture = usePostHogClientCapture();+ const migrationData = useProjectV4MigrationData({+ projectId: project?.id,+ enabled: v4UpgradeUiEnabled && Boolean(project),+ });++ if (!v4UpgradeUiEnabled || !project) {+ return null;+ }+ const readiness = getProjectMigrationReadiness({+ sdk: migrationData.sdkStatus,+ evals: migrationData.evals,+ apis: migrationData.apis,+ exports: migrationData.exports,+ });+ const label =+ readiness === "ready"+ ? "Up to date"+ : readiness === "checking"+ ? "Checking"+ : readiness === "unavailable"+ ? "Check status"+ : "Action required";++ const handleClick = () => {+ capture("sidebar:v4_migration_card_clicked");+ if (isMobile) {+ setOpenMobileSidebar(false);+ }+ setTimeout(() => {+ // push to next tick to avoid flickering when hiding sidebar on mobile+ openMigrationPanel({ id: project.id, name: project.name });+ }, 1);+ };++ return (+ <div className="px-2 py-2 group-data-[collapsible=icon]:hidden">+ <SidebarMenuButton+ onClick={handleClick}+ tooltip={label}+ className="border-input w-full gap-1.5 rounded-full border pr-2 pl-[9px]"+ >+ <span+ className={+ readiness === "ready"+ ? "h-2 w-2 shrink-0 rounded-full bg-green-500 dark:bg-green-500"+ : "h-2 w-2 shrink-0 rounded-full bg-orange-400 dark:bg-orange-400"+ }+ />+ <span className="truncate font-bold" title={label}>+ {label}+ </span>+ <ChevronRight className="text-muted-foreground ml-auto h-4 w-4 shrink-0" />+ </SidebarMenuButton>+ </div>+ );+}diff --git a/web/src/features/v4-migration/V4MigrationPanel.tsx b/web/src/features/v4-migration/V4MigrationPanel.tsxnew file mode 100644index 0000000000..c5e05e644c--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationPanel.tsx@@ -0,0 +1,68 @@+import { X } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Separator } from "@/src/components/ui/separator";+import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanelProvider";+import { useQueryProject } from "@/src/features/projects/hooks";+import {+ V4MigrationHeaderContent,+ V4MigrationDetailsContent,+} from "@/src/features/v4-migration/V4MigrationContent";+import { cn } from "@/src/utils/tailwind";++export const V4MigrationPanel = ({+ showCloseButton = true,+ className,+}: {+ showCloseButton?: boolean;+ className?: string;+}) => {+ const { open, setOpen, targetProject } = useV4MigrationPanel();+ const { project: routeProject } = useQueryProject();++ if (!open) return null;++ // Prefer the route's project so the panel follows navigation while open;+ // targetProject only decides on project-less routes (home, status page),+ // where it carries the project the opening surface was about.+ const project = routeProject+ ? { id: routeProject.id, name: routeProject.name }+ : targetProject;++ return (+ <div+ className={cn([+ "bg-background flex h-full w-full min-w-0 flex-col",+ className,+ ])}+ >+ <div className="bg-background">+ <div className="flex min-h-11 w-full items-center justify-between gap-1 px-4 py-1">+ <span className="text-sm font-bold">Update</span>+ {showCloseButton && (+ <Button+ variant="ghost"+ size="icon"+ onClick={() => setOpen(false)}+ aria-label="Close"+ >+ <X className="h-4 w-4" />+ </Button>+ )}+ </div>+ </div>+ <div className="flex-1 overflow-y-auto border-t">+ <div className="bg-background sticky top-0 z-[1] px-4 pt-4">+ <V4MigrationHeaderContent projectName={project?.name} />+ <Separator className="mt-6" />+ </div>++ <div className="flex flex-col gap-6 px-4 pt-6 pb-16">+ <V4MigrationDetailsContent+ onNavigate={() => setOpen(false)}+ projectId={project?.id}+ />+ </div>+ </div>+ </div>+ );+};diff --git a/web/src/features/v4-migration/V4MigrationPanelProvider.clienttest.tsx b/web/src/features/v4-migration/V4MigrationPanelProvider.clienttest.tsxnew file mode 100644index 0000000000..eded15a5ac--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationPanelProvider.clienttest.tsx@@ -0,0 +1,52 @@+// @vitest-environment jsdom++import { act, renderHook } from "@testing-library/react";+import { vi } from "vitest";++import {+ V4MigrationPanelProvider,+ useV4MigrationPanel,+} from "./V4MigrationPanelProvider";++const flagState = vi.hoisted(() => ({ enabled: false }));++vi.mock("./useV4UpgradeUiEnabled", () => ({+ useV4UpgradeUiEnabled: () => flagState.enabled,+}));++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <V4MigrationPanelProvider>{children}</V4MigrationPanelProvider>+);++describe("V4MigrationPanelProvider", () => {+ beforeEach(() => {+ flagState.enabled = false;+ });++ it("refuses to open when the user flag is disabled", () => {+ const { result } = renderHook(() => useV4MigrationPanel(), { wrapper });++ act(() =>+ result.current.openForProject({ id: "project-id", name: "Project" }),+ );+ act(() => result.current.setOpen(true));++ expect(result.current.open).toBe(false);+ expect(result.current.targetProject).toBeNull();+ });++ it("opens for a project when the user flag is enabled", () => {+ flagState.enabled = true;+ const { result } = renderHook(() => useV4MigrationPanel(), { wrapper });++ act(() =>+ result.current.openForProject({ id: "project-id", name: "Project" }),+ );++ expect(result.current.open).toBe(true);+ expect(result.current.targetProject).toEqual({+ id: "project-id",+ name: "Project",+ });+ });+});diff --git a/web/src/features/v4-migration/V4MigrationPanelProvider.tsx b/web/src/features/v4-migration/V4MigrationPanelProvider.tsxnew file mode 100644index 0000000000..0b6c8b21a4--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationPanelProvider.tsx@@ -0,0 +1,62 @@+import {+ createContext,+ useContext,+ useState,+ type PropsWithChildren,+} from "react";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";++export type V4MigrationTargetProject = { id: string; name: string };++type V4MigrationPanelContextType = {+ open: boolean;+ setOpen: (v: boolean) => void;+ /** Project the panel content is about; set by whichever surface opened it. */+ targetProject: V4MigrationTargetProject | null;+ openForProject: (project: V4MigrationTargetProject) => void;+};++const V4MigrationPanelContext =+ createContext<V4MigrationPanelContextType | null>(null);++interface V4MigrationPanelProviderProps extends PropsWithChildren {+ defaultOpen?: boolean;+}++// V4MigrationPanelProvider to allow us to open the panel from anywhere in the app+export function V4MigrationPanelProvider({+ children,+ defaultOpen = false,+}: V4MigrationPanelProviderProps) {+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();+ const [requestedOpen, setRequestedOpen] = useState(defaultOpen);+ const [targetProject, setTargetProject] =+ useState<V4MigrationTargetProject | null>(null);++ const open = v4UpgradeUiEnabled && requestedOpen;+ const setOpen = (nextOpen: boolean) => {+ setRequestedOpen(v4UpgradeUiEnabled && nextOpen);+ };+ const openForProject = (project: V4MigrationTargetProject) => {+ if (!v4UpgradeUiEnabled) return;+ setTargetProject(project);+ setRequestedOpen(true);+ };++ return (+ <V4MigrationPanelContext.Provider+ value={{ open, setOpen, targetProject, openForProject }}+ >+ {children}+ </V4MigrationPanelContext.Provider>+ );+}++export function useV4MigrationPanel() {+ const ctx = useContext(V4MigrationPanelContext);+ if (!ctx)+ throw new Error(+ "useV4MigrationPanel must be used within V4MigrationPanelProvider",+ );+ return ctx;+}diff --git a/web/src/features/v4-migration/V4MigrationProjectChip.tsx b/web/src/features/v4-migration/V4MigrationProjectChip.tsxnew file mode 100644index 0000000000..04346ede1c--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationProjectChip.tsx@@ -0,0 +1,51 @@+import { type V4MigrationTargetProject } from "@/src/features/v4-migration/V4MigrationPanelProvider";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import {+ getProjectMigrationReadiness,+ type ProjectMigrationStatus,+} from "@/src/features/v4-migration/migrationData";+import { useOpenV4MigrationPanel } from "@/src/features/v4-migration/hooks/useOpenV4MigrationPanel";++export function V4MigrationProjectChip({+ project,+ status,+}: {+ project: V4MigrationTargetProject;+ status: ProjectMigrationStatus | undefined;+}) {+ const openMigrationPanel = useOpenV4MigrationPanel();+ const capture = usePostHogClientCapture();++ const readiness = status ? getProjectMigrationReadiness(status) : "checking";+ const label =+ readiness === "ready"+ ? "Up to date"+ : readiness === "checking"+ ? "Checking"+ : readiness === "unavailable"+ ? "Check status"+ : "Update";++ const handleClick = () => {+ capture("v4_migration:project_chip_clicked");+ openMigrationPanel(project);+ };++ return (+ <button+ type="button"+ onClick={handleClick}+ className="text-foreground ring-border hover:bg-muted/50 relative inline-flex shrink-0 items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-bold whitespace-nowrap ring"+ >+ <span+ aria-hidden+ className={+ readiness === "ready"+ ? "size-1.75 shrink-0 rounded-full bg-green-500 dark:bg-green-500"+ : "size-1.75 shrink-0 rounded-full bg-orange-400 dark:bg-orange-400"+ }+ ></span>+ {label}+ </button>+ );+}diff --git a/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsx b/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsxnew file mode 100644index 0000000000..6f954cba4b--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsx@@ -0,0 +1,103 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import V4MigrationStatusPage from "./V4MigrationStatusPage";++vi.mock("next-auth/react", () => ({+ useSession: () => ({+ status: "authenticated",+ data: {+ user: {+ admin: false,+ organizations: [+ {+ id: "org-1",+ name: "Test organization",+ role: "MEMBER",+ projects: [+ {+ id: "project-1",+ name: "Test project",+ role: "MEMBER",+ deletedAt: null,+ },+ ],+ },+ ],+ },+ },+ }),+}));++vi.mock("@/src/components/layouts/container-page", () => ({+ default: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++vi.mock("@/src/features/support-chat/SupportDrawerProvider", () => ({+ useSupportDrawer: () => ({ setOpen: vi.fn() }),+}));++vi.mock("@/src/features/v4-migration/V4MigrationPanelProvider", () => ({+ useV4MigrationPanel: () => ({ openForProject: vi.fn() }),+}));++vi.mock(+ "@/src/ee/features/in-app-agent/components/InAppAiAgentProvider",+ () => ({+ useInAppAiAgent: () => ({ setOpen: vi.fn() }),+ }),+);++vi.mock("@/src/features/v4-migration/V4MigrationContent", () => ({+ useCopyMigrationPrompt: () => vi.fn(),+}));++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),+}));++vi.mock("@/src/features/v4-migration/useV4UpgradeUiEnabled", () => ({+ useV4UpgradeUiEnabled: () => true,+}));++vi.mock("@/src/features/v4-migration/hooks/useV4MigrationData", () => ({+ useAccountV4MigrationData: () =>+ new Map([+ [+ "project-1",+ {+ sdk: "latest",+ evals: { status: "loaded", count: 0 },+ apis: { status: "loaded", count: 0 },+ exports: { status: "loaded", count: 0 },+ },+ ],+ ]),+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ organizations: {+ lastTraceByProject: {+ useQuery: () => ({ data: [] }),+ },+ },+ },+}));++describe("V4MigrationStatusPage", () => {+ it("keeps the project table readable through horizontal scrolling", () => {+ render(<V4MigrationStatusPage />);++ const table = screen.getByRole("table");+ expect(table).toHaveClass("min-w-[60rem]", "table-auto");+ expect(table.parentElement).toHaveClass("overflow-x-auto");+ });++ it("shows migration readiness to project members", () => {+ render(<V4MigrationStatusPage />);++ expect(screen.getByText("Ready")).toBeInTheDocument();+ expect(screen.getByText("of 1 projects migrated")).toBeInTheDocument();+ });+});diff --git a/web/src/features/v4-migration/V4MigrationStatusPage.tsx b/web/src/features/v4-migration/V4MigrationStatusPage.tsxnew file mode 100644index 0000000000..b60bd955f6--- /dev/null+++ b/web/src/features/v4-migration/V4MigrationStatusPage.tsx@@ -0,0 +1,555 @@+import { useState, type ReactNode } from "react";+import Link from "next/link";+import { useSession } from "next-auth/react";+import { ArrowRight, Copy } from "lucide-react";+import ContainerPage from "@/src/components/layouts/container-page";+import { RainbowButton } from "@/src/components/magicui/rainbow-button";+import { Card } from "@/src/components/ui/card";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/src/components/ui/table";+import { useCopyMigrationPrompt } from "@/src/features/v4-migration/V4MigrationContent";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { api } from "@/src/utils/api";+import { formatCompactRelativeTime } from "@/src/utils/dates";+import { cn } from "@/src/utils/tailwind";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";+import { useOpenV4MigrationPanel } from "@/src/features/v4-migration/hooks/useOpenV4MigrationPanel";+import {+ useAccountV4MigrationData,+ type V4MigrationOrganization,+} from "@/src/features/v4-migration/hooks/useV4MigrationData";+import {+ getProjectMigrationReadiness,+ type MigrationCountState,+ type ProjectMigrationReadiness,+ type ProjectMigrationStatus,+} from "@/src/features/v4-migration/migrationData";++const V4_DOCS_URL = "https://langfuse.com/docs/v4";+const SDK_UPGRADE_URL =+ "https://langfuse.com/docs/observability/sdk/upgrade-path";+const DATA_MODEL_URL = "https://langfuse.com/docs/observability/data-model";+const OBSERVATIONS_FAQ_URL =+ "https://langfuse.com/faq/all/explore-observations-in-v4";+const API_REFERENCE_URL = "https://api.reference.langfuse.com";++function FaqLink({ href, children }: { href: string; children: ReactNode }) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ className="text-dark-blue hover:underline"+ >+ {children}+ </a>+ );+}++function AffectedCell({ count }: { count: MigrationCountState }) {+ if (count.status === "loading") {+ return <span className="text-foreground-tertiary">Checking…</span>;+ }+ if (count.status === "error") {+ return <span className="text-foreground-tertiary">Unavailable</span>;+ }+ if (count.count === 0) {+ return <span className="text-foreground-tertiary">0</span>;+ }+ return <span>{count.count}</span>;+}++function StatusPill({ readiness }: { readiness: ProjectMigrationReadiness }) {+ const label =+ readiness === "ready"+ ? "Ready"+ : readiness === "checking"+ ? "Checking"+ : readiness === "unavailable"+ ? "Unavailable"+ : "Action needed";++ return (+ <span+ className={cn(+ "inline-flex w-fit shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-bold whitespace-nowrap",+ readiness === "ready"+ ? "bg-light-green text-dark-green"+ : readiness === "checking" || readiness === "unavailable"+ ? "bg-muted text-muted-foreground"+ : "bg-light-yellow text-dark-yellow",+ )}+ >+ {label}+ </span>+ );+}++type SortKey =+ | "name"+ | "status"+ | "sdk"+ | "evals"+ | "apis"+ | "exports"+ | "lastTrace";+type OrderBy = { column: SortKey; order: "ASC" | "DESC" } | null;++// Header styling and none → DESC → ASC → none sort cycle copied from the+// trace table (DataTable); sorting here is client-side over the static rows.+function SortableHead({+ label,+ column,+ orderBy,+ onSort,+}: {+ label: string;+ column: SortKey;+ orderBy: OrderBy;+ onSort: (column: SortKey) => void;+}) {+ return (+ <TableHead+ className="group cursor-pointer px-2"+ onClick={() => onSort(column)}+ >+ <div className="flex items-center select-none">+ <span className="truncate leading-normal" title={label}>+ {label}+ </span>+ {orderBy?.column === column && (+ <span className="ml-1" title="Sort by this column">+ {orderBy.order === "ASC" ? "▲" : "▼"}+ </span>+ )}+ </div>+ </TableHead>+ );+}++function OrgStatusSection({+ org,+ statusByProjectId,+}: {+ org: V4MigrationOrganization;+ statusByProjectId: Map<string, ProjectMigrationStatus>;+}) {+ const capture = usePostHogClientCapture();+ const openMigrationPanel = useOpenV4MigrationPanel();+ const { data: lastTraceTimes } =+ api.organizations.lastTraceByProject.useQuery(+ { orgId: org.id },+ { enabled: org.projects.length > 0 },+ );++ const handleRowClick = (row: { id: string; name: string }) => {+ capture("v4_migration:status_row_clicked");+ openMigrationPanel({ id: row.id, name: row.name });+ };++ const [orderBy, setOrderBy] = useState<OrderBy>(null);++ const handleSort = (column: SortKey) => {+ const next: OrderBy =+ orderBy?.column === column+ ? orderBy.order === "DESC"+ ? { column, order: "ASC" }+ : null+ : { column, order: "DESC" };+ capture("table:column_sorting_header_click", {+ column,+ order: next ? next.order : "Disabled",+ });+ setOrderBy(next);+ };++ const rows = org.projects.map((project) => {+ const lastTraceAt = lastTraceTimes?.find(+ (trace) => trace.projectId === project.id,+ )?.lastTraceAt;+ return {+ id: project.id,+ name: project.name,+ status: statusByProjectId.get(project.id),+ lastTraceLabel: lastTraceAt+ ? formatCompactRelativeTime(new Date(lastTraceAt))+ : "—",+ lastTraceSort: lastTraceAt ? new Date(lastTraceAt).getTime() : -1,+ };+ });++ const sortValue = (+ row: (typeof rows)[number],+ column: SortKey,+ ): string | number => {+ switch (column) {+ case "name":+ return row.name.toLowerCase();+ case "status":+ return row.status+ ? {+ unavailable: 0,+ checking: 1,+ "action-needed": 2,+ ready: 3,+ }[getProjectMigrationReadiness(row.status)]+ : 0;+ case "sdk":+ return row.status?.sdk === "latest"+ ? 4+ : row.status?.sdk === "legacy"+ ? 3+ : row.status?.sdk === "unknown"+ ? 2+ : row.status?.sdk === "checking"+ ? 1+ : 0;+ case "evals":+ return row.status?.evals.count ?? 0;+ case "apis":+ return row.status?.apis.count ?? 0;+ case "exports":+ return row.status?.exports.count ?? 0;+ case "lastTrace":+ return row.lastTraceSort;+ }+ };++ const sortedRows = orderBy+ ? [...rows].sort((a, b) => {+ const va = sortValue(a, orderBy.column);+ const vb = sortValue(b, orderBy.column);+ const cmp =+ typeof va === "string"+ ? va.localeCompare(vb as string)+ : va - (vb as number);+ return orderBy.order === "ASC" ? cmp : -cmp;+ })+ : rows;++ if (rows.length === 0) return null;++ return (+ <div className="flex flex-col gap-2">+ <h3 className="text-muted-foreground truncate text-sm" title={org.name}>+ {org.name}+ </h3>+ <Card className="overflow-hidden">+ <div className="overflow-x-auto">+ <Table className="min-w-[60rem] table-auto">+ <TableHeader>+ <TableRow>+ <SortableHead+ label="Project"+ column="name"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <SortableHead+ label="Status"+ column="status"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <SortableHead+ label="SDK"+ column="sdk"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <SortableHead+ label="Affected Evals"+ column="evals"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <SortableHead+ label="Affected APIs"+ column="apis"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <SortableHead+ label="Affected Exports"+ column="exports"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <SortableHead+ label="Last trace"+ column="lastTrace"+ orderBy={orderBy}+ onSort={handleSort}+ />+ <TableHead className="w-24" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {sortedRows.map((row) => {+ if (!row.status) return null;+ const readiness = getProjectMigrationReadiness(row.status);+ return (+ <TableRow+ key={row.id}+ className="group/row cursor-pointer"+ onClick={() => handleRowClick(row)}+ >+ <TableCell density="comfortable" className="max-w-48">+ <Link+ href={`/project/${row.id}`}+ className="block truncate font-bold hover:underline"+ title={row.name}+ onClick={(event) => event.stopPropagation()}+ >+ {row.name}+ </Link>+ </TableCell>+ <TableCell+ density="comfortable"+ className="overflow-hidden"+ >+ <StatusPill readiness={readiness} />+ </TableCell>+ <TableCell density="comfortable">+ {row.status.sdk === "latest" ? (+ <span className="text-foreground-tertiary">Latest</span>+ ) : row.status.sdk === "checking" ? (+ <span className="text-foreground-tertiary">+ Checking…+ </span>+ ) : row.status.sdk === "unknown" ? (+ <span className="text-foreground-tertiary">+ Unknown+ </span>+ ) : row.status.sdk === "error" ? (+ <span className="text-foreground-tertiary">+ Unavailable+ </span>+ ) : (+ <span>Legacy</span>+ )}+ </TableCell>+ <TableCell density="comfortable">+ <AffectedCell count={row.status.evals} />+ </TableCell>+ <TableCell density="comfortable">+ <AffectedCell count={row.status.apis} />+ </TableCell>+ <TableCell density="comfortable">+ <AffectedCell count={row.status.exports} />+ </TableCell>+ <TableCell+ density="comfortable"+ className="text-muted-foreground truncate"+ title={row.lastTraceLabel}+ >+ {row.lastTraceLabel}+ </TableCell>+ <TableCell density="comfortable">+ <span className="text-dark-blue flex items-center justify-end gap-1 whitespace-nowrap opacity-0 transition-opacity group-hover/row:opacity-100">+ Review <ArrowRight className="h-3 w-3 shrink-0" />+ </span>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ </Card>+ </div>+ );+}++export default function V4MigrationStatusPage() {+ const v4UpgradeUiEnabled = useV4UpgradeUiEnabled();++ if (!v4UpgradeUiEnabled) {+ return null;+ }++ return <V4MigrationStatusPageContent />;+}++function V4MigrationStatusPageContent() {+ const session = useSession();+ const handleCopyPrompt = useCopyMigrationPrompt();++ const orgs: V4MigrationOrganization[] =+ session.data?.user?.organizations?.map((org) => ({+ id: org.id,+ name: org.name,+ projects: org.projects+ .filter((project) => !project.deletedAt)+ .map((project) => ({ id: project.id, name: project.name })),+ })) ?? [];+ const statusByProjectId = useAccountV4MigrationData({+ organizations: orgs,+ enabled: true,+ });++ const faqItems: { q: string; a: ReactNode }[] = [+ {+ q: "Why is this happening?",+ a: (+ <>+ We rebuilt the tracing and evaluation engine around{" "}+ <FaqLink href={DATA_MODEL_URL}>observations</FaqLink>. The new engine+ is real-time and holds up much better at scale.+ </>+ ),+ },+ {+ q: "What's in it for me?",+ a: (+ <>+ Your{" "}+ <FaqLink href={OBSERVATIONS_FAQ_URL}>data shows up instantly</FaqLink>+ , everything loads faster, and you get{" "}+ <FaqLink href={V4_DOCS_URL}>+ features we could not build on the old engine+ </FaqLink>+ , like full-text search, alerting, and observation-level evals.+ </>+ ),+ },+ {+ q: "Do I have to do this?",+ a: (+ <>+ Yes, eventually. The{" "}+ <FaqLink href={SDK_UPGRADE_URL}>old SDKs</FaqLink>, trace-level evals,+ and APIs are frozen and stop working on{" "}+ <span className="underline">Oct 1</span>. They keep running until+ then, but we're no longer fixing bugs in them.+ </>+ ),+ },+ {+ q: "How much work is it?",+ a: (+ <>+ Less than you'd think. For most projects it's{" "}+ <button+ type="button"+ onClick={handleCopyPrompt}+ className="text-dark-blue hover:underline"+ >+ one prompt+ </button>+ : the agent updates your SDK, repoints your evals, and migrates your+ API calls, checking with you before it changes anything.+ </>+ ),+ },+ {+ q: "What if I do nothing?",+ a: (+ <>+ On <span className="underline">Oct 1</span>, old SDKs stop sending+ data, and the{" "}+ <FaqLink href={API_REFERENCE_URL}>+ deprecated evals and endpoints+ </FaqLink>{" "}+ start returning errors.+ </>+ ),+ },+ ];++ const totalProjects = orgs.reduce(+ (total, org) => total + org.projects.length,+ 0,+ );+ const readiness = orgs.flatMap((org) =>+ org.projects.flatMap((project) => {+ const status = statusByProjectId.get(project.id);+ return status ? [getProjectMigrationReadiness(status)] : [];+ }),+ );+ const readyProjects = readiness.filter((state) => state === "ready").length;+ const isChecking =+ session.status === "loading" ||+ readiness.some((state) => state === "checking");+ const projectsNeedingAction = readiness.filter(+ (state) => state === "action-needed",+ ).length;+ const shouldShowUpdateAllButton =+ !isChecking && totalProjects > 0 && projectsNeedingAction > 0;++ return (+ <ContainerPage+ headerProps={{+ title: "Migration status",+ }}+ >+ <div className="flex flex-col gap-6 pt-2 pb-24">+ <Card className="flex flex-wrap items-center justify-between gap-x-6 gap-y-4 p-6">+ <div className="flex min-w-0 flex-col gap-2.5">+ <p className="text-base font-bold">+ Langfuse v4 is here. Real-time and up to 165× faster+ </p>+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ {isChecking ? (+ <span className="text-muted-foreground text-sm">+ Checking project status…+ </span>+ ) : totalProjects === 0 ? (+ <span className="text-muted-foreground text-sm">+ No active projects+ </span>+ ) : (+ <>+ <span className="text-2xl leading-none font-bold tracking-tight">+ {readyProjects}+ </span>+ <span className="text-muted-foreground text-sm">+ of {totalProjects} projects migrated+ </span>+ </>+ )}+ </div>+ </div>+ {shouldShowUpdateAllButton && (+ <RainbowButton onClick={handleCopyPrompt}>+ <Copy className="mr-1.5 h-4 w-4 shrink-0" />+ <span className="min-w-0 truncate" title="Update all with agents">+ Update all with agents+ </span>+ </RainbowButton>+ )}+ </Card>++ {orgs.map((org) => (+ <OrgStatusSection+ key={org.id}+ org={org}+ statusByProjectId={statusByProjectId}+ />+ ))}++ <div className="mt-6">+ <p className="text-base font-bold">What's new in v4</p>+ <div className="flex flex-col gap-6 pt-4">+ <div className="divide-y">+ {faqItems.map(({ q, a }) => (+ <div key={q} className="py-3">+ <p className="text-sm font-bold">{q}</p>+ <p className="text-muted-foreground mt-1 text-sm leading-relaxed">+ {a}+ </p>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ </ContainerPage>+ );+}diff --git a/web/src/features/v4-migration/hooks/useOpenV4MigrationPanel.ts b/web/src/features/v4-migration/hooks/useOpenV4MigrationPanel.tsnew file mode 100644index 0000000000..7c86911ad0--- /dev/null+++ b/web/src/features/v4-migration/hooks/useOpenV4MigrationPanel.ts@@ -0,0 +1,18 @@+import { useInAppAiAgent } from "@/src/ee/features/in-app-agent/components/InAppAiAgentProvider";+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import {+ useV4MigrationPanel,+ type V4MigrationTargetProject,+} from "@/src/features/v4-migration/V4MigrationPanelProvider";++export function useOpenV4MigrationPanel() {+ const { openForProject } = useV4MigrationPanel();+ const { setOpen: setSupportDrawerOpen } = useSupportDrawer();+ const { setOpen: setAiAgentOpen } = useInAppAiAgent();++ return (project: V4MigrationTargetProject) => {+ setAiAgentOpen(false);+ setSupportDrawerOpen(false);+ openForProject(project);+ };+}diff --git a/web/src/features/v4-migration/hooks/useV4MigrationData.clienttest.ts b/web/src/features/v4-migration/hooks/useV4MigrationData.clienttest.tsnew file mode 100644index 0000000000..2a682b4bff--- /dev/null+++ b/web/src/features/v4-migration/hooks/useV4MigrationData.clienttest.ts@@ -0,0 +1,135 @@+import { renderHook } from "@testing-library/react";+import { vi } from "vitest";++import { useAccountV4MigrationData } from "@/src/features/v4-migration/hooks/useV4MigrationData";++const mocks = vi.hoisted(() => ({+ summaryByProject: vi.fn(),+ traceLevelEvalSummaryByProject: vi.fn(),+ legacyApiUsageSummaryByProject: vi.fn(),+ queryResultSets: [] as unknown[][],+ sdkVersions: new Map(),+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ useQueries: (+ buildQueries: (router: {+ v4Transition: {+ summaryByProject: typeof mocks.summaryByProject;+ traceLevelEvalSummaryByProject: typeof mocks.traceLevelEvalSummaryByProject;+ legacyApiUsageSummaryByProject: typeof mocks.legacyApiUsageSummaryByProject;+ };+ }) => unknown,+ ) => {+ buildQueries({+ v4Transition: {+ summaryByProject: mocks.summaryByProject,+ traceLevelEvalSummaryByProject: mocks.traceLevelEvalSummaryByProject,+ legacyApiUsageSummaryByProject: mocks.legacyApiUsageSummaryByProject,+ },+ });+ return mocks.queryResultSets.shift() ?? [];+ },+ },+}));++vi.mock("@/src/features/sdk-version/hooks/useProjectSdkVersionInfo", () => ({+ useProjectsSdkVersionInfo: () => mocks.sdkVersions,+ useProjectSdkVersionInfo: vi.fn(),+}));++const loadedQuery = <T>(data: T) => ({+ data,+ isError: false,+});++describe("account v4 migration data", () => {+ beforeEach(() => {+ mocks.summaryByProject.mockReset();+ mocks.traceLevelEvalSummaryByProject.mockReset();+ mocks.legacyApiUsageSummaryByProject.mockReset();+ mocks.sdkVersions = new Map([+ [+ "project-1",+ {+ sdkVersion: { language: "python", version: "4.7.0" },+ checkedAt: "2026-07-23T10:00:00.000Z",+ isRefreshing: false,+ querySettled: true,+ isError: false,+ },+ ],+ ]);+ mocks.queryResultSets = [+ [+ loadedQuery({+ projects: [+ {+ projectId: "project-1",+ projectName: "Project",+ legacyIntegrationCount: 1,+ legacyIntegrations: {+ posthog: true,+ mixpanel: false,+ blobStorage: false,+ },+ },+ ],+ }),+ ],+ [+ loadedQuery([+ {+ projectId: "project-1",+ traceLevelEvalCount: 2,+ },+ ]),+ ],+ [+ loadedQuery([+ {+ projectId: "project-1",+ entrypoint: "publicapi: GET /api/public/traces",+ count: 4,+ },+ {+ projectId: "project-1",+ entrypoint: "publicapi: GET /api/public/sessions",+ count: 2,+ },+ ]),+ ],+ ];+ });++ it("combines the real organization summaries by project", () => {+ const { result } = renderHook(() =>+ useAccountV4MigrationData({+ organizations: [+ {+ id: "org-1",+ name: "Organization",+ projects: [{ id: "project-1", name: "Project" }],+ },+ ],+ enabled: true,+ }),+ );++ expect(result.current.get("project-1")).toEqual({+ sdk: "latest",+ evals: { status: "loaded", count: 2 },+ apis: { status: "loaded", count: 2 },+ exports: { status: "loaded", count: 1 },+ });+ expect(mocks.summaryByProject).toHaveBeenCalledWith(+ { orgId: "org-1" },+ expect.objectContaining({ enabled: true }),+ );+ expect(mocks.legacyApiUsageSummaryByProject).toHaveBeenCalledWith(+ expect.objectContaining({ orgId: "org-1" }),+ expect.objectContaining({ enabled: true }),+ );+ });+});diff --git a/web/src/features/v4-migration/hooks/useV4MigrationData.ts b/web/src/features/v4-migration/hooks/useV4MigrationData.tsnew file mode 100644index 0000000000..9fcc8c81d5--- /dev/null+++ b/web/src/features/v4-migration/hooks/useV4MigrationData.ts@@ -0,0 +1,175 @@+import { useState } from "react";++import { api } from "@/src/utils/api";+import { countLegacyApiEntrypoints } from "@/src/features/v4/utils";+import {+ useProjectSdkVersionInfo,+ useProjectsSdkVersionInfo,+} from "@/src/features/sdk-version/hooks/useProjectSdkVersionInfo";+import {+ aggregateLegacyApiUsage,+ createV4MigrationDetectionRange,+ getLegacyIntegrationLabels,+ getMigrationCountState,+ type ProjectMigrationStatus,+} from "@/src/features/v4-migration/migrationData";+import { getV4MigrationSdkStatus } from "@/src/features/v4-migration/sdkVersionStatus";++const QUERY_STALE_TIME_MS = 5 * 60 * 1000;++export type V4MigrationOrganization = {+ id: string;+ name: string;+ projects: { id: string; name: string }[];+};++const queryOptions = {+ refetchOnWindowFocus: false,+ staleTime: QUERY_STALE_TIME_MS,+};++export function useAccountV4MigrationData(params: {+ organizations: V4MigrationOrganization[];+ enabled: boolean;+}): Map<string, ProjectMigrationStatus> {+ const { organizations, enabled } = params;+ const [detectionRange] = useState(createV4MigrationDetectionRange);+ const projectIds = organizations.flatMap((organization) =>+ organization.projects.map((project) => project.id),+ );+ const sdkVersionByProjectId = useProjectsSdkVersionInfo({+ projectIds,+ enabled,+ refreshMode: "always",+ });++ const integrationQueries = api.useQueries((t) =>+ organizations.map((organization) =>+ t.v4Transition.summaryByProject(+ { orgId: organization.id },+ {+ ...queryOptions,+ enabled,+ },+ ),+ ),+ );+ const evalQueries = api.useQueries((t) =>+ organizations.map((organization) =>+ t.v4Transition.traceLevelEvalSummaryByProject(+ { orgId: organization.id },+ {+ ...queryOptions,+ enabled,+ trpc: { context: { skipBatch: true } },+ },+ ),+ ),+ );+ const apiQueries = api.useQueries((t) =>+ organizations.map((organization) =>+ t.v4Transition.legacyApiUsageSummaryByProject(+ {+ orgId: organization.id,+ ...detectionRange,+ },+ {+ ...queryOptions,+ enabled,+ trpc: { context: { skipBatch: true } },+ },+ ),+ ),+ );++ const statusByProjectId = new Map<string, ProjectMigrationStatus>();++ organizations.forEach((organization, organizationIndex) => {+ const integrationQuery = integrationQueries[organizationIndex] ?? null;+ const evalQuery = evalQueries[organizationIndex] ?? null;+ const apiQuery = apiQueries[organizationIndex] ?? null;++ organization.projects.forEach((project) => {+ const sdkVersionState = sdkVersionByProjectId.get(project.id);+ statusByProjectId.set(project.id, {+ sdk: sdkVersionState+ ? getV4MigrationSdkStatus(sdkVersionState)+ : "checking",+ evals: getMigrationCountState(evalQuery, (rows) => {+ return (+ rows.find((row) => row.projectId === project.id)+ ?.traceLevelEvalCount ?? 0+ );+ }),+ apis: getMigrationCountState(apiQuery, (rows) => {+ return countLegacyApiEntrypoints(+ rows.filter((row) => row.projectId === project.id),+ );+ }),+ exports: getMigrationCountState(integrationQuery, (data) => {+ return (+ data.projects.find((row) => row.projectId === project.id)+ ?.legacyIntegrationCount ?? 0+ );+ }),+ });+ });+ });++ return statusByProjectId;+}++export function useProjectV4MigrationData(params: {+ projectId: string | undefined;+ enabled: boolean;+}) {+ const { projectId, enabled } = params;+ const queryEnabled = enabled && Boolean(projectId);+ const [detectionRange] = useState(createV4MigrationDetectionRange);+ const sdkVersionState = useProjectSdkVersionInfo({+ projectId: projectId ?? "",+ enabled: queryEnabled,+ refreshMode: "always",+ });+ const evalQuery = api.v4Transition.traceLevelEvalSummary.useQuery(+ { projectId: projectId ?? "" },+ { ...queryOptions, enabled: queryEnabled },+ );+ const apiQuery = api.v4Transition.timeSeriesByEntrypoint.useQuery(+ {+ projectId: projectId ?? "",+ ...detectionRange,+ granularity: "auto",+ },+ {+ ...queryOptions,+ enabled: queryEnabled,+ trpc: { context: { skipBatch: true } },+ },+ );+ const integrationQuery = api.v4Transition.summary.useQuery(+ { projectId: projectId ?? "" },+ { ...queryOptions, enabled: queryEnabled },+ );++ const apiUsage = aggregateLegacyApiUsage(apiQuery.data);+ const legacyIntegrations = getLegacyIntegrationLabels(+ integrationQuery.data?.legacyIntegrations,+ );++ return {+ sdkVersionState,+ sdkStatus: getV4MigrationSdkStatus(sdkVersionState),+ evals: getMigrationCountState(+ evalQuery,+ (data) => data.traceLevelEvalCount,+ ),+ apis: getMigrationCountState(apiQuery, () => apiUsage.length),+ exports: getMigrationCountState(+ integrationQuery,+ (data) => data.legacyIntegrationCount,+ ),+ apiUsage,+ legacyIntegrations,+ };+}diff --git a/web/src/features/v4-migration/migrationData.clienttest.ts b/web/src/features/v4-migration/migrationData.clienttest.tsnew file mode 100644index 0000000000..5abb3082e4--- /dev/null+++ b/web/src/features/v4-migration/migrationData.clienttest.ts@@ -0,0 +1,104 @@+import {+ aggregateLegacyApiUsage,+ createV4MigrationDetectionRange,+ getLegacyIntegrationLabels,+ getMigrationCountState,+ getProjectMigrationReadiness,+} from "@/src/features/v4-migration/migrationData";++const loaded = (count: number) => ({ status: "loaded" as const, count });++describe("v4 migration data", () => {+ it("uses a stable seven-day range aligned to the hour", () => {+ const range = createV4MigrationDetectionRange(+ new Date("2026-07-23T10:42:31.000Z").getTime(),+ );++ expect(range).toEqual({+ fromTimestamp: new Date("2026-07-16T11:00:00.000Z"),+ toTimestamp: new Date("2026-07-23T11:00:00.000Z"),+ });+ });++ it("keeps loading and errors distinct from a real zero", () => {+ expect(getMigrationCountState(null, () => 4)).toEqual({+ status: "loading",+ count: 0,+ });+ expect(+ getMigrationCountState({ data: undefined, isError: true }, () => 4),+ ).toEqual({ status: "error", count: 0 });+ expect(+ getMigrationCountState({ data: { count: 0 }, isError: false }, (data) => {+ return data.count;+ }),+ ).toEqual(loaded(0));+ });++ it("only marks a fully loaded project without affected items as ready", () => {+ expect(+ getProjectMigrationReadiness({+ sdk: "latest",+ evals: loaded(0),+ apis: loaded(0),+ exports: loaded(0),+ }),+ ).toBe("ready");+ expect(+ getProjectMigrationReadiness({+ sdk: "latest",+ evals: loaded(1),+ apis: loaded(0),+ exports: loaded(0),+ }),+ ).toBe("action-needed");+ expect(+ getProjectMigrationReadiness({+ sdk: "latest",+ evals: { status: "loading", count: 0 },+ apis: loaded(0),+ exports: loaded(0),+ }),+ ).toBe("checking");+ expect(+ getProjectMigrationReadiness({+ sdk: "error",+ evals: loaded(0),+ apis: loaded(0),+ exports: loaded(0),+ }),+ ).toBe("unavailable");+ });++ it("aggregates real API usage by normalized endpoint", () => {+ expect(+ aggregateLegacyApiUsage([+ {+ time: "2026-07-23T09:00:00Z",+ entrypoint: "publicapi: GET /api/public/traces",+ count: 2,+ },+ {+ time: "2026-07-23T10:00:00Z",+ entrypoint: "publicapi: GET /api/public/traces",+ count: 3,+ },+ {+ time: "2026-07-23T10:00:00Z",+ entrypoint: "",+ count: 0,+ },+ ]),+ ).toEqual([{ endpoint: "GET /api/public/traces", count: 5 }]);+ });++ it("returns only enabled legacy integration labels", () => {+ expect(+ getLegacyIntegrationLabels({+ posthog: true,+ mixpanel: false,+ blobStorage: true,+ }),+ ).toEqual(["PostHog", "Blob Storage"]);+ });+});diff --git a/web/src/features/v4-migration/migrationData.ts b/web/src/features/v4-migration/migrationData.tsnew file mode 100644index 0000000000..36e789e02d--- /dev/null+++ b/web/src/features/v4-migration/migrationData.ts@@ -0,0 +1,137 @@+import { type RouterOutputs } from "@/src/utils/api";+import { normalizeLegacyApiEntrypoint } from "@/src/features/v4/utils";+import { type V4MigrationSdkStatus } from "@/src/features/v4-migration/sdkVersionStatus";++export const V4_MIGRATION_LOOKBACK_DAYS = 7;++const V4_MIGRATION_LOOKBACK_MS =+ V4_MIGRATION_LOOKBACK_DAYS * 24 * 60 * 60 * 1000;+const RANGE_BUCKET_MS = 60 * 60 * 1000;++export const createV4MigrationDetectionRange = (now = Date.now()) => {+ const toTimestamp = new Date(+ (Math.floor(now / RANGE_BUCKET_MS) + 1) * RANGE_BUCKET_MS,+ );+ return {+ fromTimestamp: new Date(toTimestamp.getTime() - V4_MIGRATION_LOOKBACK_MS),+ toTimestamp,+ };+};++export type MigrationCountState =+ | { status: "loading"; count: 0 }+ | { status: "error"; count: 0 }+ | { status: "loaded"; count: number };++const loadingMigrationCount = {+ status: "loading",+ count: 0,+} as const satisfies MigrationCountState;++const errorMigrationCount = {+ status: "error",+ count: 0,+} as const satisfies MigrationCountState;++const loadedMigrationCount = (count: number): MigrationCountState => ({+ status: "loaded",+ count,+});++export const getMigrationCountState = <T>(+ query: {+ data: T | undefined;+ isError: boolean;+ } | null,+ getCount: (data: T) => number,+): MigrationCountState => {+ if (query?.data !== undefined) {+ return loadedMigrationCount(getCount(query.data));+ }+ return query?.isError ? errorMigrationCount : loadingMigrationCount;+};++export type ProjectMigrationStatus = {+ sdk: V4MigrationSdkStatus;+ evals: MigrationCountState;+ apis: MigrationCountState;+ exports: MigrationCountState;+};++export type ProjectMigrationReadiness =+ | "checking"+ | "unavailable"+ | "ready"+ | "action-needed";++export const getProjectMigrationReadiness = (+ status: ProjectMigrationStatus,+): ProjectMigrationReadiness => {+ const counts = [status.evals, status.apis, status.exports];++ if (+ status.sdk === "error" ||+ counts.some((count) => count.status === "error")+ ) {+ return "unavailable";+ }+ if (+ status.sdk === "checking" ||+ counts.some((count) => count.status === "loading")+ ) {+ return "checking";+ }+ if (status.sdk === "latest" && counts.every((count) => count.count === 0)) {+ return "ready";+ }+ return "action-needed";+};++type LegacyApiUsagePoint =+ RouterOutputs["v4Transition"]["timeSeriesByEntrypoint"][number];++type LegacyApiUsageSummary = {+ endpoint: string;+ count: number;+};++export const aggregateLegacyApiUsage = (+ rows: LegacyApiUsagePoint[] | undefined,+): LegacyApiUsageSummary[] => {+ const countsByEndpoint = new Map<string, number>();++ for (const row of rows ?? []) {+ const endpoint = normalizeLegacyApiEntrypoint(row.entrypoint);+ if (!endpoint || row.count <= 0) continue;+ countsByEndpoint.set(+ endpoint,+ (countsByEndpoint.get(endpoint) ?? 0) + row.count,+ );+ }++ return Array.from(countsByEndpoint, ([endpoint, count]) => ({+ endpoint,+ count,+ })).sort(+ (left, right) =>+ right.count - left.count || left.endpoint.localeCompare(right.endpoint),+ );+};++type LegacyIntegrationSummary =+ RouterOutputs["v4Transition"]["summary"]["legacyIntegrations"];++const LEGACY_INTEGRATION_LABELS: ReadonlyArray<+ readonly [keyof LegacyIntegrationSummary, string]+> = [+ ["posthog", "PostHog"],+ ["mixpanel", "Mixpanel"],+ ["blobStorage", "Blob Storage"],+];++export const getLegacyIntegrationLabels = (+ integrations: LegacyIntegrationSummary | undefined,+): string[] =>+ LEGACY_INTEGRATION_LABELS.filter(([key]) => integrations?.[key]).map(+ ([, label]) => label,+ );diff --git a/web/src/features/v4-migration/sdkVersionStatus.clienttest.ts b/web/src/features/v4-migration/sdkVersionStatus.clienttest.tsnew file mode 100644index 0000000000..10e9d4b618--- /dev/null+++ b/web/src/features/v4-migration/sdkVersionStatus.clienttest.ts@@ -0,0 +1,65 @@+import {+ formatSdkVersion,+ getV4MigrationSdkStatus,+} from "@/src/features/v4-migration/sdkVersionStatus";++const baseState = {+ checkedAt: "2026-07-23T10:00:00.000Z",+ isRefreshing: false,+ querySettled: false,+ isError: false,+};++describe("v4 migration SDK status", () => {+ it.each([+ ["javascript", "5.4.0", "latest"],+ ["javascript", "5.3.9", "legacy"],+ ["python", "4.7.0", "latest"],+ ["python", "4.6.9", "legacy"],+ ] as const)("classifies %s %s as %s", (language, version, expected) => {+ expect(+ getV4MigrationSdkStatus({+ ...baseState,+ sdkVersion: { language, version },+ }),+ ).toBe(expected);+ });++ it("distinguishes an in-flight first check from an unknown result", () => {+ expect(+ getV4MigrationSdkStatus({+ sdkVersion: undefined,+ checkedAt: null,+ isRefreshing: true,+ querySettled: false,+ isError: false,+ }),+ ).toBe("checking");+ expect(+ getV4MigrationSdkStatus({+ ...baseState,+ sdkVersion: { language: null, version: null },+ querySettled: true,+ }),+ ).toBe("unknown");+ });++ it("distinguishes a failed first check from an unknown SDK", () => {+ expect(+ getV4MigrationSdkStatus({+ sdkVersion: undefined,+ checkedAt: null,+ isRefreshing: false,+ querySettled: false,+ isError: true,+ }),+ ).toBe("error");+ });++ it("formats detected SDK versions for migration copy", () => {+ expect(formatSdkVersion({ language: "javascript", version: "5.4.1" })).toBe(+ "JavaScript 5.4.1",+ );+ expect(formatSdkVersion({ language: null, version: null })).toBeNull();+ });+});diff --git a/web/src/features/v4-migration/sdkVersionStatus.ts b/web/src/features/v4-migration/sdkVersionStatus.tsnew file mode 100644index 0000000000..0127306386--- /dev/null+++ b/web/src/features/v4-migration/sdkVersionStatus.ts@@ -0,0 +1,46 @@+import {+ getSdkVersionCapability,+ type SdkVersionInfo,+} from "@/src/features/sdk-version/lib/sdkVersionCapabilities";++export type V4MigrationSdkStatus =+ | "checking"+ | "error"+ | "unknown"+ | "legacy"+ | "latest";++export const getV4MigrationSdkStatus = (params: {+ sdkVersion: SdkVersionInfo | undefined;+ checkedAt: string | null;+ isRefreshing: boolean;+ querySettled: boolean;+ isError: boolean;+}): V4MigrationSdkStatus => {+ const { sdkVersion } = params;+ if (sdkVersion?.language && sdkVersion.version) {+ // The migration UX and automatic app-root filter share the same boundary:+ // SDKs new enough to emit the current root-observation metadata.+ return getSdkVersionCapability(sdkVersion, "appRootObservations")+ ? "latest"+ : "legacy";+ }++ if (params.isError) return "error";++ return params.isRefreshing && !params.checkedAt && !params.querySettled+ ? "checking"+ : "unknown";+};++export const formatSdkVersion = (sdkVersion: SdkVersionInfo | undefined) => {+ if (!sdkVersion?.language || !sdkVersion.version) return null;++ const language =+ sdkVersion.language === "javascript"+ ? "JavaScript"+ : sdkVersion.language === "python"+ ? "Python"+ : sdkVersion.language;+ return `${language} ${sdkVersion.version}`;+};diff --git a/web/src/features/v4-migration/useV4UpgradeUiEnabled.clienttest.ts b/web/src/features/v4-migration/useV4UpgradeUiEnabled.clienttest.tsnew file mode 100644index 0000000000..699e88c07b--- /dev/null+++ b/web/src/features/v4-migration/useV4UpgradeUiEnabled.clienttest.ts@@ -0,0 +1,51 @@+import { renderHook } from "@testing-library/react";+import { useSession } from "next-auth/react";+import { vi } from "vitest";++import { useV4UpgradeUiEnabled } from "./useV4UpgradeUiEnabled";+import { parseFlags } from "@/src/features/feature-flags/utils";++vi.mock("next-auth/react", () => ({+ useSession: vi.fn(),+}));++const mockUseSession = vi.mocked(useSession);++describe("useV4UpgradeUiEnabled", () => {+ it("maps the database flag into the session flag shape", () => {+ expect(parseFlags(["v4UpgradeUi"]).v4UpgradeUi).toBe(true);+ expect(parseFlags([]).v4UpgradeUi).toBe(false);+ });++ it("does not enable the UI for admins or experimental deployments", () => {+ mockUseSession.mockReturnValue({+ data: {+ user: {+ admin: true,+ featureFlags: { v4UpgradeUi: false },+ },+ environment: { enableExperimentalFeatures: true },+ },+ } as never);++ const { result } = renderHook(() => useV4UpgradeUiEnabled());++ expect(result.current).toBe(false);+ });++ it("enables the UI only when the user flag is set", () => {+ mockUseSession.mockReturnValue({+ data: {+ user: {+ admin: false,+ featureFlags: { v4UpgradeUi: true },+ },+ environment: { enableExperimentalFeatures: false },+ },+ } as never);++ const { result } = renderHook(() => useV4UpgradeUiEnabled());++ expect(result.current).toBe(true);+ });+});diff --git a/web/src/features/v4-migration/useV4UpgradeUiEnabled.ts b/web/src/features/v4-migration/useV4UpgradeUiEnabled.tsnew file mode 100644index 0000000000..5235e7260e--- /dev/null+++ b/web/src/features/v4-migration/useV4UpgradeUiEnabled.ts@@ -0,0 +1,7 @@+import { useSession } from "next-auth/react";++export function useV4UpgradeUiEnabled(): boolean {+ const { data: session } = useSession();++ return session?.user?.featureFlags.v4UpgradeUi === true;+}diff --git a/web/src/features/v4/server/v4TransitionRouter.ts b/web/src/features/v4/server/v4TransitionRouter.tsindex c7449ab102..921814107b 100644--- a/web/src/features/v4/server/v4TransitionRouter.ts+++ b/web/src/features/v4/server/v4TransitionRouter.ts@@ -4,14 +4,11 @@ import {protectedOrganizationProcedure,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { v4MigrationOrgScope } from "@/src/features/rbac/constants/organizationAccessRights";-import { v4MigrationProjectScope } from "@/src/features/rbac/constants/projectAccessRights";-import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";-import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {AnalyticsIntegrationExportSource,Prisma,} from "@langfuse/shared/src/db";+import type { Session } from "next-auth";import {classifyIngestionSdkVersion,convertDateToClickhouseDateTime,@@ -321,26 +318,23 @@ const fillTraceLevelEvalExecutionBuckets = ({return filledRows;};-const protectedV4MigrationOrgProcedure = protectedOrganizationProcedure.use(- ({ ctx, next }) => {- throwIfNoOrganizationAccess({- role: ctx.session.orgRole,- scope: v4MigrationOrgScope,- });- return next();- },-);--const protectedV4MigrationProjectProcedure = protectedProjectProcedure.use(- ({ ctx, next }) => {- throwIfNoProjectAccess({- role: ctx.session.projectRole,- admin: ctx.session.user.admin,- scope: v4MigrationProjectScope,- });- return next();- },-);+const getAccessibleOrganizationProjectWhere = ({+ orgId,+ session,+}: {+ orgId: string;+ session: Session;+}): Prisma.ProjectWhereInput => {+ const projectIds = session.user?.organizations+ .find((organization) => organization.id === orgId)+ ?.projects.map((project) => project.id);++ return {+ orgId,+ deletedAt: null,+ ...(session.user?.admin ? {} : { id: { in: projectIds ?? [] } }),+ };+};const getLegacyIntegrations = ({posthogIntegration,@@ -366,7 +360,7 @@ const getLegacyIntegrations = ({});export const v4TransitionRouter = createTRPCRouter({- summary: protectedV4MigrationProjectProcedure+ summary: protectedProjectProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {const [posthogIntegration, mixpanelIntegration, blobStorageIntegration] =@@ -398,7 +392,7 @@ export const v4TransitionRouter = createTRPCRouter({};}),- traceLevelEvalSummary: protectedV4MigrationProjectProcedure+ traceLevelEvalSummary: protectedProjectProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {const traceLevelEvalCount = await ctx.prisma.jobConfiguration.count({@@ -412,14 +406,14 @@ export const v4TransitionRouter = createTRPCRouter({return { traceLevelEvalCount };}),- summaryByProject: protectedV4MigrationOrgProcedure+ summaryByProject: protectedOrganizationProcedure.input(z.object({ orgId: z.string() })).query(async ({ input, ctx }) => {const projects = await ctx.prisma.project.findMany({- where: {+ where: getAccessibleOrganizationProjectWhere({orgId: input.orgId,- deletedAt: null,- },+ session: ctx.session,+ }),select: {id: true,name: true,@@ -495,14 +489,14 @@ export const v4TransitionRouter = createTRPCRouter({};}),- traceLevelEvalSummaryByProject: protectedV4MigrationOrgProcedure+ traceLevelEvalSummaryByProject: protectedOrganizationProcedure.input(z.object({ orgId: z.string() })).query(async ({ input, ctx }) => {const projects = await ctx.prisma.project.findMany({- where: {+ where: getAccessibleOrganizationProjectWhere({orgId: input.orgId,- deletedAt: null,- },+ session: ctx.session,+ }),select: {id: true,},@@ -533,7 +527,7 @@ export const v4TransitionRouter = createTRPCRouter({);}),- traceLevelEvalExecutionsTimeSeries: protectedV4MigrationProjectProcedure+ traceLevelEvalExecutionsTimeSeries: protectedProjectProcedure.input(timelineInputSchema).query(async ({ input, ctx }) => {const granularity = resolveTimelineGranularity(@@ -585,7 +579,7 @@ ORDER BY bucket_time ASC, score_name ASC});}),- sdkUsageTimeSeries: protectedV4MigrationProjectProcedure+ sdkUsageTimeSeries: protectedProjectProcedure.input(timelineInputSchema).query(async ({ input }) => {const granularity = resolveTimelineGranularity(@@ -666,14 +660,14 @@ ORDER BY ${bucketTimeSql} ASC, sdk_name ASC, sdk_version ASC, public_key ASC} satisfies SdkUsageTimeSeriesResult;}),- sdkUsageSummaryByProject: protectedV4MigrationOrgProcedure+ sdkUsageSummaryByProject: protectedOrganizationProcedure.input(organizationTimeRangeInputSchema).query(async ({ input, ctx }) => {const projects = await ctx.prisma.project.findMany({- where: {+ where: getAccessibleOrganizationProjectWhere({orgId: input.orgId,- deletedAt: null,- },+ session: ctx.session,+ }),select: {id: true,},@@ -767,14 +761,14 @@ ORDER BY project_id ASC, sdk_name ASC, sdk_version ASC, public_key ASC);}),- legacyApiUsageSummaryByProject: protectedV4MigrationOrgProcedure+ legacyApiUsageSummaryByProject: protectedOrganizationProcedure.input(organizationTimeRangeInputSchema).query(async ({ input, ctx }) => {const projects = await ctx.prisma.project.findMany({- where: {+ where: getAccessibleOrganizationProjectWhere({orgId: input.orgId,- deletedAt: null,- },+ session: ctx.session,+ }),select: {id: true,},@@ -880,7 +874,7 @@ SETTINGS skip_unavailable_shards = 1);}),- timeSeriesByEntrypoint: protectedV4MigrationProjectProcedure+ timeSeriesByEntrypoint: protectedProjectProcedure.input(timelineInputSchema).query(async ({ input }) => {const granularity = resolveTimelineGranularity(diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex 390d587faa..8e5f7aadf8 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -80,6 +80,7 @@ import { env } from "@/src/env.mjs";import { ThemeProvider } from "@/src/features/theming/ThemeProvider";import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";import { SupportDrawerProvider } from "@/src/features/support-chat/SupportDrawerProvider";+import { V4MigrationPanelProvider } from "@/src/features/v4-migration/V4MigrationPanelProvider";import { InAppAiAgentProvider } from "@/src/ee/features/in-app-agent/components/InAppAiAgentProvider";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";import { ScoreCacheProvider } from "@/src/features/scores/contexts/ScoreCacheContext";@@ -166,13 +167,15 @@ const MyApp: AppType<{ session: Session | null }> = ({<ScoreCacheProvider><CorrectionCacheProvider><SupportDrawerProvider defaultOpen={false}>- <InAppAiAgentProvider defaultOpen={false}>- {skipAppLayout ? (- page- ) : (- <AppLayout>{page}</AppLayout>- )}- </InAppAiAgentProvider>+ <V4MigrationPanelProvider defaultOpen={false}>+ <InAppAiAgentProvider defaultOpen={false}>+ {skipAppLayout ? (+ page+ ) : (+ <AppLayout>{page}</AppLayout>+ )}+ </InAppAiAgentProvider>+ </V4MigrationPanelProvider></SupportDrawerProvider></CorrectionCacheProvider></ScoreCacheProvider>diff --git a/web/src/pages/organization/[organizationId]/v4/index.tsx b/web/src/pages/organization/[organizationId]/v4/index.tsxindex e0421b89e2..bad7889926 100644--- a/web/src/pages/organization/[organizationId]/v4/index.tsx+++ b/web/src/pages/organization/[organizationId]/v4/index.tsx@@ -2,8 +2,6 @@ import { useEffect, useMemo, useState } 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";@@ -226,10 +224,11 @@ export default function OrganizationV4Page() {allowedRanges: V4_TIME_RANGE_PRESETS,fallback: DEFAULT_DASHBOARD_AGGREGATION_SELECTION,});- const canViewOrgV4Page = useHasOrganizationAccess({- organizationId,- scope: v4MigrationOrgScope,- });+ const canViewOrgV4Page =+ session.data?.user?.admin === true ||+ session.data?.user?.organizations.some(+ (organization) => organization.id === organizationId,+ ) === true;const absoluteTimeRange = useMemo(() => {return getCappedAbsoluteTimeRange(timeRange);diff --git a/web/src/pages/project/[projectId]/experiments/index.tsx b/web/src/pages/project/[projectId]/experiments/index.tsxindex a2b3989e21..42fff771ba 100644--- a/web/src/pages/project/[projectId]/experiments/index.tsx+++ b/web/src/pages/project/[projectId]/experiments/index.tsx@@ -10,6 +10,7 @@ import { ExperimentsTable } from "@/src/features/experiments/components/table";import { useExperimentAccess } from "@/src/features/experiments/hooks/useExperimentAccess";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDelayBadge";import { api } from "@/src/utils/api";import { FlaskConical } from "lucide-react";import { useEffect, useState } from "react";@@ -59,6 +60,7 @@ export default function Experiments() {<PageheaderProps={{title: "Experiments",+ titleBadges: <V4MigrationDelayBadge />,actionButtonsRight: (<div className="flex items-center gap-2"><Dialogdiff --git a/web/src/pages/project/[projectId]/observations/index.tsx b/web/src/pages/project/[projectId]/observations/index.tsxindex 7849c01d0e..672548f4a6 100644--- a/web/src/pages/project/[projectId]/observations/index.tsx+++ b/web/src/pages/project/[projectId]/observations/index.tsx@@ -10,6 +10,7 @@ import {import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import ObservationsEventsTable from "@/src/features/events/components/EventsTable";import { useQueryProject } from "@/src/features/projects/hooks";+import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDelayBadge";export default function Generations() {const router = useRouter();@@ -41,6 +42,9 @@ export default function Generations() {<PageheaderProps={{title: "Tracing",+ // Match traces/index.tsx: no delay badge while onboarding tells the+ // user to set up tracing for the first time.+ titleBadges: showOnboarding ? undefined : <V4MigrationDelayBadge />,help: {description:"An observation captures a single function call in an application. See docs to learn more.",diff --git a/web/src/pages/project/[projectId]/traces/index.tsx b/web/src/pages/project/[projectId]/traces/index.tsxindex e0480da1e7..deddec8f00 100644--- a/web/src/pages/project/[projectId]/traces/index.tsx+++ b/web/src/pages/project/[projectId]/traces/index.tsx@@ -10,6 +10,7 @@ import {import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import ObservationsEventsTable from "@/src/features/events/components/EventsTable";import { useQueryProject } from "@/src/features/projects/hooks";+import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDelayBadge";export default function Traces() {const router = useRouter();@@ -59,6 +60,7 @@ export default function Traces() {<PageheaderProps={{title: "Tracing",+ titleBadges: <V4MigrationDelayBadge />,help: {description: (<>diff --git a/web/src/pages/v4-migration.tsx b/web/src/pages/v4-migration.tsxnew file mode 100644index 0000000000..ee2462a007--- /dev/null+++ b/web/src/pages/v4-migration.tsx@@ -0,0 +1 @@+export { default } from "@/src/features/v4-migration/V4MigrationStatusPage";diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex f57b7af3ea..a427a429b7 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -71,12 +71,14 @@--color-muted-gray: hsl(var(--muted-gray));--color-accent-light-green: hsl(var(--accent-light-green));--color-accent-dark-green: hsl(var(--accent-dark-green));- --color-light-red: hsl(var(--light-red));- --color-dark-red: hsl(var(--dark-red));- --color-light-yellow: hsl(var(--light-yellow));- --color-dark-yellow: hsl(var(--dark-yellow));- --color-light-green: hsl(var(--light-green));- --color-dark-green: hsl(var(--dark-green));+ /* These six status tokens hold complete oklch colors (tints carry baked+ alpha), unlike the hsl-triplet tokens around them — do not wrap in hsl(). */+ --color-light-red: var(--light-red);+ --color-dark-red: var(--dark-red);+ --color-light-yellow: var(--light-yellow);+ --color-dark-yellow: var(--dark-yellow);+ --color-light-green: var(--light-green);+ --color-dark-green: var(--dark-green);--color-light-blue: hsl(var(--light-blue));--color-dark-blue: hsl(var(--dark-blue));--color-accent-light-blue: hsl(var(--accent-light-blue));@@ -307,17 +309,19 @@--accent-light-green: 138 76.5% 96.7%;--accent-dark-green: 112 100% 32%;- --light-red: 329 77.8% 94.7%;- --dark-red: 0 72.2% 50.6%;+ /* Status pairs: light-* tinted fills (alpha baked in), dark-* the+ readable text/icon color on them. */+ --light-red: oklch(93.6% 0.032 17.717 / 0.7);+ --dark-red: oklch(63.7% 0.237 25.331);- --light-yellow: 55 91.7% 95.3%;- --dark-yellow: 43 96% 40%;+ --light-yellow: oklch(97.3% 0.071 103.193 / 0.7);+ --dark-yellow: oklch(47.6% 0.114 61.907);- --light-green: 141 84.2% 92.5%;- --dark-green: 176 60.8% 19%;+ --light-green: oklch(95% 0.052 163.051 / 0.7);+ --dark-green: oklch(59.6% 0.145 163.225);--light-blue: 214 94.6% 92.7%;- --dark-blue: 217 91.2% 59.8%;+ --dark-blue: 219 85% 52%;--accent-light-blue: 251 95.2% 91.8%;--accent-dark-blue: 224 76.3% 38%;@@ -461,19 +465,19 @@of --border-contrast (26%). */--muted-gray: 0 0% 16%;- /* Status pairs on Linear's hues: light-* are dark tinted backgrounds,+ /* Status pairs: light-* are dark tinted backgrounds (alpha baked in),dark-* the readable text/icon color on them. */- --light-red: 0 35% 14%;- --dark-red: 0 78.7% 63.1%;+ --light-red: oklch(39.6% 0.141 25.723 / 0.7);+ --dark-red: oklch(57.7% 0.245 27.325);- --light-yellow: 48 45% 13%;- --dark-yellow: 48 100% 47.1%;+ --light-yellow: oklch(55.4% 0.135 66.442 / 0.4);+ --dark-yellow: oklch(79.5% 0.184 86.047);- --light-green: 134 35% 13%;- --dark-green: 134 62% 40.2%;+ --light-green: oklch(37.8% 0.077 168.94 / 0.7);+ --dark-green: oklch(76.5% 0.177 163.223);--light-blue: 209 45% 15%;- --dark-blue: 209 96.7% 64.7%;+ --dark-blue: 209 88% 60%;/* accent-light-green doubles as a full-height output/diff surface(PrettyJsonView), so it stays a whisper above --card, not chip-strength. */diff --git a/web/src/utils/dates.clienttest.ts b/web/src/utils/dates.clienttest.tsindex 951df1eeb6..e3cccf2cbc 100644--- a/web/src/utils/dates.clienttest.ts+++ b/web/src/utils/dates.clienttest.ts@@ -1,6 +1,33 @@// @vitest-environment jsdom-import { formatIntervalSeconds } from "./dates";+import { describe, it, expect } from "vitest";+import {+ formatCompactRelativeTime,+ formatIntervalSeconds,+} from "@/src/utils/dates";++describe("formatCompactRelativeTime", () => {+ const ago = (seconds: number) => new Date(Date.now() - seconds * 1000);+ const DAY = 24 * 60 * 60;++ it.each([+ [30, "just now"],+ [5 * 60, "5m ago"],+ [3 * 60 * 60, "3h ago"],+ [15 * DAY, "15d ago"],+ [45 * DAY, "1mo ago"],+ // days 360-364 must stay in months, not round down to "0y ago"+ [362 * DAY, "12mo ago"],+ [400 * DAY, "1y ago"],+ [800 * DAY, "2y ago"],+ ])("formats %ds ago as %s", (seconds, expected) => {+ expect(formatCompactRelativeTime(ago(seconds))).toBe(expected);+ });++ it("clamps future timestamps to just now", () => {+ expect(formatCompactRelativeTime(ago(-120))).toBe("just now");+ });+});describe("formatIntervalSeconds", () => {it("keeps sub-minute durations in decimal-seconds form", () => {diff --git a/web/src/utils/dates.ts b/web/src/utils/dates.tsindex 69bb34b941..337982798b 100644--- a/web/src/utils/dates.ts+++ b/web/src/utils/dates.ts@@ -75,6 +75,21 @@ export const getTimezoneDetails = () => {return `${location} (UTC${utcDifference >= 0 ? "+" : ""}${utcDifference})`;};+// Compact relative time: "just now", "3m ago", "5h ago", "15d ago",+// "2mo ago", "1y ago" — largest sensible unit, no live refresh implied.+export const formatCompactRelativeTime = (timestamp: Date): string => {+ const diffInSeconds = Math.max(0, (Date.now() - timestamp.getTime()) / 1000);+ if (diffInSeconds < 60) return "just now";+ const minutes = diffInSeconds / 60;+ if (minutes < 60) return `${Math.floor(minutes)}m ago`;+ const hours = minutes / 60;+ if (hours < 24) return `${Math.floor(hours)}h ago`;+ const days = hours / 24;+ if (days < 30) return `${Math.floor(days)}d ago`;+ if (days < 365) return `${Math.floor(days / 30)}mo ago`;+ return `${Math.floor(days / 365)}y ago`;+};+export const getRelativeTimestampFromNow = (timestamp: Date): string => {const diffInMs = Math.max(0, new Date().getTime() - timestamp.getTime());const diffInMinutes = diffInMs / (1000 * 60);