Skip to content

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

refactor(layout): modernize layout architecture and fix publishable path access (#10622)

Michael Fröhlich9c619646d1de
diff --git a/web/src/__e2e__/auth.spec.ts b/web/src/__e2e__/auth.spec.ts
index 381113ddc9..9cb933def8 100644
--- a/web/src/__e2e__/auth.spec.ts
+++ b/web/src/__e2e__/auth.spec.ts
@@ -3,7 +3,7 @@ import { test, expect } from "@playwright/test";
test("should redirect to sign-in if not signed in", async ({ page }) => {
await page.goto("/");
await page.waitForTimeout(2000);
- await expect(page).toHaveURL("/auth/sign-in");
+ await expect(page).toHaveURL(/\/auth\/sign-in(\?.*)?$/);
});
test("should redirect to home if signed in", async ({ page }) => {
@@ -81,7 +81,7 @@ test("Unauthenticated user should be redirected to target URL after login", asyn
await page.getByRole("menuitem", { name: "Sign Out" }).click();
- await expect(page).toHaveURL("/auth/sign-in");
+ await expect(page).toHaveURL(/\/auth\/sign-in(\?.*)?$/);
await page.goto(promptUrl);
diff --git a/web/src/components/layouts/app-layout/components/ResizableContent.tsx b/web/src/components/layouts/app-layout/components/ResizableContent.tsx
new file mode 100644
index 0000000000..ca359481ee
--- /dev/null
+++ b/web/src/components/layouts/app-layout/components/ResizableContent.tsx
@@ -0,0 +1,115 @@
+/**
+ * Resizable content component for support drawer
+ * Desktop: Resizable panels with programmatic control
+ * Mobile: Bottom drawer
+ *
+ * Extracted from original layout.tsx (lines 414-493)
+ */
+
+import { type PropsWithChildren, useRef, useLayoutEffect } from "react";
+import { useIsMobile } from "@/src/hooks/use-mobile";
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import { SupportDrawer } from "@/src/features/support-chat/SupportDrawer";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+ type ImperativePanelHandle,
+} from "@/src/components/ui/resizable";
+import {
+ Drawer,
+ DrawerContent,
+ DrawerDescription,
+ DrawerHeader,
+ DrawerTitle,
+} from "@/src/components/ui/drawer";
+
+/**
+ * Resizable content for support drawer on the right side of the screen (desktop).
+ * On mobile, renders a Drawer instead of a resizable sidebar.
+ *
+ * Key optimization: Always renders ResizablePanelGroup on desktop to prevent
+ * remounting children when drawer opens/closes. Uses refs for programmatic control.
+ */
+export function ResizableContent({ children }: PropsWithChildren) {
+ const { open, setOpen } = useSupportDrawer();
+ const isMobile = useIsMobile();
+ const isDesktop = !isMobile;
+
+ // 👉 DESKTOP: Always render ResizablePanelGroup to prevent remounting children
+ // Use refs to programmatically control panel sizes when drawer opens/closes
+ const drawerPanelRef = useRef<ImperativePanelHandle>(null);
+ const mainPanelRef = useRef<ImperativePanelHandle>(null);
+
+ useLayoutEffect(() => {
+ if (!isDesktop) return;
+
+ if (open) {
+ // Open drawer: resize main to 70%, drawer to 30%
+ drawerPanelRef.current?.resize(30);
+ mainPanelRef.current?.resize(70);
+ } else {
+ // Close drawer: resize main to 100%, drawer to 0%
+ drawerPanelRef.current?.resize(0);
+ mainPanelRef.current?.resize(100);
+ }
+ }, [open, isDesktop]);
+
+ // 👉 MOBILE: Render bottom drawer
+ if (!isDesktop) {
+ return (
+ <>
+ <main className="h-full flex-1" style={{ overscrollBehaviorY: "none" }}>
+ {children}
+ </main>
+
+ <Drawer open={open} onOpenChange={setOpen} forceDirection="bottom">
+ <DrawerContent
+ id="support-drawer"
+ className="inset-x-0 bottom-0 top-[calc(var(--banner-offset)+10px)] min-h-screen-with-banner"
+ 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="h-2 w-20 rounded-full bg-muted" />
+ </div>
+ {/* sr-only for screen readers and accessibility */}
+ <DrawerTitle className="sr-only">Support</DrawerTitle>
+ <DrawerDescription className="sr-only">
+ A list of resources and options to help you with your questions.
+ </DrawerDescription>
+ </DrawerHeader>
+ <div className="mt-4 max-h-full">
+ <SupportDrawer showCloseButton={false} className="h-full pb-20" />
+ </div>
+ </DrawerContent>
+ </Drawer>
+ </>
+ );
+ }
+
+ // 👉 DESKTOP: Always render ResizablePanelGroup to prevent remounting children
+ return (
+ <ResizablePanelGroup direction="horizontal" className="flex h-full w-full">
+ <ResizablePanel ref={mainPanelRef} defaultSize={100} minSize={30}>
+ <main
+ className="relative h-full w-full overflow-scroll"
+ style={{ overscrollBehaviorY: "none" }}
+ >
+ {children}
+ </main>
+ </ResizablePanel>
+ {open && <ResizableHandle withHandle />}
+ <ResizablePanel
+ ref={drawerPanelRef}
+ defaultSize={0}
+ minSize={0}
+ maxSize={60}
+ collapsible={true}
+ collapsedSize={0}
+ >
+ {open && <SupportDrawer />}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+}
diff --git a/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts b/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts
new file mode 100644
index 0000000000..151bf135e3
--- /dev/null
+++ b/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts
@@ -0,0 +1,112 @@
+/**
+ * Authentication guard hook
+ * Determines if user should be redirected, signed out, or allowed to proceed
+ */
+
+import { useRouter } from "next/router";
+import { useMemo } from "react";
+import { env } from "@/src/env.mjs";
+import { PATH_CONSTANTS } from "../utils/pathClassification";
+import { getSafeRedirectPath } from "@/src/utils/redirect";
+import type { useSession } from "next-auth/react";
+
+/** Actions the auth guard can request */
+export type AuthGuardAction = "allow" | "loading" | "redirect" | "sign-out";
+
+/** Result of auth guard evaluation */
+export type AuthGuardResult =
+ | { action: "allow" }
+ | { action: "loading"; message: string }
+ | { action: "redirect"; url: string; message: string }
+ | { action: "sign-out"; message: string };
+
+/**
+ * Evaluates authentication state and determines appropriate action
+ * Handles:
+ * - Loading states
+ * - Invalid users (session exists but user is null)
+ * - Unauthenticated users on protected routes
+ * - Authenticated users on auth pages (with redirect)
+ *
+ * @param session - Session object from useSession hook
+ * @returns Guard state indicating what action to take
+ */
+export function useAuthGuard(
+ session: ReturnType<typeof useSession>,
+ _hideNavigation: boolean,
+): AuthGuardResult {
+ const router = useRouter();
+
+ return useMemo(() => {
+ const { pathname, query, asPath } = router;
+ const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";
+
+ // Loading state
+ if (session.status === "loading") {
+ return { action: "loading", message: "Loading" };
+ }
+
+ const isUnauthPath = PATH_CONSTANTS.unauthenticated.some((p) =>
+ pathname.startsWith(p),
+ );
+ const isPublicPath = pathname.startsWith("/public/");
+
+ // Check if path is publishable (can be accessed without authentication)
+ const isPublishable = PATH_CONSTANTS.publishable.some((path) => {
+ // Case 1: Exact match (e.g., pathname === "/auth/reset-password")
+ if (pathname === path) return true;
+
+ // Case 2: Prefix match for dynamic routes
+ // Example: path = "/project/[projectId]/traces/[traceId]"
+ // -> pathPrefix = "/project/[^/]+/traces" (last segment removed, params converted to regex)
+ // -> matches pathname like "/project/abc123/traces/xyz789"
+ // This allows shared trace/session links to be accessed without authentication
+ const pathPrefix = path
+ .split("/")
+ .slice(0, -1)
+ .join("/")
+ .replace(/\[([^\]]+)\]/g, "[^/]+");
+ const prefixRegex = new RegExp(`^${pathPrefix}/`);
+ return prefixRegex.test(pathname);
+ });
+
+ // Invalid user - has session but no DB user
+ // This can happen if user was deleted from DB but still has valid JWT
+ if (
+ session.data &&
+ session.data.user === null &&
+ !isUnauthPath &&
+ !isPublishable &&
+ !isPublicPath
+ ) {
+ return { action: "sign-out", message: "Redirecting" };
+ }
+
+ // Unauthenticated user trying to access protected route
+ if (
+ session.status === "unauthenticated" &&
+ !isUnauthPath &&
+ !isPublishable &&
+ !isPublicPath
+ ) {
+ const targetPath = encodeURIComponent(
+ basePath + (pathname === "/" ? pathname : asPath),
+ );
+ return {
+ action: "redirect",
+ url: `/auth/sign-in?targetPath=${targetPath}`,
+ message: "Redirecting",
+ };
+ }
+
+ // Authenticated user on authentication page - redirect to target or home
+ if (session.status === "authenticated" && isUnauthPath) {
+ const queryTargetPath = query.targetPath as string | undefined;
+ const redirectUrl = getSafeRedirectPath(queryTargetPath);
+ return { action: "redirect", url: redirectUrl, message: "Redirecting" };
+ }
+
+ // All checks passed - allow access
+ return { action: "allow" };
+ }, [session.status, session.data, router]);
+}
diff --git a/web/src/components/layouts/app-layout/hooks/useAuthSession.ts b/web/src/components/layouts/app-layout/hooks/useAuthSession.ts
new file mode 100644
index 0000000000..95e995ce26
--- /dev/null
+++ b/web/src/components/layouts/app-layout/hooks/useAuthSession.ts
@@ -0,0 +1,51 @@
+/**
+ * Enhanced session hook with retry logic
+ *
+ * TODO: Remove retry workaround once /api/auth/session reliability is fixed.
+ * This hook exists to mitigate exceptions on the /api/auth/session endpoint which
+ * cause the session to be unauthenticated even though the user is signed in.
+ */
+
+import { useSession, getSession } from "next-auth/react";
+import { useState, useEffect } from "react";
+
+const MAX_RETRIES = 2;
+
+/**
+ * Patched version of useSession that retries fetching the session if the user
+ * is unauthenticated. This is useful to mitigate exceptions on the
+ * /api/auth/session endpoint.
+ *
+ * @returns Session object with retry logic applied
+ */
+export function useAuthSession() {
+ const [retryCount, setRetryCount] = useState(0);
+ const session = useSession();
+
+ useEffect(() => {
+ if (session.status === "unauthenticated" && retryCount < MAX_RETRIES) {
+ const fetchSession = async () => {
+ try {
+ await getSession({ broadcast: true });
+ } catch (error) {
+ console.error("Error fetching session:", error);
+ // Don't throw - The /api/auth/session endpoint occasionally fails
+ // with transient errors. By not throwing, we allow the retry logic
+ // to attempt recovery on the next iteration.
+ }
+ setRetryCount((prevCount) => prevCount + 1);
+ };
+ void fetchSession();
+ }
+
+ // Reset retry count on successful authentication
+ if (session.status === "authenticated" && retryCount > 0) {
+ setRetryCount(0);
+ }
+ }, [session.status, retryCount]);
+
+ // Return loading state if we're still retrying
+ return session.status !== "unauthenticated" || retryCount >= MAX_RETRIES
+ ? session
+ : { ...session, status: "loading" as const };
+}
diff --git a/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts b/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts
new file mode 100644
index 0000000000..ab0f6112e3
--- /dev/null
+++ b/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts
@@ -0,0 +1,169 @@
+/**
+ * Hook to filter and process navigation based on user permissions and context
+ * Implements memoization to prevent unnecessary recalculations
+ */
+
+import { useRouter } from "next/router";
+import { useMemo } from "react";
+import type { Session, User } from "next-auth";
+import { useEntitlements } from "@/src/features/entitlements/hooks";
+import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import {
+ ROUTES,
+ RouteSection,
+ RouteGroup,
+ type Route,
+} from "@/src/components/layouts/routes";
+import type { NavigationItem } from "@/src/components/layouts/utilities/routes";
+import { applyNavigationFilters } from "../utils/navigationFilters";
+import type { NavigationFilterContext } from "../utils/navigationFilters.types";
+import { isPathActive } from "../utils/pathClassification";
+
+/** Organization type from user session (can be null when not in project/org context) */
+type Organization = User["organizations"][number] | null | undefined;
+
+/** Grouped navigation structure */
+type GroupedNavigation = {
+ ungrouped: NavigationItem[];
+ grouped: Partial<Record<RouteGroup, NavigationItem[]>> | null;
+ flattened: NavigationItem[];
+};
+
+/**
+ * Groups navigation items by RouteGroup
+ */
+function groupNavigationItems(items: NavigationItem[]): GroupedNavigation {
+ const ungrouped = items.filter((item) => !item.group);
+ const grouped: Partial<Record<RouteGroup, NavigationItem[]>> = {};
+
+ items.forEach((item) => {
+ if (item.group) {
+ if (!grouped[item.group]) {
+ grouped[item.group] = [];
+ }
+ grouped[item.group]!.push(item);
+ }
+ });
+
+ const groupedResult = Object.keys(grouped).length > 0 ? grouped : null;
+ const groupedItems = groupedResult
+ ? [
+ ...(grouped[RouteGroup.Observability] || []),
+ ...(grouped[RouteGroup.PromptManagement] || []),
+ ...(grouped[RouteGroup.Evaluation] || []),
+ ]
+ : [];
+
+ return {
+ ungrouped,
+ grouped: groupedResult,
+ flattened: [...ungrouped, ...groupedItems],
+ };
+}
+
+/**
+ * Filters and processes navigation items based on:
+ * - Project/organization context
+ * - User permissions (RBAC)
+ * - Plan entitlements
+ * - Feature flags
+ * - UI customization settings
+ *
+ * Returns navigation split into main/secondary sections with active states
+ *
+ * @param session - Current user session
+ * @param organization - Current organization object
+ * @returns Processed navigation with main, secondary, and flattened arrays
+ */
+export function useFilteredNavigation(
+ session: Session | null,
+ organization: Organization,
+) {
+ const router = useRouter();
+ const entitlements = useEntitlements();
+ const uiCustomization = useUiCustomization();
+ const { isLangfuseCloud, region } = useLangfuseCloudRegion();
+
+ const routerProjectId = router.query.projectId as string | undefined;
+ const routerOrganizationId = router.query.organizationId as
+ | string
+ | undefined;
+
+ // Memoize filter context to prevent unnecessary recalculations
+ const filterContext = useMemo<NavigationFilterContext>(
+ () => ({
+ routerProjectId,
+ routerOrganizationId,
+ session,
+ enableExperimentalFeatures:
+ session?.environment?.enableExperimentalFeatures ?? false,
+ cloudAdmin: Boolean(
+ session?.user?.admin && isLangfuseCloud && region !== "DEV",
+ ),
+ entitlements,
+ uiCustomization,
+ currentPath: router.asPath,
+ }),
+ [
+ routerProjectId,
+ routerOrganizationId,
+ session,
+ entitlements,
+ uiCustomization,
+ router.asPath,
+ isLangfuseCloud,
+ region,
+ ],
+ );
+
+ // Memoize filtered routes
+ const filteredRoutes = useMemo(() => {
+ return applyNavigationFilters(ROUTES, filterContext, organization);
+ }, [filterContext, organization]);
+
+ // Map filtered routes to NavigationItems with url and isActive
+ // This is O(n) - we map directly over filteredRoutes instead of re-iterating ROUTES
+ return useMemo(() => {
+ const mapRouteToNavigationItem = (route: Route): NavigationItem => {
+ const url = route.pathname
+ .replace("[projectId]", routerProjectId ?? "")
+ .replace("[organizationId]", routerOrganizationId ?? "");
+
+ // Recursively map nested items (already filtered by applyNavigationFilters)
+ const items: NavigationItem[] | undefined = route.items
+ ?.map(mapRouteToNavigationItem)
+ .filter((item): item is NavigationItem => item !== null);
+
+ return {
+ ...route,
+ url,
+ isActive: isPathActive(route.pathname, router.pathname),
+ items: items && items.length > 0 ? items : undefined,
+ };
+ };
+
+ // Map filtered routes to navigation items
+ const allItems = filteredRoutes.map(mapRouteToNavigationItem);
+
+ // Split by section and group
+ const mainItems = allItems.filter(
+ (item) => item.section === RouteSection.Main,
+ );
+ const secondaryItems = allItems.filter(
+ (item) => item.section === RouteSection.Secondary,
+ );
+
+ const mainNavigation = groupNavigationItems(mainItems);
+ const secondaryNavigation = groupNavigationItems(secondaryItems);
+
+ return {
+ mainNavigation,
+ secondaryNavigation,
+ navigation: [
+ ...mainNavigation.flattened,
+ ...secondaryNavigation.flattened,
+ ],
+ };
+ }, [filteredRoutes, routerProjectId, routerOrganizationId, router.pathname]);
+}
diff --git a/web/src/components/layouts/app-layout/hooks/useLayoutConfiguration.ts b/web/src/components/layouts/app-layout/hooks/useLayoutConfiguration.ts
new file mode 100644
index 0000000000..b5de056874
--- /dev/null
+++ b/web/src/components/layouts/app-layout/hooks/useLayoutConfiguration.ts
@@ -0,0 +1,63 @@
+/**
+ * Hook to determine which layout variant to render
+ * Combines path classification with session state to make the final decision
+ */
+
+import { useRouter } from "next/router";
+import { useMemo } from "react";
+import { classifyPath, type LayoutType } from "../utils/pathClassification";
+import type { Session } from "next-auth";
+
+export type LayoutConfiguration = {
+ /** The layout variant to render */
+ variant: LayoutType;
+ /** Whether to hide the navigation sidebar */
+ hideNavigation: boolean;
+ /** Whether this is a publishable path (shared traces/sessions) */
+ isPublishable: boolean;
+};
+
+/**
+ * Determines the appropriate layout configuration based on:
+ * - Path classification (auth pages, public pages, publishable paths)
+ * - Session state (authenticated, unauthenticated, loading)
+ *
+ * Layout decision logic:
+ * 1. Auth pages (sign-in, sign-up) → "unauthenticated" variant
+ * 2. Unauthenticated user on non-publishable route → redirect (handled by authGuard)
+ * 3. Unauthenticated user on publishable route → "minimal" variant
+ * 4. Authenticated user on hideNavigation path → "minimal" variant
+ * 5. Authenticated user on normal path → "authenticated" variant
+ *
+ * @param session - Current user session (null if unauthenticated)
+ * @returns Layout configuration with variant type and navigation visibility
+ */
+export function useLayoutConfiguration(
+ session: Session | null,
+): LayoutConfiguration {
+ const router = useRouter();
+
+ return useMemo(() => {
+ const { isAuthPage, hideNavigation, isPublishable } = classifyPath(
+ router.pathname,
+ router.asPath,
+ );
+
+ // Determine the layout variant based on path and session
+ let variant: LayoutType = "authenticated";
+
+ if (isAuthPage) {
+ // Auth pages always use unauthenticated layout
+ variant = "unauthenticated";
+ } else if (session === null && !isPublishable) {
+ // Unauthenticated user on protected route - will be redirected by authGuard
+ // but we set variant for the brief moment before redirect
+ variant = "unauthenticated";
+ } else if (hideNavigation) {
+ // Public routes, onboarding, etc.
+ variant = "minimal";
+ }
+
+ return { variant, hideNavigation, isPublishable };
+ }, [router.pathname, router.asPath, session]);
+}
diff --git a/web/src/components/layouts/app-layout/hooks/useLayoutMetadata.ts b/web/src/components/layouts/app-layout/hooks/useLayoutMetadata.ts
new file mode 100644
index 0000000000..afebe51eb7
--- /dev/null
+++ b/web/src/components/layouts/app-layout/hooks/useLayoutMetadata.ts
@@ -0,0 +1,46 @@
+/**
+ * Hook to generate layout metadata (page titles, favicons, etc.)
+ * Based on active navigation and environment
+ */
+
+import { useMemo } from "react";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import { env } from "@/src/env.mjs";
+import type { NavigationItem } from "@/src/components/layouts/utilities/routes";
+
+/**
+ * Generates metadata for the layout including:
+ * - Dynamic page title based on active route
+ * - Region-specific favicon (dev vs production)
+ * - Apple touch icon path
+ *
+ * @param activePathName - Title of the currently active navigation item
+ * @param navigation - Full navigation array for finding active item
+ * @returns Metadata object with title and icon paths
+ */
+export function useLayoutMetadata(
+ activePathName: string | undefined,
+ _navigation: NavigationItem[],
+) {
+ const { region } = useLangfuseCloudRegion();
+
+ return useMemo(() => {
+ const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";
+
+ // Determine page title from active route
+ const title = activePathName ? `${activePathName} | Langfuse` : "Langfuse";
+
+ // Use dev favicon in DEV region for visual distinction
+ // Using SVG for modern browsers with PNG fallback specified in sizes
+ const faviconPath =
+ region === "DEV" ? `${basePath}/icon-dev.svg` : `${basePath}/icon.svg`;
+
+ return {
+ title,
+ faviconPath,
+ // PNG icons with sizes for broader browser compatibility
+ favicon256Path: `${basePath}/icon256.png`,
+ appleTouchIconPath: `${basePath}/apple-touch-icon.png`,
+ };
+ }, [activePathName, region]);
+}
diff --git a/web/src/components/layouts/app-layout/hooks/useProjectAccess.ts b/web/src/components/layouts/app-layout/hooks/useProjectAccess.ts
new file mode 100644
index 0000000000..c23931cc61
--- /dev/null
+++ b/web/src/components/layouts/app-layout/hooks/useProjectAccess.ts
@@ -0,0 +1,65 @@
+/**
+ * Hook to verify user has access to the current project in the URL
+ *
+ * IMPORTANT: This hook is designed specifically for the AppLayout component to
+ * provide client-side UX protection. It should NOT be used as a security measure
+ * elsewhere - server-side validation in API routes is always required.
+ *
+ * Behavior:
+ * - Returns hasAccess=true when no projectId is in URL (allows org pages, public routes, etc.)
+ * - Returns hasAccess=true for demo project (public demo functionality)
+ * - Returns hasAccess=true for admin users (full access)
+ * - Returns hasAccess based on project membership for regular users
+ */
+
+import { useRouter } from "next/router";
+import { useMemo } from "react";
+import type { Session } from "next-auth";
+import { env } from "@/src/env.mjs";
+
+/**
+ * Checks if the authenticated user has access to the project specified in the URL.
+ * Used by AppLayout to show an error page when a user tries to access a project
+ * they don't have permission for.
+ *
+ * Note: When routerProjectId is undefined (no project in URL), returns hasAccess=true
+ * because this hook is only meant to block access to specific project routes,
+ * not to validate access to non-project routes (org pages, public pages, etc.).
+ *
+ * @param session - Current user session (must be authenticated for meaningful check)
+ * @returns Object with hasAccess boolean and projectId
+ */
+export function useProjectAccess(session: Session | null) {
+ const router = useRouter();
+ const routerProjectId = router.query.projectId as string | undefined;
+
+ return useMemo(() => {
+ // No project in URL - not a project route, so no project access check needed
+ // This allows organization pages, public pages, etc. to render normally
+ if (!routerProjectId) {
+ return { hasAccess: true, projectId: undefined };
+ }
+
+ // Demo project is always accessible for demonstration purposes
+ // Note: This is safe because the demo project contains only sample data
+ // and API routes still enforce proper authentication for write operations
+ if (routerProjectId === env.NEXT_PUBLIC_DEMO_PROJECT_ID) {
+ return { hasAccess: true, projectId: routerProjectId };
+ }
+
+ // Admin users have access to all projects
+ if (session?.user?.admin === true) {
+ return { hasAccess: true, projectId: routerProjectId };
+ }
+
+ // Check if user's organizations contain this project
+ const userProjects =
+ session?.user?.organizations
+ ?.flatMap((org) => org?.projects?.map((p) => p?.id))
+ .filter(Boolean) ?? [];
+
+ const hasAccess = userProjects.includes(routerProjectId);
+
+ return { hasAccess, projectId: routerProjectId };
+ }, [routerProjectId, session?.user?.admin, session?.user?.organizations]);
+}
diff --git a/web/src/components/layouts/app-layout/index.tsx b/web/src/components/layouts/app-layout/index.tsx
new file mode 100644
index 0000000000..341447eeab
--- /dev/null
+++ b/web/src/components/layouts/app-layout/index.tsx
@@ -0,0 +1,145 @@
+/**
+ * App Layout
+ *
+ * Improved maintainability through:
+ * - Separation of concerns via custom hooks
+ * - Composable navigation filters
+ * - Layout variant components
+ * - Memoization for performance
+ *
+ */
+
+import { type PropsWithChildren, useEffect } from "react";
+import { useRouter } from "next/router";
+import { signOut } from "next-auth/react";
+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
+import { ErrorPageWithSentry } from "@/src/components/error-page";
+
+// Layout variants
+import { LoadingLayout } from "./variants/LoadingLayout";
+import { UnauthenticatedLayout } from "./variants/UnauthenticatedLayout";
+import { MinimalLayout } from "./variants/MinimalLayout";
+import { AuthenticatedLayout } from "./variants/AuthenticatedLayout";
+
+// Custom hooks
+import { useAuthSession } from "./hooks/useAuthSession";
+import { useLayoutConfiguration } from "./hooks/useLayoutConfiguration";
+import { useAuthGuard } from "./hooks/useAuthGuard";
+import { useProjectAccess } from "./hooks/useProjectAccess";
+import { useFilteredNavigation } from "./hooks/useFilteredNavigation";
+import { useLayoutMetadata } from "./hooks/useLayoutMetadata";
+
+/**
+ * Main layout component
+ * Determines which layout variant to render based on:
+ * - Authentication state
+ * - Current route
+ * - Project access
+ * - User permissions
+ */
+export function AppLayout(props: PropsWithChildren) {
+ const router = useRouter();
+ const session = useAuthSession();
+ const { organization } = useQueryProjectOrOrganization();
+
+ // Determine layout configuration
+ const { variant, hideNavigation, isPublishable } = useLayoutConfiguration(
+ session.data ?? null,
+ );
+
+ // Check authentication and redirects
+ const authGuard = useAuthGuard(session, hideNavigation);
+
+ // Check project access
+ const projectAccess = useProjectAccess(session.data ?? null);
+
+ // IMPORTANT: Call all hooks before any conditional returns
+ // Load navigation and metadata (even if not used in all render paths)
+ const navigation = useFilteredNavigation(session.data ?? null, organization);
+ const activePathName = navigation.navigation.find(
+ (item) => item.isActive,
+ )?.title;
+ const metadata = useLayoutMetadata(activePathName, navigation.navigation);
+
+ // Handle auth guard actions (redirect or sign-out)
+ useEffect(() => {
+ if (authGuard.action === "redirect") {
+ void router.replace(authGuard.url);
+ } else if (authGuard.action === "sign-out") {
+ void signOut({ redirect: false });
+ }
+ }, [authGuard, router]);
+
+ // Loading or redirecting state
+ if (
+ authGuard.action === "loading" ||
+ authGuard.action === "redirect" ||
+ authGuard.action === "sign-out"
+ ) {
+ return <LoadingLayout message={authGuard.message} />;
+ }
+
+ // Project access denied - only check for authenticated users on non-publishable paths
+ // Publishable paths (traces, sessions) should be accessible without authentication
+ if (
+ session.status === "authenticated" &&
+ !isPublishable &&
+ !projectAccess.hasAccess
+ ) {
+ return (
+ <ErrorPageWithSentry
+ title="Project Not Found"
+ message="The project you are trying to access does not exist or you do not have access to it."
+ additionalButton={{
+ label: "Go to Home",
+ href: "/",
+ }}
+ />
+ );
+ }
+
+ // Unauthenticated layout (sign-in, sign-up)
+ // Must check variant BEFORE hideNavigation since auth pages set hideNavigation=true
+ if (variant === "unauthenticated") {
+ return <UnauthenticatedLayout>{props.children}</UnauthenticatedLayout>;
+ }
+
+ // Publishable paths (traces, sessions) when unauthenticated
+ // Render minimal layout without navigation/sidebar
+ if (isPublishable && session.status === "unauthenticated") {
+ return <MinimalLayout>{props.children}</MinimalLayout>;
+ }
+
+ // Render minimal layout (onboarding, public routes)
+ if (hideNavigation) {
+ return <MinimalLayout>{props.children}</MinimalLayout>;
+ }
+
+ // Authenticated layout
+ // At this point, all auth guards have passed and session.data is guaranteed to exist
+ // The authGuard hook ensures we don't reach here without a valid session
+ if (!session.data) {
+ // This should never happen due to guards above, but TypeScript needs this
+ return <LoadingLayout message="Loading" />;
+ }
+
+ const handleSignOut = async () => {
+ sessionStorage.clear();
+ // Redirect to sign-in with current path as targetPath for post-login redirect
+ const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
+ const targetPath = encodeURIComponent(basePath + router.asPath);
+ // explicitly set callbackUrl to avoid error pages when the user is currently on a publishable path without a published entity
+ await signOut({ callbackUrl: `/auth/sign-in?targetPath=${targetPath}` });
+ };
+
+ return (
+ <AuthenticatedLayout
+ session={session.data}
+ navigation={navigation}
+ metadata={metadata}
+ onSignOut={handleSignOut}
+ >
+ {props.children}
+ </AuthenticatedLayout>
+ );
+}
diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.ts
new file mode 100644
index 0000000000..e9db8bd939
--- /dev/null
+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts
@@ -0,0 +1,226 @@
+/**
+ * Composable navigation filter functions
+ * Each filter is a pure function that can be tested in isolation
+ */
+
+import type { Route } from "@/src/components/layouts/routes";
+import type { NavigationFilterContext } from "./navigationFilters.types";
+import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { hasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import type { User } from "next-auth";
+
+/** Organization type from user session (can be null when not in project/org context) */
+type Organization = User["organizations"][number] | null | undefined;
+
+/**
+ * Individual filter functions - each handles one concern
+ * Exported for testing and composition
+ */
+export const filters = {
+ /**
+ * Filter routes that require a project ID when none is available
+ */
+ projectScope: (route: Route, ctx: NavigationFilterContext): Route | null => {
+ if (!ctx.routerProjectId && route.pathname.includes("[projectId]")) {
+ return null;
+ }
+ return route;
+ },
+
+ /**
+ * Filter routes that require an organization ID when none is available
+ */
+ organizationScope: (
+ route: Route,
+ ctx: NavigationFilterContext,
+ ): Route | null => {
+ if (
+ !ctx.routerOrganizationId &&
+ route.pathname.includes("[organizationId]")
+ ) {
+ return null;
+ }
+ return route;
+ },
+
+ /**
+ * Filter routes based on UI customization settings (enterprise feature)
+ * Hides routes if their product module is not in visible modules list
+ */
+ uiCustomization: (
+ route: Route,
+ ctx: NavigationFilterContext,
+ ): Route | null => {
+ if (
+ route.productModule &&
+ ctx.uiCustomization &&
+ !ctx.uiCustomization.visibleModules.includes(route.productModule)
+ ) {
+ return null;
+ }
+ return route;
+ },
+
+ /**
+ * Filter routes based on feature flags
+ * Shows route if:
+ * - No flag requirement
+ * - Experimental features enabled
+ * - User is cloud admin
+ * - User has specific feature flag
+ */
+ featureFlags: (route: Route, ctx: NavigationFilterContext): Route | null => {
+ if (route.featureFlag === undefined) return route;
+
+ const hasFlag =
+ ctx.enableExperimentalFeatures ||
+ ctx.cloudAdmin ||
+ ctx.session?.user?.featureFlags?.[route.featureFlag] === true;
+
+ return hasFlag ? route : null;
+ },
+
+ /**
+ * Filter routes based on plan entitlements
+ * OR logic - user needs at least one of the required entitlements
+ * Cloud admins bypass this check
+ */
+ entitlements: (route: Route, ctx: NavigationFilterContext): Route | null => {
+ if (!route.entitlements || route.entitlements.length === 0) return route;
+
+ // Cloud admins bypass entitlement checks
+ if (ctx.cloudAdmin) return route;
+
+ // OR logic - user needs at least one entitlement
+ const hasEntitlement = route.entitlements.some((ent) =>
+ ctx.entitlements.includes(ent),
+ );
+
+ return hasEntitlement ? route : null;
+ },
+
+ /**
+ * Filter routes based on project-level RBAC scopes
+ * OR logic - user needs at least one of the required scopes
+ * Cloud admins bypass this check
+ */
+ projectRbac: (route: Route, ctx: NavigationFilterContext): Route | null => {
+ if (!route.projectRbacScopes || !ctx.routerProjectId) return route;
+
+ // Cloud admins bypass RBAC checks
+ if (ctx.cloudAdmin) return route;
+
+ // OR logic - user needs at least one scope
+ const hasScope = route.projectRbacScopes.some((scope) =>
+ hasProjectAccess({
+ session: ctx.session,
+ projectId: ctx.routerProjectId!,
+ scope,
+ }),
+ );
+
+ return hasScope ? route : null;
+ },
+
+ /**
+ * Filter routes based on organization-level RBAC scope
+ * Cloud admins bypass this check
+ */
+ organizationRbac: (
+ route: Route,
+ ctx: NavigationFilterContext,
+ ): Route | null => {
+ if (!route.organizationRbacScope || !ctx.routerOrganizationId) return route;
+
+ // Cloud admins bypass RBAC checks
+ if (ctx.cloudAdmin) return route;
+
+ const hasScope = hasOrganizationAccess({
+ session: ctx.session,
+ organizationId: ctx.routerOrganizationId,
+ scope: route.organizationRbacScope,
+ });
+
+ return hasScope ? route : null;
+ },
+
+ /**
+ * Filter routes based on custom show function
+ * Allows routes to implement custom visibility logic
+ */
+ customShow: (
+ route: Route,
+ _ctx: NavigationFilterContext,
+ organization: Organization,
+ ): Route | null => {
+ if (!route.show) return route;
+ // Convert null to undefined for route.show compatibility
+ return route.show({ organization: organization ?? undefined })
+ ? route
+ : null;
+ },
+};
+
+/**
+ * Apply all filters to a single route in sequence
+ * Returns null if any filter rejects the route
+ * Recursively processes nested items
+ */
+function applyFiltersToRoute(
+ route: Route,
+ ctx: NavigationFilterContext,
+ organization: Organization | undefined,
+): Route | null {
+ // Apply filters in sequence - chain short-circuits on first null
+ const filterChain = [
+ filters.projectScope,
+ filters.organizationScope,
+ filters.uiCustomization,
+ filters.featureFlags,
+ filters.entitlements,
+ filters.projectRbac,
+ filters.organizationRbac,
+ (r: Route) => filters.customShow(r, ctx, organization),
+ ];
+
+ let filtered: Route | null = route;
+ for (const filter of filterChain) {
+ filtered = filter(filtered, ctx);
+ if (!filtered) return null;
+ }
+
+ // Process nested items recursively
+ if (filtered.items && filtered.items.length > 0) {
+ const filteredItems = filtered.items
+ .map((item) => applyFiltersToRoute(item, ctx, organization))
+ .filter((item): item is Route => item !== null);
+
+ // If all children were filtered out, hide parent too
+ if (filteredItems.length === 0) {
+ return null;
+ }
+
+ filtered = { ...filtered, items: filteredItems };
+ }
+
+ return filtered;
+}
+
+/**
+ * Main filter function - applies all filters to an array of routes
+ * This is the primary export used by useFilteredNavigation hook
+ *
+ * @param routes - Array of route definitions to filter
+ * @param ctx - Filter context with all necessary data
+ * @param organization - Current organization object
+ * @returns Filtered array of routes visible to current user
+ */
+export function applyNavigationFilters(
+ routes: Route[],
+ ctx: NavigationFilterContext,
+ organization: Organization,
+): Route[] {
+ return routes
+ .map((route) => applyFiltersToRoute(route, ctx, organization))
+ .filter((route): route is Route => route !== null);
+}
diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.types.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.types.ts
new file mode 100644
index 0000000000..1746602dee
--- /dev/null
+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.types.ts
@@ -0,0 +1,39 @@
+/**
+ * Type definitions for navigation filtering system
+ */
+
+import type { Session } from "next-auth";
+import type { Route } from "@/src/components/layouts/routes";
+import type { Entitlement } from "@/src/features/entitlements/constants/entitlements";
+
+/**
+ * Context object containing all data needed for navigation filtering
+ * Passed to each filter function to determine route visibility
+ */
+export type NavigationFilterContext = {
+ /** Current project ID from router query params */
+ routerProjectId: string | undefined;
+ /** Current organization ID from router query params */
+ routerOrganizationId: string | undefined;
+ /** User session data including user info and environment */
+ session: Session | null;
+ /** Whether experimental features are enabled globally */
+ enableExperimentalFeatures: boolean;
+ /** Whether user is a cloud admin (bypasses most checks) */
+ cloudAdmin: boolean;
+ /** Plan-based entitlements available to current user/org */
+ entitlements: Entitlement[];
+ /** UI customization settings (enterprise feature) */
+ uiCustomization: { visibleModules: string[] } | null;
+ /** Current router path for active state detection */
+ currentPath: string;
+};
+
+/**
+ * Filter function that processes a route and returns it (if visible) or null (if hidden)
+ * Filters are composable and should be pure functions
+ */
+export type NavigationFilter = (
+ route: Route,
+ context: NavigationFilterContext,
+) => Route | null;
diff --git a/web/src/components/layouts/app-layout/utils/pathClassification.ts b/web/src/components/layouts/app-layout/utils/pathClassification.ts
new file mode 100644
index 0000000000..23a2ec972b
--- /dev/null
+++ b/web/src/components/layouts/app-layout/utils/pathClassification.ts
@@ -0,0 +1,104 @@
+/**
+ * Path classification utilities for layout routing
+ * Determines which layout variant to render based on current path
+ */
+
+export const PATH_CONSTANTS = {
+ withoutNavigation: ["/onboarding", "/auth/reset-password"] as const,
+ unauthenticated: [
+ "/auth/sign-in",
+ "/auth/sign-up",
+ "/auth/sso-initiate",
+ "/auth/error",
+ "/auth/hf-spaces",
+ ] as const,
+ publishable: [
+ "/project/[projectId]/sessions/[sessionId]",
+ "/project/[projectId]/traces/[traceId]",
+ "/auth/reset-password",
+ ] as const,
+};
+
+export type LayoutType =
+ | "loading"
+ | "unauthenticated"
+ | "minimal"
+ | "authenticated";
+
+/**
+ * Result of path classification
+ * Used by useLayoutConfiguration to determine the final layout
+ */
+export type PathClassification = {
+ /** Whether this is an auth page (sign-in, sign-up, etc.) */
+ isAuthPage: boolean;
+ /** Whether navigation should be hidden (public, onboarding, auth pages) */
+ hideNavigation: boolean;
+ /** Whether this path can be accessed without authentication (shared traces/sessions) */
+ isPublishable: boolean;
+};
+
+/**
+ * Classifies the current path to provide layout hints
+ * The final layout decision is made in useLayoutConfiguration based on
+ * both path classification AND session state.
+ */
+export function classifyPath(
+ pathname: string,
+ _asPath: string,
+): PathClassification {
+ const isPublicPath = pathname.startsWith("/public/");
+ const isWithoutNavigation = PATH_CONSTANTS.withoutNavigation.some((path) =>
+ pathname.startsWith(path),
+ );
+ const isAuthPage = PATH_CONSTANTS.unauthenticated.some((path) =>
+ pathname.startsWith(path),
+ );
+ // Check if path is publishable (can be accessed without authentication)
+ const isPublishable = PATH_CONSTANTS.publishable.some((path) => {
+ // Case 1: Exact match (e.g., pathname === "/auth/reset-password")
+ if (pathname === path) return true;
+
+ // Case 2: Prefix match for dynamic routes
+ // Example: path = "/project/[projectId]/traces/[traceId]"
+ // -> pathPrefix = "/project/[^/]+/traces" (last segment removed, params converted to regex)
+ // -> matches pathname like "/project/abc123/traces/xyz789"
+ // This allows shared trace/session links to be accessed without authentication
+ const pathPrefix = path
+ .split("/")
+ .slice(0, -1)
+ .join("/")
+ .replace(/\[([^\]]+)\]/g, "[^/]+");
+ const prefixRegex = new RegExp(`^${pathPrefix}/`);
+ return prefixRegex.test(pathname);
+ });
+
+ // Determine if navigation should be hidden
+ const hideNavigation = isPublicPath || isWithoutNavigation || isAuthPage;
+
+ return {
+ isAuthPage,
+ hideNavigation,
+ isPublishable,
+ };
+}
+
+/**
+ * Determines if a route path is currently active
+ * Handles exact matches and prefix matching with special logic for root paths
+ *
+ * @param routePath - The route path pattern (e.g., "/project/[projectId]/traces")
+ * @param currentPath - The current router path
+ * @returns true if the route should be highlighted as active
+ */
+export function isPathActive(routePath: string, currentPath: string): boolean {
+ // Exact match
+ if (currentPath === routePath) return true;
+
+ // Only allow prefix matching if the route ends with a specific page (not just project root)
+ // This prevents /project/123 from matching /project/123/datasets
+ const isRoot = routePath.split("/").length <= 3;
+ if (isRoot) return false;
+
+ return currentPath.startsWith(routePath + "/");
+}
diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
new file mode 100644
index 0000000000..0c4d37dd9d
--- /dev/null
+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
@@ -0,0 +1,119 @@
+/**
+ * Authenticated layout variant
+ * Full application layout with sidebar, navigation, support drawer, and payment banner
+ * Used for all main application pages when user is authenticated
+ */
+
+import type { PropsWithChildren } from "react";
+import Head from "next/head";
+import { SidebarProvider, SidebarInset } from "@/src/components/ui/sidebar";
+import { AppSidebar } from "@/src/components/nav/app-sidebar";
+import { CommandMenu } from "@/src/features/command-k-menu/CommandMenu";
+import { Toaster } from "@/src/components/ui/sonner";
+import {
+ PaymentBanner,
+ PaymentBannerProvider,
+} from "@/src/features/payment-banner";
+import { ResizableContent } from "../components/ResizableContent";
+import { ThemeToggle } from "@/src/features/theming/ThemeToggle";
+import type { Session } from "next-auth";
+import type { NavigationItem } from "@/src/components/layouts/utilities/routes";
+import type { RouteGroup } from "@/src/components/layouts/routes";
+
+/** Grouped navigation structure returned by processNavigation */
+type GroupedNavigation = {
+ ungrouped: NavigationItem[];
+ grouped: Partial<Record<RouteGroup, NavigationItem[]>> | null;
+ flattened: NavigationItem[];
+};
+
+type AuthenticatedLayoutProps = PropsWithChildren<{
+ session: Session;
+ navigation: {
+ mainNavigation: GroupedNavigation;
+ secondaryNavigation: GroupedNavigation;
+ navigation: NavigationItem[];
+ };
+ metadata: {
+ title: string;
+ faviconPath: string;
+ favicon256Path: string;
+ appleTouchIconPath: string;
+ };
+ onSignOut: () => void;
+}>;
+
+/**
+ * Full authenticated layout with all features:
+ * - AppSidebar with navigation
+ * - Payment banner (conditional)
+ * - Support drawer
+ * - Command menu (Cmd/Ctrl+K)
+ * - Toast notifications
+ * - Dynamic page metadata
+ */
+export function AuthenticatedLayout({
+ children,
+ session,
+ navigation,
+ metadata,
+ onSignOut,
+}: AuthenticatedLayoutProps) {
+ // Safe assertion: AuthenticatedLayout is only rendered after auth checks pass
+ // in AppLayout, which guarantees session.user exists at this point
+ const user = session.user;
+ if (!user) {
+ // This should never happen due to guards in AppLayout, but TypeScript needs this
+ return null;
+ }
+
+ // User navigation items for sidebar dropdown
+ const userNavProps = {
+ user: {
+ name: user.name ?? "",
+ email: user.email ?? "",
+ avatar: user.image ?? "",
+ },
+ items: [
+ { name: "Account Settings", href: "/account/settings" },
+ { name: "Theme", onClick: () => {}, content: <ThemeToggle /> },
+ { name: "Sign out", onClick: onSignOut },
+ ],
+ };
+
+ return (
+ <>
+ <Head>
+ <title>{metadata.title}</title>
+ <link rel="icon" type="image/svg+xml" href={metadata.faviconPath} />
+ <link
+ rel="icon"
+ type="image/png"
+ sizes="256x256"
+ href={metadata.favicon256Path}
+ />
+ <link rel="apple-touch-icon" href={metadata.appleTouchIconPath} />
+ </Head>
+
+ <PaymentBannerProvider>
+ <SidebarProvider>
+ <div className="flex h-dvh w-full flex-col">
+ <PaymentBanner />
+ <div className="flex min-h-0 flex-1 pt-banner-offset">
+ <AppSidebar
+ navItems={navigation.mainNavigation}
+ secondaryNavItems={navigation.secondaryNavigation}
+ userNavProps={userNavProps}
+ />
+ <SidebarInset className="h-screen-with-banner max-w-full md:peer-data-[state=collapsed]:w-[calc(100vw-var(--sidebar-width-icon))] md:peer-data-[state=expanded]:w-[calc(100vw-var(--sidebar-width))]">
+ <ResizableContent>{children}</ResizableContent>
+ <Toaster visibleToasts={1} />
+ <CommandMenu mainNavigation={navigation.navigation} />
+ </SidebarInset>
+ </div>
+ </div>
+ </SidebarProvider>
+ </PaymentBannerProvider>
+ </>
+ );
+}
diff --git a/web/src/components/layouts/app-layout/variants/LoadingLayout.tsx b/web/src/components/layouts/app-layout/variants/LoadingLayout.tsx
new file mode 100644
index 0000000000..b44016763f
--- /dev/null
+++ b/web/src/components/layouts/app-layout/variants/LoadingLayout.tsx
@@ -0,0 +1,14 @@
+/**
+ * Loading layout variant
+ * Shown during session loading and authentication redirects
+ */
+
+import { Spinner } from "@/src/components/layouts/spinner";
+
+type LoadingLayoutProps = {
+ message?: string;
+};
+
+export function LoadingLayout({ message = "Loading" }: LoadingLayoutProps) {
+ return <Spinner message={message} />;
+}
diff --git a/web/src/components/layouts/app-layout/variants/MinimalLayout.tsx b/web/src/components/layouts/app-layout/variants/MinimalLayout.tsx
new file mode 100644
index 0000000000..686c8906a9
--- /dev/null
+++ b/web/src/components/layouts/app-layout/variants/MinimalLayout.tsx
@@ -0,0 +1,18 @@
+/**
+ * Minimal layout variant
+ * Used for onboarding, public routes, and other pages without navigation
+ * Similar to unauthenticated but semantically different use case
+ */
+
+import type { PropsWithChildren } from "react";
+import { SidebarProvider } from "@/src/components/ui/sidebar";
+
+export function MinimalLayout({ children }: PropsWithChildren) {
+ return (
+ <SidebarProvider className="bg-primary-foreground">
+ <main className="min-h-dvh w-full overflow-y-scroll p-3 px-4 py-4 sm:px-6 lg:px-8">
+ {children}
+ </main>
+ </SidebarProvider>
+ );
+}
diff --git a/web/src/components/layouts/app-layout/variants/UnauthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/UnauthenticatedLayout.tsx
new file mode 100644
index 0000000000..1f01558eb7
--- /dev/null
+++ b/web/src/components/layouts/app-layout/variants/UnauthenticatedLayout.tsx
@@ -0,0 +1,18 @@
+/**
+ * Unauthenticated layout variant
+ * Used for sign-in, sign-up, and other auth pages
+ * Minimal layout with no sidebar or navigation
+ */
+
+import type { PropsWithChildren } from "react";
+import { SidebarProvider } from "@/src/components/ui/sidebar";
+
+export function UnauthenticatedLayout({ children }: PropsWithChildren) {
+ return (
+ <SidebarProvider className="bg-primary-foreground">
+ <main className="min-h-dvh w-full overflow-y-scroll p-3 px-4 py-4 sm:px-6 lg:px-8">
+ {children}
+ </main>
+ </SidebarProvider>
+ );
+}
diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsx
deleted file mode 100644
index b5745182aa..0000000000
--- a/web/src/components/layouts/layout.tsx
+++ /dev/null
@@ -1,483 +0,0 @@
-import { type Route } from "@/src/components/layouts/routes";
-import {
- type PropsWithChildren,
- useEffect,
- useLayoutEffect,
- useRef,
- useState,
-} from "react";
-import { useRouter } from "next/router";
-import { getSession, signOut, useSession } from "next-auth/react";
-import Head from "next/head";
-import { env } from "@/src/env.mjs";
-import { Spinner } from "@/src/components/layouts/spinner";
-import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { Toaster } from "@/src/components/ui/sonner";
-import { ThemeToggle } from "@/src/features/theming/ThemeToggle";
-import { getSafeRedirectPath } from "@/src/utils/redirect";
-import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
-import { useEntitlements } from "@/src/features/entitlements/hooks";
-import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
-import { hasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
-import { SidebarInset, SidebarProvider } from "@/src/components/ui/sidebar";
-import { AppSidebar } from "@/src/components/nav/app-sidebar";
-import { CommandMenu } from "@/src/features/command-k-menu/CommandMenu";
-import { SupportDrawer } from "@/src/features/support-chat/SupportDrawer";
-import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
-import {
- ResizableHandle,
- ResizablePanel,
- ResizablePanelGroup,
- type ImperativePanelHandle,
-} from "@/src/components/ui/resizable";
-import {
- PaymentBanner,
- PaymentBannerProvider,
-} from "@/src/features/payment-banner";
-import {
- Drawer,
- DrawerContent,
- DrawerDescription,
- DrawerHeader,
- DrawerTitle,
-} from "@/src/components/ui/drawer";
-import { useMediaQuery } from "react-responsive";
-import {
- processNavigation,
- type NavigationItem,
-} from "@/src/components/layouts/utilities/routes";
-import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
-import { ErrorPageWithSentry } from "@/src/components/error-page";
-
-const signOutUser = async () => {
- sessionStorage.clear();
-
- await signOut();
-};
-
-const getUserNavigation = () => {
- return [
- {
- name: "Account Settings",
- href: "/account/settings",
- },
- {
- name: "Theme",
- onClick: () => {},
- content: <ThemeToggle />,
- },
- {
- name: "Sign out",
- onClick: signOutUser,
- },
- ];
-};
-
-const pathsWithoutNavigation: string[] = [
- "/onboarding",
- "/auth/reset-password",
-];
-const unauthenticatedPaths: string[] = [
- "/auth/sign-in",
- "/auth/sign-up",
- "/auth/sso-initiate",
- "/auth/error",
- "/auth/hf-spaces",
-];
-// auth or unauthed
-const publishablePaths: string[] = [
- "/project/[projectId]/sessions/[sessionId]",
- "/project/[projectId]/traces/[traceId]",
- "/auth/reset-password",
-];
-
-/**
- * Patched version of useSession that retries fetching the session if the user
- * is unauthenticated. This is useful to mitigate exceptions on the
- * /api/auth/session endpoint which cause the session to be unauthenticated even
- * though the user is signed in.
- */
-function useSessionWithRetryOnUnauthenticated() {
- const MAX_RETRIES = 2;
- const [retryCount, setRetryCount] = useState(0);
- const session = useSession();
-
- useEffect(() => {
- if (session.status === "unauthenticated" && retryCount < MAX_RETRIES) {
- const fetchSession = async () => {
- try {
- await getSession({ broadcast: true });
- } catch (error) {
- console.error(
- "Error fetching session:",
- error,
- "\nError details:",
- JSON.stringify(error, null, 2),
- );
- throw error;
- }
- setRetryCount((prevCount) => prevCount + 1);
- };
- fetchSession();
- }
- if (session.status === "authenticated" && retryCount > 0) {
- setRetryCount(0);
- }
- }, [session.status, retryCount]);
-
- return session.status !== "unauthenticated" || retryCount >= MAX_RETRIES
- ? session
- : { ...session, status: "loading" };
-}
-
-export default function Layout(props: PropsWithChildren) {
- const router = useRouter();
- const routerProjectId = router.query.projectId as string | undefined;
- const routerOrganizationId = router.query.organizationId as
- | string
- | undefined;
- const session = useSessionWithRetryOnUnauthenticated();
- const { isLangfuseCloud, region } = useLangfuseCloudRegion();
-
- const enableExperimentalFeatures =
- session.data?.environment.enableExperimentalFeatures ?? false;
-
- const entitlements = useEntitlements();
-
- const uiCustomization = useUiCustomization();
-
- const cloudAdmin = isLangfuseCloud && session.data?.user?.admin === true;
-
- // project info based on projectId in the URL
- const { project, organization } = useQueryProjectOrOrganization();
-
- // Check project access from session data (client-side)
- const userProjects =
- session.data?.user?.organizations
- ?.flatMap((org) => org?.projects?.map((project) => project?.id))
- .filter(Boolean) ?? [];
- const userHasProjectAccess =
- !routerProjectId ||
- userProjects.includes(routerProjectId) ||
- session.data?.user?.admin === true;
-
- // Helper function for precise path matching
- const isPathActive = (routePath: string, currentPath: string): boolean => {
- // Exact match
- if (currentPath === routePath) return true;
-
- // Only allow prefix matching if the route ends with a specific page (not just project root)
- // This prevents /project/123 from matching /project/123/datasets
- const isRoot = routePath.split("/").length <= 3;
- if (isRoot) return false;
-
- return currentPath.startsWith(routePath + "/");
- };
-
- const mapNavigation = (route: Route): NavigationItem | null => {
- // Project-level routes
- if (!routerProjectId && route.pathname.includes("[projectId]")) return null;
- // Organization-level routes
- if (!routerOrganizationId && route.pathname.includes("[organizationId]"))
- return null;
-
- // UI customization – hide routes that belong to a disabled product module
- if (
- route.productModule &&
- uiCustomization !== null &&
- !uiCustomization.visibleModules.includes(route.productModule)
- )
- return null;
-
- // Feature Flags
- if (
- route.featureFlag !== undefined &&
- !enableExperimentalFeatures &&
- !cloudAdmin &&
- session.data?.user?.featureFlags[route.featureFlag] !== true
- )
- return null;
-
- // check entitlements
- if (
- route.entitlements !== undefined &&
- !route.entitlements.some((entitlement) =>
- entitlements.includes(entitlement),
- ) &&
- !cloudAdmin
- )
- return null;
-
- // RBAC
- if (
- route.projectRbacScopes !== undefined &&
- !cloudAdmin &&
- (!project ||
- !organization ||
- !route.projectRbacScopes.some((scope) =>
- hasProjectAccess({
- projectId: project.id,
- scope,
- session: session.data,
- }),
- ))
- )
- return null;
- if (
- route.organizationRbacScope !== undefined &&
- !cloudAdmin &&
- (!organization ||
- !hasOrganizationAccess({
- organizationId: organization.id,
- scope: route.organizationRbacScope,
- session: session.data,
- }))
- )
- return null;
-
- // check show function
- if (route.show && !route.show({ organization: organization ?? undefined }))
- return null;
-
- // apply to children as well
- const items: (NavigationItem | null)[] =
- route.items?.map((item) => mapNavigation(item)).filter(Boolean) ?? [];
-
- const url = route.pathname
-
- ?.replace("[projectId]", routerProjectId ?? "")
- .replace("[organizationId]", routerOrganizationId ?? "");
-
- return {
- ...route,
- url: url,
- isActive: isPathActive(route.pathname, router.pathname),
- items:
- items.length > 0
- ? (items as NavigationItem[]) // does not include null due to filter
- : undefined,
- };
- };
-
- // Process navigation using the dedicated utility
- const { mainNavigation, secondaryNavigation, navigation } =
- processNavigation(mapNavigation);
-
- const activePathName = navigation.find((item) => item.isActive)?.title;
-
- if (session.status === "loading") return <Spinner message="Loading" />;
-
- // If the user has a token, but does not exist in the database, sign them out
- if (
- session.data &&
- session.data.user === null &&
- !unauthenticatedPaths.includes(router.pathname) &&
- !publishablePaths.includes(router.pathname) &&
- !router.pathname.startsWith("/public/")
- ) {
- console.warn("Layout: User was signed out as db user was not found");
- signOutUser();
-
- return <Spinner message="Redirecting" />;
- }
-
- if (
- session.status === "unauthenticated" &&
- !unauthenticatedPaths.includes(router.pathname) &&
- !publishablePaths.includes(router.pathname) &&
- !router.pathname.startsWith("/public/")
- ) {
- const newTargetPath = router.asPath;
- if (newTargetPath && newTargetPath !== "/") {
- void router.replace(
- `/auth/sign-in?targetPath=${encodeURIComponent(newTargetPath)}`,
- );
- } else {
- void router.replace(`/auth/sign-in`);
- }
- return <Spinner message="Redirecting" />;
- }
-
- if (
- session.status === "authenticated" &&
- unauthenticatedPaths.includes(router.pathname)
- ) {
- const queryTargetPath = router.query.targetPath as string | undefined;
- const targetPath = getSafeRedirectPath(queryTargetPath);
-
- void router.replace(targetPath);
- return <Spinner message="Redirecting" />;
- }
-
- // Handle project access verification failure (client-side check)
- if (
- session.status === "authenticated" &&
- session.data &&
- routerProjectId &&
- router.pathname.includes("[projectId]") &&
- !userHasProjectAccess
- ) {
- return (
- <ErrorPageWithSentry
- title="Project Not Found"
- message="The project you are trying to access does not exist or you do not have access to it."
- additionalButton={{
- label: "Go to Home",
- href: "/",
- }}
- />
- );
- }
-
- const hideNavigation =
- session.status === "unauthenticated" ||
- pathsWithoutNavigation.includes(router.pathname) ||
- router.pathname.startsWith("/public/");
-
- if (hideNavigation) {
- return (
- <SidebarProvider className="bg-primary-foreground">
- <main className="min-h-dvh w-full overflow-y-scroll p-3 px-4 py-4 sm:px-6 lg:px-8">
- {props.children}
- </main>
- </SidebarProvider>
- );
- }
-
- return (
- <>
- <Head>
- <title>
- {activePathName ? `${activePathName} | Langfuse` : "Langfuse"}
- </title>
- <link
- rel="apple-touch-icon"
- sizes="180x180"
- href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/apple-touch-icon.png`}
- />
- <link
- rel="icon"
- type="image/png"
- sizes="32x32"
- href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/favicon-32x32${region === "DEV" ? "-dev" : ""}.png`}
- />
- <link
- rel="icon"
- type="image/png"
- sizes="16x16"
- href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/favicon-16x16${region === "DEV" ? "-dev" : ""}.png`}
- />
- </Head>
- <PaymentBannerProvider>
- <SidebarProvider>
- <div className="flex h-dvh w-full flex-col">
- <PaymentBanner />
- <div className="flex min-h-0 flex-1 pt-banner-offset">
- <AppSidebar
- navItems={mainNavigation}
- secondaryNavItems={secondaryNavigation}
- userNavProps={{
- items: getUserNavigation(),
- user: {
- name: session.data?.user?.name ?? "",
- email: session.data?.user?.email ?? "",
- avatar: session.data?.user?.image ?? "",
- },
- }}
- />
- <SidebarInset className="h-screen-with-banner max-w-full md:peer-data-[state=collapsed]:w-[calc(100vw-var(--sidebar-width-icon))] md:peer-data-[state=expanded]:w-[calc(100vw-var(--sidebar-width))]">
- <ResizableContent>{props.children}</ResizableContent>
- <Toaster visibleToasts={1} />
- <CommandMenu mainNavigation={navigation} />
- </SidebarInset>
- </div>
- </div>
- </SidebarProvider>
- </PaymentBannerProvider>
- </>
- );
-}
-
-/** Resizable content for support drawer on the right side of the screen (desktop).
- * On mobile, renders a Drawer instead of a resizable sidebar.
- */
-export function ResizableContent({ children }: PropsWithChildren) {
- const { open, setOpen } = useSupportDrawer();
- const isDesktop = useMediaQuery({ query: "(min-width: 768px)" });
-
- // 👉 DESKTOP: Always render ResizablePanelGroup to prevent remounting children
- // Use refs to programmatically control panel sizes when drawer opens/closes
- const drawerPanelRef = useRef<ImperativePanelHandle>(null);
- const mainPanelRef = useRef<ImperativePanelHandle>(null);
-
- useLayoutEffect(() => {
- if (!isDesktop) return;
-
- if (open) {
- // Open drawer: resize main to 70%, drawer to 30%
- drawerPanelRef.current?.resize(30);
- mainPanelRef.current?.resize(70);
- } else {
- // Close drawer: resize main to 100%, drawer to 0%
- drawerPanelRef.current?.resize(0);
- mainPanelRef.current?.resize(100);
- }
- }, [open, isDesktop]);
-
- if (!isDesktop) {
- return (
- <>
- <main className="h-full flex-1" style={{ overscrollBehaviorY: "none" }}>
- {children}
- </main>
-
- <Drawer open={open} onOpenChange={setOpen} forceDirection="bottom">
- <DrawerContent
- id="support-drawer"
- className="inset-x-0 bottom-0 top-[calc(var(--banner-offset)+10px)] min-h-screen-with-banner"
- 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="h-2 w-20 rounded-full bg-muted" />
- </div>
- {/* sr-only for screen readers and accessibility */}
- <DrawerTitle className="sr-only">Support</DrawerTitle>
- <DrawerDescription className="sr-only">
- A list of resources and options to help you with your questions.
- </DrawerDescription>
- </DrawerHeader>
- <div className="mt-4 max-h-full">
- <SupportDrawer showCloseButton={false} className="h-full pb-20" />
- </div>
- </DrawerContent>
- </Drawer>
- </>
- );
- }
-
- // 👉 DESKTOP: Always render ResizablePanelGroup to prevent remounting children
- return (
- <ResizablePanelGroup direction="horizontal" className="flex h-full w-full">
- <ResizablePanel ref={mainPanelRef} defaultSize={100} minSize={30}>
- <main
- className="relative h-full w-full overflow-scroll"
- style={{ overscrollBehaviorY: "none" }}
- >
- {children}
- </main>
- </ResizablePanel>
- {open && <ResizableHandle withHandle />}
- <ResizablePanel
- ref={drawerPanelRef}
- defaultSize={0}
- minSize={0}
- maxSize={60}
- collapsible={true}
- collapsedSize={0}
- >
- {open && <SupportDrawer />}
- </ResizablePanel>
- </ResizablePanelGroup>
- );
-}
diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.ts
index 7cb8081add..6fe82646d8 100644
--- a/web/src/ee/features/billing/server/stripeBillingService.ts
+++ b/web/src/ee/features/billing/server/stripeBillingService.ts
@@ -680,7 +680,7 @@ class BillingService {
};
const sessionConfig: Stripe.Checkout.SessionCreateParams = {
- customer: stripeCustomerId,
+ customer: stripeCustomerId ?? undefined,
line_items: lineItems,
client_reference_id: clientReferenceId,
allow_promotion_codes: true,
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsx
index 05f2dcdf24..522f2b7a47 100644
--- a/web/src/pages/_app.tsx
+++ b/web/src/pages/_app.tsx
@@ -12,7 +12,7 @@ import NextAdapterPages from "next-query-params/pages";
import { QueryParamProvider } from "use-query-params";
import "@/src/styles/globals.css";
-import Layout from "@/src/components/layouts/layout";
+import { AppLayout } from "@/src/components/layouts/app-layout";
import { useEffect, useRef } from "react";
import { useRouter } from "next/router";
@@ -143,10 +143,10 @@ const MyApp: AppType<{ session: Session | null }> = ({
>
<ScoreCacheProvider>
<SupportDrawerProvider defaultOpen={false}>
- <Layout>
+ <AppLayout>
<Component {...pageProps} />
<UserTracking />
- </Layout>
+ </AppLayout>
</SupportDrawerProvider>
<BetterStackUptimeStatusMessage />
</ScoreCacheProvider>