AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
perf(frontend/copilot): stop redrawing session rows on each list poll (#15719)
Abhimanyu Yadav1201ba8695c7
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sessionListSharing.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sessionListSharing.test.tsnew file mode 100644index 0000000000..3920a0d640--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sessionListSharing.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vitest";+import { shareSessionListData } from "../sessionListSharing";+import type { SessionListInfiniteData } from "../useSessionList";++// The API client hands these over with `Date`s for timestamps, so the tests+// build them the same way.+function session(id: string, overrides: Record<string, unknown> = {}) {+ return {+ id,+ title: `Chat ${id}`,+ is_processing: false,+ is_pinned: false,+ created_at: new Date("2026-01-05T09:00:00Z"),+ updated_at: new Date("2026-01-05T09:00:00Z"),+ ...overrides,+ };+}++function listOf(...pages: ReturnType<typeof session>[][]) {+ return {+ pages: pages.map((sessions) => ({+ status: 200,+ data: { sessions, total: 3 },+ headers: new Headers(),+ })),+ pageParams: pages.map((_, i) => i * 50),+ } as unknown as SessionListInfiniteData;+}++describe("shareSessionListData", () => {+ it("returns the cached list when a refetch brings back the same sessions", () => {+ const cached = listOf([session("a"), session("b"), session("c")]);+ const refetched = listOf([session("a"), session("b"), session("c")]);++ expect(shareSessionListData(cached, refetched)).toBe(cached);+ });++ it("gives a new object only to the session that changed", () => {+ const cached = listOf([session("a"), session("b"), session("c")]);+ const refetched = listOf([+ session("a"),+ session("b", { title: "Renamed" }),+ session("c"),+ ]);++ const shared = shareSessionListData(+ cached,+ refetched,+ ) as SessionListInfiniteData;+ const [before, after] = [cached, shared].map((list) => {+ const page = list.pages[0];+ if (page.status !== 200) throw new Error("expected a 200 page");+ return page.data.sessions;+ });++ expect(after[0]).toBe(before[0]);+ expect(after[1]).not.toBe(before[1]);+ expect(after[1].title).toBe("Renamed");+ expect(after[2]).toBe(before[2]);+ });++ it("keeps the objects of sessions that only moved", () => {+ const cached = listOf([session("a"), session("b"), session("c")]);+ const refetched = listOf([+ session("c", { is_pinned: true }),+ session("a"),+ session("b"),+ ]);++ const shared = shareSessionListData(+ cached,+ refetched,+ ) as SessionListInfiniteData;+ const page = shared.pages[0];+ const cachedPage = cached.pages[0];+ if (page.status !== 200 || cachedPage.status !== 200) {+ throw new Error("expected 200 pages");+ }++ expect(page.data.sessions.map((s) => s.id)).toEqual(["c", "a", "b"]);+ expect(page.data.sessions[0]).not.toBe(cachedPage.data.sessions[2]);+ expect(page.data.sessions[1]).toBe(cachedPage.data.sessions[0]);+ expect(page.data.sessions[2]).toBe(cachedPage.data.sessions[1]);+ });++ it("treats a moved timestamp as a change", () => {+ const cached = listOf([session("a")]);+ const refetched = listOf([+ session("a", { updated_at: new Date("2026-01-06T09:00:00Z") }),+ ]);++ expect(shareSessionListData(cached, refetched)).not.toBe(cached);+ });++ it("keeps an unchanged older page when a new page is appended", () => {+ const cached = listOf([session("a")]);+ const withNext = listOf([session("a")], [session("b")]);++ const shared = shareSessionListData(+ cached,+ withNext,+ ) as SessionListInfiniteData;++ expect(shared.pages).toHaveLength(2);+ expect(shared.pages[0]).toBe(cached.pages[0]);+ });++ it("passes the first load through untouched", () => {+ const first = listOf([session("a")]);++ expect(shareSessionListData(undefined, first)).toBe(first);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionList.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionList.test.tsxnew file mode 100644index 0000000000..285b18889b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionList.test.tsx@@ -0,0 +1,271 @@+import { server } from "@/mocks/mock-server";+import {+ focusManager,+ QueryClient,+ QueryClientProvider,+} from "@tanstack/react-query";+import { act, renderHook, waitFor } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ SESSION_LIST_QUERY_KEY,+ SESSION_LIST_REFETCH_INTERVAL_MS,+ useSessionList,+} from "../useSessionList";++// The app's query client marks data fresh for 60 s (`lib/react-query`), which+// is what decides whether a window focus refetches the older pages.+const APP_STALE_TIME_MS = 60_000;++let listed: { id: string; title: string }[] = [];+let listRequests: string[] = [];++function makeClient() {+ return new QueryClient({+ defaultOptions: {+ queries: { retry: false, staleTime: APP_STALE_TIME_MS },+ },+ });+}++function renderSessionList(client: QueryClient) {+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ }+ return renderHook(() => useSessionList(), { wrapper: Wrapper });+}++async function settle() {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 50));+ });+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ listed = Array.from({ length: 75 }, (_, i) => ({+ id: `s${i}`,+ title: `Chat ${i}`,+ }));+ listRequests = [];+ server.use(+ http.get("*/api/chat/sessions", ({ request }) => {+ const url = new URL(request.url);+ const offset = Number(url.searchParams.get("offset") ?? "0");+ const limit = Number(url.searchParams.get("limit") ?? "50");+ listRequests.push(String(offset));+ return HttpResponse.json({+ sessions: listed.slice(offset, offset + limit).map((s) => ({+ ...s,+ is_processing: false,+ created_at: "2026-01-05T09:00:00Z",+ updated_at: "2026-01-05T09:00:00Z",+ })),+ total: listed.length,+ });+ }),+ );+});++afterEach(() => {+ focusManager.setFocused(undefined);+ vi.useRealTimers();+ server.resetHandlers();+});++describe("useSessionList — older pages", () => {+ it("still refreshes the older pages on focus after first-page polls", async () => {+ const client = makeClient();+ const { result } = renderSessionList(client);+ await waitFor(() => expect(result.current.sessions).toHaveLength(50));+ await act(async () => {+ await result.current.loadMore();+ });+ await waitFor(() => expect(result.current.sessions).toHaveLength(75));+ await settle();+ const loadedAt = client.getQueryState(+ SESSION_LIST_QUERY_KEY,+ )?.dataUpdatedAt;++ await act(async () => {+ vi.advanceTimersByTime(SESSION_LIST_REFETCH_INTERVAL_MS);+ });+ await waitFor(() => expect(listRequests.at(-1)).toBe("0"));+ await settle();+ // Patching page 0 must not mark the pages it never fetched as fresh.+ expect(client.getQueryState(SESSION_LIST_QUERY_KEY)?.dataUpdatedAt).toBe(+ loadedAt,+ );++ // An older chat is renamed; page 0 is unchanged, so the poll alone+ // would never pick it up.+ listed[60] = { ...listed[60], title: "Renamed older chat" };+ listRequests = [];+ act(() => {+ focusManager.setFocused(false);+ focusManager.setFocused(true);+ });++ await waitFor(() =>+ expect(result.current.sessions.find((s) => s.id === "s60")?.title).toBe(+ "Renamed older chat",+ ),+ );+ expect(listRequests).toEqual(["0", "50"]);+ });++ it("keeps a first-page update that lands while an older page is loading", async () => {+ listed = Array.from({ length: 120 }, (_, i) => ({+ id: `s${i}`,+ title: `Chat ${i}`,+ }));+ let releaseThirdPage: () => void = () => {};+ const thirdPageHeld = new Promise<void>((resolve) => {+ releaseThirdPage = resolve;+ });+ server.use(+ http.get("*/api/chat/sessions", async ({ request }) => {+ const url = new URL(request.url);+ const offset = Number(url.searchParams.get("offset") ?? "0");+ const limit = Number(url.searchParams.get("limit") ?? "50");+ listRequests.push(String(offset));+ const page = listed.slice(offset, offset + limit);+ if (offset === 100) await thirdPageHeld;+ return HttpResponse.json({+ sessions: page.map((s) => ({+ ...s,+ is_processing: false,+ created_at: "2026-01-05T09:00:00Z",+ updated_at: "2026-01-05T09:00:00Z",+ })),+ total: listed.length,+ });+ }),+ );+ const client = makeClient();+ const { result } = renderSessionList(client);+ await waitFor(() => expect(result.current.sessions).toHaveLength(50));+ await act(async () => {+ await result.current.loadMore();+ });+ await waitFor(() => expect(result.current.sessions).toHaveLength(100));+ await settle();++ // "Load older chats" is in flight when the first-page poll comes back+ // with a renamed chat.+ let loadingThirdPage: Promise<unknown> = Promise.resolve();+ act(() => {+ loadingThirdPage = result.current.loadMore();+ });+ await waitFor(() => expect(listRequests).toContain("100"));+ listed[3] = { ...listed[3], title: "Renamed on page one" };+ listRequests = [];+ await act(async () => {+ vi.advanceTimersByTime(SESSION_LIST_REFETCH_INTERVAL_MS);+ });+ await waitFor(() => expect(listRequests).toContain("0"));+ await settle();++ await act(async () => {+ releaseThirdPage();+ await loadingThirdPage;+ });+ await waitFor(() => expect(result.current.sessions).toHaveLength(120));+ await settle();++ expect(result.current.sessions.find((s) => s.id === "s3")?.title).toBe(+ "Renamed on page one",+ );+ });++ it("drops a first-page poll that a newer refetch of the list overtook", async () => {+ let holdNextFirstPage = false;+ let releaseFirstPage: () => void = () => {};+ server.use(+ http.get("*/api/chat/sessions", async ({ request }) => {+ const url = new URL(request.url);+ const offset = Number(url.searchParams.get("offset") ?? "0");+ const limit = Number(url.searchParams.get("limit") ?? "50");+ listRequests.push(String(offset));+ // The page is read when the request arrives, as the server would.+ const body = {+ sessions: listed.slice(offset, offset + limit).map((s) => ({+ ...s,+ is_processing: false,+ created_at: "2026-01-05T09:00:00Z",+ updated_at: "2026-01-05T09:00:00Z",+ })),+ total: listed.length,+ };+ if (offset === 0 && holdNextFirstPage) {+ holdNextFirstPage = false;+ await new Promise<void>((resolve) => {+ releaseFirstPage = resolve;+ });+ }+ return HttpResponse.json(body);+ }),+ );+ const client = makeClient();+ const { result } = renderSessionList(client);+ await waitFor(() => expect(result.current.sessions).toHaveLength(50));+ await act(async () => {+ await result.current.loadMore();+ });+ await waitFor(() => expect(result.current.sessions).toHaveLength(75));+ await settle();++ // The poll's request leaves, then the chat is renamed and the rename's+ // invalidation refetches the list before the poll's response arrives.+ holdNextFirstPage = true;+ listRequests = [];+ await act(async () => {+ vi.advanceTimersByTime(SESSION_LIST_REFETCH_INTERVAL_MS);+ });+ await waitFor(() => expect(listRequests).toEqual(["0"]));+ listed[3] = { ...listed[3], title: "Renamed after the poll left" };+ await act(async () => {+ await client.invalidateQueries({ queryKey: SESSION_LIST_QUERY_KEY });+ });+ await waitFor(() =>+ expect(result.current.sessions.find((s) => s.id === "s3")?.title).toBe(+ "Renamed after the poll left",+ ),+ );++ await act(async () => {+ releaseFirstPage();+ });+ await settle();++ expect(result.current.sessions.find((s) => s.id === "s3")?.title).toBe(+ "Renamed after the poll left",+ );+ });++ it("does not poll the first page straight away when the list remounts", async () => {+ const client = makeClient();+ const first = renderSessionList(client);+ await waitFor(() => expect(first.result.current.sessions).toHaveLength(50));+ await act(async () => {+ await first.result.current.loadMore();+ });+ await waitFor(() => expect(first.result.current.sessions).toHaveLength(75));+ await settle();+ first.unmount();++ // Back within the list's own 60 s staleTime, so nothing is due yet.+ await act(async () => {+ vi.advanceTimersByTime(15_000);+ });+ listRequests = [];+ const second = renderSessionList(client);+ expect(second.result.current.sessions).toHaveLength(75);+ await settle();++ expect(listRequests).toEqual([]);+ });+});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 475bf8c864..29f170f080 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@@ -26,7 +26,8 @@ import { ShareChatDialog } from "../../sharing/ShareChatDialog";import { useQueryClient } from "@tanstack/react-query";import { motion } from "framer-motion";import { parseAsString, useQueryState } from "nuqs";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import { useStableCallback } from "@/hooks/useStableCallback";import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";import { formatNotificationTitle } from "../../helpers";import { fetchAndExportChat } from "../../helpers/exportChatAsMarkdown";@@ -47,6 +48,7 @@ import { HeaderAction } from "./components/HeaderAction";import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";import { UsagePopover } from "../UsageLimits/UsagePopover/UsagePopover";import { NotificationToggle } from "./components/NotificationToggle/NotificationToggle";+import { sessionAgeDays, useSessionAgeClock } from "./useSessionAgeClock";import {Files01Icon,PlusSignCircleIcon,@@ -203,24 +205,27 @@ export function ChatSidebar() {}}- function handleSelectSession(id: string, expertId: string | null) {- setSessionId(id);- if (isExpertsEnabled) {- setExpertIdParam(expertId);- }- closeSearch();- }+ // Row handlers are shared by every row and keep one identity across renders+ // (see `ChatSessionRow`), so a list update only re-renders the rows whose+ // own props changed.+ const handleSelectSession = useStableCallback(+ (id: string, expertId: string | null) => {+ setSessionId(id);+ if (isExpertsEnabled) {+ setExpertIdParam(expertId);+ }+ closeSearch();+ },+ );- function handleRenameClick(- e: React.MouseEvent,- id: string,- title: string | null | undefined,- ) {- e.stopPropagation();- renameCancelledRef.current = false;- setEditingSessionId(id);- setEditingTitle(title || "");- }+ const handleRenameClick = useStableCallback(+ (e: React.MouseEvent, id: string, title: string | null | undefined) => {+ e.stopPropagation();+ renameCancelledRef.current = false;+ setEditingSessionId(id);+ setEditingTitle(title || "");+ },+ );function handleRenameSubmit(id: string) {const trimmed = editingTitle.trim();@@ -231,26 +236,50 @@ export function ChatSidebar() {}}- function handleDeleteClick(- e: React.MouseEvent,- id: string,- title: string | null | undefined,- ) {- e.stopPropagation();- requestDelete(id, title);- }+ const handleRenameCancel = useStableCallback(() => {+ renameCancelledRef.current = true;+ setEditingSessionId(null);+ });- function handleExcludeClick(e: React.MouseEvent, id: string) {- e.stopPropagation();- excludeFromLearning({ sourceKind: CHAT_SOURCE_KIND, sourceRef: id });- }+ const handleRenameBlur = useStableCallback((id: string) => {+ if (renameCancelledRef.current) {+ renameCancelledRef.current = false;+ return;+ }+ handleRenameSubmit(id);+ });- function handlePinClick(e: React.MouseEvent, id: string, isPinned: boolean) {- e.stopPropagation();- setSessionPinned({ sessionId: id, data: { is_pinned: !isPinned } });- }+ const handleDeleteClick = useStableCallback(+ (e: React.MouseEvent, id: string, title: string | null | undefined) => {+ e.stopPropagation();+ requestDelete(id, title);+ },+ );- async function handleExportClick(+ const handleExcludeClick = useStableCallback(+ (e: React.MouseEvent, id: string) => {+ e.stopPropagation();+ excludeFromLearning({ sourceKind: CHAT_SOURCE_KIND, sourceRef: id });+ },+ );++ const handlePinClick = useStableCallback(+ (e: React.MouseEvent, id: string, isPinned: boolean) => {+ e.stopPropagation();+ setSessionPinned({ sessionId: id, data: { is_pinned: !isPinned } });+ },+ );++ const handleShareClick = useStableCallback(+ (e: React.MouseEvent, id: string) => {+ e.stopPropagation();+ setSharingSessionId(id);+ },+ );++ const handleExportClick = useStableCallback(handleExport);++ async function handleExport(e: React.MouseEvent,id: string,title: string | null | undefined,@@ -280,25 +309,31 @@ export function ChatSidebar() {}}- const { pinned, groups, showHeaders } = groupSessionsForSidebar({- sessions,- floatPinned: isPinningEnabled,- });+ const { pinned, groups, showHeaders } = useMemo(+ () =>+ groupSessionsForSidebar({+ sessions,+ floatPinned: isPinningEnabled,+ }),+ [sessions, isPinningEnabled],+ );const sessionSections = isExpertsEnabled && showHeaders ? groups : null;+ const ageClock = useSessionAgeClock(sessions);function renderSessionRow(session: SessionSummaryResponse,index: number,list: SessionSummaryResponse[],) {+ const isEditing = editingSessionId === session.id;return (<ChatSessionRowkey={session.id}session={session}isActive={session.id === sessionId}isNextActive={list[index + 1]?.id === sessionId}- isEditing={editingSessionId === session.id}- editingTitle={editingTitle}+ isEditing={isEditing}+ editingTitle={isEditing ? editingTitle : ""}renameInputRef={renameInputRef}isExporting={exportingSessionIds.has(session.id)}isDeleting={isDeleting}@@ -317,30 +352,17 @@ export function ChatSidebar() {showCompleted={completedSessionIDs.has(session.id) && session.id !== sessionId}- onSelect={() =>- handleSelectSession(session.id, session.expert_id ?? null)- }+ ageDays={sessionAgeDays(session.updated_at, ageClock)}+ onSelect={handleSelectSession}onEditingTitleChange={setEditingTitle}- onRenameCancel={() => {- renameCancelledRef.current = true;- setEditingSessionId(null);- }}- onRenameBlur={() => {- if (renameCancelledRef.current) {- renameCancelledRef.current = false;- return;- }- handleRenameSubmit(session.id);- }}- onPin={(e) => handlePinClick(e, session.id, !!session.is_pinned)}- onRename={(e) => handleRenameClick(e, session.id, session.title)}- onExport={(e) => handleExportClick(e, session.id, session.title)}- onShare={(e) => {- e.stopPropagation();- setSharingSessionId(session.id);- }}- onExcludeFromLearning={(e) => handleExcludeClick(e, session.id)}- onDelete={(e) => handleDeleteClick(e, session.id, session.title)}+ onRenameCancel={handleRenameCancel}+ onRenameBlur={handleRenameBlur}+ onPin={handlePinClick}+ onRename={handleRenameClick}+ onExport={handleExportClick}+ onShare={handleShareClick}+ onExcludeFromLearning={handleExcludeClick}+ onDelete={handleDeleteClick}/>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/session-list-renders.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/session-list-renders.test.tsxnew file mode 100644index 0000000000..687d8c91b9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/session-list-renders.test.tsx@@ -0,0 +1,361 @@+import { SESSION_LIST_REFETCH_INTERVAL_MS } from "@/app/(platform)/copilot/useSessionList";+import { SidebarProvider } from "@/components/ui/sidebar";+import { server } from "@/mocks/mock-server";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import { http, HttpResponse } from "msw";+import type { ComponentProps } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotUIStore } from "../../../store";+import { ChatSidebar } from "../ChatSidebar";++const blockRenders = vi.fn();++// Every render of a row renders its `ChatSessionBlock`, so counting the block+// counts the rows that re-rendered (and which ones).+vi.mock("../../ChatSessionBlock/ChatSessionBlock", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../ChatSessionBlock/ChatSessionBlock")+ >();+ function CountedChatSessionBlock(+ props: ComponentProps<typeof actual.ChatSessionBlock>,+ ) {+ blockRenders(props.title);+ return <actual.ChatSessionBlock {...props} />;+ }+ return { ...actual, ChatSessionBlock: CountedChatSessionBlock };+});++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-pinning",+ };+});++const exportChat = vi.fn();+vi.mock("../../../helpers/exportChatAsMarkdown", () => ({+ fetchAndExportChat: (id: string, title: string | null | undefined) =>+ exportChat(id, title),+}));++vi.mock("../../../sharing/ShareChatDialog", () => ({+ ShareChatDialog: ({ sessionId }: { sessionId: string }) => (+ <div role="dialog" aria-label={`Share ${sessionId}`} />+ ),+}));++vi.mock("../../UsageLimits/UsagePopover/UsagePopover", () => ({+ UsagePopover: () => null,+}));+vi.mock("../components/NotificationToggle/NotificationToggle", () => ({+ NotificationToggle: () => null,+}));++interface SessionSeed {+ id: string;+ title: string;+ is_pinned?: boolean;+ updated_at?: string;+}++function toSummary(seed: SessionSeed) {+ return {+ id: seed.id,+ title: seed.title,+ is_processing: false,+ is_pinned: seed.is_pinned ?? false,+ chat_status: "idle",+ // `Z`-suffixed, so the API client turns them into `Date`s as in the app.+ created_at: "2026-01-05T09:00:00Z",+ updated_at: seed.updated_at ?? "2026-01-05T09:00:00Z",+ };+}++let listed: SessionSeed[] = [];+let listRequests: string[] = [];++function serveList(total?: () => number) {+ server.use(+ http.get("*/api/chat/sessions", ({ request }) => {+ const url = new URL(request.url);+ const offset = Number(url.searchParams.get("offset") ?? "0");+ const limit = Number(url.searchParams.get("limit") ?? "50");+ listRequests.push(String(offset));+ return HttpResponse.json({+ sessions: listed.slice(offset, offset + limit).map(toSummary),+ total: total ? total() : listed.length,+ });+ }),+ );+}++function renderSidebar() {+ return render(+ <SidebarProvider>+ <ChatSidebar />+ </SidebarProvider>,+ );+}++async function tick(ms: number) {+ await act(async () => {+ vi.advanceTimersByTime(ms);+ });+}++/** Lets in-flight requests resolve and React commit what they returned. */+async function settle() {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 50));+ });+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ useCopilotUIStore.setState({+ sessionToDelete: null,+ completedSessionIDs: new Set(),+ });+ listed = [+ { id: "s1", title: "First chat" },+ { id: "s2", title: "Second chat" },+ { id: "s3", title: "Third chat" },+ ];+ listRequests = [];+ blockRenders.mockClear();+});++afterEach(() => {+ vi.useRealTimers();+ server.resetHandlers();+});++describe("ChatSidebar — session rows", () => {+ it("re-renders no row when a refetch returns the same sessions", async () => {+ serveList();+ renderSidebar();+ await screen.findByText("Third chat");+ await settle();+ blockRenders.mockClear();+ const requestsBefore = listRequests.length;++ await tick(SESSION_LIST_REFETCH_INTERVAL_MS);+ await waitFor(() =>+ expect(listRequests.length).toBeGreaterThan(requestsBefore),+ );+ await settle();++ expect(blockRenders).not.toHaveBeenCalled();+ });++ it("re-renders only the pinned row when one session is pinned", async () => {+ serveList();+ server.use(+ http.patch("*/api/chat/sessions/:id/pinned", async ({ params }) => {+ // The backend lists pinned chats first.+ const pinned = listed.find((s) => s.id === params.id);+ if (pinned) {+ listed = [+ { ...pinned, is_pinned: true },+ ...listed.filter((s) => s.id !== params.id),+ ];+ }+ return HttpResponse.json({ status: "ok" });+ }),+ );+ renderSidebar();+ const row = (await screen.findByText("Third chat")).closest("div.group");+ if (!row) throw new Error("row not found");+ await settle();+ blockRenders.mockClear();++ fireEvent.pointerDown(+ within(row as HTMLElement).getByRole("button", { name: /more actions/i }),+ { button: 0 },+ );+ fireEvent.click(await screen.findByRole("menuitem", { name: "Pin chat" }));++ await waitFor(() =>+ expect(blockRenders).toHaveBeenCalledWith("Third chat"),+ );+ await settle();+ expect(blockRenders.mock.calls.map(([title]) => title)).toEqual([+ "Third chat",+ ]);+ });+});++describe("ChatSidebar — session rows while editing and as they age", () => {+ it("does not re-render sibling rows while a title is being edited", async () => {+ serveList();+ renderSidebar();+ const row = (await screen.findByText("Third chat")).closest("div.group");+ if (!row) throw new Error("row not found");++ fireEvent.pointerDown(+ within(row as HTMLElement).getByRole("button", { name: /more actions/i }),+ { button: 0 },+ );+ fireEvent.click(await screen.findByRole("menuitem", { name: /rename/i }));+ const input = await screen.findByLabelText("Rename chat");+ await settle();+ blockRenders.mockClear();++ fireEvent.change(input, { target: { value: "Renamed" } });+ await settle();++ expect(blockRenders).not.toHaveBeenCalled();+ });++ it("re-renders a row when its 'Today' label turns into 'Yesterday'", async () => {+ // The rows were updated at 09:00 UTC; one becomes a day old first.+ listed = [+ { id: "s1", title: "First chat", updated_at: "2026-01-05T09:00:00Z" },+ { id: "s2", title: "Second chat", updated_at: "2026-01-05T15:00:00Z" },+ ];+ vi.setSystemTime(new Date("2026-01-06T08:59:00Z"));+ serveList();+ renderSidebar();+ await screen.findByText("Second chat");+ expect(screen.getAllByText("Today")).toHaveLength(2);+ await settle();+ blockRenders.mockClear();++ await tick(2 * 60_000);+ await settle();++ expect(blockRenders.mock.calls.map(([title]) => title)).toEqual([+ "First chat",+ ]);+ expect(screen.getByText("Yesterday")).toBeDefined();+ expect(screen.getAllByText("Today")).toHaveLength(1);+ });+});++describe("ChatSidebar — shared row callbacks", () => {+ async function openActionsFor(title: string) {+ const row = (await screen.findByText(title)).closest("div.group");+ if (!row) throw new Error(`row not found for ${title}`);+ fireEvent.pointerDown(+ within(row as HTMLElement).getByRole("button", { name: /more actions/i }),+ { button: 0 },+ );+ }++ it("runs each row action on that row's own session", async () => {+ const renames: string[] = [];+ serveList();+ server.use(+ http.patch("*/api/chat/sessions/:id/title", ({ params }) => {+ renames.push(String(params.id));+ return HttpResponse.json({ status: "ok" });+ }),+ );+ exportChat.mockClear();+ renderSidebar();++ await openActionsFor("Third chat");+ fireEvent.click(+ await screen.findByRole("menuitem", { name: /export chat/i }),+ );+ await waitFor(() =>+ expect(exportChat).toHaveBeenCalledWith("s3", "Third chat"),+ );++ await openActionsFor("Second chat");+ fireEvent.click(+ await screen.findByRole("menuitem", { name: /share chat/i }),+ );+ expect(+ await screen.findByRole("dialog", { name: "Share s2" }),+ ).toBeDefined();++ await openActionsFor("First chat");+ fireEvent.click(await screen.findByRole("menuitem", { name: /rename/i }));+ const input = await screen.findByLabelText("Rename chat");+ fireEvent.change(input, { target: { value: "Never saved" } });+ fireEvent.keyDown(input, { key: "Escape" });+ fireEvent.blur(input);+ await settle();++ expect(screen.queryByLabelText("Rename chat")).toBeNull();+ expect(screen.getByText("First chat")).toBeDefined();+ expect(renames).toEqual([]);+ });+});++describe("ChatSidebar — 10-second refresh", () => {+ function seedPages(count: number) {+ listed = Array.from({ length: count }, (_, i) => ({+ id: `s${i}`,+ title: `Chat ${i}`,+ }));+ }++ async function loadOlderChats() {+ fireEvent.click(+ await screen.findByRole("button", { name: /load older chats/i }),+ );+ await screen.findByText("Chat 74");+ await settle();+ }++ it("requests only the first page once older pages are loaded", async () => {+ seedPages(75);+ serveList();+ renderSidebar();+ await loadOlderChats();+ listRequests = [];++ await tick(SESSION_LIST_REFETCH_INTERVAL_MS);+ await waitFor(() => expect(listRequests.length).toBeGreaterThan(0));+ await settle();++ expect(listRequests).toEqual(["0"]);+ });++ it("still shows a renamed chat on the first page after one interval", async () => {+ seedPages(75);+ serveList();+ renderSidebar();+ await loadOlderChats();+ listRequests = [];++ listed[3] = { ...listed[3], title: "Renamed on the server" };+ await tick(SESSION_LIST_REFETCH_INTERVAL_MS);++ expect(await screen.findByText("Renamed on the server")).toBeDefined();+ expect(listRequests).toEqual(["0"]);+ expect(screen.getByText("Chat 74")).toBeDefined();+ });++ it("refetches every loaded page when a new chat shifts the first page", async () => {+ seedPages(75);+ serveList();+ renderSidebar();+ await loadOlderChats();++ listed = [{ id: "new", title: "Brand new chat" }, ...listed];+ await tick(SESSION_LIST_REFETCH_INTERVAL_MS);++ expect(await screen.findByText("Brand new chat")).toBeDefined();+ // Chat 49 was pushed from the first page onto the second; it must not+ // fall into the gap between them.+ await waitFor(() => expect(screen.getByText("Chat 49")).toBeDefined());+ for (let i = 0; i < 75; i++) {+ expect(screen.getAllByText(`Chat ${i}`)).toHaveLength(1);+ }+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsxindex 84f6428e60..08ab0bdbb6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/ChatSessionRow/ChatSessionRow.tsx@@ -9,7 +9,7 @@ import {} from "@/components/molecules/DropdownMenu/DropdownMenu";import { cn } from "@/lib/utils";import { AnimatePresence, motion } from "framer-motion";-import type { MouseEvent, RefObject } from "react";+import { memo, type MouseEvent, type RefObject } from "react";import { ChatSessionBlock } from "../../../ChatSessionBlock/ChatSessionBlock";import {BookOpen01Icon,@@ -39,19 +39,37 @@ interface Props {isLearningEnabled: boolean;showProcessing: boolean;showCompleted: boolean;- onSelect: () => void;+ /** Whole days since the last update (see `sessionAgeDays`). It changes+ * exactly when the relative date label ("Today", "Yesterday", "N days ago")+ * does, so the memoised row re-renders then even if the session did not. */+ ageDays: number;+ /** The callbacks below are shared by every row and take the row's session,+ * so a parent re-render passes the same props and the row skips its own. */+ onSelect: (id: string, expertId: string | null) => void;onEditingTitleChange: (title: string) => void;onRenameCancel: () => void;- onRenameBlur: () => void;- onPin: (e: MouseEvent) => void;- onRename: (e: MouseEvent) => void;- onExport: (e: MouseEvent) => void;- onShare: (e: MouseEvent) => void;- onExcludeFromLearning: (e: MouseEvent) => void;- onDelete: (e: MouseEvent) => void;+ onRenameBlur: (id: string) => void;+ onPin: (e: MouseEvent, id: string, isPinned: boolean) => void;+ onRename: (+ e: MouseEvent,+ id: string,+ title: string | null | undefined,+ ) => void;+ onExport: (+ e: MouseEvent,+ id: string,+ title: string | null | undefined,+ ) => void;+ onShare: (e: MouseEvent, id: string) => void;+ onExcludeFromLearning: (e: MouseEvent, id: string) => void;+ onDelete: (+ e: MouseEvent,+ id: string,+ title: string | null | undefined,+ ) => void;}-export function ChatSessionRow({+export const ChatSessionRow = memo(function ChatSessionRow({session,isActive,isNextActive,@@ -102,13 +120,13 @@ export function ChatSessionRow({onRenameCancel();}}}- onBlur={onRenameBlur}+ onBlur={() => onRenameBlur(session.id)}className="w-full rounded 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"/></div>) : (<button- onClick={onSelect}+ onClick={() => onSelect(session.id, session.expert_id ?? null)}className={cn("w-full px-3 py-2.5 text-left",isExporting ? "pr-[68px]" : "pr-10",@@ -168,7 +186,9 @@ export function ChatSessionRow({</DropdownMenuTrigger><DropdownMenuContent align="end">{isPinningEnabled && (- <DropdownMenuItem onClick={onPin}>+ <DropdownMenuItem+ onClick={(e) => onPin(e, session.id, !!session.is_pinned)}+ >{session.is_pinned ? (<><Icon icon={PinOffIcon} className="mr-2 h-4 w-4" />@@ -182,12 +202,14 @@ export function ChatSessionRow({)}</DropdownMenuItem>)}- <DropdownMenuItem onClick={onRename}>+ <DropdownMenuItem+ onClick={(e) => onRename(e, session.id, session.title)}+ ><Icon icon={PencilIcon} className="mr-2 h-4 w-4" />Rename</DropdownMenuItem><DropdownMenuItem- onClick={onExport}+ onClick={(e) => onExport(e, session.id, session.title)}onSelect={(e) => {if (isExporting) e.preventDefault();}}@@ -203,18 +225,20 @@ export function ChatSessionRow({)}{isExporting ? "Exporting…" : "Export chat"}</DropdownMenuItem>- <DropdownMenuItem onClick={onShare}>+ <DropdownMenuItem onClick={(e) => onShare(e, session.id)}><Icon icon={Share03Icon} className="mr-2 h-4 w-4" />Share chat</DropdownMenuItem>{isLearningEnabled && (- <DropdownMenuItem onClick={onExcludeFromLearning}>+ <DropdownMenuItem+ onClick={(e) => onExcludeFromLearning(e, session.id)}+ ><Icon icon={BookOpen01Icon} className="mr-2 h-4 w-4" />Exclude from learning</DropdownMenuItem>)}<DropdownMenuItem- onClick={onDelete}+ onClick={(e) => onDelete(e, session.id, session.title)}disabled={isDeleting}className="text-red-600 focus:bg-red-50 focus:text-red-600">@@ -226,4 +250,4 @@ export function ChatSessionRow({)}</div>);-}+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/useSessionAgeClock.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/useSessionAgeClock.tsnew file mode 100644index 0000000000..67bcd88d54--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/useSessionAgeClock.ts@@ -0,0 +1,41 @@+import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";+import { useEffect, useState } from "react";++const DAY_MS = 24 * 60 * 60 * 1000;+// `ChatSessionBlock` labels a session "Today", "Yesterday" or "N days ago"+// from whole 24-hour periods since `updated_at`, and shows a date from 7 on.+const LAST_RELATIVE_DAY = 7;++/**+ * Whole days since `updatedAt`, capped where the label turns into a date. It+ * changes exactly when the row's relative date label does, so passing it to a+ * memoised row re-renders that row then and at no other time.+ */+export function sessionAgeDays(updatedAt: string | Date, now: number) {+ const days = Math.floor((now - new Date(updatedAt).getTime()) / DAY_MS);+ return Math.min(days, LAST_RELATIVE_DAY);+}++/**+ * A timestamp that moves on only when some session's age in days changes:+ * one timeout, set for the earliest such moment across the list.+ */+export function useSessionAgeClock(sessions: SessionSummaryResponse[]) {+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ const current = Date.now();+ let next = Infinity;+ for (const session of sessions) {+ const updated = new Date(session.updated_at).getTime();+ const days = Math.floor((current - updated) / DAY_MS);+ if (days >= LAST_RELATIVE_DAY) continue;+ next = Math.min(next, updated + (days + 1) * DAY_MS);+ }+ if (next === Infinity) return;+ const timeout = setTimeout(() => setNow(Date.now()), next - current + 1);+ return () => clearTimeout(timeout);+ }, [sessions, now]);++ return now;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/sessionListSharing.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/sessionListSharing.tsnew file mode 100644index 0000000000..e8f9b6d2ed--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/sessionListSharing.ts@@ -0,0 +1,76 @@+import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";+import { replaceEqualDeep } from "@tanstack/react-query";+import type { SessionListInfiniteData } from "./useSessionList";++/**+ * `structuralSharing` for the session list. The API client turns timestamps+ * into `Date`s, and TanStack's default sharing treats every `Date` as new, so+ * each refetch rebuilt every session object and every row redrew. This keeps+ * the cached object of each session whose fields are unchanged, matched by id+ * so a session that only moved (pinned, or bumped to the top) keeps its object+ * too, and returns the cached list itself when nothing changed at all.+ */+export function shareSessionListData(+ oldData: unknown,+ newData: unknown,+): unknown {+ const previous = oldData as SessionListInfiniteData | undefined;+ const next = newData as SessionListInfiniteData | undefined;+ if (!previous?.pages || !next?.pages) return newData;++ const cachedById = new Map<string, SessionSummaryResponse>();+ for (const page of previous.pages) {+ if (page.status !== 200) continue;+ for (const session of page.data.sessions) {+ cachedById.set(session.id, session);+ }+ }++ const pages = next.pages.map((page, index) => {+ if (page.status !== 200) return page;+ const sessions = page.data.sessions.map((session) => {+ const cached = cachedById.get(session.id);+ return cached && haveSameFields(cached, session) ? cached : session;+ });+ const cachedPage = previous.pages[index];+ // The response headers are never read, and a `Headers` object never+ // compares equal, so they alone must not make an unchanged page new.+ if (+ cachedPage?.status === 200 &&+ isSameList(cachedPage.data.sessions, sessions) &&+ haveSameFields(cachedPage.data, page.data, "sessions")+ ) {+ return cachedPage;+ }+ return { ...page, data: { ...page.data, sessions } };+ });+ const pageParams = replaceEqualDeep(previous.pageParams, next.pageParams);++ const unchanged =+ pageParams === previous.pageParams &&+ pages.length === previous.pages.length &&+ pages.every((page, index) => page === previous.pages[index]);+ return unchanged ? previous : { ...next, pages, pageParams };+}++function isSameList(a: unknown[], b: unknown[]) {+ return a.length === b.length && a.every((item, i) => item === b[i]);+}++function haveSameFields<T extends object>(a: T, b: T, skip?: keyof T) {+ const aKeys = Object.keys(a) as (keyof T)[];+ if (aKeys.length !== Object.keys(b).length) return false;+ return aKeys.every(+ (key) => key === skip || (key in b && isSameValue(a[key], b[key])),+ );+}++function isSameValue(a: unknown, b: unknown) {+ if (Object.is(a, b)) return true;+ if (a instanceof Date && b instanceof Date) {+ return a.getTime() === b.getTime();+ }+ // Any other object counts as changed: a needless row render, never a+ // stale one.+ return false;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.tsindex d9bef32d4c..c8f5b46181 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts@@ -2,17 +2,23 @@ import { getV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";import {type InfiniteData,+ type QueryClient,useInfiniteQuery,useMutationState,+ useQuery,+ useQueryClient,} from "@tanstack/react-query";+import { useMemo } from "react";+import { shareSessionListData } from "./sessionListSharing";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.+// TanStack Query v5 removed `refetchPage` so we can't scope it to page 0. So+// the infinite query polls only while it holds a single page; once older+// pages are loaded, `SESSION_LIST_FIRST_PAGE_QUERY_KEY` polls page 0 alone and+// patches it into the cache. Older pages refresh on focus, on the WebSocket+// invalidations in `useCopilotNotifications`, or when page 0's membership+// changes (which shifts every later offset, so they all have to be refetched).export const SESSION_LIST_REFETCH_INTERVAL_MS = 10_000;// Fresh, paginated-cache key. The orval-generated key targets the non-infinite@@ -20,6 +26,13 @@ export const SESSION_LIST_REFETCH_INTERVAL_MS = 10_000;// shape collisions and lets us hand a stable key to invalidation callsites.export const SESSION_LIST_QUERY_KEY = ["copilot", "session-list"] as const;+// Outside `SESSION_LIST_QUERY_KEY`'s prefix, so invalidating the list does not+// also re-run this poll.+const SESSION_LIST_FIRST_PAGE_QUERY_KEY = [+ "copilot",+ "session-list-first-page",+] as const;+// Chats with a delete in flight stay out of every list, whatever a refetch// returns before the server has removed them.export const SESSION_DELETE_MUTATION_KEY = [@@ -35,6 +48,7 @@ interface Args {}export function useSessionList({ enabled = true }: Args = {}) {+ const queryClient = useQueryClient();const query = useInfiniteQuery({queryKey: SESSION_LIST_QUERY_KEY,queryFn: ({ pageParam }) =>@@ -48,19 +62,56 @@ export function useSessionList({ enabled = true }: Args = {}) {const loaded = countLoadedSessions(allPages);return loaded < lastPage.data.total ? loaded : undefined;},- refetchInterval: SESSION_LIST_REFETCH_INTERVAL_MS,+ structuralSharing: shareSessionListData,+ refetchInterval: (listQuery) =>+ hasOlderPages(listQuery.state.data)+ ? false+ : SESSION_LIST_REFETCH_INTERVAL_MS,+ // With older pages loaded the poll only covers page 0, so a focus always+ // refreshes every page, however recently page 0 was patched.+ refetchOnWindowFocus: (listQuery) =>+ hasOlderPages(listQuery.state.data) ? "always" : true,enabled,});+ const isPollingFirstPage = enabled && hasOlderPages(query.data);+ useQuery({+ // Keyed on whether it polls, so the entry is created (and seeded from the+ // list below) at the moment an older page lands, not at first mount.+ queryKey: [...SESSION_LIST_FIRST_PAGE_QUERY_KEY, isPollingFirstPage],+ queryFn: ({ client }) => refreshFirstPage(client),+ enabled: isPollingFirstPage,+ refetchInterval: SESSION_LIST_REFETCH_INTERVAL_MS,+ // Seeded from the list itself, so loading an older page does not also+ // re-request page 0 straight away; the first poll comes one interval on.+ initialData: () => readFirstPage(queryClient),+ initialDataUpdatedAt: () =>+ queryClient.getQueryState(SESSION_LIST_QUERY_KEY)?.dataUpdatedAt,+ staleTime: SESSION_LIST_REFETCH_INTERVAL_MS,+ // The list's own mount and focus refetches already cover every page, so+ // this query only ever fetches on its interval.+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ // Nothing reads this cache entry; the poll only patches the list.+ notifyOnChangeProps: [],+ });const deletingIds = useMutationState({filters: { mutationKey: SESSION_DELETE_MUTATION_KEY, status: "pending" },select: (mutation) =>(mutation.state.variables as { sessionId: string }).sessionId,});+ // `query.data` and `deletingIds` keep their identity while nothing in them+ // changes (structural sharing), so a refetch that returns the same sessions+ // hands the lists the same array and every memoised row skips its render.+ const sessions = useMemo(+ () =>+ flattenSessions(query.data).filter(+ (session) => !deletingIds.includes(session.id),+ ),+ [query.data, deletingIds],+ );return {- sessions: flattenSessions(query.data).filter(- (session) => !deletingIds.includes(session.id),- ),+ sessions,isLoading: query.isLoading,hasMore: !!query.hasNextPage,isLoadingMore: query.isFetchingNextPage,@@ -75,6 +126,27 @@ export function flattenSessions(data: SessionListInfiniteData | undefined) {);}+/**+ * Puts a freshly fetched page 0 in place of the cached one, keeping the older+ * pages. Returns `null` when page 0 no longer holds the same sessions in the+ * same order (or `total` moved): every later offset has shifted then, so the+ * caller must refetch all loaded pages instead.+ */+export function replaceFirstPage(+ data: SessionListInfiniteData | undefined,+ firstPage: SessionListPage,+): SessionListInfiniteData | null {+ const cached = data?.pages[0];+ if (!data || !cached) return null;+ if (cached.status !== 200 || firstPage.status !== 200) return null;+ const before = cached.data.sessions;+ const after = firstPage.data.sessions;+ if (cached.data.total !== firstPage.data.total) return null;+ if (before.length !== after.length) return null;+ if (before.some((session, i) => session.id !== after[i].id)) return null;+ return { ...data, pages: [firstPage, ...data.pages.slice(1)] };+}+export function removeSessionFromList(data: SessionListInfiniteData | undefined,sessionId: string,@@ -166,6 +238,56 @@ export function groupSessionsForSidebar({};}+function hasOlderPages(data: SessionListInfiniteData | undefined) {+ return (data?.pages.length ?? 0) > 1;+}++function readFirstPage(queryClient: QueryClient) {+ return queryClient.getQueryData<SessionListInfiniteData>(+ SESSION_LIST_QUERY_KEY,+ )?.pages[0];+}++async function refreshFirstPage(queryClient: QueryClient) {+ const firstPageBefore = readFirstPage(queryClient);+ const firstPage = await getV2ListSessions({+ limit: SESSION_LIST_PAGE_SIZE,+ offset: 0,+ });+ // A list fetch still in flight (say "Load older chats") started from the+ // old pages and would put the old page 0 back when it lands, so patch after+ // it instead.+ await settleListFetch(queryClient);+ // Page 0 changed while this poll was out (a refetch or an edit of the+ // list), so it is at least as new as what this poll brought back. Sharing+ // keeps page 0's object while its content is unchanged, so a fetch of an+ // older page alone does not count.+ if (readFirstPage(queryClient) !== firstPageBefore) return firstPage;+ const next = replaceFirstPage(+ queryClient.getQueryData<SessionListInfiniteData>(SESSION_LIST_QUERY_KEY),+ firstPage,+ );+ if (next) {+ // Keeps the list's own timestamp: the older pages were not fetched, so+ // they must not start counting as fresh.+ queryClient.setQueryData(SESSION_LIST_QUERY_KEY, next, {+ updatedAt: queryClient.getQueryState(SESSION_LIST_QUERY_KEY)+ ?.dataUpdatedAt,+ });+ } else {+ await queryClient.invalidateQueries({ queryKey: SESSION_LIST_QUERY_KEY });+ }+ return firstPage;+}++async function settleListFetch(queryClient: QueryClient) {+ const listQuery = queryClient+ .getQueryCache()+ .find({ queryKey: SESSION_LIST_QUERY_KEY, exact: true });+ if (listQuery?.state.fetchStatus !== "fetching") return;+ await listQuery.promise?.catch(() => undefined);+}+function countLoadedSessions(pages: SessionListPage[]) {return pages.reduce((acc, page) => acc + (page.status === 200 ? page.data.sessions.length : 0),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.tsxindex 64e0886b10..ebb4d1c0bf 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx@@ -7,6 +7,7 @@ import { useExpertMap } from "@/app/(platform)/copilot/useExpertMap";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { SidebarMenu } from "@/components/ui/sidebar";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useLocalDay } from "@/hooks/useLocalDay";import { Icon } from "@/components/atoms/Icon/Icon";import { PinIcon } from "@hugeicons/core-free-icons";import { ExpertChatGroup } from "./components/ExpertChatGroup/ExpertChatGroup";@@ -18,6 +19,9 @@ export function RecentChats() {const chatPinningEnabled = useGetFlag(Flag.CHAT_PINNING);const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);const { expertsById, activeExpertIds } = useExpertMap();+ // Re-groups "Today" / "Yesterday" at midnight: list polls that return the+ // same sessions no longer re-render this component.+ useLocalDay();const {sessions,isLoading,@@ -58,13 +62,14 @@ export function RecentChats() {}function renderItem(session: (typeof sessions)[number]) {+ const isEditing = editingSessionId === session.id;return (<RecentChatItemkey={session.id}session={session}isActive={session.id === activeSessionId}- isEditing={editingSessionId === session.id}- editingTitle={editingTitle}+ isEditing={isEditing}+ editingTitle={isEditing ? editingTitle : ""}onEditingTitleChange={setEditingTitle}onSubmitRename={submitRename}onCancelRename={cancelRename}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/row-renders.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/row-renders.test.tsxnew file mode 100644index 0000000000..557b84a445--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/row-renders.test.tsx@@ -0,0 +1,167 @@+import { SESSION_LIST_REFETCH_INTERVAL_MS } from "@/app/(platform)/copilot/useSessionList";+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { SidebarProvider } from "@/components/ui/sidebar";+import { server } from "@/mocks/mock-server";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { http, HttpResponse } from "msw";+import type { ComponentProps } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { RecentChats } from "../RecentChats";++const itemRenders = vi.fn();++// Each chat row renders one `SidebarMenuItem`, so counting those counts the+// rows that re-rendered.+vi.mock("@/components/ui/sidebar", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@/components/ui/sidebar")>();+ function CountedSidebarMenuItem(+ props: ComponentProps<typeof actual.SidebarMenuItem>,+ ) {+ itemRenders();+ return <actual.SidebarMenuItem {...props} />;+ }+ return { ...actual, SidebarMenuItem: CountedSidebarMenuItem };+});++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-pinning",+ };+});++interface SessionSeed {+ id: string;+ title: string;+ is_pinned?: boolean;+}++let listed: SessionSeed[] = [];+let listRequests = 0;++function toSummary(seed: SessionSeed) {+ return {+ id: seed.id,+ title: seed.title,+ is_processing: false,+ is_pinned: seed.is_pinned ?? false,+ // `Z`-suffixed, so the API client turns them into `Date`s as in the app.+ created_at: "2026-06-30T10:00:00Z",+ updated_at: "2026-06-30T10:00:00Z",+ };+}++function renderRecentChats() {+ return render(+ <SidebarProvider>+ <RecentChats />+ </SidebarProvider>,+ );+}++async function settle() {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 50));+ });+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ vi.setSystemTime(new Date("2026-06-30T12:00:00Z"));+ useCopilotUIStore.setState({ sessionToDelete: null });+ listed = [+ { id: "s1", title: "First chat" },+ { id: "s2", title: "Second chat" },+ { id: "s3", title: "Third chat" },+ ];+ listRequests = 0;+ itemRenders.mockClear();+ server.use(+ http.get("*/api/chat/sessions", () => {+ listRequests += 1;+ return HttpResponse.json({+ sessions: listed.map(toSummary),+ total: listed.length,+ });+ }),+ http.patch("*/api/chat/sessions/:id/pinned", ({ params }) => {+ const pinned = listed.find((s) => s.id === params.id);+ if (pinned) {+ listed = [+ { ...pinned, is_pinned: true },+ ...listed.filter((s) => s.id !== params.id),+ ];+ }+ return HttpResponse.json({ status: "ok" });+ }),+ );+});++afterEach(() => {+ vi.useRealTimers();+ server.resetHandlers();+});++describe("RecentChats — chat rows", () => {+ it("re-renders no row when a refetch returns the same sessions", async () => {+ renderRecentChats();+ await screen.findByText("Third chat");+ await settle();+ itemRenders.mockClear();+ const requestsBefore = listRequests;++ await act(async () => {+ vi.advanceTimersByTime(SESSION_LIST_REFETCH_INTERVAL_MS);+ });+ await waitFor(() => expect(listRequests).toBeGreaterThan(requestsBefore));+ await settle();++ expect(itemRenders).not.toHaveBeenCalled();+ });++ it("re-renders only the pinned row when one chat is pinned", async () => {+ renderRecentChats();+ await screen.findByText("Third chat");+ await settle();+ itemRenders.mockClear();++ const actions = screen.getAllByRole("button", { name: /chat actions/i });+ fireEvent.pointerDown(actions[2], { button: 0 });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Pin chat" }));++ expect(await screen.findByText("Pinned")).toBeDefined();+ await settle();+ expect(itemRenders).toHaveBeenCalledTimes(1);+ });++ it("re-renders only the edited row while typing a rename", async () => {+ renderRecentChats();+ await screen.findByText("Third chat");+ await settle();++ const actions = screen.getAllByRole("button", { name: /chat actions/i });+ fireEvent.pointerDown(actions[2], { button: 0 });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Rename" }));+ await screen.findByLabelText("Rename chat");+ await settle();+ itemRenders.mockClear();++ fireEvent.change(screen.getByLabelText("Rename chat"), {+ target: { value: "Renamed chat" },+ });+ await settle();++ expect(itemRenders).toHaveBeenCalledTimes(1);+ });+});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.tsxindex cbf06a3bfc..73ebfef181 100644--- 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.tsx@@ -15,7 +15,7 @@ import {SidebarMenuItem,} from "@/components/ui/sidebar";import Link, { useLinkStatus } from "next/link";-import { useRef } from "react";+import { memo, useRef } from "react";import {Delete02Icon,Download04Icon,@@ -71,7 +71,9 @@ function ChatLinkLoader() {);}-export function RecentChatItem({+// Memoised: the list hands every row the same shared callbacks (taking the+// session id), so a list refetch only re-renders rows whose session changed.+export const RecentChatItem = memo(function RecentChatItem({session,isActive,isEditing,@@ -215,4 +217,4 @@ export function RecentChatItem({</DropdownMenu></SidebarMenuItem>);-}+});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.tsindex f365cc4ac1..691f8e8773 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/useRecentChats.ts+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/useRecentChats.ts@@ -10,6 +10,7 @@ import {} from "@/app/(platform)/copilot/useSessionList";import { useSessionDeletion } from "@/app/(platform)/copilot/useSessionDeletion";import { toast } from "@/components/molecules/Toast/use-toast";+import { useStableCallback } from "@/hooks/useStableCallback";import { useQueryClient } from "@tanstack/react-query";import { usePathname, useSearchParams } from "next/navigation";import { useState } from "react";@@ -71,25 +72,35 @@ export function useRecentChats() {},});- function togglePin(id: string, isPinned: boolean) {+ // Every handler handed to the rows keeps one identity across renders, so the+ // memoised `RecentChatItem`s only re-render when their own props change.+ const togglePin = useStableCallback((id: string, isPinned: boolean) => {setSessionPinned({ sessionId: id, data: { is_pinned: !isPinned } });- }+ });- function startRename(id: string, title: string | null | undefined) {- setEditingSessionId(id);- setEditingTitle(title || "");- }+ const startRename = useStableCallback(+ (id: string, title: string | null | undefined) => {+ setEditingSessionId(id);+ setEditingTitle(title || "");+ },+ );- function submitRename(id: string) {+ const submitRename = useStableCallback((id: string) => {const trimmed = editingTitle.trim();if (trimmed) {renameSession({ sessionId: id, data: { title: trimmed } });} else {setEditingSessionId(null);}- }+ });++ const cancelRename = useStableCallback(() => setEditingSessionId(null));++ const stableRequestDelete = useStableCallback(requestDelete);- async function exportChat(id: string, title: string | null | undefined) {+ const exportChat = useStableCallback(handleExport);++ async function handleExport(id: string, title: string | null | undefined) {if (exportingIds.has(id)) return;setExportingIds((prev) => new Set(prev).add(id));try {@@ -126,14 +137,14 @@ export function useRecentChats() {setEditingTitle,startRename,submitRename,- cancelRename: () => setEditingSessionId(null),+ cancelRename,exportingIds,exportChat,sharingSessionId,setSharingSessionId,sessionToDelete,isDeleting,- requestDelete,+ requestDelete: stableRequestDelete,confirmDelete,cancelDelete,};diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useLocalDay.test.tsx b/autogpt_platform/frontend/src/hooks/__tests__/useLocalDay.test.tsxnew file mode 100644index 0000000000..6bb2fd24f5--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/__tests__/useLocalDay.test.tsx@@ -0,0 +1,37 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useLocalDay } from "../useLocalDay";++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 9, 19, 23, 58, 30));+});++afterEach(() => {+ vi.useRealTimers();+});++describe("useLocalDay", () => {+ it("re-renders once when the local day changes, and not before", () => {+ let renders = 0;+ const { result } = renderHook(() => {+ renders += 1;+ return useLocalDay();+ });+ const today = result.current;+ const rendersBefore = renders;++ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(result.current).toBe(today);+ expect(renders).toBe(rendersBefore);++ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(result.current).not.toBe(today);+ expect(result.current).toBe(new Date(2026, 9, 20).toDateString());+ expect(renders).toBe(rendersBefore + 1);+ });+});diff --git a/autogpt_platform/frontend/src/hooks/useLocalDay.ts b/autogpt_platform/frontend/src/hooks/useLocalDay.tsnew file mode 100644index 0000000000..207bf41c17--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useLocalDay.ts@@ -0,0 +1,45 @@+import { useSyncExternalStore } from "react";++const CHECK_INTERVAL_MS = 60_000;++const listeners = new Set<() => void>();+let timer: ReturnType<typeof setInterval> | null = null;+let current = localDay();++function localDay() {+ return new Date().toDateString();+}++function check() {+ const next = localDay();+ if (next === current) return;+ current = next;+ listeners.forEach((listener) => listener());+}++function subscribe(listener: () => void) {+ listeners.add(listener);+ if (timer === null) {+ current = localDay();+ timer = setInterval(check, CHECK_INTERVAL_MS);+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size > 0 || timer === null) return;+ clearInterval(timer);+ timer = null;+ };+}++function getSnapshot() {+ return timer === null ? localDay() : current;+}++/**+ * The local calendar day, e.g. "Tue Oct 20 2026". One shared timer checks it+ * once a minute, and callers re-render only when the day changes, so relative+ * date labels ("Today", "Yesterday") in memoised lists move on at midnight.+ */+export function useLocalDay() {+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+}