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.
feat(frontend): add AutoGPT new layout sidebar behind feature flag (#13365)
Abhimanyu Yadav47defad8a6a2
diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsxnew file mode 100644index 0000000000..5a0af176a1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx@@ -0,0 +1,60 @@+"use client";++import { CSSProperties, ReactNode } from "react";++import { AppSidebar } from "@/components/layout/AppSidebar/AppSidebar";+import { Navbar } from "@/components/layout/Navbar/Navbar";+import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";+import {+ SidebarInset,+ SidebarProvider,+ SidebarTrigger,+} from "@/components/ui/sidebar";++import { AdminImpersonationBanner } from "../admin/components/AdminImpersonationBanner";+import { GlobalSearchOverlay } from "../components/GlobalSearchModal/GlobalSearchOverlay";+import { PaywallGate } from "../PaywallGate/PaywallGate";+import { InsetHeaderActions } from "./components/InsetHeaderActions/InsetHeaderActions";+import { usePlatformChrome } from "./usePlatformChrome";++interface Props {+ children: ReactNode;+}++export function PlatformChrome({ children }: Props) {+ const { showNewLayout } = usePlatformChrome();++ const content = (+ <TopUpPromptProvider>+ <PaywallGate>{children}</PaywallGate>+ </TopUpPromptProvider>+ );++ if (showNewLayout) {+ return (+ <SidebarProvider style={{ "--sidebar-width": "19rem" } as CSSProperties}>+ <AppSidebar />+ <SidebarInset className="bg-[#F8F8F9]">+ <header className="flex h-12 shrink-0 items-center justify-end gap-2 px-4">+ <div className="mr-auto md:hidden">+ <SidebarTrigger />+ </div>+ <InsetHeaderActions />+ </header>+ <AdminImpersonationBanner />+ <GlobalSearchOverlay />+ <section className="flex-1">{content}</section>+ </SidebarInset>+ </SidebarProvider>+ );+ }++ return (+ <main className="flex h-screen w-full flex-col">+ <Navbar />+ <AdminImpersonationBanner />+ <GlobalSearchOverlay />+ <section className="flex-1">{content}</section>+ </main>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/PlatformChrome.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/PlatformChrome.test.tsxnew file mode 100644index 0000000000..aadb7efd7e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/PlatformChrome.test.tsx@@ -0,0 +1,72 @@+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { PlatformChrome } from "../PlatformChrome";++const showNewLayoutMock = vi.fn<() => boolean>(() => false);+vi.mock("../usePlatformChrome", () => ({+ usePlatformChrome: () => ({ showNewLayout: showNewLayoutMock() }),+}));++vi.mock("@/components/layout/AppSidebar/AppSidebar", () => ({+ AppSidebar: () => <div data-testid="app-sidebar" />,+}));+vi.mock("@/components/layout/Navbar/Navbar", () => ({+ Navbar: () => <div data-testid="navbar" />,+}));+vi.mock("@/components/layout/TopUpPrompt/TopUpPromptProvider", () => ({+ TopUpPromptProvider: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+}));+vi.mock("../../PaywallGate/PaywallGate", () => ({+ PaywallGate: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.mock("../../admin/components/AdminImpersonationBanner", () => ({+ AdminImpersonationBanner: () => null,+}));+vi.mock("../../components/GlobalSearchModal/GlobalSearchOverlay", () => ({+ GlobalSearchOverlay: () => <div data-testid="global-search" />,+}));+vi.mock("../components/InsetHeaderActions/InsetHeaderActions", () => ({+ InsetHeaderActions: () => <div data-testid="inset-actions" />,+}));++afterEach(() => {+ vi.clearAllMocks();+});++describe("PlatformChrome", () => {+ beforeEach(() => {+ showNewLayoutMock.mockReturnValue(false);+ });++ it("renders the classic Navbar shell when the new layout is off", () => {+ render(+ <PlatformChrome>+ <div data-testid="child">content</div>+ </PlatformChrome>,+ );++ expect(screen.getByTestId("navbar")).toBeDefined();+ expect(screen.queryByTestId("app-sidebar")).toBeNull();+ expect(screen.getByTestId("child")).toBeDefined();+ });++ it("renders the new sidebar shell with inset actions when enabled", async () => {+ showNewLayoutMock.mockReturnValue(true);+ render(+ <PlatformChrome>+ <div data-testid="child">content</div>+ </PlatformChrome>,+ );++ await waitFor(() => {+ expect(screen.getByTestId("app-sidebar")).toBeDefined();+ });+ expect(screen.getByTestId("inset-actions")).toBeDefined();+ expect(screen.queryByTestId("navbar")).toBeNull();+ expect(screen.getByTestId("child")).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.tsnew file mode 100644index 0000000000..154370e833--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/__tests__/usePlatformChrome.test.ts@@ -0,0 +1,71 @@+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { usePlatformChrome } from "../usePlatformChrome";++const pathnameMock = vi.fn<() => string>(() => "/marketplace");+vi.mock("next/navigation", () => ({+ usePathname: () => pathnameMock(),+}));++const flagMock = vi.fn<(flag: string) => boolean>(() => true);+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: (flag: string) => flagMock(flag),+ };+});++describe("usePlatformChrome", () => {+ beforeEach(() => {+ pathnameMock.mockReturnValue("/marketplace");+ flagMock.mockReturnValue(true);+ });++ it("enables the new layout after mount when the flag is on and route is allowed", async () => {+ const { result } = renderHook(() => usePlatformChrome());++ await waitFor(() => {+ expect(result.current.showNewLayout).toBe(true);+ });+ });++ it("keeps the classic layout when the flag is off", async () => {+ flagMock.mockReturnValue(false);+ const { result } = renderHook(() => usePlatformChrome());++ await waitFor(() => {+ expect(result.current.showNewLayout).toBe(false);+ });+ });++ it("excludes the /settings route from the new layout", async () => {+ pathnameMock.mockReturnValue("/settings");+ const { result } = renderHook(() => usePlatformChrome());++ await waitFor(() => {+ // give the mount effect a chance to run; it should still be false.+ expect(result.current.showNewLayout).toBe(false);+ });+ });++ it("excludes nested /settings/* routes from the new layout", async () => {+ pathnameMock.mockReturnValue("/settings/billing");+ const { result } = renderHook(() => usePlatformChrome());++ await waitFor(() => {+ expect(result.current.showNewLayout).toBe(false);+ });+ });++ it("passes the flag enum to useGetFlag", async () => {+ renderHook(() => usePlatformChrome());+ await waitFor(() => {+ expect(flagMock).toHaveBeenCalledWith("autogpt-new-layout");+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/InsetHeaderActions.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/InsetHeaderActions.tsxnew file mode 100644index 0000000000..42ee1118bb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/InsetHeaderActions.tsx@@ -0,0 +1,48 @@+"use client";++import { useGetV2GetUserProfile } from "@/app/api/__generated__/endpoints/store/store";+import { okData } from "@/app/api/helpers";+import { AccountMenu } from "@/components/layout/Navbar/components/AccountMenu/AccountMenu";+import { AgentActivityDropdown } from "@/components/layout/Navbar/components/AgentActivityDropdown/AgentActivityDropdown";+import { Wallet } from "@/components/layout/Navbar/components/Wallet/Wallet";+import { getAccountMenuItems } from "@/components/layout/Navbar/helpers";+import { isLogoutInProgress } from "@/lib/autogpt-server-api/helpers";+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";+import { UsageIndicator } from "@/app/(platform)/PlatformChrome/components/UsageIndicator/UsageIndicator";++export function InsetHeaderActions() {+ const { user, isLoggedIn, isUserLoading } = useSupabase();+ const logoutInProgress = isLogoutInProgress();+ const dynamicMenuItems = getAccountMenuItems(user?.role);++ const { data: profile, isLoading: isProfileLoading } = useGetV2GetUserProfile(+ {+ query: {+ select: okData,+ enabled: isLoggedIn && !!user && !logoutInProgress,+ queryKey: ["/api/store/profile", user?.id],+ },+ },+ );++ if (!isLoggedIn) return null;++ const isLoadingProfile = isProfileLoading || isUserLoading;++ return (+ <div className="flex items-center gap-4">+ <div className="[&_button:hover]:bg-zinc-200 [&_button]:flex [&_button]:h-8 [&_button]:w-8 [&_button]:items-center [&_button]:justify-center [&_button]:rounded-xl [&_button]:border [&_button]:border-zinc-200 [&_button]:bg-zinc-100 [&_button]:p-0 [&_svg]:!size-5">+ <AgentActivityDropdown />+ </div>+ <UsageIndicator />+ {profile && <Wallet key={profile.username} compact />}+ <AccountMenu+ userName={profile?.name || profile?.username}+ userEmail={user?.email}+ avatarSrc={profile?.avatar_url ?? ""}+ menuItemGroups={dynamicMenuItems}+ isLoading={isLoadingProfile}+ />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/__tests__/InsetHeaderActions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/__tests__/InsetHeaderActions.test.tsxnew file mode 100644index 0000000000..89bd768249--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/__tests__/InsetHeaderActions.test.tsx@@ -0,0 +1,75 @@+import { render, screen } from "@/tests/integrations/test-utils";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { server } from "@/mocks/mock-server";++import { InsetHeaderActions } from "../InsetHeaderActions";++const mockUseSupabase = vi.fn();+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: () => mockUseSupabase(),+}));++vi.mock(+ "@/components/layout/Navbar/components/AgentActivityDropdown/AgentActivityDropdown",+ () => ({ AgentActivityDropdown: () => <div data-testid="agent-activity" /> }),+);+vi.mock("@/components/layout/Navbar/components/Wallet/Wallet", () => ({+ Wallet: () => <div data-testid="wallet" />,+}));+vi.mock(+ "@/components/layout/Navbar/components/AccountMenu/AccountMenu",+ () => ({+ AccountMenu: ({ userName }: { userName?: string }) => (+ <div data-testid="account-menu">{userName}</div>+ ),+ }),+);+vi.mock(+ "@/app/(platform)/PlatformChrome/components/UsageIndicator/UsageIndicator",+ () => ({ UsageIndicator: () => <div data-testid="usage-indicator" /> }),+);++beforeEach(() => {+ server.use(+ http.get("*/api/store/profile", () =>+ HttpResponse.json({+ username: "alice",+ name: "Alice",+ avatar_url: "",+ }),+ ),+ );+});++afterEach(() => {+ vi.clearAllMocks();+ server.resetHandlers();+});++describe("InsetHeaderActions", () => {+ it("renders nothing when the viewer is logged out", () => {+ mockUseSupabase.mockReturnValue({+ user: null,+ isLoggedIn: false,+ isUserLoading: false,+ });+ const { container } = render(<InsetHeaderActions />);+ expect(container.firstChild).toBeNull();+ });++ it("renders the header actions for a logged-in user", async () => {+ mockUseSupabase.mockReturnValue({+ user: { id: "u1", email: "[email protected]", role: "user" },+ isLoggedIn: true,+ isUserLoading: false,+ });+ render(<InsetHeaderActions />);++ expect(screen.getByTestId("agent-activity")).toBeDefined();+ expect(screen.getByTestId("usage-indicator")).toBeDefined();+ expect(screen.getByTestId("account-menu")).toBeDefined();+ expect(await screen.findByTestId("wallet")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/UsageIndicator.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/UsageIndicator.tsxnew file mode 100644index 0000000000..4bce8ca00d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/UsageIndicator.tsx@@ -0,0 +1,49 @@+"use client";++import { UsagePopover } from "@/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover";+import { GaugeIcon } from "@phosphor-icons/react";+import { useUsageIndicator } from "./useUsageIndicator";++export function UsageIndicator() {+ const { percent } = useUsageIndicator();+ const label =+ percent !== null ? `Today's usage: ${percent}%` : "Today's usage";++ return (+ <UsagePopover+ align="end"+ trigger={+ <button+ type="button"+ aria-label={label}+ title={label}+ className="relative flex size-8 items-center justify-center rounded-xl border border-zinc-200 bg-zinc-100 p-0 transition-colors hover:bg-zinc-200"+ >+ <GaugeIcon className="size-5 text-black" />++ {percent ? (+ <svg+ viewBox="0 0 32 32"+ fill="none"+ aria-hidden+ className="pointer-events-none absolute inset-0 size-full"+ >+ <rect+ x="1"+ y="1"+ width="30"+ height="30"+ rx="11"+ pathLength={100}+ strokeDasharray={`${percent} 100`}+ strokeLinecap="round"+ strokeWidth={2}+ className="stroke-purple-600"+ />+ </svg>+ ) : null}+ </button>+ }+ />+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/__tests__/UsageIndicator.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/__tests__/UsageIndicator.test.tsxnew file mode 100644index 0000000000..290705e042--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/__tests__/UsageIndicator.test.tsx@@ -0,0 +1,46 @@+import { render, screen } from "@/tests/integrations/test-utils";+import { http, HttpResponse } from "msw";+import { afterEach, describe, expect, it, vi } from "vitest";++import { server } from "@/mocks/mock-server";++import { UsageIndicator } from "../UsageIndicator";++// UsagePopover pulls in the full usage limits stack; stub it to a passthrough+// that just renders its trigger so we can assert the indicator button itself.+vi.mock(+ "@/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover",+ () => ({+ UsagePopover: ({ trigger }: { trigger: React.ReactNode }) => (+ <div>{trigger}</div>+ ),+ }),+);++function usageHandler(body: { daily: { percent_used: number } | null }) {+ return http.get("*/api/chat/usage", () => HttpResponse.json(body));+}++afterEach(() => {+ server.resetHandlers();+});++describe("UsageIndicator", () => {+ it("renders a generic label before usage resolves", async () => {+ server.use(usageHandler({ daily: null }));+ render(<UsageIndicator />);++ expect(+ await screen.findByRole("button", { name: "Today's usage" }),+ ).toBeDefined();+ });++ it("renders the percent in the label and draws the gauge arc", async () => {+ server.use(usageHandler({ daily: { percent_used: 64 } }));+ render(<UsageIndicator />);++ expect(+ await screen.findByRole("button", { name: "Today's usage: 64%" }),+ ).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/__tests__/useUsageIndicator.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/__tests__/useUsageIndicator.test.tsxnew file mode 100644index 0000000000..aa4d82b2cb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/__tests__/useUsageIndicator.test.tsx@@ -0,0 +1,81 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it } from "vitest";++import { server } from "@/mocks/mock-server";++import { useUsageIndicator } from "../useUsageIndicator";++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ }+ return Wrapper;+}++function usageHandler(body: { daily: { percent_used: number } | null }) {+ return http.get("*/api/chat/usage", () => HttpResponse.json(body));+}++afterEach(() => {+ server.resetHandlers();+});++describe("useUsageIndicator", () => {+ it("rounds and clamps the daily percent used", async () => {+ server.use(usageHandler({ daily: { percent_used: 42.7 } }));++ const { result } = renderHook(() => useUsageIndicator(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });+ expect(result.current.percent).toBe(43);+ });++ it("clamps percentages above 100 to 100", async () => {+ server.use(usageHandler({ daily: { percent_used: 150 } }));++ const { result } = renderHook(() => useUsageIndicator(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => {+ expect(result.current.percent).toBe(100);+ });+ });++ it("clamps negative percentages to 0", async () => {+ server.use(usageHandler({ daily: { percent_used: -20 } }));++ const { result } = renderHook(() => useUsageIndicator(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => {+ expect(result.current.percent).toBe(0);+ });+ });++ it("returns a null percent when there is no daily usage", async () => {+ server.use(usageHandler({ daily: null }));++ const { result } = renderHook(() => useUsageIndicator(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });+ expect(result.current.percent).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/useUsageIndicator.ts b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/useUsageIndicator.tsnew file mode 100644index 0000000000..0d3d520734--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/UsageIndicator/useUsageIndicator.ts@@ -0,0 +1,21 @@+"use client";++import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";++export function useUsageIndicator() {+ const { data, isLoading } = useGetV2GetCopilotUsage({+ query: {+ select: (res) => res.data as CoPilotUsagePublic | undefined,+ refetchInterval: 30_000,+ staleTime: 10_000,+ },+ });++ const daily = data?.daily;+ const percent = daily+ ? Math.min(100, Math.max(0, Math.round(daily.percent_used)))+ : null;++ return { percent, isLoading };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.ts b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.tsnew file mode 100644index 0000000000..5daa993fa5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/usePlatformChrome.ts@@ -0,0 +1,31 @@+import { usePathname } from "next/navigation";+import { useEffect, useState } from "react";++import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";++// Routes that must stay outside the new top-level sidebar layout. Login,+// signup and onboarding already live in the (no-navbar) group, so settings+// is the only (platform) route to exclude here.+const NEW_LAYOUT_EXCLUDED_PREFIXES = ["/settings"];++export function usePlatformChrome() {+ const pathname = usePathname();+ const isNewLayoutEnabled = useGetFlag(Flag.AUTOGPT_NEW_LAYOUT);++ // 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+ // on it directly causes a hydration mismatch, so we only apply the new+ // layout after mount — the server and first client paint always render the+ // classic shell, then we swap once the flag is known on the client.+ const [isMounted, setIsMounted] = useState(false);+ useEffect(() => setIsMounted(true), []);++ const isExcludedRoute = NEW_LAYOUT_EXCLUDED_PREFIXES.some((prefix) => {+ if (!pathname) return false;+ return pathname === prefix || pathname.startsWith(`${prefix}/`);+ });++ return {+ showNewLayout: isMounted && isNewLayoutEnabled && !isExcludedRoute,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsx b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsxindex 931ea60c03..c6102f4da6 100644--- a/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/components/GlobalSearchModal/GlobalSearchOverlay.tsx@@ -10,7 +10,12 @@ import { useGlobalSearchStore } from "./useGlobalSearchStore";// Mounted once in the platform layout so Cmd/Ctrl+K opens the search palette// from any page. Renders a single modal instance driven by the shared store.export function GlobalSearchOverlay() {- const isEnabled = useGetFlag(Flag.CHAT_SEARCH);+ // Search is a first-class part of the new layout (sidebar Search item ++ // Cmd/Ctrl+K), so enable it whenever that layout is on, independent of the+ // chat-search flag that gates it in the classic layout.+ const isChatSearchEnabled = useGetFlag(Flag.CHAT_SEARCH);+ const isNewLayoutEnabled = useGetFlag(Flag.AUTOGPT_NEW_LAYOUT);+ const isEnabled = isChatSearchEnabled || isNewLayoutEnabled;const router = useRouter();const pathname = usePathname();const isOpen = useGlobalSearchStore((state) => state.isOpen);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsxindex 3e0cc00c7e..28965fc657 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx@@ -6,6 +6,7 @@ import { SidebarProvider } from "@/components/ui/sidebar";import { NAVBAR_HEIGHT_PX } from "@/lib/constants";import { useSupabase } from "@/lib/supabase/hooks/useSupabase";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { usePlatformChrome } from "../PlatformChrome/usePlatformChrome";import dynamic from "next/dynamic";import { parseAsString, useQueryState } from "nuqs";import { useState } from "react";@@ -41,6 +42,10 @@ export function CopilotPage() {const [droppedFiles, setDroppedFiles] = useState<File[]>([]);const isMobile = useIsMobile();const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);+ // Use the same mount-gated decision as PlatformChrome so the ChatSidebar is+ // hidden in lockstep with the layout swap — avoids a one-frame flash where+ // the classic shell renders without its sidebar before the new layout mounts.+ const { showNewLayout } = usePlatformChrome();const { isUserLoading, isLoggedIn } = useSupabase();// Read sessionId here purely to key the chat-host subtree. The view still// remounts on session switch, but the underlying AI SDK Chat runtime now@@ -59,15 +64,21 @@ export function CopilotPage() {return (<SidebarProviderdefaultOpen={true}- // Explicit height: `h-full` against <section className="flex-1"> drifts- // out of sync with the navbar-driven --preview-banner-height var during- // re-renders, clipping the navbar when the sidebar toggles.- style={{- height: `calc(100vh - ${NAVBAR_HEIGHT_PX}px - var(--preview-banner-height, 0px))`,- }}+ // New layout: fill the inset's flex-1 section (its 48px header is already+ // accounted for by the parent), so don't subtract the old navbar height.+ // Classic layout: an explicit height is needed because `h-full` against+ // <section className="flex-1"> drifts out of sync with the navbar-driven+ // --preview-banner-height var during re-renders, clipping the navbar.+ style={+ showNewLayout+ ? { height: "100%" }+ : {+ height: `calc(100vh - ${NAVBAR_HEIGHT_PX}px - var(--preview-banner-height, 0px))`,+ }+ }className="min-h-0">- {!isMobile && <ChatSidebar />}+ {!isMobile && !showNewLayout && <ChatSidebar />}<MainAreaisMobile={isMobile}isArtifactsEnabled={isArtifactsEnabled}@@ -79,7 +90,7 @@ export function CopilotPage() {<ContextPanel sessionId={sessionId} mobile />)}{isMobile && isArtifactsEnabled && <ArtifactPanel mobile />}- {isMobile && <MobileDrawer />}+ {isMobile && !showNewLayout && <MobileDrawer />}<NotificationDialog /></SidebarProvider>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsxindex 6f2002d651..c00956a333 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsx@@ -10,12 +10,18 @@ import {} from "@/components/molecules/Popover/Popover";import { ChartBarIcon } from "@phosphor-icons/react";import Link from "next/link";+import type { ReactNode } from "react";import { formatTierLabel, TIER_BADGE_CLASS_NAME } from "../../usageHelpers";import { StorageBar } from "../StorageBar";import { UsageBar } from "../UsageBar";import { useUsagePopover } from "./useUsagePopover";-export function UsagePopover() {+interface Props {+ trigger?: ReactNode;+ align?: "start" | "center" | "end";+}++export function UsagePopover({ trigger, align = "start" }: Props) {const { usage, isSuccess, isBillingEnabled } = useUsagePopover();if (!isSuccess || !usage) return null;@@ -26,14 +32,16 @@ export function UsagePopover() {return (<Popover><PopoverTrigger asChild>- <Button variant="ghost" size="icon" aria-label="Usage limits">- <ChartBarIcon className="!size-5" weight="light" />- </Button>+ {trigger ?? (+ <Button variant="ghost" size="icon" aria-label="Usage limits">+ <ChartBarIcon className="!size-5" weight="light" />+ </Button>+ )}</PopoverTrigger>{/* z-[80]: must layer above the AutoPilot mobile drawer(overlay z-[60], content z-[70] in MobileDrawer.tsx) so thepopover doesn't render under the drawer's blur. */}- <PopoverContent align="start" className="z-[80] w-72 p-4">+ <PopoverContent align={align} className="z-[80] w-72 p-4"><div className="flex flex-col gap-4"><div className="flex items-center gap-2"><Text variant="body-medium" className="text-neutral-800">diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsxindex 469ce83350..336ad5d8ec 100644--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx@@ -1,28 +1,15 @@-import { Navbar } from "@/components/layout/Navbar/Navbar";import { NetworkStatusMonitor } from "@/services/network-status/NetworkStatusMonitor";import { PushNotificationProvider } from "@/services/push-notifications/PushNotificationProvider";import { ReactNode } from "react";-import { AdminImpersonationBanner } from "./admin/components/AdminImpersonationBanner";import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";-import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";-import { PaywallGate } from "./PaywallGate/PaywallGate";-import { GlobalSearchOverlay } from "./components/GlobalSearchModal/GlobalSearchOverlay";+import { PlatformChrome } from "./PlatformChrome/PlatformChrome";export default function PlatformLayout({ children }: { children: ReactNode }) {return (<AutoPilotBridgeProvider>- <main className="flex h-screen w-full flex-col">- <NetworkStatusMonitor />- <PushNotificationProvider />- <Navbar />- <AdminImpersonationBanner />- <GlobalSearchOverlay />- <section className="flex-1">- <TopUpPromptProvider>- <PaywallGate>{children}</PaywallGate>- </TopUpPromptProvider>- </section>- </main>+ <NetworkStatusMonitor />+ <PushNotificationProvider />+ <PlatformChrome>{children}</PlatformChrome></AutoPilotBridgeProvider>);}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsxnew file mode 100644index 0000000000..fbff112c1d--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx@@ -0,0 +1,244 @@+"use client";++import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import {+ Sidebar,+ SidebarContent,+ SidebarGroup,+ SidebarGroupContent,+ SidebarGroupLabel,+ SidebarMenu,+ SidebarMenuButton,+ SidebarMenuItem,+ SidebarRail,+} from "@/components/ui/sidebar";+import {+ CaretDownIcon,+ FlowArrowIcon,+ FolderIcon,+ type Icon,+ SparkleIcon,+ SquaresFourIcon,+ StorefrontIcon,+} from "@phosphor-icons/react";+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";+import { cn } from "@/lib/utils";+import { motion, useReducedMotion } from "framer-motion";+import Link, { useLinkStatus } from "next/link";+import { usePathname } from "next/navigation";+import { ComponentProps, ReactNode, Suspense } from "react";+import { getSidebarItemVariants, sidebarContainerVariants } from "./animations";+import { AppSidebarHeader } from "./components/AppSidebarHeader/AppSidebarHeader";+import { RecentChats } from "./components/RecentChats/RecentChats";+import { SidebarSearch } from "./components/SidebarSearch/SidebarSearch";++type NavLink = {+ name: string;+ href: string;+ icon: Icon;+};++const MAIN_LINKS: NavLink[] = [+ { name: "Agents", href: "/library", icon: SquaresFourIcon },+ { name: "Marketplace", href: "/marketplace", icon: StorefrontIcon },+ { name: "Build", href: "/build", icon: FlowArrowIcon },+];++const WORKSPACE_LINKS: NavLink[] = [+ { name: "Files", href: "/artifacts", icon: FolderIcon },+];++function isLinkActive(pathname: string | null, href: string) {+ if (!pathname) return false;+ return pathname === href || pathname.startsWith(`${href}/`);+}++// Rendered inside the <Link>, so useLinkStatus reports that link's pending+// navigation — show a spinner until the destination page is reached.+function NavLinkLoader() {+ const { pending } = useLinkStatus();++ if (!pending) return null;++ return (+ <LoadingSpinner+ size="small"+ className="ml-auto !size-4 shrink-0 text-zinc-500"+ />+ );+}++// Rendered inside the New Task <Link> — swap the sparkle for a spinner while+// navigation to /copilot is pending, then back to the sparkle once it lands.+function NewTaskIcon() {+ const { pending } = useLinkStatus();++ if (pending) {+ return <LoadingSpinner size="small" className="shrink-0" />;+ }++ return <SparkleIcon className="size-4" />;+}++function NavMenu({+ links,+ leading,+}: {+ links: NavLink[];+ leading?: ReactNode;+}) {+ const pathname = usePathname();++ return (+ <SidebarMenu className="group-data-[collapsible=icon]:gap-1">+ {leading}+ {links.map((link) => (+ <SidebarMenuItem key={link.href}>+ <SidebarMenuButton+ asChild+ tooltip={link.name}+ isActive={isLinkActive(pathname, link.href)}+ className="font-normal data-[active=true]:!bg-zinc-200 data-[active=true]:font-normal group-data-[collapsible=icon]:!p-1.5 hover:!bg-zinc-200 [&>svg]:size-5"+ >+ <Link href={link.href}>+ <link.icon className="size-5" />+ <span className="truncate">{link.name}</span>+ <NavLinkLoader />+ </Link>+ </SidebarMenuButton>+ </SidebarMenuItem>+ ))}+ </SidebarMenu>+ );+}++function CollapsibleNavGroup({+ label,+ children,+ scrollable = false,+}: {+ label: string;+ children: ReactNode;+ scrollable?: boolean;+}) {+ return (+ <Collapsible+ defaultOpen+ className={cn(+ "group/collapsible",+ scrollable && "flex min-h-0 flex-1 flex-col",+ )}+ >+ <SidebarGroup+ className={cn("py-1", scrollable && "flex min-h-0 flex-1 flex-col")}+ >+ <SidebarGroupLabel asChild className="text-[13px] font-medium">+ <CollapsibleTrigger>+ {label}+ <CaretDownIcon+ weight="bold"+ className="ease-[cubic-bezier(0.33,1,0.68,1)] ml-auto size-4 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-180 motion-reduce:transition-none"+ />+ </CollapsibleTrigger>+ </SidebarGroupLabel>+ <CollapsibleContent+ className={cn(+ "overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down motion-reduce:animate-none",+ scrollable && "flex min-h-0 flex-1 flex-col",+ )}+ >+ <SidebarGroupContent+ className={+ scrollable+ ? "min-h-0 flex-1 overflow-y-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ : undefined+ }+ >+ {children}+ </SidebarGroupContent>+ </CollapsibleContent>+ </SidebarGroup>+ </Collapsible>+ );+}++type Props = ComponentProps<typeof Sidebar>;++export function AppSidebar(props: Props) {+ const reduceMotion = useReducedMotion();+ const itemVariants = getSidebarItemVariants(!!reduceMotion);++ return (+ <Sidebar+ collapsible="icon"+ {...props}+ className="[&_[data-sidebar=sidebar]]:bg-[#F3F3F4]"+ >+ <AppSidebarHeader />++ <SidebarContent className="gap-2 overflow-hidden">+ <motion.div+ variants={sidebarContainerVariants}+ initial="hidden"+ animate="show"+ className="flex min-h-0 flex-1 flex-col gap-2"+ >+ <motion.div variants={itemVariants}>+ <SidebarGroup className="mt-2 py-1 group-data-[collapsible=icon]:mt-0">+ <SidebarGroupContent>+ <SidebarMenu>+ <SidebarMenuItem>+ <SidebarMenuButton+ asChild+ tooltip="New Task"+ className="justify-center rounded-lg bg-zinc-800 font-medium text-white group-data-[collapsible=icon]:justify-start hover:!bg-zinc-900 hover:!text-white"+ >+ <Link href="/copilot">+ <NewTaskIcon />+ <span className="truncate">New Task</span>+ </Link>+ </SidebarMenuButton>+ </SidebarMenuItem>+ </SidebarMenu>+ </SidebarGroupContent>+ </SidebarGroup>+ </motion.div>++ <motion.div variants={itemVariants}>+ <SidebarGroup className="mt-2 py-1 group-data-[collapsible=icon]:mt-0">+ <SidebarGroupContent>+ <NavMenu links={MAIN_LINKS} leading={<SidebarSearch />} />+ </SidebarGroupContent>+ </SidebarGroup>+ </motion.div>++ <motion.div variants={itemVariants}>+ <CollapsibleNavGroup label="Workspace">+ <NavMenu links={WORKSPACE_LINKS} />+ </CollapsibleNavGroup>+ </motion.div>++ <motion.div+ variants={itemVariants}+ className="flex min-h-0 flex-1 flex-col group-data-[collapsible=icon]:hidden"+ >+ <CollapsibleNavGroup label="Recent chats" scrollable>+ {/* Suspense boundary: RecentChats reads useSearchParams(), which+ Next.js requires to be wrapped to avoid forcing the route to+ client-side rendering. */}+ <Suspense fallback={null}>+ <RecentChats />+ </Suspense>+ </CollapsibleNavGroup>+ </motion.div>+ </motion.div>+ </SidebarContent>++ <SidebarRail />+ </Sidebar>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/AppSidebar.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/AppSidebar.test.tsxnew file mode 100644index 0000000000..e82a9619fb--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/AppSidebar.test.tsx@@ -0,0 +1,88 @@+import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import { SidebarProvider } from "@/components/ui/sidebar";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { AppSidebar } from "../AppSidebar";++// The global next/link mock only exports `default`; AppSidebar also imports+// `useLinkStatus`, so re-mock here with a no-op pending status.+vi.mock("next/link", () => ({+ __esModule: true,+ default: ({+ children,+ href,+ ...props+ }: {+ children: ReactNode;+ href: string;+ }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+ useLinkStatus: () => ({ pending: false }),+}));++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: () => false,+ };+});++function renderSidebar() {+ return render(+ <SidebarProvider>+ <AppSidebar />+ </SidebarProvider>,+ );+}++beforeEach(() => {+ server.use(getGetV2ListSessionsMockHandler200({ sessions: [], total: 0 }));+});++afterEach(() => {+ server.resetHandlers();+});++describe("AppSidebar", () => {+ it("renders the primary navigation links", () => {+ renderSidebar();+ expect(screen.getByText("Agents")).toBeDefined();+ expect(screen.getByText("Marketplace")).toBeDefined();+ expect(screen.getByText("Build")).toBeDefined();+ expect(screen.getByText("Files")).toBeDefined();+ });++ it("renders the New Task call-to-action pointing at /copilot", () => {+ renderSidebar();+ const newTask = screen.getByRole("link", { name: /new task/i });+ expect(newTask.getAttribute("href")).toBe("/copilot");+ });++ it("renders the workspace and recent chats group headers", () => {+ renderSidebar();+ expect(screen.getByText("Workspace")).toBeDefined();+ expect(screen.getByText("Recent chats")).toBeDefined();+ });++ it("marks the active link based on the current pathname", () => {+ // global next/navigation mock resolves usePathname() to "/marketplace"+ renderSidebar();+ const marketplaceLink = screen.getByText("Marketplace").closest("a");+ expect(marketplaceLink?.getAttribute("href")).toBe("/marketplace");+ });++ it("shows the recent-chats empty state once sessions resolve", async () => {+ renderSidebar();+ expect(await screen.findByText(/no conversations yet/i)).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/animations.test.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/animations.test.tsnew file mode 100644index 0000000000..7ebfb19ca4--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/animations.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";++import {+ getSidebarItemVariants,+ sidebarContainerVariants,+} from "../animations";++describe("sidebarContainerVariants", () => {+ it("staggers its children on show", () => {+ expect(sidebarContainerVariants.hidden).toEqual({});+ expect(sidebarContainerVariants.show).toMatchObject({+ transition: { delayChildren: 0.15, staggerChildren: 0.06 },+ });+ });+});++describe("getSidebarItemVariants", () => {+ it("returns an opacity-only fade when reduced motion is requested", () => {+ const variants = getSidebarItemVariants(true);+ expect(variants.hidden).toEqual({ opacity: 0 });+ expect(variants.show).toEqual({+ opacity: 1,+ transition: { duration: 0.2 },+ });+ });++ it("returns the blur+rise variant when motion is allowed", () => {+ const variants = getSidebarItemVariants(false);+ expect(variants.hidden).toMatchObject({+ opacity: 0,+ y: 8,+ filter: "blur(4px)",+ });+ expect(variants.show).toMatchObject({+ opacity: 1,+ y: 0,+ filter: "blur(0px)",+ });+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/animations.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/animations.tsnew file mode 100644index 0000000000..c1f42de1d9--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/animations.ts@@ -0,0 +1,29 @@+import type { Variants } from "framer-motion";++// Header shows first; the nav/chat items fade+rise in after a short delay,+// staggered. ease-out, well under Emil Kowalski's 300ms UI budget.+export const sidebarContainerVariants: Variants = {+ hidden: {},+ show: {+ transition: { delayChildren: 0.15, staggerChildren: 0.06 },+ },+};++export function getSidebarItemVariants(reduceMotion: boolean): Variants {+ if (reduceMotion) {+ return {+ hidden: { opacity: 0 },+ show: { opacity: 1, transition: { duration: 0.2 } },+ };+ }++ return {+ hidden: { opacity: 0, y: 8, filter: "blur(4px)" },+ show: {+ opacity: 1,+ y: 0,+ filter: "blur(0px)",+ transition: { duration: 0.25, ease: [0.25, 0.1, 0.25, 1] },+ },+ };+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/AppSidebarHeader/AppSidebarHeader.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/AppSidebarHeader/AppSidebarHeader.tsxnew file mode 100644index 0000000000..83987c8878--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/AppSidebarHeader/AppSidebarHeader.tsx@@ -0,0 +1,57 @@+"use client";++import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";+import { SidebarHeader, useSidebar } from "@/components/ui/sidebar";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { SidebarSimpleIcon } from "@phosphor-icons/react";+import Link from "next/link";++export function AppSidebarHeader() {+ const { state, toggleSidebar } = useSidebar();+ const isCollapsed = state === "collapsed";++ return (+ <SidebarHeader className="flex animate-fade-in flex-row items-center justify-between gap-2 p-2 group-data-[collapsible=icon]:flex-col">+ <Link+ href="/copilot"+ aria-label="AutoGPT"+ className={cn(+ "flex items-center",+ isCollapsed && "group-focus-within:hidden group-hover:hidden",+ )}+ >+ {isCollapsed ? (+ <AutoGPTLogo hideText viewBox="47 -1 42 42" className="size-8" />+ ) : (+ <AutoGPTLogo className="h-7 w-auto" />+ )}+ </Link>++ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={isCollapsed ? "Expand sidebar" : "Collapse sidebar"}+ onClick={toggleSidebar}+ className={cn(+ "size-8 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-zinc-200",+ isCollapsed+ ? "hidden group-focus-within:flex group-hover:flex"+ : "flex",+ )}+ >+ <SidebarSimpleIcon className="size-5 text-sidebar-foreground" />+ </button>+ </TooltipTrigger>+ <TooltipContent side="right">+ {isCollapsed ? "Expand sidebar" : "Collapse sidebar"}+ </TooltipContent>+ </Tooltip>+ </SidebarHeader>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/AppSidebarHeader/__tests__/AppSidebarHeader.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/AppSidebarHeader/__tests__/AppSidebarHeader.test.tsxnew file mode 100644index 0000000000..e766c632f7--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/AppSidebarHeader/__tests__/AppSidebarHeader.test.tsx@@ -0,0 +1,40 @@+import { render, screen } from "@/tests/integrations/test-utils";+import { SidebarProvider } from "@/components/ui/sidebar";+import userEvent from "@testing-library/user-event";+import { describe, expect, it } from "vitest";++import { AppSidebarHeader } from "../AppSidebarHeader";++function renderHeader() {+ return render(+ <SidebarProvider>+ <AppSidebarHeader />+ </SidebarProvider>,+ );+}++describe("AppSidebarHeader", () => {+ it("renders the AutoGPT home link pointing at /copilot", () => {+ renderHeader();+ const homeLink = screen.getByRole("link", { name: "AutoGPT" });+ expect(homeLink.getAttribute("href")).toBe("/copilot");+ });++ it("shows the 'Collapse sidebar' control while expanded", () => {+ renderHeader();+ expect(+ screen.getByRole("button", { name: "Collapse sidebar" }),+ ).toBeDefined();+ });++ it("toggles to 'Expand sidebar' after collapsing", async () => {+ const user = userEvent.setup();+ renderHeader();++ await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));++ expect(+ await screen.findByRole("button", { name: "Expand sidebar" }),+ ).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsxnew file mode 100644index 0000000000..bb0efa82b1--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx@@ -0,0 +1,129 @@+"use client";++import { DeleteChatDialog } from "@/app/(platform)/copilot/components/DeleteChatDialog/DeleteChatDialog";+import { ShareChatDialog } from "@/app/(platform)/copilot/sharing/ShareChatDialog";+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import { SidebarMenu } from "@/components/ui/sidebar";+import { CaretDownIcon } from "@phosphor-icons/react";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { RecentChatItem } from "./components/RecentChatItem/RecentChatItem";+import { groupSessionsByDate } from "./helpers";+import { useRecentChats } from "./useRecentChats";++export function RecentChats() {+ const chatSharingEnabled = useGetFlag(Flag.CHAT_SHARING);+ const {+ sessions,+ isLoading,+ hasMore,+ isLoadingMore,+ loadMore,+ activeSessionId,+ editingSessionId,+ editingTitle,+ setEditingTitle,+ startRename,+ submitRename,+ cancelRename,+ exportingIds,+ exportChat,+ sharingSessionId,+ setSharingSessionId,+ sessionToDelete,+ isDeleting,+ requestDelete,+ confirmDelete,+ cancelDelete,+ } = useRecentChats();++ if (isLoading) {+ return (+ <div className="flex justify-center py-4">+ <LoadingSpinner size="small" className="text-neutral-500" />+ </div>+ );+ }++ if (!sessions.length) {+ return (+ <p className="px-2 py-2 text-sm text-neutral-500">No conversations yet</p>+ );+ }++ function renderItem(session: (typeof sessions)[number]) {+ return (+ <RecentChatItem+ key={session.id}+ session={session}+ isActive={session.id === activeSessionId}+ isEditing={editingSessionId === session.id}+ editingTitle={editingTitle}+ onEditingTitleChange={setEditingTitle}+ onSubmitRename={submitRename}+ onCancelRename={cancelRename}+ isExporting={exportingIds.has(session.id)}+ isDeleting={isDeleting}+ chatSharingEnabled={chatSharingEnabled}+ onRename={startRename}+ onExport={exportChat}+ onShare={setSharingSessionId}+ onDelete={requestDelete}+ />+ );+ }++ return (+ <>+ {groupSessionsByDate(sessions).map((group) => (+ <Collapsible key={group.label} defaultOpen className="group/day">+ <CollapsibleTrigger className="flex w-full items-center gap-2 px-2 pb-1 pt-2 text-xs font-medium text-zinc-600">+ <span>{group.label}</span>+ <CaretDownIcon+ weight="bold"+ className="ease-[cubic-bezier(0.33,1,0.68,1)] ml-auto size-3.5 text-zinc-500 transition-transform duration-200 group-data-[state=open]/day:rotate-180 motion-reduce:transition-none"+ />+ </CollapsibleTrigger>+ <CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down motion-reduce:animate-none">+ <SidebarMenu>{group.sessions.map(renderItem)}</SidebarMenu>+ </CollapsibleContent>+ </Collapsible>+ ))}++ {hasMore && (+ <button+ type="button"+ onClick={() => loadMore()}+ disabled={isLoadingMore}+ className="mt-1 flex w-full items-center justify-center gap-2 rounded-md bg-zinc-200 px-2 py-1.5 text-sm text-zinc-800 hover:bg-zinc-300 disabled:opacity-60"+ >+ {isLoadingMore && (+ <LoadingSpinner size="small" className="size-4 text-zinc-500" />+ )}+ {isLoadingMore ? "Loading…" : "Load more"}+ </button>+ )}++ <DeleteChatDialog+ session={sessionToDelete}+ isDeleting={isDeleting}+ onConfirm={confirmDelete}+ onCancel={cancelDelete}+ />++ {sharingSessionId && (+ <ShareChatDialog+ sessionId={sharingSessionId}+ open={true}+ onOpenChange={(next) => {+ if (!next) setSharingSessionId(null);+ }}+ />+ )}+ </>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/RecentChats.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/RecentChats.test.tsxnew file mode 100644index 0000000000..536b2d9a2f--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/RecentChats.test.tsx@@ -0,0 +1,157 @@+import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ within,+} from "@/tests/integrations/test-utils";+import { SidebarProvider } from "@/components/ui/sidebar";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { RecentChats } from "../RecentChats";++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: (flag: string) => flag === "chat-sharing",+ };+});++interface SessionSeed {+ id: string;+ title: string;+ updated_at: string;+}++function makeSession(seed: SessionSeed) {+ return {+ id: seed.id,+ title: seed.title,+ is_processing: false,+ created_at: seed.updated_at,+ updated_at: seed.updated_at,+ };+}++const TODAY = "2026-06-30T10:00:00";+const YESTERDAY = "2026-06-29T10:00:00";++function renderRecentChats() {+ return render(+ <SidebarProvider>+ <RecentChats />+ </SidebarProvider>,+ );+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ vi.setSystemTime(new Date("2026-06-30T12:00:00"));+ useCopilotUIStore.setState({ sessionToDelete: null });+});++afterEach(() => {+ vi.useRealTimers();+ server.resetHandlers();+});++describe("RecentChats — empty + loading", () => {+ it("shows the empty state when there are no sessions", async () => {+ server.use(getGetV2ListSessionsMockHandler200({ sessions: [], total: 0 }));+ renderRecentChats();+ expect(await screen.findByText(/no conversations yet/i)).toBeDefined();+ });+});++describe("RecentChats — grouped list", () => {+ it("renders sessions grouped under date labels", async () => {+ const sessions = [+ makeSession({ id: "a", title: "Today chat", updated_at: TODAY }),+ makeSession({+ id: "b",+ title: "Yesterday chat",+ updated_at: YESTERDAY,+ }),+ ];+ server.use(+ getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),+ );+ renderRecentChats();++ expect(await screen.findByText("Today chat")).toBeDefined();+ expect(screen.getByText("Yesterday chat")).toBeDefined();+ expect(screen.getByText("Today")).toBeDefined();+ expect(screen.getByText("Yesterday")).toBeDefined();+ });+});++describe("RecentChats — load more", () => {+ it("hides 'Load more' when all sessions are loaded", async () => {+ server.use(+ getGetV2ListSessionsMockHandler200({+ sessions: [makeSession({ id: "a", title: "Only", updated_at: TODAY })],+ total: 1,+ }),+ );+ renderRecentChats();+ await screen.findByText("Only");+ expect(screen.queryByRole("button", { name: /load more/i })).toBeNull();+ });++ it("shows 'Load more' and fetches the next page", async () => {+ const seenOffsets: string[] = [];+ server.use(+ http.get("*/api/chat/sessions", ({ request }) => {+ const offset = new URL(request.url).searchParams.get("offset") ?? "0";+ seenOffsets.push(offset);+ const sessions =+ Number(offset) === 0+ ? [makeSession({ id: "p0", title: "Page 0", updated_at: TODAY })]+ : [makeSession({ id: "p1", title: "Page 1", updated_at: TODAY })];+ return HttpResponse.json({ sessions, total: 2 });+ }),+ );+ renderRecentChats();++ const loadMore = await screen.findByRole("button", { name: /load more/i });+ fireEvent.click(loadMore);++ expect(await screen.findByText("Page 1")).toBeDefined();+ expect(seenOffsets).toContain("1");+ });+});++describe("RecentChats — delete flow", () => {+ it("stages a session for deletion when Delete is chosen", async () => {+ server.use(+ getGetV2ListSessionsMockHandler200({+ sessions: [+ makeSession({ id: "x", title: "Deletable", updated_at: TODAY }),+ ],+ total: 1,+ }),+ );+ renderRecentChats();++ const row = (await screen.findByText("Deletable")).closest("li");+ if (!row) throw new Error("row not found");+ fireEvent.pointerDown(+ within(row).getByRole("button", { name: /chat actions/i }),+ { button: 0 },+ );+ fireEvent.click(+ await screen.findByRole("menuitem", { name: /delete chat/i }),+ );++ expect(useCopilotUIStore.getState().sessionToDelete).toMatchObject({+ id: "x",+ });+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/helpers.test.tsnew file mode 100644index 0000000000..8e7787bf4e--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/helpers.test.ts@@ -0,0 +1,105 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { getDateGroupLabel, groupSessionsByDate } from "../helpers";++// Pin "now" so the day-relative labels are deterministic.+const NOW = new Date("2026-06-30T12:00:00Z");++function isoDaysAgo(days: number): string {+ const d = new Date(NOW);+ d.setDate(d.getDate() - days);+ return d.toISOString();+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+});++afterEach(() => {+ vi.useRealTimers();+});++describe("getDateGroupLabel", () => {+ it("labels today's date as 'Today'", () => {+ expect(getDateGroupLabel(isoDaysAgo(0))).toBe("Today");+ });++ it("labels a future-ish (negative diff) date as 'Today'", () => {+ const future = new Date(NOW);+ future.setHours(future.getHours() + 5);+ expect(getDateGroupLabel(future.toISOString())).toBe("Today");+ });++ it("labels yesterday as 'Yesterday'", () => {+ expect(getDateGroupLabel(isoDaysAgo(1))).toBe("Yesterday");+ });++ it("labels an older same-year date with an ordinal day and month", () => {+ // 2026-06-20 -> "20th June"+ const label = getDateGroupLabel("2026-06-20T08:00:00");+ expect(label).toBe("20th June");+ });++ it("includes the year for dates in a previous year", () => {+ const label = getDateGroupLabel("2024-12-01T08:00:00");+ expect(label).toBe("1st December 2024");+ });++ it("uses 'st', 'nd', 'rd', 'th' ordinal suffixes correctly", () => {+ expect(getDateGroupLabel("2026-06-01T08:00:00")).toBe("1st June");+ expect(getDateGroupLabel("2026-06-02T08:00:00")).toBe("2nd June");+ expect(getDateGroupLabel("2026-06-03T08:00:00")).toBe("3rd June");+ expect(getDateGroupLabel("2026-06-04T08:00:00")).toBe("4th June");+ });++ it("uses 'th' for the 11th–13th teen exceptions", () => {+ expect(getDateGroupLabel("2026-06-11T08:00:00")).toBe("11th June");+ expect(getDateGroupLabel("2026-06-12T08:00:00")).toBe("12th June");+ expect(getDateGroupLabel("2026-06-13T08:00:00")).toBe("13th June");+ });+});++describe("groupSessionsByDate", () => {+ it("returns an empty array for no sessions", () => {+ expect(groupSessionsByDate([])).toEqual([]);+ });++ it("buckets sessions from the same calendar day into one group", () => {+ // Local-time (no trailing Z) so the day boundary matches the runner's+ // timezone — startOfDay() uses local getFullYear/Month/Date.+ const sessions = [+ { id: "a", updated_at: "2026-06-30T01:00:00" },+ { id: "b", updated_at: "2026-06-30T23:00:00" },+ ];+ const groups = groupSessionsByDate(sessions);+ expect(groups).toHaveLength(1);+ expect(groups[0].label).toBe("Today");+ expect(groups[0].sessions.map((s) => s.id)).toEqual(["a", "b"]);+ });++ it("orders groups most-recent-day first regardless of input order", () => {+ const sessions = [+ { id: "old", updated_at: isoDaysAgo(5) },+ { id: "today", updated_at: isoDaysAgo(0) },+ { id: "yesterday", updated_at: isoDaysAgo(1) },+ ];+ const groups = groupSessionsByDate(sessions);+ expect(groups.map((g) => g.label)).toEqual([+ "Today",+ "Yesterday",+ getDateGroupLabel(isoDaysAgo(5)),+ ]);+ });++ it("preserves input order within a group and never duplicates day buckets", () => {+ const sessions = [+ { id: "1", updated_at: "2026-06-28T03:00:00" },+ { id: "2", updated_at: "2026-06-28T20:00:00" },+ { id: "3", updated_at: "2026-06-28T11:00:00" },+ ];+ const groups = groupSessionsByDate(sessions);+ expect(groups).toHaveLength(1);+ expect(groups[0].sessions.map((s) => s.id)).toEqual(["1", "2", "3"]);+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/useRecentChats.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/useRecentChats.test.tsxnew file mode 100644index 0000000000..be652b0a1b--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/useRecentChats.test.tsx@@ -0,0 +1,175 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook, waitFor } from "@testing-library/react";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";+import { http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { server } from "@/mocks/mock-server";++import { useRecentChats } from "../useRecentChats";++const toastMock = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >();+ return {+ ...actual,+ toast: (...args: unknown[]) => toastMock(...args),+ };+});++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>+ <NuqsTestingAdapter>{children}</NuqsTestingAdapter>+ </QueryClientProvider>+ );+ }+ return Wrapper;+}++function sessionsHandler() {+ return http.get("*/api/chat/sessions", () =>+ HttpResponse.json({+ sessions: [+ {+ id: "s1",+ title: "Chat one",+ is_processing: false,+ created_at: "2026-06-30T00:00:00Z",+ updated_at: "2026-06-30T00:00:00Z",+ },+ ],+ total: 1,+ }),+ );+}++beforeEach(() => {+ toastMock.mockClear();+ server.use(sessionsHandler());+});++afterEach(() => {+ server.resetHandlers();+});++describe("useRecentChats — rename", () => {+ it("enters and exits editing mode via startRename/cancelRename", async () => {+ const { result } = renderHook(() => useRecentChats(), {+ wrapper: makeWrapper(),+ });++ act(() => result.current.startRename("s1", "Chat one"));+ expect(result.current.editingSessionId).toBe("s1");+ expect(result.current.editingTitle).toBe("Chat one");++ act(() => result.current.cancelRename());+ expect(result.current.editingSessionId).toBeNull();+ });++ it("submits a trimmed title and clears editing on success", async () => {+ server.use(+ http.patch("*/api/chat/sessions/:id/title", () => HttpResponse.json({})),+ );+ const { result } = renderHook(() => useRecentChats(), {+ wrapper: makeWrapper(),+ });++ act(() => result.current.startRename("s1", "Chat one"));+ act(() => result.current.setEditingTitle(" Renamed "));+ act(() => result.current.submitRename("s1"));++ await waitFor(() => {+ expect(result.current.editingSessionId).toBeNull();+ });+ });++ it("just exits editing when the submitted title is blank", () => {+ const { result } = renderHook(() => useRecentChats(), {+ wrapper: makeWrapper(),+ });++ act(() => result.current.startRename("s1", "Chat one"));+ act(() => result.current.setEditingTitle(" "));+ act(() => result.current.submitRename("s1"));++ expect(result.current.editingSessionId).toBeNull();+ });++ it("toasts and exits editing when the rename request fails", async () => {+ server.use(+ http.patch("*/api/chat/sessions/:id/title", () =>+ HttpResponse.json({ detail: "nope" }, { status: 422 }),+ ),+ );+ const { result } = renderHook(() => useRecentChats(), {+ wrapper: makeWrapper(),+ });++ act(() => result.current.startRename("s1", "Chat one"));+ act(() => result.current.setEditingTitle("Renamed"));+ act(() => result.current.submitRename("s1"));++ await waitFor(() => {+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Failed to rename chat",+ variant: "destructive",+ }),+ );+ });+ expect(result.current.editingSessionId).toBeNull();+ });+});++describe("useRecentChats — export", () => {+ it("toasts success after a successful export", async () => {+ server.use(+ http.get("*/api/chat/sessions/:id", () =>+ HttpResponse.json({ messages: [], has_more_messages: false }),+ ),+ );+ const { result } = renderHook(() => useRecentChats(), {+ wrapper: makeWrapper(),+ });++ await act(async () => {+ await result.current.exportChat("s1", "Chat one");+ });++ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Chat exported" }),+ );+ expect(result.current.exportingIds.has("s1")).toBe(false);+ });++ it("toasts a destructive error when the export fetch fails", async () => {+ server.use(+ http.get("*/api/chat/sessions/:id", () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );+ const { result } = renderHook(() => useRecentChats(), {+ wrapper: makeWrapper(),+ });++ await act(async () => {+ await result.current.exportChat("s1", "Chat one");+ });++ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Export failed",+ variant: "destructive",+ }),+ );+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsxnew file mode 100644index 0000000000..41ca834bcb--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/RecentChatItem.tsx@@ -0,0 +1,179 @@+"use client";++import { ChatOriginIcon } from "@/app/(platform)/copilot/components/ChatOriginIcon/ChatOriginIcon";+import { resolvePlatformLogo } from "@/app/(platform)/copilot/components/ChatOriginIcon/platformLogos";+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/molecules/DropdownMenu/DropdownMenu";+import {+ SidebarMenuAction,+ SidebarMenuButton,+ SidebarMenuItem,+} from "@/components/ui/sidebar";+import {+ CircleNotchIcon,+ DotsThreeIcon,+ DownloadSimpleIcon,+ PencilSimpleIcon,+ ShareNetworkIcon,+ TrashIcon,+} from "@phosphor-icons/react";+import Link from "next/link";+import { useRef } from "react";++interface Session {+ id: string;+ title?: string | null;+ source_platform?: string | null;+ is_processing?: boolean | null;+ updated_at: string;+}++interface Props {+ session: Session;+ isActive: boolean;+ isEditing: boolean;+ editingTitle: string;+ onEditingTitleChange: (value: string) => void;+ onSubmitRename: (id: string) => void;+ onCancelRename: () => void;+ isExporting: boolean;+ isDeleting: boolean;+ chatSharingEnabled: boolean;+ onRename: (id: string, title: string | null | undefined) => void;+ onExport: (id: string, title: string | null | undefined) => void;+ onShare: (id: string) => void;+ onDelete: (id: string, title: string | null | undefined) => void;+}++export function RecentChatItem({+ session,+ isActive,+ isEditing,+ editingTitle,+ onEditingTitleChange,+ onSubmitRename,+ onCancelRename,+ isExporting,+ isDeleting,+ chatSharingEnabled,+ onRename,+ onExport,+ onShare,+ onDelete,+}: Props) {+ const title = session.title || "Untitled chat";+ const hasPlatformLogo = !!resolvePlatformLogo(session.source_platform);++ // Enter and Escape both blur the input, which would otherwise trigger a+ // second (or contradictory) submit via onBlur. This flag lets onBlur skip+ // the submit when the key handler already resolved the edit.+ const skipBlurSubmitRef = useRef(false);++ if (isEditing) {+ return (+ <SidebarMenuItem>+ <input+ autoFocus+ aria-label="Rename chat"+ value={editingTitle}+ onChange={(e) => onEditingTitleChange(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ skipBlurSubmitRef.current = true;+ onSubmitRename(session.id);+ e.currentTarget.blur();+ } else if (e.key === "Escape") {+ e.preventDefault();+ skipBlurSubmitRef.current = true;+ onCancelRename();+ e.currentTarget.blur();+ }+ }}+ onBlur={() => {+ if (skipBlurSubmitRef.current) {+ skipBlurSubmitRef.current = false;+ return;+ }+ onSubmitRename(session.id);+ }}+ className="w-full rounded-md border border-zinc-300 bg-white px-2 py-1 text-sm text-zinc-800 outline-none focus:border-purple-500 focus:ring-1 focus:ring-purple-500"+ />+ </SidebarMenuItem>+ );+ }++ return (+ <SidebarMenuItem>+ <SidebarMenuButton+ asChild+ isActive={isActive}+ tooltip={title}+ className="font-normal data-[active=true]:!bg-zinc-200 data-[active=true]:font-normal hover:!bg-zinc-200"+ >+ <Link href={`/copilot?sessionId=${session.id}`}>+ {session.is_processing ? (+ <LoadingSpinner+ size="small"+ className="size-4 shrink-0 text-purple-600"+ />+ ) : hasPlatformLogo ? (+ <ChatOriginIcon sourcePlatform={session.source_platform} />+ ) : null}+ <span className="truncate">{title}</span>+ </Link>+ </SidebarMenuButton>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <SidebarMenuAction+ showOnHover+ aria-label="Chat actions"+ className="border border-zinc-200 bg-white"+ >+ <DotsThreeIcon weight="bold" />+ </SidebarMenuAction>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => onRename(session.id, session.title)}>+ <PencilSimpleIcon className="mr-2 h-4 w-4" />+ Rename+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => onExport(session.id, session.title)}+ onSelect={(e) => {+ if (isExporting) e.preventDefault();+ }}+ disabled={isExporting}+ >+ {isExporting ? (+ <CircleNotchIcon className="mr-2 h-4 w-4 animate-spin" />+ ) : (+ <DownloadSimpleIcon className="mr-2 h-4 w-4" />+ )}+ {isExporting ? "Exporting…" : "Export chat"}+ </DropdownMenuItem>+ {chatSharingEnabled && (+ <DropdownMenuItem onClick={() => onShare(session.id)}>+ <ShareNetworkIcon className="mr-2 h-4 w-4" />+ Share chat+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ onClick={() => onDelete(session.id, session.title)}+ disabled={isDeleting}+ className="text-red-600 focus:bg-red-50 focus:text-red-600"+ >+ <TrashIcon className="mr-2 h-4 w-4" />+ Delete chat+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </SidebarMenuItem>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsxnew file mode 100644index 0000000000..91906e5922--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/RecentChatItem/__tests__/RecentChatItem.test.tsx@@ -0,0 +1,179 @@+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import { SidebarProvider } from "@/components/ui/sidebar";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { RecentChatItem } from "../RecentChatItem";++interface Session {+ id: string;+ title?: string | null;+ source_platform?: string | null;+ is_processing?: boolean | null;+ updated_at: string;+}++const baseSession: Session = {+ id: "s1",+ title: "My chat",+ updated_at: "2026-06-30T00:00:00Z",+};++function makeProps(+ overrides: Partial<React.ComponentProps<typeof RecentChatItem>> = {},+) {+ return {+ session: baseSession,+ isActive: false,+ isEditing: false,+ editingTitle: "",+ onEditingTitleChange: vi.fn(),+ onSubmitRename: vi.fn(),+ onCancelRename: vi.fn(),+ isExporting: false,+ isDeleting: false,+ chatSharingEnabled: false,+ onRename: vi.fn(),+ onExport: vi.fn(),+ onShare: vi.fn(),+ onDelete: vi.fn(),+ ...overrides,+ };+}++function renderItem(props: React.ComponentProps<typeof RecentChatItem>) {+ return render(+ <SidebarProvider>+ <RecentChatItem {...props} />+ </SidebarProvider>,+ );+}++function openActions() {+ fireEvent.pointerDown(screen.getByRole("button", { name: /chat actions/i }), {+ button: 0,+ });+}++describe("RecentChatItem — display", () => {+ it("links to the session and shows its title", () => {+ renderItem(makeProps());+ const link = screen.getByRole("link", { name: /my chat/i });+ expect(link.getAttribute("href")).toBe("/copilot?sessionId=s1");+ });++ it("falls back to 'Untitled chat' when the title is empty", () => {+ renderItem(makeProps({ session: { ...baseSession, title: null } }));+ expect(screen.getByText("Untitled chat")).toBeDefined();+ });++ it("shows a platform logo for external-origin chats", () => {+ renderItem(+ makeProps({+ session: { ...baseSession, source_platform: "discord" },+ }),+ );+ expect(screen.getByAltText("Discord")).toBeDefined();+ });+});++describe("RecentChatItem — editing mode", () => {+ it("renders an input and submits on Enter", () => {+ const onSubmitRename = vi.fn();+ renderItem(+ makeProps({ isEditing: true, editingTitle: "New title", onSubmitRename }),+ );++ const input = screen.getByLabelText("Rename chat");+ fireEvent.keyDown(input, { key: "Enter" });+ expect(onSubmitRename).toHaveBeenCalledWith("s1");+ });++ it("cancels on Escape", () => {+ const onCancelRename = vi.fn();+ renderItem(makeProps({ isEditing: true, onCancelRename }));++ fireEvent.keyDown(screen.getByLabelText("Rename chat"), { key: "Escape" });+ expect(onCancelRename).toHaveBeenCalled();+ });++ it("submits on blur when no key already resolved the edit", () => {+ const onSubmitRename = vi.fn();+ renderItem(makeProps({ isEditing: true, onSubmitRename }));++ fireEvent.blur(screen.getByLabelText("Rename chat"));+ expect(onSubmitRename).toHaveBeenCalledWith("s1");+ });++ it("forwards typed input via onEditingTitleChange", () => {+ const onEditingTitleChange = vi.fn();+ renderItem(makeProps({ isEditing: true, onEditingTitleChange }));++ fireEvent.change(screen.getByLabelText("Rename chat"), {+ target: { value: "abc" },+ });+ expect(onEditingTitleChange).toHaveBeenCalledWith("abc");+ });+});++describe("RecentChatItem — actions menu", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("invokes onRename when Rename is chosen", async () => {+ const onRename = vi.fn();+ renderItem(makeProps({ onRename }));++ openActions();+ fireEvent.click(await screen.findByRole("menuitem", { name: /rename/i }));+ expect(onRename).toHaveBeenCalledWith("s1", "My chat");+ });++ it("invokes onExport when Export chat is chosen", async () => {+ const onExport = vi.fn();+ renderItem(makeProps({ onExport }));++ openActions();+ fireEvent.click(+ await screen.findByRole("menuitem", { name: /export chat/i }),+ );+ expect(onExport).toHaveBeenCalledWith("s1", "My chat");+ });++ it("invokes onDelete when Delete chat is chosen", async () => {+ const onDelete = vi.fn();+ renderItem(makeProps({ onDelete }));++ openActions();+ fireEvent.click(+ await screen.findByRole("menuitem", { name: /delete chat/i }),+ );+ expect(onDelete).toHaveBeenCalledWith("s1", "My chat");+ });++ it("hides the Share action when sharing is disabled", async () => {+ renderItem(makeProps({ chatSharingEnabled: false }));++ openActions();+ await screen.findByRole("menuitem", { name: /rename/i });+ expect(screen.queryByRole("menuitem", { name: /share chat/i })).toBeNull();+ });++ it("shows and triggers the Share action when sharing is enabled", async () => {+ const onShare = vi.fn();+ renderItem(makeProps({ chatSharingEnabled: true, onShare }));++ openActions();+ fireEvent.click(+ await screen.findByRole("menuitem", { name: /share chat/i }),+ );+ expect(onShare).toHaveBeenCalledWith("s1");+ });++ it("shows an exporting label while an export is in flight", async () => {+ renderItem(makeProps({ isExporting: true }));++ openActions();+ expect(await screen.findByText(/exporting/i)).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/helpers.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/helpers.tsnew file mode 100644index 0000000000..eb5756e142--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/helpers.ts@@ -0,0 +1,69 @@+function startOfDay(date: Date): number {+ return new Date(+ date.getFullYear(),+ date.getMonth(),+ date.getDate(),+ ).getTime();+}++function diffInDays(iso: string): number {+ const date = new Date(iso);+ const dayMs = 86_400_000;+ return Math.round((startOfDay(new Date()) - startOfDay(date)) / dayMs);+}++function ordinalSuffix(day: number): string {+ if (day >= 11 && day <= 13) return "th";+ switch (day % 10) {+ case 1:+ return "st";+ case 2:+ return "nd";+ case 3:+ return "rd";+ default:+ return "th";+ }+}++// e.g. "26th June" (current year) or "26th June 2024" (older).+function formatDayLabel(date: Date): string {+ const day = date.getDate();+ const month = date.toLocaleDateString(undefined, { month: "long" });+ const label = `${day}${ordinalSuffix(day)} ${month}`;+ const sameYear = date.getFullYear() === new Date().getFullYear();+ return sameYear ? label : `${label} ${date.getFullYear()}`;+}++export function getDateGroupLabel(iso: string): string {+ const diffDays = diffInDays(iso);+ if (diffDays <= 0) return "Today";+ if (diffDays === 1) return "Yesterday";+ return formatDayLabel(new Date(iso));+}++// Buckets sessions by calendar day and orders groups most-recent-first. Doesn't+// rely on the input being pre-sorted, so an unsorted list can never produce+// duplicate day groups; within a group, input order is preserved.+export function groupSessionsByDate<T extends { updated_at: string }>(+ sessions: T[],+): { label: string; sessions: T[] }[] {+ const buckets = new Map<number, { label: string; sessions: T[] }>();++ for (const session of sessions) {+ const dayKey = startOfDay(new Date(session.updated_at));+ const bucket = buckets.get(dayKey);+ if (bucket) {+ bucket.sessions.push(session);+ } else {+ buckets.set(dayKey, {+ label: getDateGroupLabel(session.updated_at),+ sessions: [session],+ });+ }+ }++ return [...buckets.entries()]+ .sort((a, b) => b[0] - a[0])+ .map(([, group]) => group);+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/useRecentChats.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/useRecentChats.tsnew file mode 100644index 0000000000..23689dfce6--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/useRecentChats.ts@@ -0,0 +1,118 @@+import {+ getV2GetSession,+ usePatchV2UpdateSessionTitle,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { fetchAndExportChat } from "@/app/(platform)/copilot/helpers/exportChatAsMarkdown";+import {+ SESSION_LIST_QUERY_KEY,+ useSessionList,+} from "@/app/(platform)/copilot/useSessionList";+import { useSessionDeletion } from "@/app/(platform)/copilot/useSessionDeletion";+import { toast } from "@/components/molecules/Toast/use-toast";+import { useQueryClient } from "@tanstack/react-query";+import { usePathname, useSearchParams } from "next/navigation";+import { useState } from "react";++export function useRecentChats() {+ const queryClient = useQueryClient();+ const { sessions, isLoading, hasMore, isLoadingMore, loadMore } =+ useSessionList();++ const pathname = usePathname();+ const searchParams = useSearchParams();+ const activeSessionId =+ pathname === "/copilot" ? searchParams.get("sessionId") : null;++ const [editingSessionId, setEditingSessionId] = useState<string | null>(null);+ const [editingTitle, setEditingTitle] = useState("");+ const [exportingIds, setExportingIds] = useState<Set<string>>(new Set());+ const [sharingSessionId, setSharingSessionId] = useState<string | null>(null);++ const {+ sessionToDelete,+ isDeleting,+ requestDelete,+ confirmDelete,+ cancelDelete,+ } = useSessionDeletion();++ const { mutate: renameSession } = usePatchV2UpdateSessionTitle({+ mutation: {+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: SESSION_LIST_QUERY_KEY });+ setEditingSessionId(null);+ },+ onError: (error) => {+ toast({+ title: "Failed to rename chat",+ description:+ error instanceof Error ? error.message : "An error occurred",+ variant: "destructive",+ });+ setEditingSessionId(null);+ },+ },+ });++ function startRename(id: string, title: string | null | undefined) {+ setEditingSessionId(id);+ setEditingTitle(title || "");+ }++ function submitRename(id: string) {+ const trimmed = editingTitle.trim();+ if (trimmed) {+ renameSession({ sessionId: id, data: { title: trimmed } });+ } else {+ setEditingSessionId(null);+ }+ }++ async function exportChat(id: string, title: string | null | undefined) {+ if (exportingIds.has(id)) return;+ setExportingIds((prev) => new Set(prev).add(id));+ try {+ await fetchAndExportChat(id, title, getV2GetSession);+ toast({ title: "Chat exported" });+ } catch (error) {+ toast({+ title: "Export failed",+ description:+ error instanceof Error+ ? error.message+ : "Could not export this chat. Please try again.",+ variant: "destructive",+ });+ } finally {+ setExportingIds((prev) => {+ const next = new Set(prev);+ next.delete(id);+ return next;+ });+ }+ }++ return {+ sessions,+ isLoading,+ hasMore,+ isLoadingMore,+ loadMore,+ activeSessionId,+ editingSessionId,+ editingTitle,+ setEditingTitle,+ startRename,+ submitRename,+ cancelRename: () => setEditingSessionId(null),+ exportingIds,+ exportChat,+ sharingSessionId,+ setSharingSessionId,+ sessionToDelete,+ isDeleting,+ requestDelete,+ confirmDelete,+ cancelDelete,+ };+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/SidebarSearch/SidebarSearch.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/SidebarSearch/SidebarSearch.tsxnew file mode 100644index 0000000000..ee08348eb7--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/SidebarSearch/SidebarSearch.tsx@@ -0,0 +1,22 @@+"use client";++import { useGlobalSearchStore } from "@/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore";+import { SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar";+import { MagnifyingGlassIcon } from "@phosphor-icons/react";++export function SidebarSearch() {+ const openSearch = useGlobalSearchStore((state) => state.openSearch);++ return (+ <SidebarMenuItem>+ <SidebarMenuButton+ tooltip="Search"+ onClick={openSearch}+ className="font-normal group-data-[collapsible=icon]:!p-1.5 hover:!bg-zinc-200 [&>svg]:size-5"+ >+ <MagnifyingGlassIcon className="size-5" />+ <span className="truncate">Search</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/SidebarSearch/__tests__/SidebarSearch.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/SidebarSearch/__tests__/SidebarSearch.test.tsxnew file mode 100644index 0000000000..15fb8cdf64--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/SidebarSearch/__tests__/SidebarSearch.test.tsx@@ -0,0 +1,35 @@+import { render, screen } from "@/tests/integrations/test-utils";+import { SidebarProvider } from "@/components/ui/sidebar";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it } from "vitest";++import { useGlobalSearchStore } from "@/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore";+import { SidebarSearch } from "../SidebarSearch";++function renderSearch() {+ return render(+ <SidebarProvider>+ <SidebarSearch />+ </SidebarProvider>,+ );+}++describe("SidebarSearch", () => {+ beforeEach(() => {+ useGlobalSearchStore.setState({ isOpen: false });+ });++ it("renders a Search menu button", () => {+ renderSearch();+ expect(screen.getByText("Search")).toBeDefined();+ });++ it("opens the global search palette when clicked", async () => {+ const user = userEvent.setup();+ renderSearch();++ expect(useGlobalSearchStore.getState().isOpen).toBe(false);+ await user.click(screen.getByText("Search"));+ expect(useGlobalSearchStore.getState().isOpen).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsxindex f629d64a50..932f8cd70b 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx@@ -43,7 +43,11 @@ export interface TaskGroup {tasks: Task[];}-export function Wallet() {+interface Props {+ compact?: boolean;+}++export function Wallet({ compact = false }: Props) {const { state, updateState } = useOnboarding();const isPaymentEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);@@ -266,28 +270,45 @@ export function Wallet() {<div className="relative inline-block"><buttonref={walletRef}- className="group relative flex flex-nowrap items-center gap-2 rounded-md bg-zinc-50 px-3 py-2 text-sm"+ className={cn(+ "group relative flex flex-nowrap items-center gap-2 rounded-md px-3 py-2 text-sm",+ compact+ ? "rounded-xl border border-zinc-200 bg-zinc-100 py-1 hover:bg-zinc-200"+ : "bg-zinc-50",+ )}onClick={onWalletOpen}>- <WalletIcon size={20} className="inline-block xl:hidden" />+ <WalletIcon+ size={20}+ className={cn("inline-block", !compact && "xl:hidden")}+ /><div>- <span className="mr-1 hidden xl:inline-block">Earn credits </span>+ {!compact && (+ <span className="mr-1 hidden xl:inline-block">+ Earn credits{" "}+ </span>+ )}<span className="text-sm font-semibold">{formatCredits(credits)}</span>- {completedCount !== null && completedCount < totalCount && (- <span className="absolute right-1 top-1 h-2 w-2 rounded-full bg-violet-600"></span>+ {!compact &&+ completedCount !== null &&+ completedCount < totalCount && (+ <span className="absolute right-1 top-1 h-2 w-2 rounded-full bg-violet-600"></span>+ )}+ {!compact && (+ <div className="absolute bottom-[-2.5rem] left-1/2 z-50 hidden -translate-x-1/2 transform whitespace-nowrap rounded-small bg-white px-4 py-2 shadow-md group-hover:block">+ <Text variant="body-medium">+ {completedCount} of {totalCount} rewards claimed+ </Text>+ </div>)}- <div className="absolute bottom-[-2.5rem] left-1/2 z-50 hidden -translate-x-1/2 transform whitespace-nowrap rounded-small bg-white px-4 py-2 shadow-md group-hover:block">- <Text variant="body-medium">- {completedCount} of {totalCount} rewards claimed- </Text>- </div></div></button><divclassName={cn(- "pointer-events-none absolute inset-0 rounded-md bg-violet-400 duration-2000 ease-in-out",+ "pointer-events-none absolute inset-0 bg-violet-400 duration-2000 ease-in-out",+ compact ? "rounded-xl" : "rounded-md",flash ? "opacity-50 duration-0" : "opacity-0",)}/>diff --git a/autogpt_platform/frontend/src/components/ui/collapsible.tsx b/autogpt_platform/frontend/src/components/ui/collapsible.tsxnew file mode 100644index 0000000000..1fe76f5d16--- /dev/null+++ b/autogpt_platform/frontend/src/components/ui/collapsible.tsx@@ -0,0 +1,11 @@+"use client";++import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";++const Collapsible = CollapsiblePrimitive.Root;++const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;++const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;++export { Collapsible, CollapsibleContent, CollapsibleTrigger };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 23d06b866f..b2a5c009d5 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@@ -17,6 +17,7 @@ export enum Flag {GENERIC_TRIGGER_AGENTS = "generic-trigger-agents",CHAT_SEARCH = "chat-search",CHAT_SHARING = "chat-sharing",+ AUTOGPT_NEW_LAYOUT = "autogpt-new-layout",CHAT_WORKSPACE_FILES = "chat-workspace-files",// Graphiti memory + dream-system gates. Mirror of the backend// ``Flag`` enum in ``backend/util/feature_flag.py``. Frontend reads@@ -47,6 +48,7 @@ const defaultFlags = {[Flag.GENERIC_TRIGGER_AGENTS]: false,[Flag.CHAT_SEARCH]: false,[Flag.CHAT_SHARING]: false,+ [Flag.AUTOGPT_NEW_LAYOUT]: false,[Flag.CHAT_WORKSPACE_FILES]: false,[Flag.GRAPHITI_MEMORY]: false,[Flag.GRAPHITI_COMMUNITIES_ENABLED]: false,@@ -98,6 +100,8 @@ function readEnvOverride(flag: Flag): string | undefined {return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_SEARCH;case Flag.CHAT_SHARING:return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_SHARING;+ case Flag.AUTOGPT_NEW_LAYOUT:+ return process.env.NEXT_PUBLIC_FORCE_FLAG_AUTOGPT_NEW_LAYOUT;case Flag.CHAT_WORKSPACE_FILES:return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_WORKSPACE_FILES;case Flag.GRAPHITI_MEMORY:diff --git a/autogpt_platform/frontend/tailwind.config.ts b/autogpt_platform/frontend/tailwind.config.tsindex b29531745d..2211d03856 100644--- a/autogpt_platform/frontend/tailwind.config.ts+++ b/autogpt_platform/frontend/tailwind.config.ts@@ -151,6 +151,36 @@ const config = {height: "0",},},+ // Bridge the height change with an opacity fade so the content+ // doesn't clip in/out abruptly (Emil Kowalski: fade to soften+ // state transitions). Opacity resolves over the first/last ~60%+ // so text is fully legible before the height finishes settling.+ "collapsible-down": {+ from: {+ height: "0",+ opacity: "0",+ },+ "60%": {+ opacity: "1",+ },+ to: {+ height: "var(--radix-collapsible-content-height)",+ opacity: "1",+ },+ },+ "collapsible-up": {+ from: {+ height: "var(--radix-collapsible-content-height)",+ opacity: "1",+ },+ "40%": {+ opacity: "0",+ },+ to: {+ height: "0",+ opacity: "0",+ },+ },"fade-in": {"0%": {opacity: "0",@@ -198,6 +228,12 @@ const config = {animation: {"accordion-down": "accordion-down 0.2s ease-out","accordion-up": "accordion-up 0.2s ease-out",+ // easeOutCubic for a smooth, decelerating settle; asymmetric+ // timing (open a touch slower than close) per Emil Kowalski.+ // Both stay under the 300ms UI budget.+ "collapsible-down":+ "collapsible-down 0.26s cubic-bezier(0.33, 1, 0.68, 1)",+ "collapsible-up": "collapsible-up 0.2s cubic-bezier(0.33, 1, 0.68, 1)","fade-in": "fade-in 0.2s ease-out",shimmer: "shimmer 4s ease-in-out infinite",loader: "loader 1s infinite",