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 Chats to the collapsed sidebar (#15349)
John Ababseh7aaa60f99942
diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsxindex adac74f3cd..5fd0535ff8 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx@@ -1,16 +1,10 @@"use client";-import {- Collapsible,- CollapsibleContent,- CollapsibleTrigger,-} from "@/components/ui/collapsible";import {Sidebar,SidebarContent,SidebarGroup,SidebarGroupContent,- SidebarGroupLabel,SidebarMenu,SidebarMenuButton,SidebarMenuItem,@@ -19,19 +13,19 @@ import {import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { isEditableElement } from "@/lib/platform";-import { cn } from "@/lib/utils";import { useAuth } from "@/lib/auth/hooks/useAuth";import { motion, useReducedMotion } from "framer-motion";import Link, { useLinkStatus } from "next/link";import { usePathname, useRouter } from "next/navigation";-import { ComponentProps, ReactNode, Suspense, useEffect } from "react";+import { ComponentProps, ReactNode, useEffect } from "react";import { getSidebarItemVariants, sidebarContainerVariants } from "./animations";import { AppSidebarHeader } from "./components/AppSidebarHeader/AppSidebarHeader";-import { RecentChats } from "./components/RecentChats/RecentChats";+import { ChatsNavSection } from "./components/ChatsNavSection/ChatsNavSection";+import { CollapsibleNavGroup } from "./components/CollapsibleNavGroup/CollapsibleNavGroup";import { ShortcutHint } from "./components/ShortcutHint/ShortcutHint";import { SidebarUserActions } from "./components/SidebarUserActions/SidebarUserActions";+import { useNavItemClassName } from "./useNavItemClassName";import {- ArrowDown01Icon,FlowIcon,Folder01Icon,GridViewIcon,@@ -98,17 +92,6 @@ function HomeIcon() {);}-// The stronger active state ships with the brain-dump experience.-function useNavItemClassName() {- const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);- return cn(- "h-auto rounded-xl p-2 pl-3 font-normal data-[active=true]:font-normal group-data-[collapsible=icon]:!p-1.5 hover:!bg-zinc-100 [&>svg]:size-4 group-data-[collapsible=icon]:[&>svg]:size-4.5",- isBrainDumpEnabled- ? "data-[active=true]:!bg-zinc-200 data-[active=true]:hover:!bg-zinc-200"- : "data-[active=true]:!bg-zinc-100",- );-}-function HomeItem() {const pathname = usePathname();const navItemClassName = useNavItemClassName();@@ -177,36 +160,6 @@ function NavMenu({);}-function CollapsibleNavGroup({- label,- children,-}: {- label: string;- children: ReactNode;-}) {- return (- <Collapsible defaultOpen className="group/collapsible">- <SidebarGroup className="py-1">- <SidebarGroupLabel- asChild- className="text-[13px] font-medium text-zinc-500 group-data-[collapsible=icon]:hidden"- >- <CollapsibleTrigger>- {label}- <Icon- icon={ArrowDown01Icon}- className="ease-[cubic-bezier(0.33,1,0.68,1)] ml-auto size-4 text-sidebar-foreground/90 transition-transform duration-200 group-data-[collapsible=icon]:size-4.5 group-data-[state=open]/collapsible:rotate-180 motion-reduce:transition-none"- />- </CollapsibleTrigger>- </SidebarGroupLabel>- <CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down motion-reduce:animate-none">- <SidebarGroupContent>{children}</SidebarGroupContent>- </CollapsibleContent>- </SidebarGroup>- </Collapsible>- );-}-type Props = ComponentProps<typeof Sidebar>;export function AppSidebar(props: Props) {@@ -267,21 +220,7 @@ export function AppSidebar(props: Props) {</motion.div>) : null}- {isLoggedIn && (- <motion.div- variants={itemVariants}- className="group-data-[collapsible=icon]:hidden"- >- <CollapsibleNavGroup label="Recent chats">- {/* 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>- )}+ {isLoggedIn && <ChatsNavSection itemVariants={itemVariants} />}</motion.div><SidebarUserActions />diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/chats-rail.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/chats-rail.test.tsxnew file mode 100644index 0000000000..bd21ae82ee--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/chats-rail.test.tsx@@ -0,0 +1,395 @@+import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { SidebarProvider } from "@/components/ui/sidebar";+import { server } from "@/mocks/mock-server";+import { Flag } from "@/services/feature-flags/use-get-flag";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import type { ReactNode } from "react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type Mock,+} from "vitest";++import { AppSidebar } from "../AppSidebar";++const auth = vi.hoisted(() => ({ isLoggedIn: true }));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: auth.isLoggedIn+ ? { id: "user-1", email: "[email protected]", role: "user" }+ : null,+ isLoggedIn: auth.isLoggedIn,+ isUserLoading: false,+ }),+}));++// 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("next/navigation", async (importOriginal) => {+ const actual = await importOriginal<typeof import("next/navigation")>();+ return {+ ...actual,+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),+ usePathname: () => "/team",+ useSearchParams: () => new URLSearchParams(),+ };+});++const useGetFlagMock = vi.hoisted(() =>+ vi.fn<(flag: Flag) => 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: Flag) => useGetFlagMock(flag),+ };+});++const motionPreference = vi.hoisted(() => ({ reduced: false }));++vi.mock("framer-motion", async (importOriginal) => {+ const actual = await importOriginal<typeof import("framer-motion")>();+ return {+ ...actual,+ useReducedMotion: () => motionPreference.reduced,+ };+});++const viewport = vi.hoisted(() => ({ isMobile: false }));++vi.mock("@/hooks/use-mobile", () => ({+ useIsMobile: () => viewport.isMobile,+}));++// happy-dom applies no CSS and has no Web Animations, so the tests stub the+// scroll and drive the "animations finished" signal themselves.+const scrollTo = vi.fn();+const getAnimations = vi.fn<() => Animation[]>(() => []);+const originalScrollTo = Element.prototype.scrollTo;++function runningAnimation() {+ let finish!: () => void;+ const animation = {+ playState: "running",+ effect: { getComputedTiming: () => ({ endTime: 260 }) },+ } as unknown as Animation;+ Object.defineProperty(animation, "finished", {+ value: new Promise<Animation>((resolve) => {+ finish = () => {+ Object.assign(animation, { playState: "finished" });+ resolve(animation);+ };+ }),+ });+ return { animation, finish };+}++function renderSidebar({ open = false } = {}) {+ return render(+ <SidebarProvider defaultOpen={open}>+ <AppSidebar />+ </SidebarProvider>,+ );+}++function getSidebarState() {+ return document+ .querySelector('[data-sidebar="sidebar"]')+ ?.closest("[data-state]")+ ?.getAttribute("data-state");+}++function getSidebarScrollArea() {+ return document.querySelector('[data-sidebar="content"]');+}++function getChatsButton() {+ return screen.getByRole("button", { name: "Chats" });+}++function getRecentChatsHeading() {+ return screen.getByRole("button", { name: "Recent chats" });+}++function toggleSidebarWithShortcut() {+ fireEvent.keyDown(window, { key: "b", ctrlKey: true });+}++beforeEach(() => {+ auth.isLoggedIn = true;+ motionPreference.reduced = false;+ viewport.isMobile = false;+ useGetFlagMock.mockReturnValue(true);+ scrollTo.mockReset();+ getAnimations.mockReset();+ getAnimations.mockReturnValue([]);+ Element.prototype.scrollTo = scrollTo;+ Element.prototype.getAnimations = getAnimations;+ server.use(getGetV2ListSessionsMockHandler200({ sessions: [], total: 0 }));+});++afterEach(() => {+ Element.prototype.scrollTo = originalScrollTo;+ Reflect.deleteProperty(Element.prototype, "getAnimations");+ vi.unstubAllGlobals();+});++describe("Chats in the collapsed sidebar", () => {+ it("shows a Chats button in the collapsed rail for a logged-in user", () => {+ renderSidebar();++ expect(getSidebarState()).toBe("collapsed");+ const chats = getChatsButton();+ expect(chats.tagName).toBe("BUTTON");+ expect(chats.getAttribute("data-active")).toBe("false");+ });++ it("is only displayed inside the collapsed icon rail", () => {+ renderSidebar({ open: true });++ // `hidden` keeps it out of the expanded sidebar and the phone sheet; only+ // the desktop sidebar's data-collapsible="icon" group displays it.+ const wrapper = getChatsButton().closest(+ '[data-sidebar="group"]',+ )?.parentElement;+ expect(wrapper?.classList.contains("hidden")).toBe(true);+ expect(+ wrapper?.classList.contains("group-data-[collapsible=icon]:block"),+ ).toBe(true);+ });++ it("expands the sidebar, then scrolls only the sidebar to Recent chats and focuses its heading", async () => {+ const user = userEvent.setup();+ renderSidebar();+ const statesAtScroll: unknown[] = [];+ scrollTo.mockImplementation(() => statesAtScroll.push(getSidebarState()));+ const statesAtFocus: unknown[] = [];+ getRecentChatsHeading().addEventListener("focus", () =>+ statesAtFocus.push(getSidebarState()),+ );+ const focusHeading = vi.spyOn(getRecentChatsHeading(), "focus");++ await user.click(getChatsButton());++ expect(getSidebarState()).toBe("expanded");+ await waitFor(() => expect(statesAtScroll).toEqual(["expanded"]));+ expect(statesAtFocus).toEqual(["expanded"]);+ expect(focusHeading).toHaveBeenCalledWith({ preventScroll: true });+ expect(scrollTo.mock.contexts[0]).toBe(getSidebarScrollArea());+ expect(scrollTo).toHaveBeenCalledWith(+ expect.objectContaining({ behavior: "smooth" }),+ );+ expect(document.activeElement).toBe(getRecentChatsHeading());+ });++ it("jumps from the keyboard", async () => {+ const user = userEvent.setup();+ renderSidebar();++ getChatsButton().focus();+ await user.keyboard("{Enter}");++ expect(getSidebarState()).toBe("expanded");+ await waitFor(() => expect(scrollTo).toHaveBeenCalledTimes(1));+ expect(document.activeElement).toBe(getRecentChatsHeading());+ });++ it("scrolls without animation when the user prefers reduced motion", async () => {+ motionPreference.reduced = true;+ const user = userEvent.setup();+ renderSidebar();++ await user.click(getChatsButton());++ await waitFor(() => expect(scrollTo).toHaveBeenCalledTimes(1));+ expect(scrollTo).toHaveBeenCalledWith(+ expect.objectContaining({ behavior: "auto" }),+ );+ });++ it("reopens Recent chats when the user had closed it, and scrolls once the sidebar has finished animating", async () => {+ const user = userEvent.setup();+ renderSidebar();+ expect(await screen.findByText("No conversations yet")).toBeDefined();++ await user.click(screen.getByRole("button", { name: "Expand sidebar" }));+ await user.click(getRecentChatsHeading());+ await waitFor(() =>+ expect(screen.queryByText("No conversations yet")).toBeNull(),+ );+ await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));+ expect(getSidebarState()).toBe("collapsed");+ const opening = runningAnimation();+ getAnimations.mockReturnValue([opening.animation]);+ let headingTop = 400;+ vi.spyOn(+ getRecentChatsHeading(),+ "getBoundingClientRect",+ ).mockImplementation(() => new DOMRect(0, headingTop, 0, 0));++ await user.click(getChatsButton());++ expect(getSidebarState()).toBe("expanded");+ expect(await screen.findByText("No conversations yet")).toBeDefined();+ expect(getRecentChatsHeading().getAttribute("aria-expanded")).toBe("true");+ expect(document.activeElement).toBe(getRecentChatsHeading());+ expect(scrollTo).not.toHaveBeenCalled();++ await act(async () => {+ headingTop = 420;+ opening.finish();+ });++ await waitFor(() => expect(scrollTo).toHaveBeenCalledTimes(1));+ expect(scrollTo.mock.contexts[0]).toBe(getSidebarScrollArea());+ expect(scrollTo).toHaveBeenCalledWith(+ expect.objectContaining({ top: 420 }),+ );+ expect(getAnimations.mock.contexts).not.toHaveLength(0);+ for (const element of getAnimations.mock.contexts) {+ expect(element).toBe(getSidebarScrollArea());+ }+ });++ it("keeps scrolling while the Recent chats list grows, until the sidebar collapses", async () => {+ const observers: {+ callback: () => void;+ observe: Mock;+ disconnect: Mock;+ }[] = [];+ vi.stubGlobal(+ "ResizeObserver",+ class {+ callback: () => void;+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ constructor(callback: () => void) {+ this.callback = callback;+ observers.push(this);+ }+ },+ );+ const user = userEvent.setup();+ renderSidebar();+ expect(await screen.findByText("No conversations yet")).toBeDefined();+ vi.spyOn(getRecentChatsHeading(), "getBoundingClientRect").mockReturnValue(+ new DOMRect(0, 420, 0, 0),+ );++ await user.click(getChatsButton());+ await waitFor(() => expect(scrollTo).toHaveBeenCalledTimes(1));++ const followers = observers.filter((observer) =>+ observer.observe.mock.calls.some(([element]) =>+ element.contains(getRecentChatsHeading()),+ ),+ );+ expect(followers).toHaveLength(1);+ const [watched] = followers[0].observe.mock.calls[0];+ expect(watched).not.toBe(getSidebarScrollArea());+ expect(watched.contains(screen.getByText("No conversations yet"))).toBe(+ true,+ );+ followers[0].callback();+ expect(scrollTo).toHaveBeenCalledTimes(2);+ expect(followers[0].disconnect).not.toHaveBeenCalled();++ toggleSidebarWithShortcut();++ expect(followers[0].disconnect).toHaveBeenCalled();+ });++ it("does not scroll if the sidebar collapses again before it finishes animating", async () => {+ const user = userEvent.setup();+ renderSidebar();+ const expanding = runningAnimation();+ getAnimations.mockReturnValue([expanding.animation]);++ await user.click(getChatsButton());+ expect(getSidebarState()).toBe("expanded");+ toggleSidebarWithShortcut();+ expect(getSidebarState()).toBe("collapsed");+ await act(async () => expanding.finish());++ expect(scrollTo).not.toHaveBeenCalled();+ });++ it("does not jump again when the sidebar is later expanded another way", async () => {+ const user = userEvent.setup();+ renderSidebar();++ await user.click(getChatsButton());+ await waitFor(() => expect(scrollTo).toHaveBeenCalledTimes(1));++ await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));+ await user.click(screen.getByRole("button", { name: "Expand sidebar" }));++ expect(getSidebarState()).toBe("expanded");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(scrollTo).toHaveBeenCalledTimes(1);+ });++ it("does not show Chats to a logged-out visitor", () => {+ auth.isLoggedIn = false;+ renderSidebar();++ expect(screen.queryByRole("button", { name: "Chats" })).toBeNull();+ });++ it("still reopens Recent chats each time the phone sheet opens", async () => {+ viewport.isMobile = true;+ const user = userEvent.setup();+ renderSidebar();++ toggleSidebarWithShortcut();+ expect(await screen.findByText("No conversations yet")).toBeDefined();+ await user.click(getRecentChatsHeading());+ await waitFor(() =>+ expect(screen.queryByText("No conversations yet")).toBeNull(),+ );++ toggleSidebarWithShortcut();+ await waitFor(() =>+ expect(screen.queryByRole("button", { name: "Recent chats" })).toBeNull(),+ );+ toggleSidebarWithShortcut();++ expect(await screen.findByText("No conversations yet")).toBeDefined();+ expect(getRecentChatsHeading().getAttribute("aria-expanded")).toBe("true");+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/helpers.test.tsnew file mode 100644index 0000000000..5b9e6b1741--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/helpers.test.ts@@ -0,0 +1,276 @@+import { afterEach, describe, expect, it, vi, type Mock } from "vitest";++import {+ afterAnimations,+ scrollSidebarTo,+ scrollSidebarToWhenReachable,+} from "../helpers";++function rectAt(top: number) {+ return new DOMRect(0, top, 0, 0);+}++function fakeAnimation(endTime: number) {+ let finish!: () => void;+ let cancel!: () => void;+ const animation = {+ playState: "running",+ effect: { getComputedTiming: () => ({ endTime }) },+ } as unknown as Animation;+ Object.defineProperty(animation, "finished", {+ value: new Promise<Animation>((resolve, reject) => {+ finish = () => {+ Object.assign(animation, { playState: "finished" });+ resolve(animation);+ };+ cancel = () => {+ Object.assign(animation, { playState: "idle" });+ reject(new DOMException("Cancelled", "AbortError"));+ };+ }),+ });+ return { animation, finish, cancel };+}++function elementWithAnimations(...rounds: Animation[][]) {+ const element = document.createElement("div");+ const getAnimations = vi.fn(() => rounds[rounds.length - 1]);+ rounds+ .slice(0, -1)+ .forEach((animations) => getAnimations.mockReturnValueOnce(animations));+ element.getAnimations = getAnimations;+ return element;+}++function flushPromises() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}++function sidebarScrollArea({+ scrollTop = 0,+ scrollHeight = 2000,+ clientHeight = 800,+} = {}) {+ const container = document.createElement("div");+ container.setAttribute("data-sidebar", "content");+ container.style.scrollPaddingTop = "64px";+ const target = document.createElement("div");+ const list = document.createElement("div");+ container.append(target, list);+ document.body.appendChild(container);+ Object.defineProperty(container, "scrollTop", { value: scrollTop });+ Object.defineProperty(container, "scrollHeight", {+ value: scrollHeight,+ configurable: true,+ });+ Object.defineProperty(container, "clientHeight", { value: clientHeight });+ container.getBoundingClientRect = () => rectAt(50);+ target.getBoundingClientRect = () => rectAt(350);+ const scrollTo = vi.fn();+ container.scrollTo = scrollTo;+ return { container, target, list, scrollTo };+}++afterEach(() => {+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe("scrollSidebarTo", () => {+ it("scrolls the sidebar so the target sits just below its scroll padding", () => {+ const { target, scrollTo } = sidebarScrollArea({ scrollTop: 100 });++ expect(scrollSidebarTo(target, "smooth")).toBe(true);+ expect(scrollTo).toHaveBeenCalledWith({ top: 336, behavior: "smooth" });+ });++ it("reports when the sidebar cannot scroll that far yet", () => {+ const { target, scrollTo } = sidebarScrollArea({+ scrollHeight: 900,+ clientHeight: 800,+ });++ expect(scrollSidebarTo(target, "auto")).toBe(false);+ expect(scrollTo).toHaveBeenCalledWith({ top: 236, behavior: "auto" });+ });++ it("does nothing when the target is outside the sidebar", () => {+ const target = document.createElement("div");+ const outer = document.createElement("div");+ outer.appendChild(target);+ document.body.appendChild(outer);+ const scrollTo = vi.fn();+ outer.scrollTo = scrollTo;++ scrollSidebarTo(target, "auto");++ expect(scrollTo).not.toHaveBeenCalled();+ });+});++describe("scrollSidebarToWhenReachable", () => {+ function stubResizeObserver() {+ const observers: {+ callback: () => void;+ observe: Mock;+ disconnect: Mock;+ }[] = [];+ vi.stubGlobal(+ "ResizeObserver",+ class {+ callback: () => void;+ disconnect = vi.fn();+ observe = vi.fn();+ constructor(callback: () => void) {+ this.callback = callback;+ observers.push(this);+ }+ },+ );+ return observers;+ }++ it("scrolls once and stops when the target is already reachable", () => {+ const observers = stubResizeObserver();+ const { target, list, scrollTo } = sidebarScrollArea();++ scrollSidebarToWhenReachable(target, list, "smooth");++ expect(scrollTo).toHaveBeenCalledTimes(1);+ expect(observers).toHaveLength(0);+ });++ it("scrolls again as the list grows until the target is reachable", () => {+ const observers = stubResizeObserver();+ const { container, target, list, scrollTo } = sidebarScrollArea({+ scrollHeight: 900,+ });++ scrollSidebarToWhenReachable(target, list, "auto");+ expect(observers).toHaveLength(1);+ expect(observers[0].observe.mock.lastCall?.[0]).toBe(list);+ observers[0].callback();+ expect(observers[0].disconnect).not.toHaveBeenCalled();++ Object.defineProperty(container, "scrollHeight", { value: 2000 });+ observers[0].callback();++ expect(scrollTo).toHaveBeenCalledTimes(3);+ expect(scrollTo).toHaveBeenLastCalledWith({ top: 236, behavior: "auto" });+ expect(observers[0].disconnect).toHaveBeenCalled();+ });++ it.each(["wheel", "touchstart", "pointerdown", "keydown"])(+ "stops following on %s in the sidebar, not on its own scrolling or input elsewhere",+ (type) => {+ const observers = stubResizeObserver();+ const { container, target, list } = sidebarScrollArea({+ scrollHeight: 900,+ });+ scrollSidebarToWhenReachable(target, list, "smooth");++ container.dispatchEvent(new Event("scroll"));+ document.body.dispatchEvent(new Event(type, { bubbles: true }));+ expect(observers[0].disconnect).not.toHaveBeenCalled();++ target.dispatchEvent(new Event(type, { bubbles: true }));+ expect(observers[0].disconnect).toHaveBeenCalled();+ },+ );++ it("gives up after a few seconds, or when stopped", () => {+ vi.useFakeTimers();+ const observers = stubResizeObserver();+ const short = sidebarScrollArea({ scrollHeight: 900 });+ scrollSidebarToWhenReachable(short.target, short.list, "auto");+ const other = sidebarScrollArea({ scrollHeight: 900 });+ const stop = scrollSidebarToWhenReachable(other.target, other.list, "auto");++ stop();+ expect(observers[1].disconnect).toHaveBeenCalled();+ vi.advanceTimersByTime(4999);+ expect(observers[0].disconnect).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(observers[0].disconnect).toHaveBeenCalled();+ });+});++describe("afterAnimations", () => {+ it("waits for every finite animation and ignores endless ones", async () => {+ const short = fakeAnimation(150);+ const long = fakeAnimation(260);+ const spinner = fakeAnimation(Infinity);+ const element = elementWithAnimations([+ short.animation,+ long.animation,+ spinner.animation,+ ]);+ const callback = vi.fn();++ afterAnimations(element, callback);+ expect(element.getAnimations).toHaveBeenCalledWith({ subtree: true });+ short.finish();+ await flushPromises();+ expect(callback).not.toHaveBeenCalled();+ long.finish();++ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1));+ });++ it("waits for an animation that replaces a cancelled one", async () => {+ const first = fakeAnimation(260);+ const replacement = fakeAnimation(260);+ const callback = vi.fn();++ afterAnimations(+ elementWithAnimations([first.animation], [replacement.animation]),+ callback,+ );+ first.cancel();+ await flushPromises();+ expect(callback).not.toHaveBeenCalled();+ replacement.finish();++ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1));+ });++ it("calls back right away when nothing is animating", async () => {+ const callback = vi.fn();++ afterAnimations(elementWithAnimations([]), callback);++ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1));+ });++ it("stops waiting after a few rounds of new animations", async () => {+ const element = document.createElement("div");+ element.getAnimations = vi.fn(() => {+ const animation = fakeAnimation(150);+ animation.finish();+ Object.assign(animation.animation, { playState: "running" });+ return [animation.animation];+ });+ const callback = vi.fn();++ afterAnimations(element, callback);++ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1));+ expect(element.getAnimations).toHaveBeenCalledTimes(5);+ });++ it("never calls back once cancelled", async () => {+ const opening = fakeAnimation(260);+ const callback = vi.fn();++ const cancel = afterAnimations(+ elementWithAnimations([opening.animation]),+ callback,+ );+ cancel();+ opening.finish();+ await flushPromises();++ expect(callback).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/ChatsNavSection/ChatsNavSection.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/ChatsNavSection/ChatsNavSection.tsxnew file mode 100644index 0000000000..36bfa052c1--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/ChatsNavSection/ChatsNavSection.tsx@@ -0,0 +1,48 @@+"use client";++import { motion, type Variants } from "framer-motion";+import { Suspense } from "react";+import { useJumpToRecentChats } from "../../useJumpToRecentChats";+import { ChatsRailItem } from "../ChatsRailItem/ChatsRailItem";+import { CollapsibleNavGroup } from "../CollapsibleNavGroup/CollapsibleNavGroup";+import { RecentChats } from "../RecentChats/RecentChats";++interface Props {+ itemVariants: Variants;+}++export function ChatsNavSection({ itemVariants }: Props) {+ const {+ isRecentChatsOpen,+ setIsRecentChatsOpen,+ recentChatsRef,+ jumpToRecentChats,+ } = useJumpToRecentChats();++ // One stagger slot: only one of the two is ever displayed.+ return (+ <motion.div variants={itemVariants}>+ <div className="hidden group-data-[collapsible=icon]:block">+ <ChatsRailItem onClick={jumpToRecentChats} />+ </div>++ <div+ ref={recentChatsRef}+ className="group-data-[collapsible=icon]:hidden"+ >+ <CollapsibleNavGroup+ label="Recent chats"+ open={isRecentChatsOpen}+ onOpenChange={setIsRecentChatsOpen}+ >+ {/* 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>+ </div>+ </motion.div>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/ChatsRailItem/ChatsRailItem.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/ChatsRailItem/ChatsRailItem.tsxnew file mode 100644index 0000000000..a3ec8065d2--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/ChatsRailItem/ChatsRailItem.tsx@@ -0,0 +1,37 @@+import { Icon } from "@/components/atoms/Icon/Icon";+import {+ SidebarGroup,+ SidebarMenu,+ SidebarMenuButton,+ SidebarMenuItem,+} from "@/components/ui/sidebar";+import { BubbleChatIcon } from "@hugeicons/core-free-icons";+import { useNavItemClassName } from "../../useNavItemClassName";++interface Props {+ onClick: () => void;+}++export function ChatsRailItem({ onClick }: Props) {+ const navItemClassName = useNavItemClassName();++ return (+ <SidebarGroup className="py-1">+ <SidebarMenu className="group-data-[collapsible=icon]:gap-1">+ <SidebarMenuItem>+ <SidebarMenuButton+ tooltip="Chats"+ onClick={onClick}+ className={navItemClassName}+ >+ <Icon+ icon={BubbleChatIcon}+ className="size-4 text-sidebar-foreground/90 group-data-[collapsible=icon]:size-4.5"+ />+ <span className="truncate">Chats</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ </SidebarMenu>+ </SidebarGroup>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/CollapsibleNavGroup/CollapsibleNavGroup.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/CollapsibleNavGroup/CollapsibleNavGroup.tsxnew file mode 100644index 0000000000..f63f654981--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/CollapsibleNavGroup/CollapsibleNavGroup.tsx@@ -0,0 +1,56 @@+"use client";++import { Icon } from "@/components/atoms/Icon/Icon";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import {+ SidebarGroup,+ SidebarGroupContent,+ SidebarGroupLabel,+} from "@/components/ui/sidebar";+import { ArrowDown01Icon } from "@hugeicons/core-free-icons";+import type { ReactNode } from "react";++interface Props {+ label: string;+ children: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}++export function CollapsibleNavGroup({+ label,+ children,+ open,+ onOpenChange,+}: Props) {+ return (+ <Collapsible+ defaultOpen+ open={open}+ onOpenChange={onOpenChange}+ className="group/collapsible"+ >+ <SidebarGroup className="py-1">+ <SidebarGroupLabel+ asChild+ className="text-[13px] font-medium text-zinc-500 group-data-[collapsible=icon]:hidden"+ >+ <CollapsibleTrigger>+ {label}+ <Icon+ icon={ArrowDown01Icon}+ className="ease-[cubic-bezier(0.33,1,0.68,1)] ml-auto size-4 text-sidebar-foreground/90 transition-transform duration-200 group-data-[collapsible=icon]:size-4.5 group-data-[state=open]/collapsible:rotate-180 motion-reduce:transition-none"+ />+ </CollapsibleTrigger>+ </SidebarGroupLabel>+ <CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down motion-reduce:animate-none">+ <SidebarGroupContent>{children}</SidebarGroupContent>+ </CollapsibleContent>+ </SidebarGroup>+ </Collapsible>+ );+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/helpers.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/helpers.tsnew file mode 100644index 0000000000..b5da06f0f2--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/helpers.ts@@ -0,0 +1,74 @@+const MAX_ANIMATION_ROUNDS = 5;+const FOLLOW_GROWTH_MS = 5000;+const USER_SCROLL_EVENTS = ["wheel", "touchstart", "pointerdown", "keydown"];++export function scrollSidebarTo(target: HTMLElement, behavior: ScrollBehavior) {+ const container = target.closest<HTMLElement>('[data-sidebar="content"]');+ if (!container) return true;+ const padding = parseFloat(getComputedStyle(container).scrollPaddingTop) || 0;+ const top =+ container.scrollTop ++ target.getBoundingClientRect().top -+ container.getBoundingClientRect().top -+ padding;+ container.scrollTo({ top, behavior });+ return top <= container.scrollHeight - container.clientHeight + 1;+}++export function scrollSidebarToWhenReachable(+ target: HTMLElement,+ growing: Element,+ behavior: ScrollBehavior,+) {+ if (scrollSidebarTo(target, behavior)) return () => {};+ const container = target.closest('[data-sidebar="content"]');+ const observer = new ResizeObserver(() => {+ if (scrollSidebarTo(target, behavior)) stop();+ });+ const timeout = setTimeout(stop, FOLLOW_GROWTH_MS);+ observer.observe(growing);+ for (const type of USER_SCROLL_EVENTS) {+ container?.addEventListener(type, stop, { passive: true });+ }++ function stop() {+ clearTimeout(timeout);+ observer.disconnect();+ for (const type of USER_SCROLL_EVENTS) {+ container?.removeEventListener(type, stop);+ }+ }++ return stop;+}++export function afterAnimations(element: Element, callback: () => void) {+ let isCancelled = false;++ // An animation can be cancelled and restarted while we wait (Radix does+ // this when it measures a reopened collapsible), so check again each round.+ function waitForRunningAnimations(round: number) {+ const running = element+ .getAnimations({ subtree: true })+ .filter(+ (animation) =>+ animation.playState !== "finished" &&+ animation.effect?.getComputedTiming().endTime !== Infinity,+ );+ Promise.allSettled(running.map((animation) => animation.finished)).then(+ () => {+ if (isCancelled) return;+ if (running.length > 0 && round < MAX_ANIMATION_ROUNDS) {+ waitForRunningAnimations(round + 1);+ return;+ }+ callback();+ },+ );+ }++ waitForRunningAnimations(1);+ return () => {+ isCancelled = true;+ };+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/useJumpToRecentChats.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/useJumpToRecentChats.tsnew file mode 100644index 0000000000..0da8e550d0--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/useJumpToRecentChats.ts@@ -0,0 +1,56 @@+import { useSidebar } from "@/components/ui/sidebar";+import { useReducedMotion } from "framer-motion";+import { useEffect, useRef, useState } from "react";+import { afterAnimations, scrollSidebarToWhenReachable } from "./helpers";++export function useJumpToRecentChats() {+ const { state, setOpen } = useSidebar();+ const reduceMotion = useReducedMotion();+ const [isRecentChatsOpen, setIsRecentChatsOpen] = useState(true);+ const recentChatsRef = useRef<HTMLDivElement>(null);+ const isJumpPendingRef = useRef(false);++ function jumpToRecentChats() {+ isJumpPendingRef.current = true;+ setIsRecentChatsOpen(true);+ setOpen(true);+ }++ useEffect(() => {+ if (state !== "expanded" || !isJumpPendingRef.current) return;+ isJumpPendingRef.current = false;+ const recentChats = recentChatsRef.current;+ const heading = recentChats?.querySelector<HTMLElement>(+ '[data-sidebar="group-label"]',+ );+ const scrollArea = heading?.closest<HTMLElement>(+ '[data-sidebar="content"]',+ );+ if (!recentChats || !heading || !scrollArea) return;++ heading.focus({ preventScroll: true });+ const behavior = reduceMotion ? "auto" : "smooth";+ let stopFollowing = () => {};+ // Expanding animates the nav items above Recent chats, and reopening it+ // animates its list open (and may reload it). Measure once they have+ // their final size, and follow the list while it is still loading.+ const cancelWaiting = afterAnimations(scrollArea, () => {+ stopFollowing = scrollSidebarToWhenReachable(+ heading,+ recentChats,+ behavior,+ );+ });+ return () => {+ cancelWaiting();+ stopFollowing();+ };+ }, [state, reduceMotion]);++ return {+ isRecentChatsOpen,+ setIsRecentChatsOpen,+ recentChatsRef,+ jumpToRecentChats,+ };+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/useNavItemClassName.ts b/autogpt_platform/frontend/src/components/layout/AppSidebar/useNavItemClassName.tsnew file mode 100644index 0000000000..2ddebc5721--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/useNavItemClassName.ts@@ -0,0 +1,13 @@+import { cn } from "@/lib/utils";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";++// The stronger active state ships with the brain-dump experience.+export function useNavItemClassName() {+ const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);+ return cn(+ "h-auto rounded-xl p-2 pl-3 font-normal data-[active=true]:font-normal group-data-[collapsible=icon]:!p-1.5 hover:!bg-zinc-100 [&>svg]:size-4 group-data-[collapsible=icon]:[&>svg]:size-4.5",+ isBrainDumpEnabled+ ? "data-[active=true]:!bg-zinc-200 data-[active=true]:hover:!bg-zinc-200"+ : "data-[active=true]:!bg-zinc-100",+ );+}