Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(v4): default new orgs to v4 (#13105)

Nimar5d99c5a4a9cf
diff --git a/web/src/__tests__/widget-default-view.clienttest.ts b/web/src/__tests__/widget-default-view.clienttest.ts
index ceac9b8420..c84b48189b 100644
--- a/web/src/__tests__/widget-default-view.clienttest.ts
+++ b/web/src/__tests__/widget-default-view.clienttest.ts
@@ -17,7 +17,7 @@ describe("shouldUseWidgetSSE", () => {
it("should enable SSE on the v4 beta v2 path", () => {
expect(
shouldUseWidgetSSE({
- isV4BetaEnabled: true,
+ isV4Enabled: true,
version: "v2",
}),
).toBe(true);
@@ -26,7 +26,7 @@ describe("shouldUseWidgetSSE", () => {
it("should disable SSE when v4 beta is off", () => {
expect(
shouldUseWidgetSSE({
- isV4BetaEnabled: false,
+ isV4Enabled: false,
version: "v2",
}),
).toBe(false);
@@ -35,7 +35,7 @@ describe("shouldUseWidgetSSE", () => {
it("should disable SSE for non-v4 query versions", () => {
expect(
shouldUseWidgetSSE({
- isV4BetaEnabled: true,
+ isV4Enabled: true,
version: "v1",
}),
).toBe(false);
diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.ts
index ae4588b6e8..1ffccaa8e5 100644
--- a/web/src/components/layouts/app-layout/utils/navigationFilters.ts
+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts
@@ -68,7 +68,6 @@ export const filters = {
* - Experimental features enabled
* - User is cloud admin
* - User has specific feature flag
- * - For v4Beta: show to all cloud users and keep it visible for opted-in users outside cloud
*/
featureFlags: (route: Route, ctx: NavigationFilterContext): Route | null => {
if (route.featureFlag === undefined) return route;
@@ -80,14 +79,9 @@ export const filters = {
}
if (route.featureFlag === "v4BetaToggleVisible") {
- const hasOptedIn = ctx.session?.user?.v4BetaEnabled === true;
+ const canToggleV4 = ctx.session?.user?.canToggleV4 === true;
- return ctx.isLangfuseCloud ||
- ctx.enableExperimentalFeatures ||
- ctx.cloudAdmin ||
- hasOptedIn
- ? route
- : null;
+ return canToggleV4 && ctx.isLangfuseCloud ? route : null;
}
const hasFlag =
diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
index a526ae0525..844328c4bc 100644
--- a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
@@ -37,25 +37,21 @@ const PaymentBanner = dynamic(
},
);
-const V4BetaEnabledBanner = dynamic(
+const V4EnabledBanner = dynamic(
() =>
- import("@/src/features/events/components/V4BetaEnabledBanner").then(
- (mod) => ({
- default: mod.V4BetaEnabledBanner,
- }),
- ),
+ import("@/src/features/events/components/V4EnabledBanner").then((mod) => ({
+ default: mod.V4EnabledBanner,
+ })),
{
ssr: false,
},
);
-const V4BetaPromoBanner = dynamic(
+const V4PromoBanner = dynamic(
() =>
- import("@/src/features/events/components/V4BetaPromoBanner").then(
- (mod) => ({
- default: mod.V4BetaPromoBanner,
- }),
- ),
+ import("@/src/features/events/components/V4PromoBanner").then((mod) => ({
+ default: mod.V4PromoBanner,
+ })),
{
ssr: false,
},
@@ -140,8 +136,8 @@ export function AuthenticatedLayout({
<SidebarProvider>
<div className="flex h-dvh w-full flex-col">
<PaymentBanner />
- <V4BetaEnabledBanner />
- <V4BetaPromoBanner />
+ <V4EnabledBanner />
+ <V4PromoBanner />
<div className="pt-banner-offset flex min-h-0 flex-1">
<AppSidebar
navItems={navigation.mainNavigation}
diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsx
index c9c07810d2..b755952ffb 100644
--- a/web/src/components/layouts/routes.tsx
+++ b/web/src/components/layouts/routes.tsx
@@ -26,7 +26,7 @@ import { type User } from "next-auth";
import { type OrganizationScope } from "@/src/features/rbac/constants/organizationAccessRights";
import { SupportButton } from "@/src/components/nav/support-button";
import { BookACallButton } from "@/src/components/nav/book-a-call-button";
-import { V4BetaSidebarToggle } from "@/src/features/events/components/V4BetaSidebarToggle";
+import { V4SidebarToggle } from "@/src/features/events/components/V4SidebarToggle";
import { SidebarMenuButton } from "@/src/components/ui/sidebar";
import { useCommandMenu } from "@/src/features/command-k-menu/CommandMenuProvider";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
@@ -209,7 +209,7 @@ export const ROUTES: Route[] = [
pathname: "",
section: RouteSection.Secondary,
featureFlag: "v4BetaToggleVisible",
- menuNode: <V4BetaSidebarToggle />,
+ menuNode: <V4SidebarToggle />,
},
{
title: "Settings",
diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
index c788164c2b..a4b40565c1 100644
--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
@@ -82,9 +82,9 @@ export function ObservationDetailView({
} = useSelection();
// V4 beta mode and observations for log tab
- const { isBetaEnabled: isV4BetaEnabled } = useV4Beta();
+ const { isBetaEnabled: isV4Enabled } = useV4Beta();
const { observations, roots, nodeMap } = useTraceData();
- const showLogViewTab = isV4BetaEnabled && observations.length > 0;
+ const showLogViewTab = isV4Enabled && observations.length > 0;
const isLogViewVirtualized =
observations.length >= TRACE_VIEW_CONFIG.logView.virtualizationThreshold;
diff --git a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
index 0ebdffa1cc..f6355dd11c 100644
--- a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
+++ b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
@@ -42,7 +42,7 @@ export async function createUserEmailPassword(
},
});
- await createProjectMembershipsOnSignup(newUser);
+ await createProjectMembershipsOnSignup(newUser, { userWasJustCreated: true });
return newUser.id;
}
diff --git a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts
index 23fb235099..22b321d98f 100644
--- a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts
+++ b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts
@@ -4,12 +4,18 @@ import { logger } from "@langfuse/shared/src/server";
import { ServerPosthog } from "@/src/features/posthog-analytics/ServerPosthog";
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
+import { shouldAutoEnableV4 } from "@/src/features/events/lib/v4Rollout";
-export async function createProjectMembershipsOnSignup(user: {
- id: string;
- email: string | null;
-}) {
+export async function createProjectMembershipsOnSignup(
+ user: {
+ id: string;
+ email: string | null;
+ },
+ options?: { userWasJustCreated?: boolean },
+) {
try {
+ const isCloudDeployment = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+
// in no case do we want to send duplicate sign up events to posthog
const isNewUser = !(await prisma.organizationMembership.findFirst({
where: { userId: user.id },
@@ -150,6 +156,60 @@ export async function createProjectMembershipsOnSignup(user: {
// Invites do not work for users without emails (some future SSO users)
if (user.email) await processMembershipInvitations(user.email, user.id);
+ if (isCloudDeployment && (options?.userWasJustCreated || isNewUser)) {
+ const userRolloutState = await prisma.user.findUnique({
+ where: { id: user.id },
+ select: {
+ createdAt: true,
+ v4BetaEnabled: true,
+ organizationMemberships: {
+ select: {
+ organization: {
+ select: {
+ id: true,
+ createdAt: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (userRolloutState) {
+ const shouldAutoEnableV4ForUser = shouldAutoEnableV4({
+ userCreatedAt: userRolloutState.createdAt,
+ organizations: userRolloutState.organizationMemberships.map(
+ (membership) => ({
+ id: membership.organization.id,
+ createdAt: membership.organization.createdAt,
+ }),
+ ),
+ excludedOrganizationIds: env.NEXT_PUBLIC_DEMO_ORG_ID
+ ? [env.NEXT_PUBLIC_DEMO_ORG_ID]
+ : [],
+ });
+ const shouldInitializeForNewUser =
+ options?.userWasJustCreated &&
+ !userRolloutState.v4BetaEnabled &&
+ shouldAutoEnableV4ForUser;
+ const shouldInitializeForFirstOrganization =
+ !options?.userWasJustCreated &&
+ isNewUser &&
+ !userRolloutState.v4BetaEnabled &&
+ shouldAutoEnableV4ForUser;
+
+ if (
+ shouldInitializeForNewUser ||
+ shouldInitializeForFirstOrganization
+ ) {
+ await prisma.user.update({
+ where: { id: user.id },
+ data: { v4BetaEnabled: true },
+ });
+ }
+ }
+ }
+
// for conversion metric tracking in posthog: did a new user sign up?
if (
isNewUser &&
diff --git a/web/src/features/evals/hooks/useEvalCapabilities.ts b/web/src/features/evals/hooks/useEvalCapabilities.ts
index 11d48d475c..384da26333 100644
--- a/web/src/features/evals/hooks/useEvalCapabilities.ts
+++ b/web/src/features/evals/hooks/useEvalCapabilities.ts
@@ -1,4 +1,6 @@
+import { useSession } from "next-auth/react";
import { api } from "@/src/utils/api";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
export interface EvalCapabilities {
isNewCompatible: boolean;
allowLegacy: boolean;
@@ -18,6 +20,9 @@ const mockOtelStatus = {
* @returns Capabilities object indicating which eval features are allowed
*/
export function useEvalCapabilities(projectId: string): EvalCapabilities {
+ const { data: session, status: sessionStatus } = useSession();
+ const isSessionLoading = sessionStatus === "loading";
+
// Query OTEL SDK status
const { isOtel, isPropagating } = mockOtelStatus;
@@ -25,13 +30,20 @@ export function useEvalCapabilities(projectId: string): EvalCapabilities {
const evalCounts = api.evals.counts.useQuery({ projectId });
const hasLegacyEvals = (evalCounts.data?.legacyConfigCount ?? 0) > 0;
+ // Only hide legacy options for new cloud users (canToggleV4 = false)
+ // Non-cloud deployments always see legacy options
+ // Use === true to default to false while session is loading, preventing flash of legacy options
+ // New users (canToggleV4 = false) default to observation-level evals regardless of v3/v4
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const canToggleV4 = session?.user?.canToggleV4 === true;
+
return {
isNewCompatible: isOtel,
- // Allow legacy evals if user already has them OR if not using OTEL
- allowLegacy: hasLegacyEvals || !isOtel,
+ // Allow legacy if: not cloud OR user has legacy evals OR user can toggle v4 (existing user)
+ allowLegacy: !isLangfuseCloud || hasLegacyEvals || canToggleV4,
// Allow propagation filters only when using OTEL and spans are propagating
allowPropagationFilters: isOtel && isPropagating,
- isLoading: evalCounts.isLoading,
+ isLoading: evalCounts.isLoading || isSessionLoading,
hasLegacyEvals,
};
}
diff --git a/web/src/features/events/components/V4BetaEnabledBanner.tsx b/web/src/features/events/components/V4EnabledBanner.tsx
similarity index 98%
rename from web/src/features/events/components/V4BetaEnabledBanner.tsx
rename to web/src/features/events/components/V4EnabledBanner.tsx
index 26b09ef953..5d63d3a44c 100644
--- a/web/src/features/events/components/V4BetaEnabledBanner.tsx
+++ b/web/src/features/events/components/V4EnabledBanner.tsx
@@ -16,7 +16,7 @@ const DISMISSED_STORAGE_KEY = "v4-beta-enabled-banner:v1:dismissed";
const V4_BETA_BANNER_ID = "v4-beta-enabled-banner";
const V4_BETA_BANNER_ORDER = 20;
-export function V4BetaEnabledBanner() {
+export function V4EnabledBanner() {
const session = useSession();
const { isBetaEnabled } = useV4Beta();
const { getTopBannerOffset } = useTopBanner();
diff --git a/web/src/features/events/components/V4BetaIntroDialog.tsx b/web/src/features/events/components/V4IntroDialog.tsx
similarity index 96%
rename from web/src/features/events/components/V4BetaIntroDialog.tsx
rename to web/src/features/events/components/V4IntroDialog.tsx
index 7fb6b61c25..3398851828 100644
--- a/web/src/features/events/components/V4BetaIntroDialog.tsx
+++ b/web/src/features/events/components/V4IntroDialog.tsx
@@ -6,15 +6,17 @@ import {
DialogFooter,
} from "@/src/components/ui/dialog";
-export function V4BetaIntroDialog({
+export function V4IntroDialog({
open,
onConfirm,
+ onDismiss,
}: {
open: boolean;
onConfirm: () => void;
+ onDismiss: () => void;
}) {
return (
- <Dialog open={open} onOpenChange={(o) => !o && onConfirm()}>
+ <Dialog open={open} onOpenChange={(o) => !o && onDismiss()}>
<DialogContent
className="[&>div:last-child]:hidden"
aria-label="Welcome to a faster Langfuse"
diff --git a/web/src/features/events/components/V4BetaPromoBanner.tsx b/web/src/features/events/components/V4PromoBanner.tsx
similarity index 90%
rename from web/src/features/events/components/V4BetaPromoBanner.tsx
rename to web/src/features/events/components/V4PromoBanner.tsx
index 739c0bde1a..f4072d60e0 100644
--- a/web/src/features/events/components/V4BetaPromoBanner.tsx
+++ b/web/src/features/events/components/V4PromoBanner.tsx
@@ -10,7 +10,7 @@ import {
useTopBannerRegistration,
} from "@/src/features/top-banner";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
-import { V4BetaIntroDialog } from "@/src/features/events/components/V4BetaIntroDialog";
+import { V4IntroDialog } from "@/src/features/events/components/V4IntroDialog";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
@@ -29,14 +29,16 @@ const PAGE_MESSAGES: Record<string, string> = {
"/project/[projectId]/traces/[traceId]": "Faster trace UI available.",
};
-export function V4BetaPromoBanner() {
+export function V4PromoBanner() {
const router = useRouter();
const session = useSession();
const {
isBetaEnabled,
+ canToggleV4,
enableWithIntro,
showIntroDialog,
confirmIntroDialog,
+ dismissIntroDialog,
isLoading,
} = useV4Beta();
const capture = usePostHogClientCapture();
@@ -49,12 +51,9 @@ export function V4BetaPromoBanner() {
const bannerRef = useRef<HTMLDivElement>(null);
const isAuthenticated = session.status === "authenticated";
- const enableExperimentalFeatures =
- session.data?.environment?.enableExperimentalFeatures ?? false;
- // Match the v4BetaToggleVisible logic from navigationFilters.ts
- // cloudAdmin = isLangfuseCloud && isAdmin (already covered by isLangfuseCloud)
- const isToggleVisible = isLangfuseCloud || enableExperimentalFeatures;
+ // Match the v4BetaToggleVisible logic from navigationFilters.ts.
+ const isToggleVisible = canToggleV4 && isLangfuseCloud;
const pageMessage = PAGE_MESSAGES[router.pathname];
const isVisible =
@@ -75,9 +74,10 @@ export function V4BetaPromoBanner() {
if (!isVisible) {
return (
- <V4BetaIntroDialog
+ <V4IntroDialog
open={showIntroDialog}
onConfirm={confirmIntroDialog}
+ onDismiss={dismissIntroDialog}
/>
);
}
@@ -137,9 +137,10 @@ export function V4BetaPromoBanner() {
<X className="h-4 w-4 shrink-0" />
</Button>
</div>
- <V4BetaIntroDialog
+ <V4IntroDialog
open={showIntroDialog}
onConfirm={confirmIntroDialog}
+ onDismiss={dismissIntroDialog}
/>
</div>
);
diff --git a/web/src/features/events/components/V4BetaSidebarToggle.tsx b/web/src/features/events/components/V4SidebarToggle.tsx
similarity index 91%
rename from web/src/features/events/components/V4BetaSidebarToggle.tsx
rename to web/src/features/events/components/V4SidebarToggle.tsx
index 5ca2e906d8..1a725d18e3 100644
--- a/web/src/features/events/components/V4BetaSidebarToggle.tsx
+++ b/web/src/features/events/components/V4SidebarToggle.tsx
@@ -7,7 +7,7 @@ import {
TooltipTrigger,
} from "@/src/components/ui/tooltip";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
-import { V4BetaIntroDialog } from "@/src/features/events/components/V4BetaIntroDialog";
+import { V4IntroDialog } from "@/src/features/events/components/V4IntroDialog";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { ZapIcon } from "lucide-react";
@@ -15,17 +15,23 @@ const PREVIEW_FAST_DESCRIPTION =
"Get a more performant Langfuse experience. Upgrade SDKs to the latest major for real-time data. This is a personal setting.";
const PREVIEW_FAST_DESCRIPTION_ID = "preview-fast-toggle-description";
-export function V4BetaSidebarToggle() {
+export function V4SidebarToggle() {
const {
isBetaEnabled,
+ canToggleV4,
setBetaEnabled,
enableWithIntro,
showIntroDialog,
confirmIntroDialog,
+ dismissIntroDialog,
isLoading,
} = useV4Beta();
const capture = usePostHogClientCapture();
+ if (!canToggleV4) {
+ return null;
+ }
+
const handleToggle = (enabled: boolean) => {
if (enabled) {
enableWithIntro({
@@ -82,9 +88,10 @@ export function V4BetaSidebarToggle() {
</span>
</div>
</SidebarMenuButton>
- <V4BetaIntroDialog
+ <V4IntroDialog
open={showIntroDialog}
onConfirm={confirmIntroDialog}
+ onDismiss={dismissIntroDialog}
/>
</>
);
diff --git a/web/src/features/events/hooks/useV4Beta.ts b/web/src/features/events/hooks/useV4Beta.ts
index 5de73fc395..37d48aebf8 100644
--- a/web/src/features/events/hooks/useV4Beta.ts
+++ b/web/src/features/events/hooks/useV4Beta.ts
@@ -4,7 +4,7 @@ import { useCallback, useState } from "react";
import posthog from "posthog-js";
import { V4_BETA_ENABLED_POSTHOG_PROPERTY } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-type SetV4BetaEnabledOptions = {
+type SetV4EnabledOptions = {
onSuccess?: () => void | Promise<void>;
};
@@ -20,13 +20,14 @@ export function useV4Beta() {
const mutation = api.userAccount.setV4BetaEnabled.useMutation();
const isBetaEnabled = session?.user?.v4BetaEnabled ?? false;
+ const canToggleV4 = session?.user?.canToggleV4 === true;
const isInitializing = sessionStatus === "loading";
const [showIntroDialog, setShowIntroDialog] = useState(false);
const [pendingOnSuccess, setPendingOnSuccess] =
- useState<SetV4BetaEnabledOptions["onSuccess"]>();
+ useState<SetV4EnabledOptions["onSuccess"]>();
const setBetaEnabled = useCallback(
- (enabled: boolean, options?: SetV4BetaEnabledOptions) => {
+ (enabled: boolean, options?: SetV4EnabledOptions) => {
mutation.mutate(
{ enabled },
{
@@ -47,7 +48,7 @@ export function useV4Beta() {
);
const enableWithIntro = useCallback(
- (options?: SetV4BetaEnabledOptions) => {
+ (options?: SetV4EnabledOptions) => {
if (
typeof window !== "undefined" &&
!localStorage.getItem(INTRO_DIALOG_SEEN_KEY)
@@ -76,6 +77,7 @@ export function useV4Beta() {
return {
isBetaEnabled,
+ canToggleV4,
isInitializing,
setBetaEnabled,
enableWithIntro,
diff --git a/web/src/features/events/lib/v4Rollout.ts b/web/src/features/events/lib/v4Rollout.ts
new file mode 100644
index 0000000000..ac21ab3947
--- /dev/null
+++ b/web/src/features/events/lib/v4Rollout.ts
@@ -0,0 +1,42 @@
+export const V4_DEFAULT_ENABLED_FROM_AT = new Date("2026-04-14T13:00:00.000Z");
+
+type RolloutOrganization = {
+ id: string;
+ createdAt: Date;
+};
+
+type V4RolloutContext = {
+ organizations: RolloutOrganization[];
+ userCreatedAt?: Date | null;
+ excludedOrganizationIds?: string[];
+};
+
+export function shouldAutoEnableV4({
+ organizations,
+ userCreatedAt,
+ excludedOrganizationIds = [],
+}: V4RolloutContext): boolean {
+ const excludedOrganizationIdSet = new Set(excludedOrganizationIds);
+ const rolloutRelevantOrganizations = organizations.filter(
+ (organization) => !excludedOrganizationIdSet.has(organization.id),
+ );
+
+ if (rolloutRelevantOrganizations.length === 0) {
+ return userCreatedAt != null && userCreatedAt >= V4_DEFAULT_ENABLED_FROM_AT;
+ }
+
+ // Use the oldest rollout-relevant org the user belongs to so existing users
+ // are not reclassified as "new" just because they later join or create a
+ // newer org. Excluded system orgs like the demo org do not influence rollout.
+ const oldestOrganizationCreatedAt = rolloutRelevantOrganizations.reduce(
+ (oldest, organization) =>
+ organization.createdAt < oldest ? organization.createdAt : oldest,
+ rolloutRelevantOrganizations[0].createdAt,
+ );
+
+ return oldestOrganizationCreatedAt >= V4_DEFAULT_ENABLED_FROM_AT;
+}
+
+export function canToggleV4(context: V4RolloutContext): boolean {
+ return !shouldAutoEnableV4(context);
+}
diff --git a/web/src/features/experiments/hooks/useExperimentAccess.ts b/web/src/features/experiments/hooks/useExperimentAccess.ts
index 7211c3c690..eb0b7c3ef2 100644
--- a/web/src/features/experiments/hooks/useExperimentAccess.ts
+++ b/web/src/features/experiments/hooks/useExperimentAccess.ts
@@ -13,10 +13,14 @@ function getStorageKey(prefix: string, userId?: string) {
export function useExperimentAccess() {
const { data: session } = useSession();
const { isLangfuseCloud } = useLangfuseCloudRegion();
- const { isBetaEnabled: isV4BetaEnabled } = useV4Beta();
+ const { isBetaEnabled: isV4BetaEnabled, canToggleV4 } = useV4Beta();
const userId = session?.user?.id;
+ // New users (canToggleV4 = false) get experiments beta auto-enabled
+ // Only compute isNewCloudUser after session loads to avoid treating all users as "new" during loading
+ const isNewCloudUser = isLangfuseCloud && !canToggleV4;
+
const { isEnabled: canAccessExperiments } = getExperimentsAccess({
isLangfuseCloud,
isV4BetaEnabled,
@@ -28,13 +32,20 @@ export function useExperimentAccess() {
false,
);
+ // For new cloud users, experiments beta is always enabled (bypass localStorage)
+ const effectiveExperimentsBetaEnabled =
+ isNewCloudUser || isExperimentsBetaEnabled;
+
return {
canAccessExperiments,
- canUseExperimentsBetaToggle: canAccessExperiments,
+ // Hide toggle for new cloud users - they get experiments beta automatically
+ canUseExperimentsBetaToggle: canAccessExperiments && !isNewCloudUser,
canSeeExperimentsNav: canAccessExperiments,
+ // New cloud users always have experiments beta active; others need localStorage toggle
isExperimentsBetaActive:
- canAccessExperiments && isExperimentsBetaEnabled && isV4BetaEnabled,
- isExperimentsBetaEnabled,
+ canAccessExperiments && effectiveExperimentsBetaEnabled,
+ // Return effective value so pages render correctly for new users
+ isExperimentsBetaEnabled: effectiveExperimentsBetaEnabled,
setExperimentsBetaEnabled,
isV4BetaEnabled,
};
diff --git a/web/src/features/organizations/components/NewOrganizationForm.tsx b/web/src/features/organizations/components/NewOrganizationForm.tsx
index db7e7287eb..e639498b71 100644
--- a/web/src/features/organizations/components/NewOrganizationForm.tsx
+++ b/web/src/features/organizations/components/NewOrganizationForm.tsx
@@ -30,7 +30,7 @@ import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
export const NewOrganizationForm = ({
onSuccess,
}: {
- onSuccess: (orgId: string) => void;
+ onSuccess: (orgId: string) => void | Promise<void>;
}) => {
const { update: updateSession } = useSession();
@@ -78,8 +78,11 @@ export const NewOrganizationForm = ({
}
}
- void updateSession();
- onSuccess(org.id);
+ // the setup (next step) resolves the current org from session state,
+ // so we refresh it, so that the UI doesn't render stale state.
+ // for example, it could otherwise show the v4 enable toggle.
+ await updateSession();
+ await onSuccess(org.id);
form.reset();
})
.catch((error) => {
diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.ts
index c4bf54ad52..1f39e9e146 100644
--- a/web/src/features/organizations/server/organizationRouter.ts
+++ b/web/src/features/organizations/server/organizationRouter.ts
@@ -15,6 +15,7 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { 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";
import { env } from "@/src/env.mjs";
@@ -28,16 +29,80 @@ export const organizationsRouter = createTRPCRouter({
message: "You do not have permission to create organizations",
});
- const organization = await ctx.prisma.organization.create({
- data: {
- name: input.name,
- organizationMemberships: {
- create: {
+ const organization = await ctx.prisma.$transaction(async (tx) => {
+ const organizationCountBeforeCreate =
+ await tx.organizationMembership.count({
+ where: {
userId: ctx.session.user.id,
- role: "OWNER",
+ ...(env.NEXT_PUBLIC_DEMO_ORG_ID
+ ? { orgId: { not: env.NEXT_PUBLIC_DEMO_ORG_ID } }
+ : {}),
+ },
+ });
+
+ const organization = await tx.organization.create({
+ data: {
+ name: input.name,
+ organizationMemberships: {
+ create: {
+ userId: ctx.session.user.id,
+ role: "OWNER",
+ },
},
},
- },
+ });
+
+ if (organizationCountBeforeCreate === 0) {
+ const isCloudDeployment = Boolean(
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ );
+
+ if (isCloudDeployment) {
+ const userRolloutState = await tx.user.findUnique({
+ where: { id: ctx.session.user.id },
+ select: {
+ createdAt: true,
+ v4BetaEnabled: true,
+ organizationMemberships: {
+ select: {
+ organization: {
+ select: {
+ id: true,
+ createdAt: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (
+ userRolloutState &&
+ !userRolloutState.v4BetaEnabled &&
+ shouldAutoEnableV4({
+ userCreatedAt: userRolloutState.createdAt,
+ organizations: userRolloutState.organizationMemberships.map(
+ (membership) => ({
+ id: membership.organization.id,
+ createdAt: membership.organization.createdAt,
+ }),
+ ),
+ excludedOrganizationIds: env.NEXT_PUBLIC_DEMO_ORG_ID
+ ? [env.NEXT_PUBLIC_DEMO_ORG_ID]
+ : [],
+ })
+ ) {
+ // This path is both the normal first-org initialization and a
+ // recovery path if signup-side initialization failed earlier.
+ await tx.user.update({
+ where: { id: ctx.session.user.id },
+ data: { v4BetaEnabled: true },
+ });
+ }
+ }
+ }
+
+ return organization;
});
await auditLog({
resourceType: "organization",
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index fb244669a9..06bae0cb71 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -195,7 +195,7 @@ export function DashboardWidget({
},
refreshKey: retryCount,
useSSE: shouldUseWidgetSSE({
- isV4BetaEnabled: isBetaEnabled,
+ isV4Enabled: isBetaEnabled,
version: metricsVersion,
}),
enabled:
@@ -209,7 +209,7 @@ export function DashboardWidget({
errorMessage: queryResult.error,
});
const usesBackendProgress = shouldUseWidgetSSE({
- isV4BetaEnabled: isBetaEnabled,
+ isV4Enabled: isBetaEnabled,
version: metricsVersion,
});
const loadingStateLayout =
diff --git a/web/src/features/widgets/utils.ts b/web/src/features/widgets/utils.ts
index 99fccc76b7..cb03599a28 100644
--- a/web/src/features/widgets/utils.ts
+++ b/web/src/features/widgets/utils.ts
@@ -149,11 +149,11 @@ export function getDefaultView(
* SSE progress is only enabled on the v4 beta dashboard query path.
*/
export function shouldUseWidgetSSE({
- isV4BetaEnabled,
+ isV4Enabled,
version,
}: {
- isV4BetaEnabled: boolean;
+ isV4Enabled: boolean;
version: "v1" | "v2";
}): boolean {
- return isV4BetaEnabled && version === "v2";
+ return isV4Enabled && version === "v2";
}
diff --git a/web/src/server/api/routers/userAccount.ts b/web/src/server/api/routers/userAccount.ts
index c7e7da8636..f784be77c8 100644
--- a/web/src/server/api/routers/userAccount.ts
+++ b/web/src/server/api/routers/userAccount.ts
@@ -7,6 +7,8 @@ import { TRPCError } from "@trpc/server";
import { StringNoHTML } from "@langfuse/shared";
import { Role, Prisma } from "@langfuse/shared/src/db";
import type { PrismaClient } from "@langfuse/shared/src/db";
+import { canToggleV4 } from "@/src/features/events/lib/v4Rollout";
+import { env } from "@/src/env.mjs";
const updateDisplayNameSchema = z.object({
name: StringNoHTML.min(1, "Name cannot be empty").max(
@@ -129,10 +131,71 @@ export const userAccountRouter = createTRPCRouter({
setV4BetaEnabled: authenticatedProcedure
.input(z.object({ enabled: z.boolean() }))
.mutation(async ({ input, ctx }) => {
+ const isCloudDeployment = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+
+ if (!isCloudDeployment) {
+ return {
+ success: true,
+ v4BetaEnabled: false,
+ canToggleV4: false,
+ };
+ }
+
+ const userRolloutState = await ctx.prisma.user.findUnique({
+ where: { id: ctx.session.user.id },
+ select: {
+ createdAt: true,
+ v4BetaEnabled: true,
+ organizationMemberships: {
+ select: {
+ organization: {
+ select: {
+ id: true,
+ createdAt: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!userRolloutState) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
+ });
+ }
+
+ const userCanToggleV4 = canToggleV4({
+ userCreatedAt: userRolloutState.createdAt,
+ organizations: userRolloutState.organizationMemberships.map(
+ (membership) => ({
+ id: membership.organization.id,
+ createdAt: membership.organization.createdAt,
+ }),
+ ),
+ excludedOrganizationIds: env.NEXT_PUBLIC_DEMO_ORG_ID
+ ? [env.NEXT_PUBLIC_DEMO_ORG_ID]
+ : [],
+ });
+
+ if (!userCanToggleV4) {
+ return {
+ success: true,
+ v4BetaEnabled: userRolloutState.v4BetaEnabled,
+ canToggleV4: false,
+ };
+ }
+
await ctx.prisma.user.update({
where: { id: ctx.session.user.id },
data: { v4BetaEnabled: input.enabled },
});
- return { success: true, v4BetaEnabled: input.enabled };
+
+ return {
+ success: true,
+ v4BetaEnabled: input.enabled,
+ canToggleV4: true,
+ };
}),
});
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index f5ff2977f4..a02aa13e0e 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -64,6 +64,7 @@ import { projectRoleAccessRights } from "@/src/features/rbac/constants/projectAc
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { getSSOBlockedDomains } from "@/src/features/auth-credentials/server/signupApiHandler";
import { createSupportEmailHash } from "@/src/features/support-chat/createSupportEmailHash";
+import { canToggleV4 } from "@/src/features/events/lib/v4Rollout";
function canCreateOrganizations(userEmail: string | null): boolean {
const instancePlan = getSelfHostedInstancePlanServerSide();
@@ -550,7 +551,7 @@ const extendedPrismaAdapter: Adapter = {
const user = await prismaAdapter.createUser(profile);
- await createProjectMembershipsOnSignup(user);
+ await createProjectMembershipsOnSignup(user, { userWasJustCreated: true });
return user;
},
@@ -695,6 +696,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
email: true,
image: true,
emailVerified: true,
+ createdAt: true,
featureFlags: true,
admin: true,
v4BetaEnabled: true,
@@ -723,6 +725,9 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
span.setAttribute("langfuse.user.email", dbUser?.email ?? "");
span.setAttribute("langfuse.user.id", dbUser?.id ?? "");
+ const isCloudDeployment = Boolean(
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ );
return {
...session,
@@ -745,7 +750,23 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
: undefined,
image: dbUser.image,
admin: dbUser.admin,
- v4BetaEnabled: dbUser.v4BetaEnabled,
+ v4BetaEnabled: isCloudDeployment
+ ? dbUser.v4BetaEnabled
+ : false,
+ canToggleV4: isCloudDeployment
+ ? canToggleV4({
+ userCreatedAt: dbUser.createdAt,
+ organizations: dbUser.organizationMemberships.map(
+ (orgMembership) => ({
+ id: orgMembership.organization.id,
+ createdAt: orgMembership.organization.createdAt,
+ }),
+ ),
+ excludedOrganizationIds: env.NEXT_PUBLIC_DEMO_ORG_ID
+ ? [env.NEXT_PUBLIC_DEMO_ORG_ID]
+ : [],
+ })
+ : false,
canCreateOrganizations: canCreateOrganizations(
dbUser.email,
),
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index b4d45d3c2a..ce5ee38094 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -34,6 +34,7 @@ declare module "next-auth" {
image?: PrismaUser["image"];
admin?: PrismaUser["admin"];
v4BetaEnabled?: boolean;
+ canToggleV4?: boolean;
emailVerified?: string | null; // iso datetime string, need to stringify as JWT & useSession do not support Date objects
canCreateOrganizations: boolean; // default true, allowlist can be set via LANGFUSE_ALLOWED_ORGANIZATION_CREATORS
organizations: {