AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend/marketplace): make public expert profiles readable by search engines (SECRT-2749) (#14902)
Abhimanyu Yadav0a205a02ecd4
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/(home)/loading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/(home)/loading.tsxnew file mode 100644index 0000000000..53da05c1b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/(home)/loading.tsx@@ -0,0 +1,5 @@+import { MainMarketplacePageLoading } from "../components/MainMarketplacePageLoading";++export default function Loading() {+ return <MainMarketplacePageLoading />;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/page.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/(home)/page.tsxsimilarity index 90%rename from autogpt_platform/frontend/src/app/(platform)/marketplace/page.tsxrename to autogpt_platform/frontend/src/app/(platform)/marketplace/(home)/page.tsxindex 3e2c280f80..a0d50f0afc 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/(home)/page.tsx@@ -2,14 +2,14 @@ import {prefetchGetV2ListMarketplaceSkillsQuery,prefetchGetV2ListStoreAgentsQuery,} from "@/app/api/__generated__/endpoints/store/store";-import { SHELF_PREVIEW_SIZE } from "./components/Shelf/helpers";+import { SHELF_PREVIEW_SIZE } from "../components/Shelf/helpers";import { getQueryClient } from "@/lib/react-query/queryClient";import { buildPageMetadata } from "@/lib/metadata";import { dehydrate, HydrationBoundary } from "@tanstack/react-query";import { Metadata } from "next";import { Suspense } from "react";-import { MainMarkeplacePage } from "./components/MainMarketplacePage/MainMarketplacePage";-import { MainMarketplacePageLoading } from "./components/MainMarketplacePageLoading";+import { MainMarkeplacePage } from "../components/MainMarketplacePage/MainMarketplacePage";+import { MainMarketplacePageLoading } from "../components/MainMarketplacePageLoading";export const dynamic = "force-dynamic";diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/loading-states.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/loading-states.test.tsxnew file mode 100644index 0000000000..61263224e6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/loading-states.test.tsx@@ -0,0 +1,26 @@+import { render } from "@testing-library/react";+import { describe, expect, test } from "vitest";+import HomeLoading from "../(home)/loading";+import AgentLoading from "../agent/loading";+import CreatorLoading from "../creator/loading";+import SearchLoading from "../search/loading";+import SkillsLoading from "../skills/loading";++// The expert page deliberately has no loading state: a loading boundary+// streams its content in a hidden chunk that a crawler without JavaScript+// never sees. Every other marketplace route keeps the shared skeleton.+describe("Marketplace loading states", () => {+ test.each([+ ["home", HomeLoading],+ ["agent", AgentLoading],+ ["creator", CreatorLoading],+ ["search", SearchLoading],+ ["skills", SkillsLoading],+ ])("%s shows the marketplace skeleton", (_route, Loading) => {+ const { container } = render(<Loading />);++ expect(container.querySelectorAll(".animate-pulse").length).toBeGreaterThan(+ 0,+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/loading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/loading.tsxnew file mode 100644index 0000000000..53da05c1b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/loading.tsx@@ -0,0 +1,5 @@+import { MainMarketplacePageLoading } from "../components/MainMarketplacePageLoading";++export default function Loading() {+ return <MainMarketplacePageLoading />;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/creator/loading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/creator/loading.tsxnew file mode 100644index 0000000000..53da05c1b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/creator/loading.tsx@@ -0,0 +1,5 @@+import { MainMarketplacePageLoading } from "../components/MainMarketplacePageLoading";++export default function Loading() {+ return <MainMarketplacePageLoading />;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsxindex 964f49d044..ee822d5d6d 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx@@ -1,12 +1,25 @@-import { getExpertRoleLabel } from "@/services/experts/expert-role-label";-import { listExpertTemplates } from "@/app/api/__generated__/endpoints/experts/experts";+import {+ getListExpertTemplatesQueryKey,+ listExpertTemplates,+} from "@/app/api/__generated__/endpoints/experts/experts";import { Expert } from "@/app/api/__generated__/models/expert";import { buildPageMetadata } from "@/lib/metadata";+import { getQueryClient } from "@/lib/react-query/queryClient";+import { getExpertRoleLabel } from "@/services/experts/expert-role-label";+import { dehydrate, HydrationBoundary } from "@tanstack/react-query";import { Metadata } from "next";+import { notFound } from "next/navigation";+import { cache } from "react";import { ExpertPage } from "./components/ExpertPage";+export const dynamic = "force-dynamic";+export type MarketplaceExpertPageParams = { expertId: string };+// Ads traffic lands here in bursts and the templates change rarely, so the+// server keeps one copy for a minute instead of asking the backend per view.+const TEMPLATES_REVALIDATE_SECONDS = 60;+export async function generateMetadata({params: _params,}: {@@ -14,7 +27,10 @@ export async function generateMetadata({}): Promise<Metadata> {const params = await _params;const path = `/marketplace/experts/${params.expertId}`;- const expert = await findExpertTemplate(params.expertId);+ const expert = findExpertTemplate(+ await fetchExpertTemplates(),+ params.expertId,+ );if (!expert) {return buildPageMetadata({ title: "Expert - AutoGPT Marketplace", path });@@ -30,16 +46,65 @@ export async function generateMetadata({});}-export default function MarketplaceExpertPage() {- return <ExpertPage />;+// Crawlers and the Ads landing-page check read the first response, so the+// expert's text has to be in the server HTML: the templates are fetched here+// and handed to the client tree, which hydrates useExpertPage with the expert+// on its first render instead of showing a skeleton. The route also sits+// outside the marketplace home's loading boundary (see ../(home)/loading.tsx):+// under one, the content would stream in a hidden chunk that only an inline+// script reveals, which is what a crawler without JavaScript never sees.+export default async function MarketplaceExpertPage({+ params: _params,+}: {+ params: Promise<MarketplaceExpertPageParams>;+}) {+ const { expertId } = await _params;+ const queryClient = getQueryClient();+ await queryClient.prefetchQuery({+ queryKey: getListExpertTemplatesQueryKey(),+ // Arg-less on purpose: React's cache keys on arguments, and react-query+ // would otherwise pass its context and miss generateMetadata's entry.+ queryFn: () => fetchExpertTemplatesOrThrow(),+ });+ const templates = queryClient.getQueryData<ExpertTemplatesResponse>(+ getListExpertTemplatesQueryKey(),+ );++ // Only a loaded list can say the id is unknown. When the backend was+ // unreachable nothing is dehydrated and the client fetch renders the error.+ if (templates && !findExpertTemplate(templates, expertId)) {+ notFound();+ }++ return (+ <HydrationBoundary state={dehydrate(queryClient)}>+ <ExpertPage />+ </HydrationBoundary>+ );}-async function findExpertTemplate(expertId: string): Promise<Expert | null> {+type ExpertTemplatesResponse = Awaited<ReturnType<typeof listExpertTemplates>>;++// One backend call per request, shared by generateMetadata and the page body.+const fetchExpertTemplatesOrThrow = cache(() =>+ listExpertTemplates(undefined, {+ next: { revalidate: TEMPLATES_REVALIDATE_SECONDS },+ }),+);++async function fetchExpertTemplates(): Promise<ExpertTemplatesResponse | null> {try {- const { data } = await listExpertTemplates();- return (data as Expert[]).find((t) => t.id === expertId) ?? null;+ return await fetchExpertTemplatesOrThrow();} catch {// Metadata must never break the page; the client fetch renders the error.return null;}}++function findExpertTemplate(+ templates: ExpertTemplatesResponse | null,+ expertId: string,+): Expert | null {+ if (!templates) return null;+ return (templates.data as Expert[]).find((t) => t.id === expertId) ?? null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page-ssr.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page-ssr.test.tsxnew file mode 100644index 0000000000..7cea79c728--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page-ssr.test.tsx@@ -0,0 +1,178 @@+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";+import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";+import { getQueryClient } from "@/lib/react-query/queryClient";+import { server } from "@/mocks/mock-server";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";+import type { ReactElement } from "react";+import { renderToString } from "react-dom/server";+import { beforeEach, describe, expect, test, vi } from "vitest";+import MarketplaceExpertPage from "../[expertId]/page";++const mockListExpertTemplates = vi.hoisted(() => vi.fn());+const mockParams = vi.hoisted(() => ({ expertId: "template-maria" }));++vi.mock(+ "@/app/api/__generated__/endpoints/experts/experts",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/app/api/__generated__/endpoints/experts/experts")+ >()),+ listExpertTemplates: mockListExpertTemplates,+ }),+);++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ usePathname: () => `/marketplace/experts/${mockParams.expertId}`,+ useSearchParams: () => new URLSearchParams(),+ useParams: () => mockParams,+ notFound: () => {+ throw new Error("NEXT_NOT_FOUND");+ },+}));++// The session only resolves in the browser, so on the server it is loading.+vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ user: null, isLoggedIn: false, isUserLoading: true }),+}));++const maria = {+ id: "template-maria",+ name: "Maria",+ avatar_url: null,+ role: "Marketing Strategist",+ job_title: "Marketing Strategist",+ bio: "Maria is a senior marketing strategist with fifteen years across B2B SaaS.",+ skills: [],+ bundled_skills: [+ {+ id: "listing-1",+ slug: "brand-voice-guide",+ title: "Brand voice guide",+ description: "Keeps every draft on-brand.",+ },+ ],+ day_one: [+ {+ title: "Social listening on your brand",+ description:+ "Tracks mentions of your brand across X, LinkedIn and Reddit.",+ timing: "first scan · 1 hr",+ },+ ],+ tagline: "Grows your brand while you sleep",+ identity: "You are Maria, a senior marketing strategist.",+ voice_preferences: "Warm, concise, and direct.",+ boundaries: "Never invent customer evidence.",+ protected_soul_rules: [],+ is_template: true,+ source_template_id: null,+ is_archived: false,+ weekly_budget: 500,+ workflows: [+ {+ id: "wf-1",+ name: "LinkedIn Post Generator",+ description: "Create research-driven LinkedIn posts in minutes.",+ store_listing_version_id: null,+ library_agent_id: null,+ graph_id: null,+ integration_providers: ["anthropic"],+ },+ ],+};++function okResponse(data: unknown) {+ return { status: 200, data, headers: new Headers() };+}++// What Next does with the page's output: one pass to HTML, no effects, so+// nothing the client would fetch after mount can leak into the result.+function renderServerHTML(page: ReactElement) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return renderToString(+ <QueryClientProvider client={queryClient}>+ <NuqsTestingAdapter>+ <BackendAPIProvider>+ <TooltipProvider>{page}</TooltipProvider>+ </BackendAPIProvider>+ </NuqsTestingAdapter>+ </QueryClientProvider>,+ );+}++function renderPage(expertId: string) {+ mockParams.expertId = expertId;+ return MarketplaceExpertPage({ params: Promise.resolve({ expertId }) });+}++describe("Marketplace expert page on the server", () => {+ const requests: string[] = [];++ beforeEach(() => {+ mockListExpertTemplates.mockReset();+ // Shared across tests in the browser build of the query client.+ getQueryClient().clear();+ requests.length = 0;+ server.events.removeAllListeners();+ server.events.on("request:start", ({ request }) => {+ requests.push(request.url);+ });+ });++ test("puts the expert's text in the HTML without a client fetch", async () => {+ mockListExpertTemplates.mockResolvedValue(okResponse([maria]));++ const html = renderServerHTML(await renderPage("template-maria"));++ expect(html).toMatch(/<h1[^>]*>[^<]*Maria/);+ expect(html).toContain("Marketing Strategist");+ expect(html).toContain("Grows your brand while you sleep");+ expect(html).toContain(+ "Maria is a senior marketing strategist with fifteen years across B2B SaaS.",+ );+ expect(html).toContain("Social listening on your brand");+ expect(html).toContain("Brand voice guide");+ expect(html).toContain("LinkedIn Post Generator");+ expect(mockListExpertTemplates).toHaveBeenCalledTimes(1);+ expect(requests).toEqual([]);+ });++ test("shows no skeleton in place of the profile", async () => {+ mockListExpertTemplates.mockResolvedValue(okResponse([maria]));++ const html = renderServerHTML(await renderPage("template-maria"));++ // Only the header's hire action waits for the session and the flag; the+ // profile that follows the header must be text, not placeholders.+ const [header, body] = html.split("</header>");+ expect(header).toContain("<h1");+ expect(body).toContain("Maria is a senior marketing strategist");+ expect(body).not.toContain("animate-pulse");+ });++ test("404s on the server for an id that matches no template", async () => {+ mockListExpertTemplates.mockResolvedValue(okResponse([maria]));++ await expect(renderPage("nobody")).rejects.toThrow("NEXT_NOT_FOUND");+ });++ test("leaves the fetch to the client when the backend is unreachable", async () => {+ mockListExpertTemplates.mockRejectedValue(new Error("fetch failed"));++ const html = renderServerHTML(await renderPage("template-maria"));++ expect(html).not.toContain("<h1");+ expect(html).toContain("animate-pulse");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/generateMetadata.test.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/generateMetadata.test.tsindex 8c4f1585ef..6b6b3a60f4 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/generateMetadata.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/generateMetadata.test.ts@@ -2,9 +2,15 @@ import { beforeEach, describe, expect, test, vi } from "vitest";const mockListExpertTemplates = vi.hoisted(() => vi.fn());-vi.mock("@/app/api/__generated__/endpoints/experts/experts", () => ({- listExpertTemplates: mockListExpertTemplates,-}));+vi.mock(+ "@/app/api/__generated__/endpoints/experts/experts",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/app/api/__generated__/endpoints/experts/experts")+ >()),+ listExpertTemplates: mockListExpertTemplates,+ }),+);vi.mock("../[expertId]/components/ExpertPage", () => ({ExpertPage: () => null,diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/loading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/loading.tsxdeleted file mode 100644index f69720d4ad..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { MainMarketplacePageLoading } from "./components/MainMarketplacePageLoading";--export default function Loading() {- return <MainMarketplacePageLoading />;-}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/search/loading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/loading.tsxnew file mode 100644index 0000000000..53da05c1b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/loading.tsx@@ -0,0 +1,5 @@+import { MainMarketplacePageLoading } from "../components/MainMarketplacePageLoading";++export default function Loading() {+ return <MainMarketplacePageLoading />;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/loading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/loading.tsxnew file mode 100644index 0000000000..53da05c1b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/loading.tsx@@ -0,0 +1,5 @@+import { MainMarketplacePageLoading } from "../components/MainMarketplacePageLoading";++export default function Loading() {+ return <MainMarketplacePageLoading />;+}diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsx b/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsxnew file mode 100644index 0000000000..3aaa8748ca--- /dev/null+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsx@@ -0,0 +1,202 @@+import { act, render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { LaunchDarklyProvider } from "../feature-flag-provider";+import { Flag, useFlagStatus } from "../use-get-flag";++const ld = vi.hoisted(() => ({+ props: [] as Array<{ context?: unknown; deferInitialization?: boolean }>,+ // What the SDK has answered so far; empty until it initialises.+ flags: {} as Record<string, unknown>,+}));++const auth = vi.hoisted(() => ({+ state: { user: null as { id: string } | null, isUserLoading: true },+}));++interface Props {+ context?: unknown;+ deferInitialization?: boolean;+ children: ReactNode;+}++vi.mock("launchdarkly-react-client-sdk", () => {+ function MockLDProvider({ context, deferInitialization, children }: Props) {+ ld.props.push({ context, deferInitialization });+ return <>{children}</>;+ }+ return {+ LDProvider: MockLDProvider,+ useFlags: () => ld.flags,+ useLDClient: () => undefined,+ };+});++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => auth.state,+}));++vi.mock("@/services/environment", () => ({+ environment: {+ areFeatureFlagsEnabled: () => true,+ getLaunchDarklyClientId: () => "test-client-id",+ getCookiebotCBID: () => undefined,+ },+}));++vi.mock("@/app/(platform)/marketplace/components/HeroSection/helpers", () => ({+ DEFAULT_SEARCH_TERMS: [],+}));++function HireProbe() {+ const { enabled, ready } = useFlagStatus(Flag.HIRE_EXPERTS);+ return (+ <span>+ hire: {String(enabled)} ready: {String(ready)}+ </span>+ );+}++describe("LaunchDarklyProvider while the session loads", () => {+ beforeEach(() => {+ ld.props.length = 0;+ ld.flags = {};+ auth.state = { user: null, isUserLoading: true };+ });++ it("renders the page instead of a spinner, so server HTML carries it", () => {+ render(+ <LaunchDarklyProvider>+ <h1>Maria</h1>+ </LaunchDarklyProvider>,+ );++ expect(screen.getByRole("heading", { name: "Maria" })).toBeDefined();+ });++ it("defers LaunchDarkly until the context is known", () => {+ render(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );++ expect(ld.props.at(-1)).toEqual({+ context: undefined,+ deferInitialization: true,+ });+ });++ it("keeps gated UI in the not-answered state rather than off", () => {+ render(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );++ expect(screen.getByText("hire: false ready: false")).toBeDefined();+ });++ it("hands the resolved session to LaunchDarkly without remounting the page", () => {+ const { rerender } = render(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );+ const probe = screen.getByText(/^hire:/);++ auth.state = { user: { id: "user-1" }, isUserLoading: false };+ rerender(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );++ expect(ld.props.at(-1)?.context).toMatchObject({+ user: { key: "user-1", anonymous: false },+ });+ // Same DOM node: the provider stayed mounted across the session resolving.+ expect(screen.getByText(/^hire:/)).toBe(probe);+ });+});++// The route gates (/raise, /team, /home, skills) call notFound() once a flag+// reads ready-but-off. With LaunchDarkly deferred until the session resolves,+// the fallback timeout must not count down while the vendor cannot answer.+describe("flag resolution timeout while LaunchDarkly is deferred", () => {+ function renderProbe() {+ return render(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );+ }++ beforeEach(() => {+ vi.useFakeTimers();+ ld.props.length = 0;+ ld.flags = {};+ auth.state = { user: null, isUserLoading: true };+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("does not fall back to the default while the session is still loading", () => {+ renderProbe();++ act(() => {+ vi.advanceTimersByTime(10_000);+ });++ expect(screen.getByText("hire: false ready: false")).toBeDefined();+ });++ it("gives LaunchDarkly its full timeout once the session resolves", () => {+ const { rerender } = renderProbe();+ act(() => {+ vi.advanceTimersByTime(6_000);+ });++ auth.state = { user: { id: "user-1" }, isUserLoading: false };+ rerender(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );+ act(() => {+ vi.advanceTimersByTime(4_000);+ });+ expect(screen.getByText("hire: false ready: false")).toBeDefined();++ ld.flags = { "hire-experts": true };+ rerender(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );++ expect(screen.getByText("hire: true ready: true")).toBeDefined();+ });++ it("still times out once initialisation has started and nothing answers", () => {+ const { rerender } = renderProbe();++ auth.state = { user: null, isUserLoading: false };+ rerender(+ <LaunchDarklyProvider>+ <HireProbe />+ </LaunchDarklyProvider>,+ );+ act(() => {+ vi.advanceTimersByTime(4_999);+ });+ expect(screen.getByText("hire: false ready: false")).toBeDefined();++ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(screen.getByText("hire: false ready: true")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx b/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsxindex 83105895e6..1aac229396 100644--- a/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx+++ b/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx@@ -1,6 +1,5 @@"use client";-import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { useAuth } from "@/lib/auth/hooks/useAuth";import { LDProvider } from "launchdarkly-react-client-sdk";import type { ReactNode } from "react";@@ -9,6 +8,7 @@ import { getAnonymousID } from "../analytics/anonymous-id";import { environment } from "../environment";import { LD_INIT_TIMEOUT_SECONDS } from "./constants";import { usesLaunchDarkly } from "./flag-backend";+import { FlagResolutionContext } from "./flag-resolution";import { buildLDContext } from "./helpers";export function LaunchDarklyProvider({ children }: { children: ReactNode }) {@@ -16,6 +16,11 @@ export function LaunchDarklyProvider({ children }: { children: ReactNode }) {const envEnabled = usesLaunchDarkly() && environment.areFeatureFlagsEnabled();const clientId = environment.getLaunchDarklyClientId();+ // Undefined until the session check resolves, which it never does on the+ // server. The page renders regardless so crawlers get its content; the+ // provider below just holds off initialising until the context is known,+ // during which every flag reads as "not answered yet" and the resolution+ // timeout in ``useFlagStatus`` has not started counting.const context = useMemo(() => {if (isUserLoading) return;return buildLDContext(user, getAnonymousID());@@ -25,18 +30,17 @@ export function LaunchDarklyProvider({ children }: { children: ReactNode }) {return <>{children}</>;}- if (isUserLoading) {- return <LoadingSpinner size="large" cover />;- }-return (- <LDProvider- clientSideID={clientId ?? ""}- context={context}- timeout={LD_INIT_TIMEOUT_SECONDS}- reactOptions={{ useCamelCaseFlagKeys: false }}- >- {children}- </LDProvider>+ <FlagResolutionContext.Provider value={context !== undefined}>+ <LDProvider+ clientSideID={clientId ?? ""}+ context={context}+ deferInitialization+ timeout={LD_INIT_TIMEOUT_SECONDS}+ reactOptions={{ useCamelCaseFlagKeys: false }}+ >+ {children}+ </LDProvider>+ </FlagResolutionContext.Provider>);}diff --git a/autogpt_platform/frontend/src/services/feature-flags/flag-resolution.ts b/autogpt_platform/frontend/src/services/feature-flags/flag-resolution.tsnew file mode 100644index 0000000000..50112c10fd--- /dev/null+++ b/autogpt_platform/frontend/src/services/feature-flags/flag-resolution.ts@@ -0,0 +1,15 @@+"use client";++import { createContext, useContext } from "react";++// Whether the configured vendor has been given the chance to answer. The+// LaunchDarkly provider holds initialisation until the session resolves, and+// during that wait the fallback timeout in ``useFlagStatus`` must not count+// down: timing out there serves the default, and a route gated on the flag+// would 404 a user who has it on. Defaults to true so that with no deferring+// provider above (PostHog, flags disabled, tests) the timeout runs from mount.+export const FlagResolutionContext = createContext(true);++export function useFlagResolutionStarted() {+ return useContext(FlagResolutionContext);+}diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.tsindex 5d8be25be4..0d9ce4a2b2 100644--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts@@ -6,6 +6,7 @@ import * as Sentry from "@sentry/nextjs";import type { FeatureFlagsIntegration } from "@sentry/nextjs";import { useEffect, useState } from "react";import { FLAG_BACKEND, isPostHogFlagsEnabled } from "./flag-backend";+import { useFlagResolutionStarted } from "./flag-resolution";import { useFlagSource } from "./flag-source";export enum Flag {@@ -227,7 +228,10 @@ const FLAG_RESOLUTION_TIMEOUT_MS = 5000;* ``notFound()`` before the vendor responds 404s users that actually have* the flag on. Falls back to "ready" after ``FLAG_RESOLUTION_TIMEOUT_MS``* so an unregistered flag key doesn't spin forever; ``answered`` stays- * false then, for callers that must not act on a timeout.+ * false then, for callers that must not act on a timeout. The timeout only+ * counts from the moment the vendor can actually start answering: while the+ * provider is still waiting on the session it would otherwise expire first+ * and serve the default to a user whose flag is on.*/export function useFlagStatus<T extends Flag>(flag: T,@@ -236,14 +240,16 @@ export function useFlagStatus<T extends Flag>(const areFlagsEnabled = areFeatureFlagsEnabled();const override = envFlagOverride(flag);+ const resolutionStarted = useFlagResolutionStarted();const [timedOut, setTimedOut] = useState(false);useEffect(() => {+ if (!resolutionStarted) return;const timer = setTimeout(() => setTimedOut(true),FLAG_RESOLUTION_TIMEOUT_MS,);return () => clearTimeout(timer);- }, []);+ }, [resolutionStarted]);const served = override ?? servedFlagValue(flag, value);recordFlagForSentry(flag, override === undefined ? served : undefined);