OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: New multi chat deletion feature (#2208)
Zephyrus7c8d5f5ba90e
diff --git a/frontend/app/api/mutations/useBulkDeleteSessionsMutation.ts b/frontend/app/api/mutations/useBulkDeleteSessionsMutation.tsnew file mode 100644index 000000000..394ae8dfc--- /dev/null+++ b/frontend/app/api/mutations/useBulkDeleteSessionsMutation.ts@@ -0,0 +1,65 @@+import {+ type UseMutationOptions,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";+import type { EndpointType } from "@/contexts/chat-context";++export interface BulkDeleteSessionsRequest {+ session_ids: string[];+ endpoint: EndpointType;+}++export interface BulkDeleteSessionsResponse {+ deleted: string[];+ failed: string[];+}++async function bulkDeleteSessions(+ variables: BulkDeleteSessionsRequest,+): Promise<BulkDeleteSessionsResponse> {+ const response = await fetch("/api/sessions", {+ method: "DELETE",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ session_ids: variables.session_ids }),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(+ errorData.error || `Failed to delete sessions: ${response.status}`,+ );+ }++ return response.json();+}++export const useBulkDeleteSessionsMutation = (+ options?: Omit<+ UseMutationOptions<+ BulkDeleteSessionsResponse,+ Error,+ BulkDeleteSessionsRequest+ >,+ "mutationFn"+ >,+) => {+ const queryClient = useQueryClient();++ const { onSuccess, onError, onSettled, ...restOptions } = options ?? {};++ return useMutation({+ mutationFn: bulkDeleteSessions,+ ...restOptions,+ onSuccess: (...args) => {+ const [, variables] = args;+ queryClient.invalidateQueries({+ queryKey: ["conversations", variables.endpoint],+ });+ queryClient.invalidateQueries({ queryKey: ["conversations"] });+ onSuccess?.(...args);+ },+ onError,+ onSettled,+ });+};diff --git a/frontend/components/bulk-delete-button.tsx b/frontend/components/bulk-delete-button.tsxnew file mode 100644index 000000000..e998b0269--- /dev/null+++ b/frontend/components/bulk-delete-button.tsx@@ -0,0 +1,32 @@+"use client";++import { Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";++interface BulkDeleteButtonProps {+ count: number;+ onDelete: () => void;+ isDeleting: boolean;+}++export const BulkDeleteButton = ({+ count,+ onDelete,+ isDeleting,+}: BulkDeleteButtonProps) => {+ return (+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={count === 0 || isDeleting}+ onClick={onDelete}+ data-testid="bulk-delete-confirm"+ className="w-full !bg-transparent !border-red-600 text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30+ disabled:opacity-100 disabled:!border-red-200 disabled:text-red-200 dark:disabled:!border-red-900 dark:disabled:text-red-900"+ >+ <Trash2 className="mr-2 h-4 w-4" />+ Delete {count} chats+ </Button>+ );+};diff --git a/frontend/components/chat-renderer.tsx b/frontend/components/chat-renderer.tsxindex 885516d2d..e7447151b 100644--- a/frontend/components/chat-renderer.tsx+++ b/frontend/components/chat-renderer.tsx@@ -2,7 +2,7 @@import { useQueryClient } from "@tanstack/react-query";import { motion } from "framer-motion";-import { Loader2 } from "lucide-react";+import { File, Loader2 } from "lucide-react";import { usePathname, useRouter } from "next/navigation";import { useCallback, useEffect, useRef, useState } from "react";import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateOnboardingStateMutation";@@ -52,6 +52,7 @@ export function ChatRenderer({setConversationFilter,setOnboardingComplete,} = useChat();+ const [isSelectingChats, setIsSelectingChats] = useState(false);// Initialize onboarding state from backend settingsconst [currentStep, setCurrentStep] = useState<number>(@@ -294,13 +295,30 @@ export function ChatRenderer({conversations={conversations}isConversationsLoading={isConversationsLoading}onNewConversation={handleNewConversation}+ onSelectionChange={setIsSelectingChats}/>)}</AnimatedConditional></div>{/* Main Content */}- <main className="overflow-hidden flex-1 flex items-center justify-center">+ <main className="overflow-hidden flex-1 flex items-center justify-center relative">+ {isSelectingChats && (+ <div className="absolute inset-0 z-10 backdrop-blur-sm bg-background/60 flex items-center justify-center">+ <div className="flex flex-col items-center gap-3 text-center px-8">+ <div className="p-4 rounded-xl bg-muted">+ <File className="h-8 w-8 text-muted-foreground" />+ </div>+ <p className="font-semibold text-foreground">+ Select chats to delete+ </p>+ <p className="text-sm text-muted-foreground max-w-72">+ Choose conversations from the sidebar then delete them all at+ once+ </p>+ </div>+ </div>+ )}<motion.divinitial={{width: showLayout ? "100%" : "100vw",diff --git a/frontend/components/navigation.tsx b/frontend/components/navigation.tsxindex ea15bfd89..ef3a4c0cb 100644--- a/frontend/components/navigation.tsx+++ b/frontend/components/navigation.tsx@@ -11,8 +11,9 @@ import {} from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";-import { useEffect, useRef, useState } from "react";+import { use, useEffect, useRef, useState } from "react";import { toast } from "sonner";+import { useBulkDeleteSessionsMutation } from "@/app/api/mutations/useBulkDeleteSessionsMutation";import { useDeleteSessionMutation } from "@/app/api/queries/useDeleteSessionMutation";import {DropdownMenu,@@ -24,8 +25,10 @@ import { useIsCloudBrand } from "@/contexts/brand-context";import { type EndpointType, useChat } from "@/contexts/chat-context";import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";import { usePermissions } from "@/hooks/use-permissions";+import { useChatSelection } from "@/hooks/useChatSelection";import { FILES_REGEX } from "@/lib/constants";import { cn } from "@/lib/utils";+import { BulkDeleteButton } from "./bulk-delete-button";import { DeleteSessionModal } from "./delete-session-modal";import { KnowledgeFilterList } from "./knowledge-filter-list";@@ -68,12 +71,14 @@ interface NavigationProps {conversations?: ChatConversation[];isConversationsLoading?: boolean;onNewConversation?: () => void;+ onSelectionChange?: (isSelecting: boolean) => void;}export function Navigation({conversations = [],isConversationsLoading = false,onNewConversation,+ onSelectionChange,}: NavigationProps = {}) {const isCloudBrand = useIsCloudBrand();const pathname = usePathname();@@ -91,6 +96,13 @@ export function Navigation({conversationLoaded,loading,} = useChat();+ const selection = useChatSelection({ onChange: onSelectionChange });++ useEffect(() => {+ onSelectionChange?.(selection.isSelecting);+ }, [selection.isSelecting, onSelectionChange]);++ const allIds = conversations.map((c) => c.response_id);const previousConversationCountRef = useRef(0);const [deleteModalOpen, setDeleteModalOpen] = useState(false);@@ -139,6 +151,39 @@ export function Navigation({},});+ const bulkDeleteMutation = useBulkDeleteSessionsMutation({+ onSuccess: (res) => {+ const deletedSet = new Set(res.deleted);++ if (res.failed.length == 0) {+ toast.success(`${res.deleted.length} conversations deleted`);+ } else {+ toast.success(+ `${res.deleted.length} deleted, ${res.failed.length} couldn't be removed`,+ );+ }++ // if we delete a conversation the user is currently on+ if (currentConversationId && deletedSet.has(currentConversationId)) {+ const remaining = conversations.filter(+ (c) => !deletedSet.has(c.response_id),+ );++ if (remaining.length > 0) {+ loadConversation(remaining[0]);+ } else {+ setCurrentConversationId(null);+ startNewConversation();+ }+ }++ selection.exit();+ },+ onError: (error) => {+ toast.error(`Failed to delete conversations: ${error.message}`);+ },+ });+const handleNewConversation = () => {// Use the prop callback if provided, otherwise use the context methodif (onNewConversation) {@@ -380,21 +425,37 @@ export function Navigation({<h3 className="text-xs font-medium text-muted-foreground">Conversations</h3>- <button- type="button"- className="p-1 hover:bg-accent rounded"- data-testid="new-conversation-button"- onClick={handleNewConversation}- title="Start new conversation"- disabled={loading}- >- <Plus- className={cn(- "h-4 w-4",- isCloudBrand ? "text-foreground" : "text-muted-foreground",- )}- />- </button>+ <div className="flex items-center gap-1">+ {!selection.isSelecting && (+ <button+ type="button"+ className="p-1 hover:bg-accent rounded"+ data-testid="new-conversation-button"+ onClick={handleNewConversation}+ title="Start new conversation"+ disabled={loading}+ >+ <Plus+ className={cn(+ "h-4 w-4",+ isCloudBrand+ ? "text-foreground"+ : "text-muted-foreground",+ )}+ />+ </button>+ )}+ <button+ type="button"+ data-testid="chat-select-toggle"+ className="text-xs text-muted-foreground hover:text-foreground px-2 py-1 rounded hover:bg-accent bg-accent/50"+ onClick={() =>+ selection.isSelecting ? selection.exit() : selection.enter()+ }+ >+ {selection.isSelecting ? "Cancel" : "Select"}+ </button>+ </div></div></div>@@ -483,12 +544,31 @@ export function Navigation({));})()}+ {selection.isSelecting && (+ <div className="flex items-center justify-between p-2 text-sm">+ <label className="flex items-center gap-2 cursor-pointer font-bold">+ <input+ type="checkbox"+ aria-label="Select all conversations"+ data-testid="chat-select-all"+ checked={selection.isAllSelected(allIds)}+ onChange={() => selection.toggleAll(allIds)}+ />+ Select all+ </label>+ <span className="text-muted-foreground/50 text-xs">+ {conversations.length} chats+ </span>+ </div>+ )}{conversations.map((conversation) => (<buttonkey={conversation.response_id}data-testid={`conversation-button-${conversation.title}`}type="button"- className={`w-full px-3 h-11 rounded-lg group relative text-left ${+ className={`w-full h-11 rounded-lg group relative text-left ${+ selection.isSelecting ? "px-2" : "px-3"+ } ${loading || isConversationsLoading? "opacity-50 cursor-not-allowed": "hover:bg-accent cursor-pointer"@@ -498,6 +578,10 @@ export function Navigation({: ""}`}onClick={() => {+ if (selection.isSelecting) {+ selection.toggle(conversation.response_id);+ return;+ }if (loading || isConversationsLoading) return;loadConversation(conversation);// Don't refresh - just loading an existing conversation@@ -505,51 +589,68 @@ export function Navigation({disabled={loading || isConversationsLoading}><div className="flex items-center justify-between">- <div className="flex-1 min-w-0">+ <div className="flex min-w-0">+ {selection.isSelecting && (+ <input+ type="checkbox"+ aria-label={`Select ${conversation.title}`}+ data-testid={`chat-select-${conversation.response_id}`}+ checked={selection.selectedIds.has(+ conversation.response_id,+ )}+ onChange={() =>+ selection.toggle(conversation.response_id)+ }+ onClick={(e) => e.stopPropagation()}+ className="mr-2 flex-shrink-0"+ />+ )}<div className="text-sm font-medium text-foreground truncate">{conversation.title}</div></div>- <DropdownMenu>- <DropdownMenuTrigger- disabled={- loading ||- isConversationsLoading ||- deleteSessionMutation.isPending- }- asChild- >- <div- className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 data-[state=open]:text-foreground transition-opacity p-1 hover:bg-accent rounded text-muted-foreground hover:text-foreground ml-2 flex-shrink-0 cursor-pointer"- title="More options"- onClick={(e) => {- e.stopPropagation();- }}+ {!selection.isSelecting && (+ <DropdownMenu>+ <DropdownMenuTrigger+ disabled={+ loading ||+ isConversationsLoading ||+ deleteSessionMutation.isPending+ }+ asChild>- <EllipsisVertical className="h-4 w-4" />- </div>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"- className="w-48"- onClick={(e) => e.stopPropagation()}- >- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- handleContextMenuAction(- "delete",- conversation,- );- }}- className="cursor-pointer text-destructive focus:text-destructive"+ <div+ className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 data-[state=open]:text-foreground transition-opacity p-1 hover:bg-accent rounded text-muted-foreground hover:text-foreground ml-2 flex-shrink-0 cursor-pointer"+ title="More options"+ onClick={(e) => {+ e.stopPropagation();+ }}+ >+ <EllipsisVertical className="h-4 w-4" />+ </div>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="bottom"+ align="end"+ className="w-48"+ onClick={(e) => e.stopPropagation()}>- <Trash2 className="mr-2 h-4 w-4" />- Delete conversation- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ handleContextMenuAction(+ "delete",+ conversation,+ );+ }}+ className="cursor-pointer text-destructive focus:text-destructive"+ >+ <Trash2 className="mr-2 h-4 w-4" />+ Delete conversation+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div></button>))}@@ -580,6 +681,26 @@ export function Navigation({</div>)}</div>+ {selection.isSelecting && (+ <div className="flex-shrink-0 py-3 border-t mx-3">+ <div className="flex items-center justify-between pb-1 text-xs text-muted-foreground">+ <span>{selection.count} selected</span>+ <span>of {conversations.length}</span>+ </div>+ <div className="pt-1 pb-3 w-full">+ <BulkDeleteButton+ count={selection.count}+ isDeleting={bulkDeleteMutation.isPending}+ onDelete={() =>+ bulkDeleteMutation.mutate({+ session_ids: [...selection.selectedIds],+ endpoint,+ })+ }+ />+ </div>+ </div>+ )}</div>)}diff --git a/frontend/hooks/useChatSelection.tsx b/frontend/hooks/useChatSelection.tsxnew file mode 100644index 000000000..3965d9870--- /dev/null+++ b/frontend/hooks/useChatSelection.tsx@@ -0,0 +1,53 @@+import { useCallback, useState } from "react";++export function useChatSelection({+ onChange,+}: {+ onChange?: (isSelecting: boolean) => void;+} = {}) {+ const [isSelecting, setIsSelecting] = useState(false);+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());++ const enter = useCallback(() => {+ setIsSelecting(true);+ onChange?.(true);+ }, [onChange]);+ const clear = useCallback(() => setSelectedIds(new Set()), []);+ const exit = useCallback(() => {+ setIsSelecting(false);+ setSelectedIds(new Set());+ onChange?.(false);+ }, [onChange]);+ const toggle = useCallback((id: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ next.has(id) ? next.delete(id) : next.add(id);++ return next;+ });+ }, []);++ const isAllSelected = useCallback(+ (ids: string[]) => ids.length > 0 && ids.every((id) => selectedIds.has(id)),+ [selectedIds],+ );+ const toggleAll = useCallback((ids: string[]) => {+ setSelectedIds((prev) => {+ const allSelected = ids.length > 0 && ids.every((id) => prev.has(id));++ return allSelected ? new Set() : new Set(ids);+ });+ }, []);++ return {+ isSelecting,+ selectedIds,+ count: selectedIds.size,+ enter,+ exit,+ toggle,+ toggleAll,+ clear,+ isAllSelected,+ };+}diff --git a/frontend/tests/core/bulk_delete_chats.spec.ts b/frontend/tests/core/bulk_delete_chats.spec.tsnew file mode 100644index 000000000..1f6c69bce--- /dev/null+++ b/frontend/tests/core/bulk_delete_chats.spec.ts@@ -0,0 +1,48 @@+import { expect, test } from "../utils/fixtures";+import logger from "../utils/logger";+import { navigateToHome } from "../utils/navigation";++test("Bulk delete: deleting selected chats removes them and keeps the rest", async ({+ page,+ chat,+}) => {+ test.setTimeout(120000);+ await navigateToHome(page);++ // Conversations persist in a shared DB with no per-test cleanup, and the+ // sidebar testid is keyed on the conversation title. A unique per-run suffix+ // keeps this run's chats from colliding with leftovers of prior runs+ // (duplicate testids → strict-mode violations / ambiguous visibility checks).+ const id = `${Date.now()}-${Math.floor(Math.random() * 1e6)}`;+ const alpha = `bulk probe alpha ${id}`;+ const beta = `bulk probe beta ${id}`;+ const gamma = `bulk probe gamma ${id}`;++ await chat.openNewChat();+ await chat.askQuestion(alpha);+ await chat.openNewChat();+ await chat.askQuestion(beta);+ await chat.openNewChat();+ await chat.askQuestion(gamma);++ // All rows present before selecting, so their ids are in the list.+ await expect(page.getByTestId(`conversation-button-${gamma}`)).toBeVisible({+ timeout: 30000,+ });++ await chat.enterSelectionMode();+ await chat.selectConversationByTitle(alpha);+ await chat.selectConversationByTitle(beta);+ await chat.clickBulkDelete();++ // Selected chats disappear from the sidebar; the unselected one remains.+ await expect(page.getByTestId(`conversation-button-${alpha}`)).toBeHidden({+ timeout: 30000,+ });+ await expect(page.getByTestId(`conversation-button-${beta}`)).toBeHidden({+ timeout: 30000,+ });+ await expect(page.getByTestId(`conversation-button-${gamma}`)).toBeVisible();++ logger.info("Bulk delete partial: PASSED");+});diff --git a/frontend/tests/pages/Chat.ts b/frontend/tests/pages/Chat.tsindex 84f20079b..f65e271db 100644--- a/frontend/tests/pages/Chat.ts+++ b/frontend/tests/pages/Chat.ts@@ -30,6 +30,10 @@ export class Chat {this.page.getByRole("button", { name: /^delete$/i });private readonly conversationDeletedToast = () =>this.page.getByText(/conversation deleted successfully/i);+ private readonly selectToggleButton = () =>+ this.page.getByTestId("chat-select-toggle");+ private readonly selectAllCheckBox = () =>+ this.page.getByTestId("chat-select-all");/*** Get locator for a filter option by name@@ -635,4 +639,31 @@ export class Chat {}}}++ async getConversationCount(): Promise<number> {+ return this.page.locator('[data-testid^="conversation-button-"]').count();+ }++ async enterSelectionMode() {+ await this.selectToggleButton().click();+ await expect(this.selectAllCheckBox()).toBeVisible({ timeout: 5000 });+ }++ async exitSelectionMode() {+ await this.selectToggleButton().click();+ }++ async selectAllConversations() {+ await this.selectAllCheckBox().check();+ }++ async clickBulkDelete() {+ await this.page.getByTestId("bulk-delete-confirm").click();+ }++ async selectConversationByTitle(title: string) {+ const row = this.page.getByTestId(`conversation-button-${title}`);+ const checkbox = row.locator('input[type="checkbox"]');+ await checkbox.check();+ }}diff --git a/src/api/chat.py b/src/api/chat.pyindex a3baa7e1c..c30f15289 100644--- a/src/api/chat.py+++ b/src/api/chat.py@@ -14,6 +14,8 @@ from utils.logging_config import get_loggerlogger = get_logger(__name__)+MAX_BULK_DELETE = 100+def _openrag_user_id(user: User) -> str:return getattr(user, "db_user_id", None) or user.user_id@@ -50,6 +52,10 @@ class ChatBody(BaseModel):filter_id: str | None = None+class BulkDeleteBody(BaseModel):+ session_ids: list[str]++async def chat_endpoint(body: ChatBody,chat_service=Depends(get_chat_service),@@ -224,3 +230,29 @@ async def delete_session_endpoint(except Exception:logger.exception("Error deleting session")return JSONResponse({"error": "Failed to delete session"}, status_code=500)+++async def bulk_delete_sessions_endpoint(+ body: BulkDeleteBody,+ chat_service=Depends(get_chat_service),+ user: User = Depends(require_permission("conversations:delete:own")),+) -> JSONResponse:+ """Best-effort bulk delete of chat sessions owned by user (caller)"""+ if not body.session_ids:+ raise HTTPException(status_code=400, detail={"error": "no_session_ids"})+ if len(body.session_ids) > MAX_BULK_DELETE:+ raise HTTPException(status_code=400, detail={"error": "too_many_session_ids"})++ storage_user_id = _openrag_user_id(user)+ try:+ result = await chat_service.delete_sessions(storage_user_id, body.session_ids)+ return JSONResponse(+ {+ "deleted": result.get("deleted", []),+ "failed": result.get("failed", []),+ }+ )+ except Exception:+ logger.exception("Error bulk-deleting sessions")++ return JSONResponse({"error": "Failed to delete sessions"}, status_code=500)diff --git a/src/app/routes/internal.py b/src/app/routes/internal.pyindex 8ecb56786..383f40f06 100644--- a/src/app/routes/internal.py+++ b/src/app/routes/internal.py@@ -211,13 +211,19 @@ def register_internal_routes(app: FastAPI):tags=["internal"],)- # Session deletion endpoint+ # Session deletion endpointsapp.add_api_route("/sessions/{session_id}",chat.delete_session_endpoint,methods=["DELETE"],tags=["internal"],)+ app.add_api_route(+ "/sessions",+ chat.bulk_delete_sessions_endpoint,+ methods=["DELETE"],+ tags=["internal"],+ )# Authentication endpointsapp.add_api_route("/auth/init", auth.auth_init, methods=["POST"], tags=["internal"])diff --git a/src/services/chat_service.py b/src/services/chat_service.pyindex 55f42ce73..af00e4054 100644--- a/src/services/chat_service.py+++ b/src/services/chat_service.py@@ -937,6 +937,36 @@ class ChatService:logger.error(f"Error deleting session {session_id} for user {user_id}: {e}")return {"success": False, "error": str(e)}+ async def delete_sessions(self, user_id: str, session_ids: list[str]) -> dict[str, list[str]]:+ """Best-effort bulk delete, any failures are returned in response + logged++ Returns {"deleted": [ids], "failed": [ids]}.+ """+ from services.session_ownership_service import session_ownership_service++ deleted: list[str] = []+ failed: list[str] = []++ for session_id in dict.fromkeys(session_ids):+ try:+ owner = await session_ownership_service.get_session_owner(session_id)+ if owner != user_id:+ logger.warning("bulk_delete: %s not owned by %s", session_id, user_id)+ failed.append(session_id)+ continue++ result = await self.delete_session(user_id, session_id)+ if result.get("success"):+ deleted.append(session_id)+ else:+ logger.warning("bulk_delete: %s error: %s", session_id, result.get("error"))+ failed.append(session_id)+ except Exception:+ logger.exception("bulk_delete: %s unexpected error", session_id)+ failed.append(session_id)++ return {"deleted": deleted, "failed": failed}+async def _delete_langflow_session(self, session_id: str):"""Delete a session from Langflow using the monitor API"""try:diff --git a/tests/unit/api/test_bulk_delete_sessions_endpoint.py b/tests/unit/api/test_bulk_delete_sessions_endpoint.pynew file mode 100644index 000000000..30e47d8d1--- /dev/null+++ b/tests/unit/api/test_bulk_delete_sessions_endpoint.py@@ -0,0 +1,47 @@+from unittest.mock import AsyncMock++import pytest+from fastapi import HTTPException+++class _User:+ def __init__(self, uid):+ self.db_user_id = uid+ self.user_id = uid+++async def test_bulk_delete_forwards_ids_and_maps_response():+ import json++ from api import chat as chat_module++ fake_service = AsyncMock()+ fake_service.delete_sessions = AsyncMock(return_value={"deleted": ["a"], "failed": ["b"]})+ body = chat_module.BulkDeleteBody(session_ids=["a", "b"])++ resp = await chat_module.bulk_delete_sessions_endpoint(+ body=body,+ chat_service=fake_service,+ user=_User("alice"),+ )++ payload = json.loads(resp.body)+ fake_service.delete_sessions.assert_awaited_once_with("alice", ["a", "b"])+ assert payload == {"deleted": ["a"], "failed": ["b"]}++[email protected](argnames="session_ids", argvalues=[[], [str(i) for i in range(101)]])+async def test_bulk_delete_reject_cases(session_ids):+ from api import chat as chat_module++ body = chat_module.BulkDeleteBody(session_ids=session_ids)++ with pytest.raises(HTTPException) as exc:+ await chat_module.bulk_delete_sessions_endpoint(+ body=body,+ chat_service=AsyncMock(),+ user=_User("alice"),+ )+ assert exc.value.status_code == 400diff --git a/tests/unit/test_chat_service_bulk_delete.py b/tests/unit/test_chat_service_bulk_delete.pynew file mode 100644index 000000000..81783308b--- /dev/null+++ b/tests/unit/test_chat_service_bulk_delete.py@@ -0,0 +1,77 @@+from unittest.mock import AsyncMock++import pytest+++def _make_service():+ from services.chat_service import ChatService++ return ChatService.__new__(ChatService)+++def _patch_owner(monkeypatch, owners):+ monkeypatch.setattr(+ "services.session_ownership_service.session_ownership_service.get_session_owner",+ AsyncMock(side_effect=lambda sid: owners.get(sid)),+ )+++async def test_bulk_delete_mixed_ownership(monkeypatch):+ svc = _make_service()+ # alice owns s1; s2 is bob's; s3 has no owner+ _patch_owner(monkeypatch, {"s1": "alice", "s2": "bob", "s3": None})+ svc.delete_session = AsyncMock(return_value={"success": True, "error": None})++ result = await svc.delete_sessions("alice", ["s1", "s2", "s3"])++ assert result["deleted"] == ["s1"]+ assert sorted(result["failed"]) == ["s2", "s3"]+ # only the owned id ever reaches delete_session+ called = {c.args[1] for c in svc.delete_session.call_args_list}+ assert called == {"s1"}+++async def test_bulk_delete_all_succeed(monkeypatch):+ svc = _make_service()+ _patch_owner(monkeypatch, {"a": "alice", "b": "alice"})+ svc.delete_session = AsyncMock(return_value={"success": True, "error": None})++ result = await svc.delete_sessions("alice", ["a", "b"])++ assert result == {"deleted": ["a", "b"], "failed": []}+++async def test_bulk_delete_dedupes(monkeypatch):+ svc = _make_service()+ _patch_owner(monkeypatch, {"a": "alice"})+ svc.delete_session = AsyncMock(return_value={"success": True, "error": None})++ result = await svc.delete_sessions("alice", ["a", "a", "a"])++ assert result == {"deleted": ["a"], "failed": []}+ assert svc.delete_session.await_count == 1 # deleted at most once+++async def test_bulk_delete_reports_delete_failure(monkeypatch):+ svc = _make_service()+ _patch_owner(monkeypatch, {"x": "alice"})+ svc.delete_session = AsyncMock(return_value={"success": False, "error": "nope"})++ result = await svc.delete_sessions("alice", ["x"])++ assert result == {"deleted": [], "failed": ["x"]}+++async def test_bulk_delete_never_raises_on_error(monkeypatch):+ svc = _make_service()+ _patch_owner(monkeypatch, {"x": "alice"})+ svc.delete_session = AsyncMock(side_effect=RuntimeError("boom"))++ result = await svc.delete_sessions("alice", ["x"])++ assert result == {"deleted": [], "failed": ["x"]}