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/copilot): paginate session sidebar so threads past 50 stay reachable (#13128)
Ubbe1a4fecf8120d
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsxindex ad7ef02a65..744fb075c7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx@@ -1,8 +1,6 @@"use client";import {- getGetV2ListSessionsQueryKey,getV2GetSession,- useGetV2ListSessions,usePatchV2UpdateSessionTitle,} from "@/app/api/__generated__/endpoints/chat/chat";import { Button } from "@/components/atoms/Button/Button";@@ -28,8 +26,8 @@ import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import {CheckCircle,CircleNotch,- DownloadSimpleIcon,DotsThree,+ DownloadSimpleIcon,HourglassIcon,MagnifyingGlassIcon,PencilSimpleIcon,@@ -43,14 +41,15 @@ import { parseAsString, useQueryState } from "nuqs";import { useEffect, useRef, useState } from "react";import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";import { formatNotificationTitle } from "../../helpers";+import { fetchAndExportChat } from "../../helpers/exportChatAsMarkdown";import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";import { useCopilotUIStore } from "../../store";import { useSessionDeletion } from "../../useSessionDeletion";-import { NotificationToggle } from "./components/NotificationToggle/NotificationToggle";-import { fetchAndExportChat } from "../../helpers/exportChatAsMarkdown";+import { SESSION_LIST_QUERY_KEY, useSessionList } from "../../useSessionList";import { ChatSearchModal } from "../ChatSearchModal/ChatSearchModal";import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";import { UsagePopover } from "../UsageLimits/UsagePopover/UsagePopover";+import { NotificationToggle } from "./components/NotificationToggle/NotificationToggle";export function ChatSidebar() {const { state } = useSidebar();@@ -65,8 +64,13 @@ export function ChatSidebar() {const queryClient = useQueryClient();- const { data: sessionsResponse, isLoading: isLoadingSessions } =- useGetV2ListSessions({ limit: 50 }, { query: { refetchInterval: 10_000 } });+ const {+ sessions,+ isLoading: isLoadingSessions,+ hasMore,+ isLoadingMore,+ loadMore,+ } = useSessionList();const {sessionToDelete,@@ -88,7 +92,7 @@ export function ChatSidebar() {mutation: {onSuccess: () => {queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),+ queryKey: SESSION_LIST_QUERY_KEY,});setEditingSessionId(null);},@@ -115,7 +119,7 @@ export function ChatSidebar() {// Refetch session list when active session changesuseEffect(() => {queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),+ queryKey: SESSION_LIST_QUERY_KEY,});}, [sessionId, queryClient]);@@ -141,9 +145,6 @@ export function ChatSidebar() {return () => document.removeEventListener("keydown", handleSearchShortcut);}, [isChatSearchEnabled, setSearchOpen]);- const sessions =- sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];-function handleNewChat() {setSessionId(null);}@@ -543,6 +544,18 @@ export function ChatSidebar() {</div>)))}+ {hasMore && (+ <Button+ variant="secondary"+ size="small"+ onClick={() => loadMore()}+ loading={isLoadingMore}+ disabled={isLoadingMore}+ className="mt-2 w-full"+ >+ {isLoadingMore ? "Loading…" : "Load older chats"}+ </Button>+ )}</motion.div>)}</SidebarContent>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsxindex 3df51f3637..a38f2f8db0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx@@ -11,6 +11,7 @@ import {within,} from "@/tests/integrations/test-utils";import { SidebarProvider } from "@/components/ui/sidebar";+import { http, HttpResponse } from "msw";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useCopilotUIStore } from "../../../store";@@ -362,3 +363,75 @@ describe("ChatSidebar — chat_status indicators", () => {expect(screen.queryByTestId("session-status-queued")).toBeNull();});});++describe("ChatSidebar — pagination", () => {+ afterEach(() => {+ server.resetHandlers();+ });++ function makeSessions(count: number, offset = 0) {+ return Array.from({ length: count }, (_, i) => ({+ id: `s${offset + i}`,+ title: `Chat ${offset + i}`,+ is_processing: false,+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+ }));+ }++ it("hides 'Load older chats' when all sessions are loaded", async () => {+ server.use(+ getGetV2ListSessionsMockHandler200({+ sessions: makeSessions(3),+ total: 3,+ }),+ );+ renderSidebar();+ await screen.findByText("Chat 0");+ expect(+ screen.queryByRole("button", { name: /load older chats/i }),+ ).toBeNull();+ });++ it("renders 'Load older chats' when total exceeds loaded sessions", async () => {+ server.use(+ getGetV2ListSessionsMockHandler200({+ sessions: makeSessions(50),+ total: 75,+ }),+ );+ renderSidebar();+ await screen.findByText("Chat 0");+ expect(+ await screen.findByRole("button", { name: /load older chats/i }),+ ).toBeDefined();+ });++ it("fetches the next page with the loaded count as offset", 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 offsetN = Number(offset);+ const sessions =+ offsetN === 0 ? makeSessions(50, 0) : makeSessions(25, 50);+ return HttpResponse.json({ sessions, total: 75 });+ }),+ );+ renderSidebar();++ const loadMore = await screen.findByRole("button", {+ name: /load older chats/i,+ });+ fireEvent.click(loadMore);++ await screen.findByText("Chat 50");+ expect(seenOffsets).toContain("50");+ await vi.waitFor(() => {+ expect(+ screen.queryByRole("button", { name: /load older chats/i }),+ ).toBeNull();+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsxindex d531e92530..c554cd2c01 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx@@ -1,4 +1,3 @@-import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { scrollbarStyles } from "@/components/styles/scrollbars";@@ -25,6 +24,7 @@ import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";import { useCopilotUIStore } from "../../store";import { useSessionDeletion } from "../../useSessionDeletion";+import { useSessionList } from "../../useSessionList";import { ChatSearchResults } from "../ChatSearchModal/ChatSearchResults";import { useChatSearch } from "../ChatSearchModal/useChatSearch";import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";@@ -77,12 +77,8 @@ export function MobileDrawer() {(state) => state.sessionNeedsReload,);- const { data: sessionsResponse, isLoading } = useGetV2ListSessions(- { limit: 50 },- { query: { enabled: !isUserLoading && isLoggedIn } },- );- const sessions =- sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];+ const { sessions, isLoading, hasMore, isLoadingMore, loadMore } =+ useSessionList({ enabled: !isUserLoading && isLoggedIn });const {query,debouncedQuery,@@ -312,6 +308,18 @@ export function MobileDrawer() {</button>)))}+ {hasMore && (+ <Button+ variant="ghost"+ size="small"+ onClick={() => loadMore()}+ loading={isLoadingMore}+ disabled={isLoadingMore}+ className="mt-2 w-full justify-center text-neutral-500"+ >+ {isLoadingMore ? "Loading…" : "Load older chats"}+ </Button>+ )}</div></Drawer.Content></Drawer.Portal>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex 440e20d1de..941bf02684 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -1,9 +1,9 @@import {getGetV2GetSessionQueryKey,- getGetV2ListSessionsQueryKey,useGetV2GetSession,usePostV2CreateSession,} from "@/app/api/__generated__/endpoints/chat/chat";+import { SESSION_LIST_QUERY_KEY } from "./useSessionList";import { toast } from "@/components/molecules/Toast/use-toast";import * as Sentry from "@sentry/nextjs";import { useQueryClient } from "@tanstack/react-query";@@ -125,7 +125,7 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {if (response.status === 200 && response.data?.id) {setSessionId(response.data.id);queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),+ queryKey: SESSION_LIST_QUERY_KEY,});}},diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.tsindex 5e8c837837..a57f428a90 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts@@ -1,4 +1,3 @@-import { getGetV2ListSessionsQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";import { useBackendAPI } from "@/lib/autogpt-server-api/context";import type { WebSocketNotification } from "@/lib/autogpt-server-api/types";import { Key } from "@/services/storage/local-storage";@@ -10,6 +9,7 @@ import {parseSessionIDs,} from "./helpers";import { useCopilotUIStore } from "./store";+import { SESSION_LIST_QUERY_KEY } from "./useSessionList";const NOTIFICATION_SOUND_PATH = "/notification.mp3";@@ -172,7 +172,7 @@ export function useCopilotNotifications(activeSessionID: string | null) {// Refetch the session list so the sidebar reflects the latest// is_processing state (avoids stale spinner after cross-tab clear).queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),+ queryKey: SESSION_LIST_QUERY_KEY,});}window.addEventListener("storage", handleStorage);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.tsindex cc1d0991b1..5621c7974e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts@@ -1,11 +1,9 @@-import {- getGetV2ListSessionsQueryKey,- useDeleteV2DeleteSession,-} from "@/app/api/__generated__/endpoints/chat/chat";+import { useDeleteV2DeleteSession } from "@/app/api/__generated__/endpoints/chat/chat";import { toast } from "@/components/molecules/Toast/use-toast";import { useQueryClient } from "@tanstack/react-query";import { parseAsString, useQueryState } from "nuqs";import { useCopilotUIStore } from "./store";+import { SESSION_LIST_QUERY_KEY } from "./useSessionList";/*** Session deletion flow: reads the pending `sessionToDelete` from the store,@@ -25,7 +23,7 @@ export function useSessionDeletion() {mutation: {onSuccess: (_data, variables) => {queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),+ queryKey: SESSION_LIST_QUERY_KEY,});// Use the mutation's own `variables` — not the closed-over store// value — so a rapid open/cancel/open-different sequence can'tdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.tsnew file mode 100644index 0000000000..457b74b3a6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts@@ -0,0 +1,64 @@+import { getV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";+import { type InfiniteData, useInfiniteQuery } from "@tanstack/react-query";++export const SESSION_LIST_PAGE_SIZE = 50;+// `refetchInterval` on a `useInfiniteQuery` refetches every loaded page, and+// TanStack Query v5 removed `refetchPage` so we can't scope it to page 0.+// Worst case is bounded by the user's session count (and the WebSocket+// invalidations in `useCopilotNotifications` already handle the high-signal+// completion events) — revisit by extracting a separate live-status query if+// this ever becomes a real bandwidth concern.+export const SESSION_LIST_REFETCH_INTERVAL_MS = 10_000;++// Fresh, paginated-cache key. The orval-generated key targets the non-infinite+// `useQuery` cache shape; keeping the infinite cache on a separate key avoids+// shape collisions and lets us hand a stable key to invalidation callsites.+export const SESSION_LIST_QUERY_KEY = ["copilot", "session-list"] as const;++type SessionListPage = Awaited<ReturnType<typeof getV2ListSessions>>;+export type SessionListInfiniteData = InfiniteData<SessionListPage>;++interface Args {+ enabled?: boolean;+}++export function useSessionList({ enabled = true }: Args = {}) {+ const query = useInfiniteQuery({+ queryKey: SESSION_LIST_QUERY_KEY,+ queryFn: ({ pageParam }) =>+ getV2ListSessions({+ limit: SESSION_LIST_PAGE_SIZE,+ offset: pageParam,+ }),+ initialPageParam: 0,+ getNextPageParam: (lastPage, allPages) => {+ if (lastPage.status !== 200) return undefined;+ const loaded = countLoadedSessions(allPages);+ return loaded < lastPage.data.total ? loaded : undefined;+ },+ refetchInterval: SESSION_LIST_REFETCH_INTERVAL_MS,+ enabled,+ });++ return {+ sessions: flattenSessions(query.data),+ isLoading: query.isLoading,+ hasMore: !!query.hasNextPage,+ isLoadingMore: query.isFetchingNextPage,+ loadMore: query.fetchNextPage,+ };+}++export function flattenSessions(data: SessionListInfiniteData | undefined) {+ if (!data) return [];+ return data.pages.flatMap((page) =>+ page.status === 200 ? page.data.sessions : [],+ );+}++function countLoadedSessions(pages: SessionListPage[]) {+ return pages.reduce(+ (acc, page) => acc + (page.status === 200 ? page.data.sessions.length : 0),+ 0,+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.tsindex d0a89cc399..06eb62e2bb 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.ts@@ -1,13 +1,13 @@-import {- getGetV2ListSessionsQueryKey,- type getV2ListSessionsResponse,-} from "@/app/api/__generated__/endpoints/chat/chat";import { useQueryClient } from "@tanstack/react-query";import { useEffect, useRef } from "react";+import {+ flattenSessions,+ SESSION_LIST_QUERY_KEY,+ type SessionListInfiniteData,+} from "./useSessionList";const TITLE_POLL_INTERVAL_MS = 2_000;const TITLE_POLL_MAX_ATTEMPTS = 5;-const SESSION_LIST_LIMIT = 50;interface Args {sessionId: string | null;@@ -38,29 +38,25 @@ export function useSessionTitlePoll({if (!wasActive || !isNowReady || !sessionId || isReconnecting) return;- queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey({ limit: SESSION_LIST_LIMIT }),- });+ queryClient.invalidateQueries({ queryKey: SESSION_LIST_QUERY_KEY });const sid = sessionId;let attempts = 0;clearInterval(titlePollRef.current);titlePollRef.current = setInterval(() => {- const data = queryClient.getQueryData<getV2ListSessionsResponse>(- getGetV2ListSessionsQueryKey({ limit: SESSION_LIST_LIMIT }),+ const data = queryClient.getQueryData<SessionListInfiniteData>(+ SESSION_LIST_QUERY_KEY,+ );+ const hasTitle = flattenSessions(data).some(+ (s) => s.id === sid && s.title,);- const hasTitle =- data?.status === 200 &&- data.data.sessions.some((s) => s.id === sid && s.title);if (hasTitle || attempts >= TITLE_POLL_MAX_ATTEMPTS) {clearInterval(titlePollRef.current);titlePollRef.current = undefined;return;}attempts += 1;- queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey({ limit: SESSION_LIST_LIMIT }),- });+ queryClient.invalidateQueries({ queryKey: SESSION_LIST_QUERY_KEY });}, TITLE_POLL_INTERVAL_MS);}, [status, sessionId, isReconnecting, queryClient]);