🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(auth): keep the page mounted through a session re-check (LFE-14949) (#16041)
Nikita Kabardin3ae055d70634
diff --git a/web/src/components/layouts/app-layout/hooks/useAuthSession.ts b/web/src/components/layouts/app-layout/hooks/useAuthSession.tsdeleted file mode 100644index d0c2231d2f..0000000000--- a/web/src/components/layouts/app-layout/hooks/useAuthSession.ts+++ /dev/null@@ -1,51 +0,0 @@-/**- * 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);- };- 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/index.tsx b/web/src/components/layouts/app-layout/index.tsxindex 06d8ece397..08a1b98796 100644--- a/web/src/components/layouts/app-layout/index.tsx+++ b/web/src/components/layouts/app-layout/index.tsx@@ -11,7 +11,7 @@import { type PropsWithChildren, useEffect } from "react";import { useRouter } from "next/router";-import { signOut } from "next-auth/react";+import { signOut, useSession } from "next-auth/react";import { signOutCleanly } from "@/src/features/auth/lib/signOut";import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";import { ErrorPage } from "@/src/components/error-page";@@ -23,7 +23,6 @@ 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";@@ -40,23 +39,29 @@ import { useLayoutMetadata } from "./hooks/useLayoutMetadata";*/export function AppLayout(props: PropsWithChildren) {const router = useRouter();- const session = useAuthSession();+ const session = useSession();const { organization } = useQueryProjectOrOrganization();+ // `session.update()` reports `loading` with the previous session still in+ // hand. Rendering the loading layout for that replaces `children` and throws+ // away everything unsaved in them, so keep the shell that is already on+ // screen; only a cold load has no session to keep showing.+ const sessionData = session.data ?? null;+ const isRecheckingSession = session.status === "loading" && !!sessionData;+// Determine layout configuration- const { variant, hideNavigation, isPublishable } = useLayoutConfiguration(- session.data ?? null,- );+ const { variant, hideNavigation, isPublishable } =+ useLayoutConfiguration(sessionData);// Check authentication and redirectsconst authGuard = useAuthGuard(session, hideNavigation);// Check project access- const projectAccess = useProjectAccess(session.data ?? null);+ const projectAccess = useProjectAccess(sessionData);// 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 navigation = useFilteredNavigation(sessionData, organization);const activePathName = navigation.navigation.find((item) => item.isActive,)?.title;@@ -71,16 +76,19 @@ export function AppLayout(props: PropsWithChildren) {}}, [authGuard, router]);- // Loading or redirecting state+ // Loading or redirecting state. Loading only applies to a cold load: once a+ // shell has rendered, a re-check keeps it instead of unmounting it.if (- authGuard.action === "loading" ||+ (authGuard.action === "loading" && !isRecheckingSession) ||authGuard.action === "redirect" ||authGuard.action === "sign-out") {return <LoadingLayout message={authGuard.message} />;}- // Project access denied - handle based on path type+ // Project access denied - handle based on path type. Only a settled session+ // can rule a project out: while one is in flight the URL can legitimately+ // point at a project the previous session did not have yet (just created).if (session.status === "authenticated" && !projectAccess.hasAccess) {// For publishable paths (shared traces/sessions), render minimal layout without sidebar// This allows authenticated users to view shared content without seeing project navigation@@ -125,14 +133,14 @@ export function AppLayout(props: PropsWithChildren) {// 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) {+ if (!sessionData) {// This should never happen due to guards above, but TypeScript needs thisreturn <LoadingLayout message="Loading" />;}return (<AuthenticatedLayout- session={session.data}+ session={sessionData}navigation={navigation}metadata={metadata}onSignOut={signOutCleanly}diff --git a/web/src/features/auth/components/ResilientSessionProvider.clienttest.tsx b/web/src/features/auth/components/ResilientSessionProvider.clienttest.tsxnew file mode 100644index 0000000000..8d45dd9452--- /dev/null+++ b/web/src/features/auth/components/ResilientSessionProvider.clienttest.tsx@@ -0,0 +1,150 @@+import { act, render, screen } from "@testing-library/react";+import { useContext } from "react";+import type { MockInstance } from "vitest";+import type { Session } from "next-auth";+import { SessionContext, type SessionContextValue } from "next-auth/react";+import type * as nextAuthReactModule from "next-auth/react";++import { ResilientSessionProvider } from "@/src/features/auth/components/ResilientSessionProvider";++const { useSessionMock } = vi.hoisted(() => ({ useSessionMock: vi.fn() }));++vi.mock("next-auth/react", async (importOriginal) => {+ const actual = await importOriginal<typeof nextAuthReactModule>();+ return { ...actual, useSession: useSessionMock };+});++const authenticated = (email: string): SessionContextValue => ({+ data: { user: { email }, expires: "2999-01-01" } as unknown as Session,+ status: "authenticated",+ update: vi.fn(),+});++const noSession: SessionContextValue = {+ data: null,+ status: "unauthenticated",+ update: vi.fn(),+};++/** Stands in for every session consumer: next-auth's useSession reads this context. */+function SessionReadout() {+ const session = useContext(SessionContext);+ return (+ <>+ <span data-testid="session">+ {`${session?.status}:${session?.data?.user?.email ?? "none"}`}+ </span>+ <button+ onClick={() => {+ session?.update();+ }}+ >+ refresh session+ </button>+ </>+ );+}++const tree = () => (+ <ResilientSessionProvider basePath="/api/auth">+ <SessionReadout />+ </ResilientSessionProvider>+);++type DispatchSpy = MockInstance<(event: Event) => boolean>;++const storageKicks = (dispatch: DispatchSpy) =>+ dispatch.mock.calls.filter(+ ([event]) =>+ event instanceof StorageEvent && event.key === "nextauth.message",+ ).length;++/** The session endpoint's two answers, plus not answering at all. */+const endpointSays = (body: Record<string, unknown>) =>+ vi.fn().mockResolvedValue({ ok: true, json: async () => body });+const endpointUnreachable = () =>+ vi.fn().mockRejectedValue(new Error("Failed to fetch"));++/** Runs the pending re-check timer and lets its probe resolve. */+const advanceRecheck = (ms: number) =>+ act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });++describe("ResilientSessionProvider", () => {+ let dispatch: DispatchSpy;++ beforeEach(() => {+ vi.useFakeTimers();+ useSessionMock.mockReset();+ dispatch = vi.spyOn(window, "dispatchEvent");+ vi.stubGlobal("fetch", endpointSays({}));+ });++ afterEach(() => {+ dispatch.mockRestore();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it("keeps the last session while re-checking, and asks next-auth to re-fetch", async () => {+ useSessionMock.mockReturnValue(authenticated("[email protected]"));+ const { rerender } = render(tree());+ expect(screen.getByTestId("session")).toHaveTextContent(+ "authenticated:[email protected]",+ );++ // A blip: next-auth reports no session, so consumers would unmount.+ useSessionMock.mockReturnValue(noSession);+ await act(async () => rerender(tree()));+ expect(screen.getByTestId("session")).toHaveTextContent(+ "authenticated:[email protected]",+ );+ expect(storageKicks(dispatch)).toBe(1);++ // next-auth would drop an update() here, so it becomes a re-read instead.+ await act(async () => {+ screen.getByRole("button", { name: "refresh session" }).click();+ });+ expect(storageKicks(dispatch)).toBe(2);++ // The re-fetch lands, so the real session takes over again.+ useSessionMock.mockReturnValue(authenticated("[email protected]"));+ await act(async () => rerender(tree()));+ expect(screen.getByTestId("session")).toHaveTextContent(+ "authenticated:[email protected]",+ );+ });++ it("reports unauthenticated when the server says the session is gone", async () => {+ useSessionMock.mockReturnValue(authenticated("[email protected]"));+ const { rerender } = render(tree());++ useSessionMock.mockReturnValue(noSession);+ await act(async () => rerender(tree()));+ await advanceRecheck(400);++ expect(screen.getByTestId("session")).toHaveTextContent(+ "unauthenticated:none",+ );+ });++ it("never signs the user out while the session endpoint is unreachable", async () => {+ vi.stubGlobal("fetch", endpointUnreachable());+ useSessionMock.mockReturnValue(authenticated("[email protected]"));+ const { rerender } = render(tree());++ useSessionMock.mockReturnValue(noSession);+ await act(async () => rerender(tree()));++ // Long past every re-check, with the endpoint still refusing to answer.+ for (const ms of [400, 800, 1600, 3200, 10_000, 10_000]) {+ await advanceRecheck(ms);+ }++ expect(screen.getByTestId("session")).toHaveTextContent(+ "authenticated:[email protected]",+ );+ expect(storageKicks(dispatch)).toBeGreaterThan(2);+ });+});diff --git a/web/src/features/auth/components/ResilientSessionProvider.tsx b/web/src/features/auth/components/ResilientSessionProvider.tsxnew file mode 100644index 0000000000..d616e7e28c--- /dev/null+++ b/web/src/features/auth/components/ResilientSessionProvider.tsx@@ -0,0 +1,138 @@+import { type Session } from "next-auth";+import {+ SessionContext,+ useSession,+ type SessionContextValue,+} from "next-auth/react";+import {+ type PropsWithChildren,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";++/** Delay before re-checking a session that went missing, doubling up to the cap. */+const RECHECK_DELAY_MS = 400;+const MAX_RECHECK_DELAY_MS = 10_000;++const recheckDelay = (attempt: number) =>+ Math.min(RECHECK_DELAY_MS * 2 ** attempt, MAX_RECHECK_DELAY_MS);++/**+ * Asks next-auth's SessionProvider to re-fetch the session.+ *+ * Once its session is null the provider stops re-fetching on its own: the+ * window-focus and poll paths both bail out, and the exported `getSession()`+ * never writes back into provider state. Its cross-tab broadcast is the one+ * path that re-fetches a null session, so replay that message in this tab. If+ * next-auth ever renames the channel this becomes a no-op and we keep serving+ * the last known session, which is better than the sign-out it replaces.+ */+function refetchSessionInProvider() {+ window.dispatchEvent(+ new StorageEvent("storage", {+ key: "nextauth.message", // next-auth's BroadcastChannel key+ newValue: JSON.stringify({+ event: "session",+ data: { trigger: "getSession" },+ }),+ }),+ );+}++/**+ * Asks the session endpoint the one question next-auth's client cannot answer:+ * is the user signed out, or did the request simply not get through? Anything+ * short of a readable "no session" answer counts as unreachable.+ */+async function probeSession(+ basePath: string,+): Promise<"signed-in" | "signed-out" | "unreachable"> {+ try {+ const response = await fetch(`${basePath}/session`);+ if (!response.ok) return "unreachable";+ const body = (await response.json()) as Record<string, unknown> | null;+ return body && Object.keys(body).length > 0 ? "signed-in" : "signed-out";+ } catch {+ return "unreachable";+ }+}++/**+ * Keeps a session gap from reading as a sign-out.+ *+ * next-auth returns the same "no session" value when `/api/auth/session` fails+ * as when the server says the user is signed out, so one failed response used+ * to unmount everything that reads the session — the entire page subtree via+ * `AppLayout`, plus every session-gated control — taking open dialogs and+ * unsaved edits with it.+ *+ * The rule here: only the server ends a session. While a session that was+ * present goes missing, keep serving it, nudge next-auth to re-fetch, and ask+ * the endpoint directly what happened. A "no session" answer is passed straight+ * through, so a real sign-out (here or in another tab) still tears the session+ * down; an unreachable endpoint is not an answer, so the page stays as it is+ * for as long as it takes.+ */+export function ResilientSessionProvider({+ basePath,+ children,+}: PropsWithChildren<{ basePath: string }>) {+ const session = useSession();+ const [attempt, setAttempt] = useState(0);+ const [serverSaysSignedOut, setServerSaysSignedOut] = useState(false);+ const lastKnownSession = useRef<Session | null>(null);+ if (session.data) lastKnownSession.current = session.data;++ const knownSession = lastKnownSession.current;+ const isRechecking =+ session.status === "unauthenticated" &&+ knownSession !== null &&+ !serverSaysSignedOut;++ useEffect(() => {+ if (session.status === "authenticated") {+ if (attempt > 0) setAttempt(0);+ if (serverSaysSignedOut) setServerSaysSignedOut(false);+ return;+ }+ if (!isRechecking) return;++ let cancelled = false;+ // Recovering flips the status, which re-runs this effect and cancels the+ // timer before it can ask why the session went missing.+ refetchSessionInProvider();+ const timer = setTimeout(async () => {+ const verdict = await probeSession(basePath);+ if (cancelled) return;+ if (verdict === "signed-out") setServerSaysSignedOut(true);+ else setAttempt((count) => count + 1);+ }, recheckDelay(attempt));++ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [session.status, attempt, isRechecking, serverSaysSignedOut, basePath]);++ const value = useMemo<SessionContextValue>(() => {+ if (!isRechecking || !knownSession) return session;+ return {+ data: knownSession,+ status: "authenticated",+ // next-auth's own update() bails while it has no session, so passing it+ // through here would drop the call. Callers use it to re-read the+ // session, which is what a re-check does anyway.+ update: async (data) => {+ if (data !== undefined) return session.update(data);+ refetchSessionInProvider();+ return null;+ },+ };+ }, [isRechecking, knownSession, session]);++ return (+ <SessionContext.Provider value={value}>{children}</SessionContext.Provider>+ );+}diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex e9ea6ec9c1..02b60125a7 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -76,6 +76,7 @@ if (typeof window !== "undefined") {};}+import { ResilientSessionProvider } from "@/src/features/auth/components/ResilientSessionProvider";import { DetailPageListsProvider } from "@/src/features/navigate-detail-pages/context";import { env } from "@/src/env.mjs";import { ThemeProvider } from "@/src/features/theming/ThemeProvider";@@ -121,6 +122,7 @@ const MyApp: AppType<{ session: Session | null }> = ({const router = useRouter();const skipAppLayout ="skipAppLayout" in Component && Component.skipAppLayout === true;+ const authBasePath = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth`;useEffect(() => {// PostHog (cloud.langfuse.com)@@ -169,33 +171,35 @@ const MyApp: AppType<{ session: Session | null }> = ({session={session}refetchOnWindowFocus={true}refetchInterval={5 * 60} // 5 minutes- basePath={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth`}+ basePath={authBasePath}>- <DetailPageListsProvider>- <MarkdownContextProvider>- <ThemeProvider- attribute="class"- enableSystem- disableTransitionOnChange- >- <ScoreCacheProvider>- <CorrectionCacheProvider>- <SupportDrawerProvider defaultOpen={false}>- <V4MigrationPanelProvider defaultOpen={false}>- <InAppAiAgentProvider defaultOpen={false}>- {skipAppLayout ? (- page- ) : (- <AppLayout>{page}</AppLayout>- )}- </InAppAiAgentProvider>- </V4MigrationPanelProvider>- </SupportDrawerProvider>- </CorrectionCacheProvider>- </ScoreCacheProvider>- </ThemeProvider>- </MarkdownContextProvider>- </DetailPageListsProvider>+ <ResilientSessionProvider basePath={authBasePath}>+ <DetailPageListsProvider>+ <MarkdownContextProvider>+ <ThemeProvider+ attribute="class"+ enableSystem+ disableTransitionOnChange+ >+ <ScoreCacheProvider>+ <CorrectionCacheProvider>+ <SupportDrawerProvider defaultOpen={false}>+ <V4MigrationPanelProvider defaultOpen={false}>+ <InAppAiAgentProvider defaultOpen={false}>+ {skipAppLayout ? (+ page+ ) : (+ <AppLayout>{page}</AppLayout>+ )}+ </InAppAiAgentProvider>+ </V4MigrationPanelProvider>+ </SupportDrawerProvider>+ </CorrectionCacheProvider>+ </ScoreCacheProvider>+ </ThemeProvider>+ </MarkdownContextProvider>+ </DetailPageListsProvider>+ </ResilientSessionProvider></SessionProvider></PostHogProvider></CommandMenuProvider>