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.
perf(frontend): stop the app chrome re-rendering on URL-param writes (#15684)
Abhimanyu Yadav89583dca8fcb
diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsxindex d2a96b817b..45baaebdf5 100644--- a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx@@ -22,6 +22,7 @@ import { PaywallGate } from "../PaywallGate/PaywallGate";import { ArtifactsPanelNavCollapse } from "./components/ArtifactsPanelNavCollapse/ArtifactsPanelNavCollapse";import { BuilderSidebarAutoClose } from "./components/BuilderSidebarAutoClose/BuilderSidebarAutoClose";import { InsetHeaderActions } from "./components/InsetHeaderActions/InsetHeaderActions";+import { InsetHeaderSidebarTrigger } from "./components/InsetHeaderSidebarTrigger/InsetHeaderSidebarTrigger";import { InsetHeaderTitle } from "./components/InsetHeaderTitle/InsetHeaderTitle";import { usePlatformChrome } from "./usePlatformChrome";@@ -31,18 +32,12 @@ interface Props {persistedSidebarOpen?: boolean;}-// Mobile header buttons float over the content, so they get a pill surface to-// stay readable against whatever scrolls underneath.-const mobileTriggerClassName =- "rounded-full border border-[#DADADC] bg-white shadow-md hover:bg-[#F5F5F6]";-export function PlatformChrome({ children, persistedSidebarOpen }: Props) {const {showNewLayout,isNewLayoutActive,showTourSidebar,overlayInsetHeader,- isChatSession,hasInsetHeaderTitle,isSettingsRoute,isAdminRoute,@@ -99,13 +94,7 @@ export function PlatformChrome({ children, persistedSidebarOpen }: Props) {)}><div className="mx-auto flex w-full max-w-7xl items-center gap-2 px-6 md:px-8">- {/* An open chat carries both buttons in its thread chip- (ThreadHeader), so they float here everywhere else. */}- {!isChatSession && (- <div className="pointer-events-auto md:hidden">- <SidebarTrigger className={mobileTriggerClassName} />- </div>- )}+ <InsetHeaderSidebarTrigger /><InsetHeaderTitle /><InsetHeaderActions /></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/searchParamRenders.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/searchParamRenders.test.tsxnew file mode 100644index 0000000000..7294b51091--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/searchParamRenders.test.tsx@@ -0,0 +1,154 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import {+ AppRouterContext,+ type AppRouterInstance,+} from "next/dist/shared/lib/app-router-context.shared-runtime";+import {+ PathnameContext,+ SearchParamsContext,+} from "next/dist/shared/lib/hooks-client-context.shared-runtime";+import { useState, type ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { SidebarProvider } from "@/components/ui/sidebar";++import { InsetHeaderSidebarTrigger } from "../components/InsetHeaderSidebarTrigger/InsetHeaderSidebarTrigger";+import { useIsChatSession } from "../useIsChatSession";+import { usePlatformChrome } from "../usePlatformChrome";++// The real hooks, reading the same contexts the App Router provides, so a+// search-param write reaches the components exactly as it does in the app.+vi.mock("next/navigation", async () => vi.importActual("next/navigation"));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return { ...actual, useGetFlag: () => true };+});++interface URLState {+ pathname: string;+ searchParams: URLSearchParams;+}++const router = {+ push: vi.fn(),+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+} satisfies AppRouterInstance;++let navigate: (pathname: string, search: string) => void = () => {};++function FakeRouter({+ initialPathname,+ initialSearch,+ children,+}: {+ initialPathname: string;+ initialSearch: string;+ children: ReactNode;+}) {+ const [url, setURL] = useState<URLState>({+ pathname: initialPathname,+ searchParams: new URLSearchParams(initialSearch),+ });+ navigate = (pathname, search) =>+ setURL({ pathname, searchParams: new URLSearchParams(search) });+ return (+ <AppRouterContext.Provider value={router}>+ <PathnameContext.Provider value={url.pathname}>+ <SearchParamsContext.Provider value={url.searchParams}>+ {children}+ </SearchParamsContext.Provider>+ </PathnameContext.Provider>+ </AppRouterContext.Provider>+ );+}++let chromeRenders = 0;+function ChromeConsumer() {+ const { isCopilotRoute } = usePlatformChrome();+ chromeRenders += 1;+ return <span data-testid="copilot-route">{String(isCopilotRoute)}</span>;+}++function ChatSessionConsumer() {+ return <span data-testid="chat-session">{String(useIsChatSession())}</span>;+}++function navigateTo(pathname: string, search: string) {+ act(() => navigate(pathname, search));+}++describe("platform chrome and search-param writes", () => {+ beforeEach(() => {+ chromeRenders = 0;+ });++ it("does not re-render a usePlatformChrome consumer when only a search param changes", async () => {+ render(+ <FakeRouter+ initialPathname="/library/agents/agent-1"+ initialSearch="activeItem=run-1"+ >+ <ChromeConsumer />+ </FakeRouter>,+ );+ // Mount, then the post-mount layout swap.+ await waitFor(() => expect(chromeRenders).toBe(2));++ navigateTo("/library/agents/agent-1", "activeItem=run-2");+ navigateTo("/library/agents/agent-1", "activeItem=run-2&activeTab=runs");+ navigateTo("/copilot", "sessionId=chat-1");+ const afterPathnameChange = chromeRenders;+ navigateTo("/copilot", "sessionId=chat-2");++ expect(afterPathnameChange).toBe(3);+ expect(chromeRenders).toBe(3);+ expect(screen.getByTestId("copilot-route").textContent).toBe("true");+ });++ it("reports an open chat only on the copilot routes", () => {+ render(+ <FakeRouter initialPathname="/home" initialSearch="">+ <ChatSessionConsumer />+ </FakeRouter>,+ );+ const isChatSession = () => screen.getByTestId("chat-session").textContent;+ expect(isChatSession()).toBe("false");++ navigateTo("/home", "sessionId=chat-1");+ expect(isChatSession()).toBe("true");++ navigateTo("/copilot", "sessionId=chat-2");+ expect(isChatSession()).toBe("true");++ navigateTo("/copilot", "");+ expect(isChatSession()).toBe("false");++ navigateTo("/library", "sessionId=chat-1");+ expect(isChatSession()).toBe("false");+ });++ it("hides the floating sidebar trigger while a chat is open", () => {+ render(+ <FakeRouter initialPathname="/copilot" initialSearch="">+ <SidebarProvider>+ <InsetHeaderSidebarTrigger />+ </SidebarProvider>+ </FakeRouter>,+ );+ expect(screen.getByText("Toggle Sidebar")).toBeDefined();++ navigateTo("/copilot", "sessionId=chat-1");+ expect(screen.queryByText("Toggle Sidebar")).toBeNull();++ navigateTo("/copilot", "");+ expect(screen.getByText("Toggle Sidebar")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/usePlatformChrome.test.ts b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/usePlatformChrome.test.tsindex c419355ccf..5c848dc1f6 100644--- a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/usePlatformChrome.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/usePlatformChrome.test.ts@@ -1,22 +1,28 @@import { renderHook, waitFor } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import type { User } from "@/lib/auth/types";+import { usePlatformChrome } from "../usePlatformChrome";const pathnameMock = vi.fn<() => string>(() => "/marketplace");-const searchParamsMock = vi.fn(() => new URLSearchParams());vi.mock("next/navigation", () => ({usePathname: () => pathnameMock(),- useSearchParams: () => searchParamsMock(),}));-const authMock = vi.fn(() => ({- isLoggedIn: true,- isUserLoading: false,-}));-vi.mock("@/lib/auth/hooks/useAuth", () => ({- useAuth: () => authMock(),-}));+function setAuth({+ isLoggedIn,+ isUserLoading,+}: {+ isLoggedIn: boolean;+ isUserLoading: boolean;+}) {+ useAuthStore.setState({+ user: isLoggedIn ? ({ id: "user-1" } as User) : null,+ isUserLoading,+ });+}const flagMock = vi.fn<(flag: string) => boolean>(() => true);vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {@@ -33,9 +39,8 @@ vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {describe("usePlatformChrome", () => {beforeEach(() => {pathnameMock.mockReturnValue("/marketplace");- searchParamsMock.mockReturnValue(new URLSearchParams());flagMock.mockReturnValue(true);- authMock.mockReturnValue({ isLoggedIn: true, isUserLoading: false });+ setAuth({ isLoggedIn: true, isUserLoading: false });});it("enables the new layout after mount when the flag is on and route is allowed", async () => {@@ -111,7 +116,7 @@ describe("usePlatformChrome", () => {});it("shows the tour sidebar for logged-out marketplace visitors", async () => {- authMock.mockReturnValue({ isLoggedIn: false, isUserLoading: false });+ setAuth({ isLoggedIn: false, isUserLoading: false });const { result } = renderHook(() => usePlatformChrome());await waitFor(() => {@@ -121,7 +126,7 @@ describe("usePlatformChrome", () => {});it("keeps the tour sidebar hidden while the session check is in flight", async () => {- authMock.mockReturnValue({ isLoggedIn: false, isUserLoading: true });+ setAuth({ isLoggedIn: false, isUserLoading: true });const { result } = renderHook(() => usePlatformChrome());await waitFor(() => {@@ -139,7 +144,7 @@ describe("usePlatformChrome", () => {});it("keeps the tour sidebar off non-marketplace routes when logged out", async () => {- authMock.mockReturnValue({ isLoggedIn: false, isUserLoading: false });+ setAuth({ isLoggedIn: false, isUserLoading: false });pathnameMock.mockReturnValue("/library");const { result } = renderHook(() => usePlatformChrome());@@ -155,13 +160,3 @@ it("gives home the chat controls and floating header", () => {expect(result.current.isCopilotRoute).toBe(true);expect(result.current.overlayInsetHeader).toBe(true);});--it("flags an open chat session so its chip takes over the header buttons", () => {- pathnameMock.mockReturnValue("/home");- const { result, rerender } = renderHook(() => usePlatformChrome());- expect(result.current.isChatSession).toBe(false);-- searchParamsMock.mockReturnValue(new URLSearchParams("sessionId=abc"));- rerender();- expect(result.current.isChatSession).toBe(true);-});diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderSidebarTrigger/InsetHeaderSidebarTrigger.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderSidebarTrigger/InsetHeaderSidebarTrigger.tsxnew file mode 100644index 0000000000..44a34c0d7f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderSidebarTrigger/InsetHeaderSidebarTrigger.tsx@@ -0,0 +1,22 @@+"use client";++import { SidebarTrigger } from "@/components/ui/sidebar";++import { useIsChatSession } from "../../useIsChatSession";++// Mobile header buttons float over the content, so they get a pill surface to+// stay readable against whatever scrolls underneath.+const mobileTriggerClassName =+ "rounded-full border border-[#DADADC] bg-white shadow-md hover:bg-[#F5F5F6]";++export function InsetHeaderSidebarTrigger() {+ const isChatSession = useIsChatSession();+ // An open chat carries the button in its thread chip (ThreadHeader).+ if (isChatSession) return null;++ return (+ <div className="pointer-events-auto md:hidden">+ <SidebarTrigger className={mobileTriggerClassName} />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/helpers.tsnew file mode 100644index 0000000000..66c2169f21--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/helpers.ts@@ -0,0 +1,5 @@+import { matchesRoute } from "@/lib/utils";++export function isCopilotPathname(pathname: string) {+ return matchesRoute(pathname, "/home") || matchesRoute(pathname, "/copilot");+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/useIsChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/useIsChatSession.tsnew file mode 100644index 0000000000..bd60331f65--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/useIsChatSession.ts@@ -0,0 +1,14 @@+import { usePathname, useSearchParams } from "next/navigation";++import { isCopilotPathname } from "./helpers";++// An open chat carries the sidebar and workspace-files buttons in its thread+// chip. Kept out of usePlatformChrome on purpose: reading the search params+// re-renders the caller on every URL-param write (copilot `sessionId`, builder+// `flowVersion`, library `activeItem`), so only the header leaf that needs+// the answer subscribes to them.+export function useIsChatSession() {+ const pathname = usePathname();+ const searchParams = useSearchParams();+ return isCopilotPathname(pathname) && Boolean(searchParams.get("sessionId"));+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.ts b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.tsindex 94243fcd65..d0bcd2fc40 100644--- a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.ts+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.ts@@ -1,11 +1,12 @@-import { usePathname, useSearchParams } from "next/navigation";+import { usePathname } from "next/navigation";import { useEffect, useState } from "react";-import { useAuth } from "@/lib/auth/hooks/useAuth";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";import { matchesRoute } from "@/lib/utils";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { getRouteTitle } from "./components/InsetHeaderTitle/InsetHeaderTitle";+import { isCopilotPathname } from "./helpers";// Routes that must stay outside the new top-level sidebar layout. Login,// signup and onboarding already live in the (no-navbar) group. These@@ -21,13 +22,17 @@ const NEW_LAYOUT_EXCLUDED_PREFIXES = ["/unauthorized",];+// Nothing here may read the search params (directly or through useAuth): this+// runs at the platform layout root, so it would re-render the whole chrome on+// every URL-param write. See useIsChatSession.export function usePlatformChrome() {const pathname = usePathname();- const searchParams = useSearchParams();const isNewLayoutEnabled = useGetFlag(Flag.AUTOGPT_NEW_LAYOUT);- // Also initializes the auth store — required here because the tour shell- // replaces the Navbar, which is what normally kicks off the session check.- const { isLoggedIn, isUserLoading } = useAuth();+ // The store, not useAuth: useAuth reads the search params too. The app-root+ // providers (CredentialsProvider, OnboardingProvider) call useAuth on every+ // page, so the session check still starts in the tour shell.+ const isLoggedIn = useAuthStore((state) => Boolean(state.user));+ const isUserLoading = useAuthStore((state) => state.isUserLoading);// The LaunchDarkly flag is client-side data that can resolve differently on// the server vs the client's first render. Switching the whole layout shell@@ -43,8 +48,7 @@ export function usePlatformChrome() {const isMarketplaceRoute = matchesRoute(pathname, "/marketplace");- const isCopilotRoute =- matchesRoute(pathname, "/home") || matchesRoute(pathname, "/copilot");+ const isCopilotRoute = isCopilotPathname(pathname);const isBuilderRoute = matchesRoute(pathname, "/build");@@ -75,9 +79,6 @@ export function usePlatformChrome() {// copilot's header controls.overlayInsetHeader: isCopilotRoute,isCopilotRoute,- // An open chat carries the sidebar and workspace-files buttons in its- // thread chip, so the inset header leaves them out.- isChatSession: isCopilotRoute && Boolean(searchParams.get("sessionId")),// Titleless pages collapse the header on desktop so content doesn't sit// below an empty strip; on mobile it stays for the sidebar trigger.hasInsetHeaderTitle: Boolean(getRouteTitle(pathname)),diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsxindex 89a8fb5f7a..7eca06252b 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsx@@ -216,13 +216,25 @@ describe("CredentialsProvider device-auth upserts", () => {}async function mountProbe() {- render(+ const view = render(<CredentialsProvider><UpsertProbe provider="stripe_link" /></CredentialsProvider>,{ wrapper: TestWrapper },);await waitFor(() => expect(apiMock.listCredentials).toHaveBeenCalled());+ return view;+ }++ // The real useAuth is a store subscription, so a login or logout re-renders+ // the provider; the mock only takes effect on the next render.+ function setLoggedIn(view: ReturnType<typeof render>, value: boolean) {+ isLoggedIn.value = value;+ view.rerender(+ <CredentialsProvider>+ <UpsertProbe provider="stripe_link" />+ </CredentialsProvider>,+ );}/** Click reload and wait for that specific request to have been issued. */@@ -279,18 +291,18 @@ describe("CredentialsProvider device-auth upserts", () => {// pendingUpsertsRef outlives a session unless cleared. Left in place it// would be merged into the next user's list on the same mounted provider,// exposing the previous account's credential metadata.- await mountProbe();+ const view = await mountProbe();await act(async () => {screen.getByTestId("do-upsert").click();});expect(savedIds()).toContain("cred-device");- isLoggedIn.value = false;+ await act(async () => setLoggedIn(view, false));await act(async () => {screen.getByTestId("do-reload").click();});- isLoggedIn.value = true;+ await act(async () => setLoggedIn(view, true));apiMock.listCredentials.mockResolvedValue([] as never);await reloadAndSettle();diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-identity.test.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-identity.test.tsxnew file mode 100644index 0000000000..a2160f1608--- /dev/null+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-identity.test.tsx@@ -0,0 +1,157 @@+import { getGetV1ListCredentialsQueryKey } from "@/app/api/__generated__/endpoints/integrations/integrations";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, render, screen, waitFor } from "@testing-library/react";+import { useContext, type ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const { apiMock, onFailToastMock } = vi.hoisted(() => {+ const errorHandler = vi.fn();+ return {+ apiMock: {+ listCredentials: vi.fn(),+ listProviders: vi.fn(),+ listSystemProviders: vi.fn(),+ },+ onFailToastMock: vi.fn(() => errorHandler),+ };+});++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isLoggedIn: true, isUserLoading: false }),+}));++vi.mock("@/lib/autogpt-server-api/context", () => ({+ useBackendAPI: () => apiMock,+}));++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToastOnFail: () => onFailToastMock,+}));++import CredentialsProvider, {+ CredentialsActionsContext,+ CredentialsProvidersContext,+} from "../credentials-provider";++const queryClient = new QueryClient();++interface Props {+ children: ReactNode;+}++function TestWrapper({ children }: Props) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++// A fresh object every call, as each list response is.+function githubCredential(title = "GitHub") {+ return { id: "cred-1", provider: "github", type: "api_key", title };+}++const providerValues: unknown[] = [];+function ProvidersProbe() {+ const providers = useContext(CredentialsProvidersContext);+ providerValues.push(providers);+ const saved = providers?.github?.savedCredentials ?? [];+ return (+ <span data-testid="titles">{saved.map((c) => c.title).join(",")}</span>+ );+}++const actionValues: unknown[] = [];+function ActionsProbe() {+ actionValues.push(useContext(CredentialsActionsContext));+ return null;+}++const probes = (+ <>+ <ProvidersProbe />+ <ActionsProbe />+ </>+);++async function mountLoaded() {+ const view = render(<CredentialsProvider>{probes}</CredentialsProvider>, {+ wrapper: TestWrapper,+ });+ await waitFor(() =>+ expect(screen.getByTestId("titles").textContent).toBe("GitHub"),+ );+ return view;+}++async function invalidateCredentialsList() {+ const calls = apiMock.listCredentials.mock.calls.length;+ await act(async () => {+ await queryClient.invalidateQueries({+ queryKey: getGetV1ListCredentialsQueryKey(),+ });+ });+ await waitFor(() =>+ expect(apiMock.listCredentials.mock.calls.length).toBeGreaterThan(calls),+ );+ await act(async () => undefined);+}++describe("CredentialsProvider value identity", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ queryClient.clear();+ providerValues.length = 0;+ actionValues.length = 0;+ apiMock.listProviders.mockResolvedValue(["github", "google"]);+ apiMock.listSystemProviders.mockResolvedValue([]);+ apiMock.listCredentials.mockImplementation(() =>+ Promise.resolve([githubCredential()]),+ );+ // The provider only reacts to an existing query's cache events.+ queryClient.setQueryData(getGetV1ListCredentialsQueryKey(), []);+ });++ it("keeps the providers map when a refetch returns the same credentials", async () => {+ await mountLoaded();+ const loaded = providerValues[providerValues.length - 1];+ const renders = providerValues.length;++ await invalidateCredentialsList();++ expect(providerValues.length).toBe(renders);+ expect(providerValues[providerValues.length - 1]).toBe(loaded);+ });++ it("publishes a refetch that changed a credential, keeping the untouched entries", async () => {+ await mountLoaded();+ const loaded = providerValues[providerValues.length - 1] as Record<+ string,+ unknown+ >;++ apiMock.listCredentials.mockImplementation(() =>+ Promise.resolve([githubCredential("Renamed")]),+ );+ await invalidateCredentialsList();++ expect(screen.getByTestId("titles").textContent).toBe("Renamed");+ const updated = providerValues[providerValues.length - 1] as Record<+ string,+ unknown+ >;+ expect(updated).not.toBe(loaded);+ expect(updated.github).not.toBe(loaded.github);+ expect(updated.google).toBe(loaded.google);+ });++ it("keeps the actions value across a provider re-render", async () => {+ const view = await mountLoaded();+ const actions = actionValues[actionValues.length - 1];+ const renders = actionValues.length;++ view.rerender(<CredentialsProvider>{probes}</CredentialsProvider>);++ expect(actionValues.length).toBe(renders);+ expect(actionValues[actionValues.length - 1]).toBe(actions);+ });+});diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsxindex 4d791f9def..ebc0c551a7 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx@@ -18,7 +18,15 @@ import { useBackendAPI } from "@/lib/autogpt-server-api/context";import { useAuth } from "@/lib/auth/hooks/useAuth";import { toDisplayName } from "@/providers/agent-credentials/helper";import { hashKey, useQueryClient } from "@tanstack/react-query";-import { createContext, useCallback, useEffect, useState, useRef } from "react";+import isEqual from "lodash/isEqual";+import {+ createContext,+ useCallback,+ useEffect,+ useMemo,+ useState,+ useRef,+} from "react";type APIKeyCredentialsCreatable = Omit<APIKeyCredentials,@@ -168,6 +176,10 @@ export default function CredentialsProvider({// Only the newest list request may publish or retire; an older one can// resolve last with a response that predates an upsert.const loadGenerationRef = useRef(0);+ // The handlers the published provider entries close over. A load may keep an+ // entry whose credentials did not change only while these are the same, so+ // a reused entry never calls a stale handler.+ const entryHandlersRef = useRef<unknown[]>([]);const upsertCredentials = useCallback((@@ -192,18 +204,21 @@ export default function CredentialsProvider({* Upsert a credential straight off the API. The generated model marks several* fields nullable where the store's model uses `undefined`.*/- function upsertFromApi(- provider: CredentialsProviderName,- credentials: GeneratedCredentialsMetaResponse,- ) {- upsertCredentials(provider, {- ...credentials,- title: credentials.title ?? undefined,- scopes: credentials.scopes ?? undefined,- username: credentials.username ?? undefined,- host: credentials.host ?? undefined,- } as CredentialsMetaResponse);- }+ const upsertFromApi = useCallback(+ (+ provider: CredentialsProviderName,+ credentials: GeneratedCredentialsMetaResponse,+ ) => {+ upsertCredentials(provider, {+ ...credentials,+ title: credentials.title ?? undefined,+ scopes: credentials.scopes ?? undefined,+ username: credentials.username ?? undefined,+ host: credentials.host ?? undefined,+ } as CredentialsMetaResponse);+ },+ [upsertCredentials],+ );/** Wraps `BackendAPI.oAuthCallback`, and adds the result to the internal credentials store. */const oAuthCallback = useCallback(@@ -442,9 +457,23 @@ export default function CredentialsProvider({{} as Record<CredentialsProviderName, CredentialsMetaResponse[]>,);- setProviders((prev) => ({- ...prev,- ...Object.fromEntries(+ const entryHandlers = [+ oAuthCallback,+ mcpOAuthCallback,+ mcpStoreToken,+ createAPIKeyCredentials,+ createUserPasswordCredentials,+ createHostScopedCredentials,+ deleteCredentials,+ ];+ const canReuseEntries = isEqual(+ entryHandlersRef.current,+ entryHandlers,+ );+ entryHandlersRef.current = entryHandlers;++ setProviders((prev) => {+ const loadedEntries = Object.fromEntries(providerNames.map((provider) => {const loaded = credentialsByProvider[provider] ?? [];const pending = pendingUpsertsRef.current[provider];@@ -469,13 +498,26 @@ export default function CredentialsProvider({}}+ // Every invalidate/success refetch lands here; an entry that did+ // not change keeps its identity so consumers skip a re-render.+ const isSystemProvider = systemProviders.has(provider);+ const existing = prev?.[provider];+ if (+ canReuseEntries &&+ existing &&+ existing.isSystemProvider === isSystemProvider &&+ isEqual(existing.savedCredentials, providerCredentials)+ ) {+ return [provider, existing];+ }+return [provider,{provider,providerName: toDisplayName(provider),savedCredentials: providerCredentials,- isSystemProvider: systemProviders.has(provider),+ isSystemProvider,oAuthCallback: (code: string, state_token: string) =>oAuthCallback(provider, code, state_token),mcpOAuthCallback,@@ -494,8 +536,15 @@ export default function CredentialsProvider({} satisfies CredentialsProviderData,];}),- ),- }));+ );+ const unchanged =+ prev !== null &&+ Object.entries(loadedEntries).every(+ ([provider, entry]) =>+ prev[provider as CredentialsProviderName] === entry,+ );+ return unchanged ? prev : { ...prev, ...loadedEntries };+ });}).catch(onFailToast("load credentials"));}, [@@ -567,10 +616,13 @@ export default function CredentialsProvider({return unsubscribe;}, [queryClient, loadCredentials]);+ const actions = useMemo(+ () => ({ reload: loadCredentials, upsert: upsertFromApi }),+ [loadCredentials, upsertFromApi],+ );+return (- <CredentialsActionsContext.Provider- value={{ reload: loadCredentials, upsert: upsertFromApi }}- >+ <CredentialsActionsContext.Provider value={actions}><CredentialsProvidersContext.Provider value={providers}>{children}</CredentialsProvidersContext.Provider>diff --git a/autogpt_platform/frontend/src/providers/onboarding/AuthDeepLinkWatcher.tsx b/autogpt_platform/frontend/src/providers/onboarding/AuthDeepLinkWatcher.tsxnew file mode 100644index 0000000000..d75562450b--- /dev/null+++ b/autogpt_platform/frontend/src/providers/onboarding/AuthDeepLinkWatcher.tsx@@ -0,0 +1,24 @@+"use client";++import { sanitizeAuthNext } from "@/lib/auth-redirect";+import { useSearchParams } from "next/navigation";+import { useEffect } from "react";++interface Props {+ onChange: (hasPendingAuthDeepLink: boolean) => void;+}++// Rendered only on /login and /signup, so only those pages subscribe the+// onboarding flow to search-param writes: a `?next=` that appears or goes away+// without a pathname change re-runs the provider's init effect.+export function AuthDeepLinkWatcher({ onChange }: Props) {+ const searchParams = useSearchParams();+ const hasPendingAuthDeepLink =+ sanitizeAuthNext(searchParams.get("next")) !== null;++ useEffect(() => {+ onChange(hasPendingAuthDeepLink);+ }, [hasPendingAuthDeepLink, onChange]);++ return null;+}diff --git a/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-identity.test.tsx b/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-identity.test.tsxnew file mode 100644index 0000000000..2b07d62fb9--- /dev/null+++ b/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-identity.test.tsx@@ -0,0 +1,130 @@+import { act, render, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { WebSocketNotification } from "@/lib/autogpt-server-api";+import OnboardingProvider, { useOnboarding } from "../onboarding-provider";++// Stable across renders, like the real module-level `toast` and the memoised+// BackendAPI instance.+const { onboardingState, notificationHandlers, toast, api } = vi.hoisted(() => {+ const handlers: Array<(n: WebSocketNotification) => void> = [];+ return {+ onboardingState: {+ completedSteps: ["WELCOME"] as string[],+ walletShown: false,+ },+ notificationHandlers: handlers,+ toast: () => {},+ api: {+ onWebSocketMessage: (+ _type: string,+ handler: (n: WebSocketNotification) => void,+ ) => {+ handlers.push(handler);+ return () => {};+ },+ connectWebSocket: () => {},+ },+ };+});++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast }),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ replace: vi.fn(), push: vi.fn(), refresh: vi.fn() }),+ usePathname: () => "/marketplace",+ useSearchParams: () => new URLSearchParams(),+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isLoggedIn: true, isUserLoading: false }),+}));++vi.mock("@/lib/autogpt-server-api/context", () => ({+ useBackendAPI: () => api,+}));++vi.mock("@/hooks/useOnboardingTimezoneDetection", () => ({+ useOnboardingTimezoneDetection: () => undefined,+}));++const getOnboardingState = vi.fn(() =>+ // A fresh object every call, as each response is.+ Promise.resolve({ status: 200, data: structuredClone(onboardingState) }),+);+vi.mock("@/app/api/__generated__/endpoints/onboarding/onboarding", () => ({+ getV1CheckIfOnboardingIsCompleted: () =>+ Promise.resolve({ status: 200, data: { is_completed: true } }),+ getV1OnboardingState: () => getOnboardingState(),+ patchV1UpdateOnboardingState: () => Promise.resolve({ status: 200 }),+ postV1CompleteOnboardingStep: () => Promise.resolve({ status: 200 }),+}));++const contextValues: Array<ReturnType<typeof useOnboarding>> = [];+function Consumer() {+ contextValues.push(useOnboarding());+ return null;+}+const consumer = <Consumer />;++async function mountLoaded() {+ const view = render(<OnboardingProvider>{consumer}</OnboardingProvider>);+ await waitFor(() =>+ expect(contextValues[contextValues.length - 1]?.state).not.toBeNull(),+ );+ return view;+}++async function pushOnboardingNotification() {+ const calls = getOnboardingState.mock.calls.length;+ await act(async () => {+ notificationHandlers[notificationHandlers.length - 1]({+ type: "onboarding",+ } as WebSocketNotification);+ });+ await waitFor(() =>+ expect(getOnboardingState.mock.calls.length).toBe(calls + 1),+ );+ await act(async () => undefined);+}++describe("OnboardingProvider context identity", () => {+ beforeEach(() => {+ contextValues.length = 0;+ notificationHandlers.length = 0;+ getOnboardingState.mockClear();+ onboardingState.completedSteps = ["WELCOME"];+ });++ test("keeps the context value across a provider re-render with unchanged state", async () => {+ const view = await mountLoaded();+ const value = contextValues[contextValues.length - 1];+ const renders = contextValues.length;++ view.rerender(<OnboardingProvider>{consumer}</OnboardingProvider>);++ expect(contextValues.length).toBe(renders);+ expect(contextValues[contextValues.length - 1]).toBe(value);+ });++ test("an onboarding notification with identical data does not re-render consumers", async () => {+ await mountLoaded();+ const renders = contextValues.length;++ await pushOnboardingNotification();++ expect(contextValues.length).toBe(renders);+ });++ test("an onboarding notification with new data still reaches consumers", async () => {+ await mountLoaded();+ onboardingState.completedSteps = ["WELCOME", "MARKETPLACE_VISIT"];++ await pushOnboardingNotification();++ expect(+ contextValues[contextValues.length - 1].state?.completedSteps,+ ).toEqual(["WELCOME", "MARKETPLACE_VISIT"]);+ });+});diff --git a/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx b/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsxindex 24c9cf1c6e..bdf1461360 100644--- a/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx+++ b/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx@@ -2,7 +2,16 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { act, render, waitFor } from "@testing-library/react";import OnboardingProvider from "../onboarding-provider";-const routerReplace = vi.fn();+// Stable across renders like the real router and BackendAPI instance, so an+// effect re-runs only when its real inputs change.+const { routerReplace, router, api } = vi.hoisted(() => {+ const replace = vi.fn();+ return {+ routerReplace: replace,+ router: { replace, push: () => {}, refresh: () => {} },+ api: { onWebSocketMessage: () => () => {}, connectWebSocket: () => {} },+ };+});const toast = vi.hoisted(() => vi.fn());let completionError: Error | null = null;@@ -10,16 +19,11 @@ vi.mock("@/components/molecules/Toast/use-toast", () => ({useToast: () => ({ toast }),}));let mockPathname = "/signup";-let mockSearchParams = new URLSearchParams();vi.mock("next/navigation", () => ({- useRouter: () => ({- replace: routerReplace,- push: vi.fn(),- refresh: vi.fn(),- }),- useSearchParams: () => mockSearchParams,+ useRouter: () => router,usePathname: () => mockPathname,+ useSearchParams: () => new URLSearchParams(window.location.search),}));let mockIsLoggedIn = true;@@ -32,10 +36,7 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({}));vi.mock("@/lib/autogpt-server-api/context", () => ({- useBackendAPI: () => ({- onWebSocketMessage: () => () => {},- connectWebSocket: () => {},- }),+ useBackendAPI: () => api,}));vi.mock("@/hooks/useOnboardingTimezoneDetection", () => ({@@ -70,7 +71,7 @@ describe("OnboardingProvider routing — logged-in user", () => {routerReplace.mockClear();toast.mockClear();completionError = null;- mockSearchParams = new URLSearchParams();+ window.history.replaceState(null, "", "/");mockPathname = "/signup";mockIsLoggedIn = true;mockIsCompleted = false;@@ -173,7 +174,8 @@ describe("OnboardingProvider routing — logged-in user", () => {test("a safe ?next= deep link defers to the auth page — no redirect from provider", async () => {mockPathname = "/login";- mockSearchParams = new URLSearchParams({ next: "/library" });+ // The provider reads `next` off the committed URL, not useSearchParams.+ window.history.replaceState(null, "", "/login?next=%2Flibrary");mockIsCompleted = true;render(@@ -189,12 +191,38 @@ describe("OnboardingProvider routing — logged-in user", () => {expect(completedCallCount.value).toBe(0);});+ test("dropping ?next= on the same auth page re-runs the redirect", async () => {+ mockPathname = "/login";+ window.history.replaceState(null, "", "/login?next=%2Flibrary");+ mockIsCompleted = true;+ const { rerender } = render(+ <OnboardingProvider>+ <div data-testid="child" />+ </OnboardingProvider>,+ );+ await new Promise((r) => setTimeout(r, 30));+ expect(routerReplace).not.toHaveBeenCalled();++ window.history.replaceState(null, "", "/login");+ rerender(+ <OnboardingProvider>+ <div data-testid="child" />+ </OnboardingProvider>,+ );++ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ });+test("an unsafe ?next= value is treated as no deep link and the provider routes normally", async () => {// `sanitizeAuthNext` drops absolute URLs as null. Without the alignment// fix, OnboardingProvider would defer (assuming the auth page handles it)// while the auth page silently drops the value — deadlocking the user.mockPathname = "/signup";- mockSearchParams = new URLSearchParams({ next: "https://phishing.site" });+ window.history.replaceState(+ null,+ "",+ `/signup?next=${encodeURIComponent("https://phishing.site")}`,+ );mockIsCompleted = false;render(diff --git a/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx b/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsxindex 322f78939f..5f762b784b 100644--- a/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx+++ b/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx@@ -17,13 +17,14 @@ import {} from "@/lib/autogpt-server-api";import { useBackendAPI } from "@/lib/autogpt-server-api/context";import { useAuth } from "@/lib/auth/hooks/useAuth";-import { usePathname, useRouter, useSearchParams } from "next/navigation";+import { usePathname, useRouter } from "next/navigation";import {createContext,ReactNode,useCallback,useContext,useEffect,+ useMemo,useRef,useState,} from "react";@@ -34,6 +35,8 @@ import {shouldRedirectFromOnboarding,updateOnboardingState,} from "./helpers";+import { AuthDeepLinkWatcher } from "./AuthDeepLinkWatcher";+import isEqual from "lodash/isEqual";type FrontendOnboardingStep = PostV1CompleteOnboardingStepStep;@@ -78,6 +81,21 @@ export function useOnboarding(return context;}+// When `/login?next=/profile` is hit, useLoginPage/useSignupPage fires its own+// redirect to the requested target, so the provider must not race it. Sanitize+// with the same helper the auth pages use — otherwise an unsafe value (e.g.+// `?next=https://evil.site`) would defer us here while the auth page drops it+// as `null`, deadlocking the user on the auth loader. Read from the location+// (only ever inside an effect, after Next has committed the URL) instead of+// useSearchParams, which would re-render this app-root provider on every+// search-param write anywhere in the app. AuthDeepLinkWatcher re-runs the+// effect when `next` changes on an auth route.+function readPendingAuthDeepLink(isOnAuthRoute: boolean) {+ if (!isOnAuthRoute) return false;+ const next = new URLSearchParams(window.location.search).get("next");+ return sanitizeAuthNext(next) !== null;+}+export default function OnboardingProvider({children,}: {@@ -85,6 +103,8 @@ export default function OnboardingProvider({}) {const [state, setState] = useState<UserOnboarding | null>(null);const [step, setStep] = useState(1);+ // Only a re-run trigger for the init effect, which reads the live URL.+ const [authDeepLinkPending, setAuthDeepLinkPending] = useState(false);const hasInitialized = useRef(false);const isMounted = useRef(true);const pendingUpdatesRef = useRef<Set<Promise<void>>>(new Set());@@ -92,7 +112,6 @@ export default function OnboardingProvider({const api = useBackendAPI();const pathname = usePathname();- const searchParams = useSearchParams();const router = useRouter();const { isLoggedIn } = useAuth();@@ -129,20 +148,16 @@ export default function OnboardingProvider({// Handling them here (instead of in useSignupPage/useLoginPage) avoids the// /signup → / → /copilot → /onboarding bounce that flashes /copilot.const isOnAuthRoute = pathname === "/signup" || pathname === "/login";- // When `/login?next=/profile` is hit, useLoginPage/useSignupPage fires its- // own redirect to the requested target. Skip our redirect in that window so- // the deep link isn't clobbered by the awaited completion check. Sanitize- // with the same helper the auth pages use — otherwise an unsafe value (e.g.- // `?next=https://evil.site`) would defer us here while the auth page drops- // it as `null`, deadlocking the user on the auth loader.- const hasPendingAuthDeepLink =- isOnAuthRoute && sanitizeAuthNext(searchParams.get("next")) !== null;const fetchOnboarding = useCallback(async () => {const onboarding = await resolveResponse(getV1OnboardingState());const processedOnboarding = fromBackendUserOnboarding(onboarding);if (isMounted.current) {- setState(processedOnboarding);+ // A websocket `onboarding` notification refetches even when nothing+ // changed; keeping the old object spares every consumer a re-render.+ setState((prev) =>+ isEqual(prev, processedOnboarding) ? prev : processedOnboarding,+ );}return processedOnboarding;}, []);@@ -173,6 +188,7 @@ export default function OnboardingProvider({// Defer to the auth-page's own deep-link redirect (`?next=…`) instead of// racing it. Don't mark hasInitialized so the next pathname change// (after the auth page redirects) gets us properly initialized.+ const hasPendingAuthDeepLink = readPendingAuthDeepLink(isOnAuthRoute);if (hasPendingAuthDeepLink) {return;}@@ -232,7 +248,7 @@ export default function OnboardingProvider({api,isOnOnboardingRoute,isOnAuthRoute,- hasPendingAuthDeepLink,+ authDeepLinkPending,router,isLoggedIn,pathname,@@ -332,16 +348,16 @@ export default function OnboardingProvider({[isLoggedIn, state?.completedSteps, fetchOnboarding, toast],);+ const value = useMemo(+ () => ({ state, updateState, step, setStep, completeStep }),+ [state, updateState, step, completeStep],+ );+return (- <OnboardingContext.Provider- value={{- state,- updateState,- step,- setStep,- completeStep,- }}- >+ <OnboardingContext.Provider value={value}>+ {isOnAuthRoute && (+ <AuthDeepLinkWatcher onChange={setAuthDeepLinkPending} />+ )}{children}</OnboardingContext.Provider>);