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.
fix(platform): stop chat delete waiting on best-effort cleanup (SECRT-2954) (#15579)
Abhimanyu Yadav1a3d10d08a18
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 61734cce39..1a9afc8f3d 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -1073,17 +1073,15 @@ async def delete_session(detail=f"Session {session_id} not found or access denied",)- # Best-effort cleanup of the E2B sandbox (if any).+ # Best-effort cleanup of the E2B sandbox (if any), after the response.# sandbox_id is in Redis; kill_sandbox() fetches it from there.e2b_cfg = ChatConfig()if e2b_cfg.e2b_active:assert e2b_cfg.e2b_api_key # guaranteed by e2b_active check- try:- await kill_sandbox(session_id, e2b_cfg.e2b_api_key)- except Exception:- logger.warning(- "[E2B] Failed to kill sandbox for session %s", session_id[:12]- )+ spawn_background_task(+ kill_sandbox(session_id, e2b_cfg.e2b_api_key),+ name=f"e2b-session-kill-{session_id[:12]}",+ )return Response(status_code=204)diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 25ca52b8d4..5493629301 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -3566,9 +3566,63 @@ def test_delete_session_not_found(mocker: pytest_mock.MockerFixture) -> None:return_value=False,)+ spawn = mocker.patch.object(chat_routes, "spawn_background_task")+response = client.delete("/sessions/sess-missing")assert response.status_code == 404+ spawn.assert_not_called()+++def test_delete_session_without_e2b_spawns_no_cleanup(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """With E2B inactive the delete starts no sandbox-kill task."""+ mocker.patch(+ "backend.api.features.chat.routes.delete_chat_session",+ new_callable=AsyncMock,+ return_value=True,+ )+ mocker.patch.object(+ chat_routes,+ "ChatConfig",+ return_value=SimpleNamespace(e2b_active=False, e2b_api_key=None),+ )+ kill = mocker.patch.object(chat_routes, "kill_sandbox", new_callable=AsyncMock)+ spawn = mocker.patch.object(chat_routes, "spawn_background_task")++ response = client.delete("/sessions/sess-1")++ assert response.status_code == 204+ kill.assert_not_called()+ spawn.assert_not_called()+++def test_delete_session_kills_sandbox_in_background(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """The E2B sandbox kill is handed to a background task, not awaited inline."""+ mocker.patch(+ "backend.api.features.chat.routes.delete_chat_session",+ new_callable=AsyncMock,+ return_value=True,+ )+ mocker.patch.object(+ chat_routes,+ "ChatConfig",+ return_value=SimpleNamespace(e2b_active=True, e2b_api_key="test-e2b-key"),+ )+ kill = mocker.patch.object(chat_routes, "kill_sandbox", new_callable=AsyncMock)+ spawn = mocker.patch.object(chat_routes, "spawn_background_task")++ response = client.delete("/sessions/sess-1")++ assert response.status_code == 204+ kill.assert_called_once_with("sess-1", "test-e2b-key")+ kill.assert_not_awaited()+ spawn.assert_called_once()+ assert spawn.call_args.kwargs["name"] == "e2b-session-kill-sess-1"+ spawn.call_args.args[0].close()# ─── cancel_session_task ──────────────────────────────────────────────diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex a792e99b9d..8774d25b00 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -28,6 +28,7 @@ from backend.data.db_accessors import chat_db, experts_db, library_dbfrom backend.data.graph import GraphSettingsfrom backend.data.redis_client import get_redis_asyncfrom backend.util import json+from backend.util.background import spawn_background_taskfrom backend.util.exceptions import (DatabaseError,ExpertNotFoundError,@@ -1650,29 +1651,25 @@ async def delete_chat_session(except Exception as e:logger.warning(f"Failed to delete session {session_id} from cache: {e}")- # Best-effort embedding cleanup so deleted sessions stop appearing in- # /search/global hits. Only attempt when we have a user_id since the- # embedding row is user-scoped; without it the user-filter would miss- # and the orphan row (if any) gets cleaned up by the periodic embedder.- if user_id:- try:- from backend.copilot.chat_session_embeddings import (- delete_chat_session_embedding,- )-- await delete_chat_session_embedding(session_id, user_id)- except Exception as e:- logger.warning(f"Failed to delete session embedding for {session_id}: {e}")-- # Shut down any local browser daemon for this session (best-effort).- # Inline import required: all tool modules import ChatSession from this+ # Inline imports required: all tool modules import ChatSession from this# module, so any top-level import from tools.* would create a cycle.- try:- from .tools.agent_browser import close_browser_session+ from backend.copilot.chat_session_embeddings import delete_chat_session_embedding- await close_browser_session(session_id, user_id=user_id)- except Exception as e:- logger.debug(f"Browser cleanup for session {session_id}: {e}")+ from .tools.agent_browser import close_browser_session++ # The cleanups below are best-effort and log their own failures, so they+ # run after the caller gets its answer instead of holding it up.+ # The embedding row is user-scoped; without a user_id the filter would+ # miss and the periodic embedder sweeps the orphan row instead.+ if user_id:+ spawn_background_task(+ delete_chat_session_embedding(session_id, user_id),+ name=f"chat-embedding-delete-{session_id[:12]}",+ )+ spawn_background_task(+ close_browser_session(session_id, user_id=user_id),+ name=f"browser-close-{session_id[:12]}",+ )return Truediff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.pyindex 80874f1443..7d1807139b 100644--- a/autogpt_platform/backend/backend/copilot/model_test.py+++ b/autogpt_platform/backend/backend/copilot/model_test.py@@ -1,3 +1,4 @@+import asynciofrom contextlib import asynccontextmanagerfrom typing import cast@@ -15,6 +16,7 @@ from openai.types.chat.chat_completion_message_tool_call_param import (from prisma.models import Expertfrom pytest_mock import MockerFixture+from backend.copilot import model as chat_modelfrom backend.copilot.constants import COPILOT_SYSTEM_PREFIXfrom backend.copilot.continuation import KEEP_GOING_NOTEfrom backend.data.redis_client import get_redis_async@@ -27,6 +29,7 @@ from .model import (_save_session_to_db,append_and_save_message,create_chat_session,+ delete_chat_session,get_chat_session,get_or_create_builder_session,invalidate_session_cache,@@ -2265,3 +2268,76 @@ async def test_save_session_to_db_stamp_backfill_failure_keeps_flag()assert flushed.stamps_pending_save is True+++def _mock_delete_dependencies(mocker: MockerFixture, *, deleted: bool):+ db = mocker.MagicMock()+ db.delete_chat_session = mocker.AsyncMock(return_value=deleted)+ mocker.patch("backend.copilot.model.chat_db", return_value=db)+ redis = mocker.MagicMock()+ redis.delete = mocker.AsyncMock()+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new=mocker.AsyncMock(return_value=redis),+ )+ release = asyncio.Event()++ async def wait_for_release(*_args, **_kwargs):+ await release.wait()++ close_browser = mocker.patch(+ "backend.copilot.tools.agent_browser.close_browser_session",+ new=mocker.AsyncMock(side_effect=wait_for_release),+ )+ delete_embedding = mocker.patch(+ "backend.copilot.chat_session_embeddings.delete_chat_session_embedding",+ new=mocker.AsyncMock(side_effect=wait_for_release),+ )+ return redis, release, close_browser, delete_embedding+++async def test_delete_chat_session_returns_before_cleanup_finishes(+ mocker: MockerFixture,+) -> None:+ redis, release, close_browser, delete_embedding = _mock_delete_dependencies(+ mocker, deleted=True+ )+ spawn = mocker.spy(chat_model, "spawn_background_task")+ redis_started = asyncio.Event()+ redis_release = asyncio.Event()++ async def wait_for_redis_delete(*_args, **_kwargs):+ redis_started.set()+ await redis_release.wait()++ redis.delete.side_effect = wait_for_redis_delete++ delete_task = asyncio.create_task(delete_chat_session("sess-1", "user-1"))+ await asyncio.wait_for(redis_started.wait(), 1)+ assert not delete_task.done()+ redis_release.set()+ deleted = await asyncio.wait_for(delete_task, 1)++ assert deleted is True+ redis.delete.assert_awaited_once()+ release.set()+ await asyncio.wait_for(asyncio.gather(*spawn.spy_return_list), 1)+ delete_embedding.assert_awaited_once_with("sess-1", "user-1")+ close_browser.assert_awaited_once_with("sess-1", user_id="user-1")+++async def test_delete_chat_session_not_found_runs_no_cleanup(+ mocker: MockerFixture,+) -> None:+ redis, _release, close_browser, delete_embedding = _mock_delete_dependencies(+ mocker, deleted=False+ )++ deleted = await delete_chat_session("sess-missing", "user-1")++ assert deleted is False+ redis.delete.assert_not_called()+ close_browser.assert_not_called()+ delete_embedding.assert_not_called()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 92bf9a197d..3ec7c372f4 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@@ -1,6 +1,5 @@import {getDeleteV2DeleteSessionMockHandler,- getDeleteV2DeleteSessionMockHandler422,getGetV2ListSessionsMockHandler200,} from "@/app/api/__generated__/endpoints/chat/chat.msw";import { server } from "@/mocks/mock-server";@@ -12,10 +11,14 @@ import {} from "@/tests/integrations/test-utils";import { SidebarProvider } from "@/components/ui/sidebar";import { http, HttpResponse } from "msw";+import { parseAsString, useQueryState } from "nuqs";+import { withNuqsTestingAdapter } from "nuqs/adapters/testing";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useGlobalSearchStore } from "@/app/(platform)/components/GlobalSearchModal/useGlobalSearchStore";import { useCopilotUIStore } from "../../../store";+import { useChatSession } from "../../../useChatSession";+import { useSendMessage } from "../../../useSendMessage";import { ChatSidebar } from "../ChatSidebar";const toastMock = vi.fn();@@ -137,43 +140,268 @@ describe("ChatSidebar — delete flow", () => {expect(useCopilotUIStore.getState().sessionToDelete).toBeNull();});- it("closes the dialog after a successful delete", async () => {- server.use(getDeleteV2DeleteSessionMockHandler());+ it("removes the chat from the list as soon as Delete is confirmed", async () => {+ let deleted = false;+ let releaseDelete = () => {};+ const deleteHeld = new Promise<void>((resolve) => {+ releaseDelete = resolve;+ });+ server.use(+ getGetV2ListSessionsMockHandler200(() => {+ const remaining = deleted+ ? sessions.filter((session) => session.id !== "s2")+ : sessions;+ return { sessions: remaining, total: remaining.length };+ }),+ getDeleteV2DeleteSessionMockHandler(async () => {+ await deleteHeld;+ deleted = true;+ }),+ );renderSidebar();await openDeleteDialogFor("Other chat");- expect(- await screen.findByRole("heading", { name: /delete chat/i }),- ).toBeDefined();const confirmButton = await screen.findByRole("button", {name: /^delete$/i,});fireEvent.click(confirmButton);await vi.waitFor(() => {- expect(useCopilotUIStore.getState().sessionToDelete).toBeNull();+ expect(screen.queryByText("Other chat")).toBeNull();});+ expect(screen.queryByRole("heading", { name: /delete chat/i })).toBeNull();+ expect(useCopilotUIStore.getState().sessionToDelete).toBeNull();+ expect(screen.getByText("Active chat")).toBeDefined();++ releaseDelete();+await vi.waitFor(() => {- expect(- screen.queryByRole("heading", { name: /delete chat/i }),- ).toBeNull();+ expect(deleted).toBe(true);});+ expect(screen.queryByText("Other chat")).toBeNull();expect(toastMock).not.toHaveBeenCalled();});- it("toasts on delete failure and clears the staged session", async () => {- server.use(getDeleteV2DeleteSessionMockHandler422());+ it("keeps a chat out of the list while its delete is pending, even after the list refetches", async () => {+ let activeTitle = "Active chat";+ let releaseDelete = () => {};+ const deleteHeld = new Promise<void>((resolve) => {+ releaseDelete = resolve;+ });+ server.use(+ getGetV2ListSessionsMockHandler200(() => ({+ sessions: sessions.map((session) =>+ session.id === "s1" ? { ...session, title: activeTitle } : session,+ ),+ total: sessions.length,+ })),+ getDeleteV2DeleteSessionMockHandler(async () => {+ await deleteHeld;+ }),+ );renderSidebar();+ await openDeleteDialogFor("Other chat");+ fireEvent.click(await screen.findByRole("button", { name: /^delete$/i }));+ await vi.waitFor(() => {+ expect(screen.queryByText("Other chat")).toBeNull();+ });++ activeTitle = "Active chat, refetched";+ fireEvent.click(screen.getByText("Active chat"));++ expect(await screen.findByText("Active chat, refetched")).toBeDefined();+ expect(screen.queryByText("Other chat")).toBeNull();++ releaseDelete();+ });++ it("leaves the open chat as soon as its delete is confirmed, so nothing more is sent to it", async () => {+ let releaseDelete = () => {};+ const deleteHeld = new Promise<void>((resolve) => {+ releaseDelete = resolve;+ });+ let deleted = false;+ server.use(+ getDeleteV2DeleteSessionMockHandler(async () => {+ await deleteHeld;+ deleted = true;+ }),+ );+ const sent: (string | null)[] = [];+ const createSession = vi.fn();+ const ActiveChatWrapper = withNuqsTestingAdapter({+ searchParams: "?sessionId=s1",+ hasMemory: true,+ });+ function ActiveChatComposer() {+ const [sessionId] = useQueryState("sessionId", parseAsString);+ const { onSend } = useSendMessage({+ sessionId,+ createSession,+ isUserStoppingRef: { current: false },+ sendMessage: async () => {+ sent.push(sessionId);+ },+ });+ return (+ <>+ <span data-testid="open-session">{sessionId ?? "none"}</span>+ <button onClick={() => onSend("One more thing")}>Send</button>+ </>+ );+ }+ render(+ <ActiveChatWrapper>+ <SidebarProvider>+ <ChatSidebar />+ </SidebarProvider>+ <ActiveChatComposer />+ </ActiveChatWrapper>,+ );+ expect(screen.getByTestId("open-session").textContent).toBe("s1");+await openDeleteDialogFor("Active chat");- const confirmButton = await screen.findByRole("button", {- name: /^delete$/i,+ fireEvent.click(await screen.findByRole("button", { name: /^delete$/i }));++ await vi.waitFor(() => {+ expect(screen.getByTestId("open-session").textContent).toBe("none");});- fireEvent.click(confirmButton);+ expect(deleted).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ await vi.waitFor(() => expect(createSession).toHaveBeenCalled());+ expect(sent).not.toContain("s1");++ releaseDelete();+ await vi.waitFor(() => expect(deleted).toBe(true));+ });++ it.each([+ ["while the delete is pending", "pending"],+ ["after the delete has returned", "deleted"],+ ])(+ "does not reopen a deleted expert chat when the expert's latest-thread lookup answers %s",+ async (_label, answerExpertLookup) => {+ const expertId = "expert-maria";+ const expertChat = { ...sessions[0], expert_id: expertId };+ let releaseDelete = () => {};+ const deleteHeld = new Promise<void>((resolve) => {+ releaseDelete = resolve;+ });+ let releaseExpertLookup = () => {};+ const expertLookupHeld = new Promise<void>((resolve) => {+ releaseExpertLookup = resolve;+ });+ let deleted = false;+ server.use(+ getGetV2ListSessionsMockHandler200(async ({ request }) => {+ if (new URL(request.url).searchParams.has("expert_id")) {+ if (answerExpertLookup === "deleted") await expertLookupHeld;+ return { sessions: [expertChat], total: 1 };+ }+ return deleted+ ? { sessions: [sessions[1]], total: 1 }+ : { sessions: [expertChat, sessions[1]], total: 2 };+ }),+ getDeleteV2DeleteSessionMockHandler(async () => {+ await deleteHeld;+ deleted = true;+ }),+ );+ useCopilotUIStore.setState({ adoptedExpertThreads: new Set<string>() });+ const sent: (string | null)[] = [];+ const createSession = vi.fn();+ const ExpertChatWrapper = withNuqsTestingAdapter({+ searchParams: `?sessionId=s1&expertId=${expertId}`,+ hasMemory: true,+ });+ function ExpertChat() {+ const [expertIdParam] = useQueryState("expertId", parseAsString);+ const { sessionId } = useChatSession({ expertId: expertIdParam });+ const { onSend } = useSendMessage({+ sessionId,+ createSession,+ isUserStoppingRef: { current: false },+ sendMessage: async () => {+ sent.push(sessionId);+ },+ });+ return (+ <>+ <span data-testid="open-session">{sessionId ?? "none"}</span>+ <button onClick={() => onSend("New task")}>Send</button>+ </>+ );+ }+ function KeyedChatHost() {+ const [sessionId] = useQueryState("sessionId", parseAsString);+ return <ExpertChat key={sessionId ?? "new"} />;+ }+ render(+ <ExpertChatWrapper>+ <SidebarProvider>+ <ChatSidebar />+ </SidebarProvider>+ <KeyedChatHost />+ </ExpertChatWrapper>,+ );++ await openDeleteDialogFor("Active chat");+ fireEvent.click(await screen.findByRole("button", { name: /^delete$/i }));+ await vi.waitFor(() => {+ expect(screen.getByTestId("open-session").textContent).toBe("none");+ });++ if (answerExpertLookup === "pending") {+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(deleted).toBe(false);+ expect(screen.getByTestId("open-session").textContent).toBe("none");+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ await vi.waitFor(() => expect(createSession).toHaveBeenCalled());+ }++ releaseDelete();+ await vi.waitFor(() => expect(deleted).toBe(true));+ releaseExpertLookup();+ await new Promise((resolve) => setTimeout(resolve, 200));++ expect(screen.getByTestId("open-session").textContent).toBe("none");+ expect(screen.queryByText("Active chat")).toBeNull();+ expect(sent).not.toContain("s1");+ },+ );++ it("puts the chat back and toasts when the delete fails, without waiting for a refetch", async () => {+ let holdListRequests = false;+ let rejectDelete = () => {};+ const deleteHeld = new Promise<void>((resolve) => {+ rejectDelete = resolve;+ });+ server.use(+ getGetV2ListSessionsMockHandler200(async () => {+ if (holdListRequests) await new Promise(() => {});+ return { sessions, total: sessions.length };+ }),+ http.delete("/api/proxy/api/chat/sessions/:sessionId", async () => {+ await deleteHeld;+ return HttpResponse.json({ detail: "boom" }, { status: 500 });+ }),+ );+ renderSidebar();++ await openDeleteDialogFor("Other chat");+ holdListRequests = true;+ fireEvent.click(await screen.findByRole("button", { name: /^delete$/i }));await vi.waitFor(() => {- expect(toastMock).toHaveBeenCalledTimes(1);+ expect(screen.queryByText("Other chat")).toBeNull();});+ expect(screen.queryByRole("heading", { name: /delete chat/i })).toBeNull();++ rejectDelete();++ expect(await screen.findByText("Other chat")).toBeDefined();+ expect(toastMock).toHaveBeenCalledTimes(1);expect(toastMock.mock.calls[0][0]).toMatchObject({title: "Failed to delete chat",variant: "destructive",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.tsindex 5621c7974e..58c845534a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts@@ -1,38 +1,50 @@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 { parseAsString, useQueryStates } from "nuqs";import { useCopilotUIStore } from "./store";-import { SESSION_LIST_QUERY_KEY } from "./useSessionList";+import {+ SESSION_DELETE_MUTATION_KEY,+ SESSION_LIST_QUERY_KEY,+ type SessionListInfiniteData,+ removeSessionFromList,+} from "./useSessionList";/*** Session deletion flow: reads the pending `sessionToDelete` from the store,- * fires the delete mutation, clears the active session if it was the one- * deleted, and toasts on error.+ * closes the dialog as soon as the user confirms, leaves the chat if it is+ * the open one (with its `expertId`, so the expert's latest-thread adoption+ * cannot select it again), and fires the delete mutation. `useSessionList`+ * hides the chat while the mutation is pending. On success it is dropped from+ * the cached list; on error the chat shows again and a toast is shown.*- * Consumed by both `ChatSidebar` and `MobileDrawer` so each can render its- * own `DeleteChatDialog` without duplicating the mutation wiring.+ * Consumed by `ChatSidebar`, `MobileDrawer` and `RecentChats` so each can+ * render its own `DeleteChatDialog` without duplicating the mutation wiring.*/export function useSessionDeletion() {const queryClient = useQueryClient();- const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);+ const [{ sessionId }, setChatParams] = useQueryStates({+ sessionId: parseAsString,+ expertId: parseAsString,+ });const { sessionToDelete, setSessionToDelete } = useCopilotUIStore();const { mutate: deleteSession, isPending: isDeleting } =useDeleteV2DeleteSession({mutation: {+ mutationKey: SESSION_DELETE_MUTATION_KEY,onSuccess: (_data, variables) => {- queryClient.invalidateQueries({- queryKey: SESSION_LIST_QUERY_KEY,- });+ queryClient.setQueryData<SessionListInfiniteData>(+ SESSION_LIST_QUERY_KEY,+ (data) => removeSessionFromList(data, variables.sessionId),+ );// Use the mutation's own `variables` — not the closed-over store// value — so a rapid open/cancel/open-different sequence can't// accidentally clear the wrong active session after the network// round-trip.if (variables.sessionId === sessionId) {- setSessionId(null);+ leaveChat();}- setSessionToDelete(null);},onError: (error) => {toast({@@ -41,20 +53,31 @@ export function useSessionDeletion() {error instanceof Error ? error.message : "An error occurred",variant: "destructive",});- setSessionToDelete(null);+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: SESSION_LIST_QUERY_KEY });},},});+ function leaveChat() {+ setChatParams({ sessionId: null, expertId: null });+ }+function requestDelete(id: string, title: string | null | undefined) {if (isDeleting) return;setSessionToDelete({ id, title });}function confirmDelete() {- if (sessionToDelete) {- deleteSession({ sessionId: sessionToDelete.id });+ if (!sessionToDelete) return;+ deleteSession({ sessionId: sessionToDelete.id });+ // Leaving now keeps the composer from sending into a chat that is+ // already on its way out.+ if (sessionToDelete.id === sessionId) {+ leaveChat();}+ setSessionToDelete(null);}function cancelDelete() {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.tsindex a4b2cad963..d9bef32d4c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionList.ts@@ -1,6 +1,10 @@import { getV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";-import { type InfiniteData, useInfiniteQuery } from "@tanstack/react-query";+import {+ type InfiniteData,+ useInfiniteQuery,+ useMutationState,+} from "@tanstack/react-query";export const SESSION_LIST_PAGE_SIZE = 50;// `refetchInterval` on a `useInfiniteQuery` refetches every loaded page, and@@ -16,6 +20,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;+// 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 = [+ "copilot",+ "delete-session",+] as const;+type SessionListPage = Awaited<ReturnType<typeof getV2ListSessions>>;export type SessionListInfiniteData = InfiniteData<SessionListPage>;@@ -40,9 +51,16 @@ export function useSessionList({ enabled = true }: Args = {}) {refetchInterval: SESSION_LIST_REFETCH_INTERVAL_MS,enabled,});+ const deletingIds = useMutationState({+ filters: { mutationKey: SESSION_DELETE_MUTATION_KEY, status: "pending" },+ select: (mutation) =>+ (mutation.state.variables as { sessionId: string }).sessionId,+ });return {- sessions: flattenSessions(query.data),+ sessions: flattenSessions(query.data).filter(+ (session) => !deletingIds.includes(session.id),+ ),isLoading: query.isLoading,hasMore: !!query.hasNextPage,isLoadingMore: query.isFetchingNextPage,@@ -57,6 +75,33 @@ export function flattenSessions(data: SessionListInfiniteData | undefined) {);}+export function removeSessionFromList(+ data: SessionListInfiniteData | undefined,+ sessionId: string,+): SessionListInfiniteData | undefined {+ if (!data) return data;+ return {+ ...data,+ pages: data.pages.map((page) => {+ if (page.status !== 200) return page;+ const sessions = page.data.sessions.filter(+ (session) => session.id !== sessionId,+ );+ if (sessions.length === page.data.sessions.length) return page;+ // Lowering `total` keeps `getNextPageParam`'s offset in step with the+ // server once the row is really gone.+ return {+ ...page,+ data: {+ ...page.data,+ sessions,+ total: Math.max(0, page.data.total - 1),+ },+ };+ }),+ };+}+export interface SessionGroup {expertId: string | null;sessions: SessionSummaryResponse[];