Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

feat: task notification overhaul — persistent delete, count badge, click-to-expand, light/dark mode fixes (#2291)

Jason Dong7e17c52f1b4e
diff --git a/frontend/.husky/pre-commit b/frontend/.husky/pre-commit
index f450749af..2f11b31e8 100755
--- a/frontend/.husky/pre-commit
+++ b/frontend/.husky/pre-commit
@@ -1 +1,4 @@
+# Load nvm so npx is available regardless of how the hook is launched (e.g. GUI Git clients).
+export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
+[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
cd frontend && npx lint-staged
diff --git a/frontend/app/api/mutations/useDeleteTaskMutation.test.ts b/frontend/app/api/mutations/useDeleteTaskMutation.test.ts
new file mode 100644
index 000000000..e737447d7
--- /dev/null
+++ b/frontend/app/api/mutations/useDeleteTaskMutation.test.ts
@@ -0,0 +1,243 @@
+/**
+ * Tests for useDeleteTaskMutation and useDeleteAllTerminalTasksMutation.
+ *
+ * Network is mocked via MSW (per-test overrides). react-query wiring, URL,
+ * response.ok handling, cache updates, and error paths all stay under test.
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import {
+ useDeleteAllTerminalTasksMutation,
+ useDeleteTaskMutation,
+} from "@/app/api/mutations/useDeleteTaskMutation";
+import { TASKS_QUERY_KEY, type Task } from "@/app/api/queries/useGetTasksQuery";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, createTestQueryClient } from "@/test-utils/render";
+
+// ─── helpers ──────────────────────────────────────────────────────────────────
+
+function makeTask(partial: Partial<Task> = {}): Task {
+ return {
+ task_id: "aaaaaaaa-0000-0000-0000-000000000000",
+ status: "completed",
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:01Z",
+ ...partial,
+ };
+}
+
+// ─── useDeleteTaskMutation ────────────────────────────────────────────────────
+
+describe("useDeleteTaskMutation", () => {
+ it("calls DELETE /api/tasks/:id and removes the task from cache on success", async () => {
+ const taskId = "task-001";
+ server.use(
+ http.delete(
+ `/api/tasks/${taskId}`,
+ () => new HttpResponse(null, { status: 204 }),
+ ),
+ );
+
+ // Use a longer gcTime so cache entries survive the test without an active observer.
+ const queryClient = createTestQueryClient();
+ queryClient.setDefaultOptions({
+ queries: {
+ retry: false,
+ staleTime: 0,
+ gcTime: 60_000,
+ refetchOnWindowFocus: false,
+ },
+ mutations: { retry: false },
+ });
+ // Seed the cache with the task to be deleted.
+ queryClient.setQueryData<Task[]>(
+ ["tasks", "enhanced"],
+ [makeTask({ task_id: taskId })],
+ );
+
+ const { result } = renderHook(() => useDeleteTaskMutation(), {
+ wrapper: createQueryWrapper(queryClient),
+ });
+
+ act(() => {
+ result.current.mutate(taskId);
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ // onSuccess calls setQueryData, removing the deleted task from the cache list.
+ await waitFor(() => {
+ const cached = queryClient.getQueryData<Task[]>(["tasks", "enhanced"]);
+ expect(Array.isArray(cached)).toBe(true);
+ expect(cached!.find((t) => t.task_id === taskId)).toBeUndefined();
+ });
+ });
+
+ it("treats a 404 as success without throwing", async () => {
+ const taskId = "missing-task";
+ server.use(
+ http.delete(
+ `/api/tasks/${taskId}`,
+ () => new HttpResponse(null, { status: 404 }),
+ ),
+ );
+
+ const queryClient = createTestQueryClient();
+ queryClient.setQueryData<Task[]>([...TASKS_QUERY_KEY], []);
+
+ const { result } = renderHook(() => useDeleteTaskMutation(), {
+ wrapper: createQueryWrapper(queryClient),
+ });
+
+ act(() => {
+ result.current.mutate(taskId);
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.error).toBeNull();
+ });
+
+ it("throws an error and sets isError when the response is not ok", async () => {
+ const taskId = "bad-task";
+ server.use(
+ http.delete(`/api/tasks/${taskId}`, () =>
+ HttpResponse.json({ error: "server exploded" }, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useDeleteTaskMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => {
+ result.current.mutate(taskId);
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("server exploded");
+ });
+
+ it("falls back to default error message when body has no error field", async () => {
+ const taskId = "no-body-task";
+ server.use(
+ http.delete(`/api/tasks/${taskId}`, () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useDeleteTaskMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => {
+ result.current.mutate(taskId);
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to delete task");
+ });
+});
+
+// ─── useDeleteAllTerminalTasksMutation ────────────────────────────────────────
+
+describe("useDeleteAllTerminalTasksMutation", () => {
+ it("calls DELETE /api/tasks, returns deleted IDs, and removes them from cache", async () => {
+ const keepId = "keep-001";
+ const deleteId = "del-001";
+ server.use(
+ http.delete("/api/tasks", () =>
+ HttpResponse.json({ deleted_ids: [deleteId] }),
+ ),
+ );
+
+ // Use a longer gcTime so cache entries survive the test without an active observer.
+ const queryClient = createTestQueryClient();
+ queryClient.setDefaultOptions({
+ queries: {
+ retry: false,
+ staleTime: 0,
+ gcTime: 60_000,
+ refetchOnWindowFocus: false,
+ },
+ mutations: { retry: false },
+ });
+ queryClient.setQueryData<Task[]>(
+ ["tasks", "enhanced"],
+ [makeTask({ task_id: keepId }), makeTask({ task_id: deleteId })],
+ );
+
+ const { result } = renderHook(() => useDeleteAllTerminalTasksMutation(), {
+ wrapper: createQueryWrapper(queryClient),
+ });
+
+ act(() => {
+ result.current.mutate();
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ // onSuccess calls setQueryData, keeping only the non-deleted tasks.
+ await waitFor(() => {
+ const cached = queryClient.getQueryData<Task[]>(["tasks", "enhanced"]);
+ expect(Array.isArray(cached)).toBe(true);
+ expect(cached!.find((t) => t.task_id === deleteId)).toBeUndefined();
+ expect(cached!.find((t) => t.task_id === keepId)).toBeDefined();
+ });
+ });
+
+ it("throws when deleted_ids is not an array of strings", async () => {
+ server.use(
+ http.delete("/api/tasks", () =>
+ HttpResponse.json({ deleted_ids: [1, 2, 3] }),
+ ),
+ );
+
+ const { result } = renderHook(() => useDeleteAllTerminalTasksMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => {
+ result.current.mutate();
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toMatch(/Unexpected response shape/);
+ });
+
+ it("treats a 404 as a no-op returning empty array", async () => {
+ server.use(
+ http.delete("/api/tasks", () => new HttpResponse(null, { status: 404 })),
+ );
+
+ const { result } = renderHook(() => useDeleteAllTerminalTasksMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => {
+ result.current.mutate();
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data).toEqual([]);
+ });
+
+ it("throws when the response is not ok", async () => {
+ server.use(
+ http.delete("/api/tasks", () =>
+ HttpResponse.json({ error: "forbidden" }, { status: 403 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useDeleteAllTerminalTasksMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => {
+ result.current.mutate();
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("forbidden");
+ });
+});
diff --git a/frontend/app/api/mutations/useDeleteTaskMutation.ts b/frontend/app/api/mutations/useDeleteTaskMutation.ts
new file mode 100644
index 000000000..149b51541
--- /dev/null
+++ b/frontend/app/api/mutations/useDeleteTaskMutation.ts
@@ -0,0 +1,61 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { TASKS_QUERY_KEY, type Task } from "@/app/api/queries/useGetTasksQuery";
+
+export function useDeleteTaskMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (taskId: string) => {
+ const res = await fetch(`/api/tasks/${taskId}`, { method: "DELETE" });
+ if (res.status === 404) return;
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(
+ (body as { error?: string }).error ?? "Failed to delete task",
+ );
+ }
+ },
+ onSuccess: (_data, taskId) => {
+ queryClient.setQueryData<Task[]>([...TASKS_QUERY_KEY], (old) =>
+ (old ?? []).filter((t) => t.task_id !== taskId),
+ );
+ },
+ onError: (error) => {
+ console.error("Delete task failed:", error);
+ },
+ });
+}
+
+export function useDeleteAllTerminalTasksMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (): Promise<string[]> => {
+ const res = await fetch("/api/tasks", { method: "DELETE" });
+ if (res.status === 404) return [];
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(
+ (body as { error?: string }).error ?? "Failed to delete tasks",
+ );
+ }
+ const body = await res.json();
+ if (
+ !Array.isArray(body.deleted_ids) ||
+ !body.deleted_ids.every((id: unknown) => typeof id === "string")
+ ) {
+ throw new Error(
+ `Unexpected response shape: deleted_ids=${JSON.stringify(body.deleted_ids)}`,
+ );
+ }
+ return body.deleted_ids;
+ },
+ onSuccess: (deletedIds) => {
+ const deleted = new Set(deletedIds);
+ queryClient.setQueryData<Task[]>([...TASKS_QUERY_KEY], (old) =>
+ (old ?? []).filter((t) => !deleted.has(t.task_id)),
+ );
+ },
+ onError: (error) => {
+ console.error("Delete all tasks failed:", error);
+ },
+ });
+}
diff --git a/frontend/app/api/queries/useGetTasksQuery.ts b/frontend/app/api/queries/useGetTasksQuery.ts
index 8fd106489..442d66128 100644
--- a/frontend/app/api/queries/useGetTasksQuery.ts
+++ b/frontend/app/api/queries/useGetTasksQuery.ts
@@ -75,6 +75,11 @@ export interface Task {
result?: Record<string, unknown>;
error?: string;
files?: Record<string, TaskFileEntry>;
+ /** True when this task belongs to the shared anonymous store, not the
+ * calling user. Shared tasks are visible to all signed-in users but can
+ * only be bulk-cleared by the system (cleanup_old_tasks), not by any
+ * individual user's "Clear all" action. */
+ is_shared?: boolean;
}
export interface TasksResponse {
diff --git a/frontend/app/settings/_components/connector-card.tsx b/frontend/app/settings/_components/connector-card.tsx
index 7f97f7352..940bf65c2 100644
--- a/frontend/app/settings/_components/connector-card.tsx
+++ b/frontend/app/settings/_components/connector-card.tsx
@@ -81,7 +81,7 @@ export default function ConnectorCard({
"flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium",
isCloudBrand
? "bg-primary/10 text-primary dark:bg-white/10 dark:text-layer-contextual-foreground"
- : "bg-foreground text-muted",
+ : "bg-muted text-muted-foreground",
)}
>
<span className="h-2 w-2 rounded-full bg-green-500" />
diff --git a/frontend/app/settings/_components/model-provider-card.tsx b/frontend/app/settings/_components/model-provider-card.tsx
index 89256680f..72765e6e9 100644
--- a/frontend/app/settings/_components/model-provider-card.tsx
+++ b/frontend/app/settings/_components/model-provider-card.tsx
@@ -87,7 +87,6 @@ export default function ModelProviderCard({
<CardContent className="flex-1 flex flex-col justify-end space-y-4">
<Button
className={cn(
- !isCloudBrand && "group-hover:bg-background",
isConfigured && !isCloudBrand && "border-primary",
isCloudBrand &&
isEditSetup &&
diff --git a/frontend/components/console-status/button.tsx b/frontend/components/console-status/button.tsx
index 7f27c4eb0..04449cd79 100644
--- a/frontend/components/console-status/button.tsx
+++ b/frontend/components/console-status/button.tsx
@@ -32,16 +32,13 @@ export function ConsoleStatusButton({
"relative flex items-center gap-2 rounded-lg transition-colors",
isNarrow
? "h-8 w-8 justify-center hover:bg-muted"
- : "px-3 py-2 bg-zinc-800 border border-zinc-700 text-zinc-200 text-sm font-medium hover:bg-zinc-700 hover:border-zinc-600 shadow-lg",
- !isNarrow && isOpen && "bg-zinc-700 border-zinc-500",
+ : "px-3 py-2 bg-muted border border-border text-foreground text-sm font-medium hover:bg-muted/80 hover:border-muted-foreground/40 shadow-sm",
+ !isNarrow && isOpen && "bg-muted/80 border-muted-foreground/40",
)}
>
<EvCharger
size={isNarrow ? 16 : 14}
- className={cn(
- "shrink-0",
- isNarrow ? "text-muted-foreground" : "text-zinc-400",
- )}
+ className="shrink-0 text-muted-foreground"
/>
{!isNarrow && <span>Console Status</span>}
{overallStatus &&
diff --git a/frontend/components/header.test.tsx b/frontend/components/header.test.tsx
index c8c094fda..6020b1d64 100644
--- a/frontend/components/header.test.tsx
+++ b/frontend/components/header.test.tsx
@@ -21,6 +21,11 @@ const {
mockExpandSidebar: vi.fn(),
}));
+// Mutable tasks list so individual tests can swap in different data.
+const mockTasksHolder = vi.hoisted(() => ({
+ tasks: [] as { status: string }[],
+}));
+
vi.mock("@/contexts/brand-context", () => ({
useIsCloudBrand: () => false,
}));
@@ -30,7 +35,7 @@ vi.mock("@/contexts/auth-context", () => ({
}));
vi.mock("@/contexts/task-context", () => ({
- useTask: () => ({ tasks: [] }),
+ useTask: () => ({ tasks: mockTasksHolder.tasks }),
}));
vi.mock("@/contexts/console-status-context", () => ({
@@ -72,6 +77,7 @@ import { useNarrowLayout } from "@/hooks/use-narrow-layout";
describe("Header", () => {
it("renders brand and header elements in wide non-collapsed layout", () => {
+ mockTasksHolder.tasks = [];
render(<Header />);
expect(screen.getByText("OpenRAG")).toBeInTheDocument();
expect(screen.queryByLabelText("Open navigation")).not.toBeInTheDocument();
@@ -127,3 +133,38 @@ describe("Header", () => {
expect(mockPinSidebar).toHaveBeenCalled();
});
});
+
+describe("Header — notification badge counts", () => {
+ it("shows active task count badge when pending/running/processing tasks exist", () => {
+ mockTasksHolder.tasks = [
+ { status: "pending" },
+ { status: "running" },
+ { status: "processing" },
+ ];
+ render(<Header />);
+ // activeTaskCount = 3, badge should display "3"
+ expect(screen.getByText("3")).toBeInTheDocument();
+ });
+
+ it("shows failed task count badge when only failed/error tasks exist", () => {
+ mockTasksHolder.tasks = [{ status: "failed" }, { status: "error" }];
+ render(<Header />);
+ // activeTaskCount = 0, failedTaskCount = 2 → red badge with "2"
+ expect(screen.getByText("2")).toBeInTheDocument();
+ });
+
+ it("shows active badge and not failed badge when both active and failed tasks exist", () => {
+ mockTasksHolder.tasks = [{ status: "running" }, { status: "failed" }];
+ render(<Header />);
+ // activeTaskCount = 1 takes precedence; active badge shows, failed badge hidden
+ expect(screen.getByText("1")).toBeInTheDocument();
+ // Only one badge rendered
+ expect(screen.getAllByText(/^\d+$/).length).toBe(1);
+ });
+
+ it("shows no badge when all tasks are in terminal non-failed states", () => {
+ mockTasksHolder.tasks = [{ status: "completed" }, { status: "cancelled" }];
+ render(<Header />);
+ expect(screen.queryByText(/^\d+$/)).toBeNull();
+ });
+});
diff --git a/frontend/components/header.tsx b/frontend/components/header.tsx
index 792e7eca4..1f9cfd083 100644
--- a/frontend/components/header.tsx
+++ b/frontend/components/header.tsx
@@ -21,6 +21,15 @@ import { useProviderHealth } from "./provider-health-banner";
export function Header() {
const isCloudBrand = useIsCloudBrand();
const { tasks } = useTask();
+ const activeTaskCount = tasks.filter(
+ (t) =>
+ t.status === "pending" ||
+ t.status === "running" ||
+ t.status === "processing",
+ ).length;
+ const failedTaskCount = tasks.filter(
+ (t) => t.status === "failed" || t.status === "error",
+ ).length;
const toggleTaskMenu = useToggleTaskMenu();
const { runMode } = useAuth();
const isNarrow = useNarrowLayout();
@@ -35,7 +44,6 @@ export function Header() {
} = useSidebarOverlay();
const {
- hasProblem,
toggle,
isOpen,
overallStatus: consoleOverallStatus,
@@ -45,17 +53,6 @@ export function Header() {
? "unhealthy"
: consoleOverallStatus;
- // Calculate active tasks for the bell icon
- const activeTasks = tasks.filter(
- (task) =>
- task.status === "pending" ||
- task.status === "running" ||
- task.status === "processing",
- );
-
- // The bell dot lights for in-flight tasks OR a degraded/down component.
- const showNotificationDot = activeTasks.length > 0 || hasProblem;
-
return (
<header className={cn(`flex w-full h-full items-center justify-between`)}>
<div className="header-start-display px-[16px]">
@@ -142,7 +139,16 @@ export function Header() {
isCloudBrand ? "text-foreground" : "text-muted-foreground"
}
/>
- {showNotificationDot && <div className="header-notifications" />}
+ {activeTaskCount > 0 && (
+ <span className="absolute -right-1 -top-1 flex min-w-[16px] h-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground">
+ {activeTaskCount > 99 ? "99+" : activeTaskCount}
+ </span>
+ )}
+ {activeTaskCount === 0 && failedTaskCount > 0 && (
+ <span className="absolute -right-1 -top-1 flex min-w-[16px] h-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-semibold leading-none text-destructive-foreground">
+ {failedTaskCount > 99 ? "99+" : failedTaskCount}
+ </span>
+ )}
</button>
{/* Separator */}
diff --git a/frontend/components/task-error-content.test.tsx b/frontend/components/task-error-content.test.tsx
index 0fa5b136c..f02482df5 100644
--- a/frontend/components/task-error-content.test.tsx
+++ b/frontend/components/task-error-content.test.tsx
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { Task } from "@/app/api/queries/useGetTasksQuery";
-import { renderWithProviders, screen } from "@/test-utils/render";
+import { renderWithProviders, screen, userEvent } from "@/test-utils/render";
import { TaskErrorContent } from "./task-error-content";
/**
@@ -10,6 +10,12 @@ import { TaskErrorContent } from "./task-error-content";
* - "cancelled" count in the summary line
* - early-return when all counts are zero
*
+ * Also covers the interaction handlers added in the same diff:
+ * - toggleAccordion (click, Enter, Space)
+ * - openTaskDialog button click (stopPropagation + openTaskDialog)
+ * - Accordion trigger stopPropagation
+ * - headerEnd stopPropagation span
+ *
* TaskErrorContent depends on useTask (for openTaskDialog) and useIsCloudBrand.
* Both are mocked at the module level — the context providers are not needed
* because we are testing component logic, not the context wiring.
@@ -19,9 +25,14 @@ import { TaskErrorContent } from "./task-error-content";
* factory mock drops an export it needs.
*/
+// Hoist the spy so it is available inside the vi.mock factory below.
+const { mockOpenTaskDialog } = vi.hoisted(() => ({
+ mockOpenTaskDialog: vi.fn(),
+}));
+
vi.mock("@/contexts/task-context", async (importOriginal) => ({
...(await importOriginal<typeof import("@/contexts/task-context")>()),
- useTask: () => ({ openTaskDialog: vi.fn() }),
+ useTask: () => ({ openTaskDialog: mockOpenTaskDialog }),
}));
vi.mock("@/contexts/brand-context", async (importOriginal) => ({
@@ -119,3 +130,105 @@ describe("TaskErrorContent — cancellation display", () => {
expect(screen.getByText(/1 cancelled/)).toBeInTheDocument();
});
});
+
+describe("TaskErrorContent — interaction handlers", () => {
+ function makeFailedTask(overrides: Partial<Task> = {}): Task {
+ return {
+ task_id: "task-interaction-1",
+ status: "failed",
+ created_at: "2026-09-08T10:00:00Z",
+ updated_at: "2026-09-08T10:05:00Z",
+ failed_files: 1,
+ files: {
+ "doc.pdf": { status: "failed", error: "Parse error" },
+ },
+ ...overrides,
+ };
+ }
+
+ it("toggles accordion open/closed when header row is clicked", async () => {
+ const user = userEvent.setup();
+
+ renderWithProviders(<TaskErrorContent task={makeFailedTask()} />);
+
+ // The outer header div carries aria-expanded and acts as the toggle target.
+ const expandableRow = document.querySelector(
+ "[aria-expanded]",
+ ) as HTMLElement;
+ expect(expandableRow).not.toBeNull();
+ expect(expandableRow.getAttribute("aria-expanded")).toBe("false");
+
+ await user.click(expandableRow);
+ expect(expandableRow.getAttribute("aria-expanded")).toBe("true");
+
+ await user.click(expandableRow);
+ expect(expandableRow.getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("toggles accordion open via Enter key on the header row", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<TaskErrorContent task={makeFailedTask()} />);
+
+ const expandableRow = document.querySelector(
+ "[aria-expanded]",
+ ) as HTMLElement;
+ expandableRow.focus();
+ await user.keyboard("{Enter}");
+ expect(expandableRow.getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("toggles accordion open via Space key on the header row", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<TaskErrorContent task={makeFailedTask()} />);
+
+ const expandableRow = document.querySelector(
+ "[aria-expanded]",
+ ) as HTMLElement;
+ expandableRow.focus();
+ await user.keyboard(" ");
+ expect(expandableRow.getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("calls openTaskDialog with the task id when the details button is clicked", async () => {
+ const user = userEvent.setup();
+ mockOpenTaskDialog.mockReset();
+
+ renderWithProviders(
+ <TaskErrorContent task={makeFailedTask()} defaultExpanded />,
+ );
+
+ await user.click(screen.getByRole("button", { name: "Open task details" }));
+
+ expect(mockOpenTaskDialog).toHaveBeenCalledWith("task-interaction-1");
+ });
+
+ it("headerEnd click does not toggle the accordion (stopPropagation)", async () => {
+ const user = userEvent.setup();
+ const headerEndClick = vi.fn();
+
+ renderWithProviders(
+ <TaskErrorContent
+ task={makeFailedTask()}
+ headerEnd={
+ <button
+ type="button"
+ onClick={headerEndClick}
+ aria-label="header-end-action"
+ >
+ action
+ </button>
+ }
+ />,
+ );
+
+ const expandableRow = document.querySelector(
+ "[aria-expanded]",
+ ) as HTMLElement;
+
+ await user.click(screen.getByRole("button", { name: "header-end-action" }));
+
+ expect(headerEndClick).toHaveBeenCalledTimes(1);
+ // The wrapper <span> stopPropagation must prevent the accordion from toggling.
+ expect(expandableRow.getAttribute("aria-expanded")).toBe("false");
+ });
+});
diff --git a/frontend/components/task-error-content.tsx b/frontend/components/task-error-content.tsx
index 69980894a..e4b7f1e33 100644
--- a/frontend/components/task-error-content.tsx
+++ b/frontend/components/task-error-content.tsx
@@ -35,6 +35,7 @@ interface TaskErrorContentProps {
nowMs?: number;
showHeader?: boolean;
defaultExpanded?: boolean;
+ headerEnd?: React.ReactNode;
}
export function TaskErrorContent({
@@ -43,6 +44,7 @@ export function TaskErrorContent({
nowMs = Date.now(),
showHeader = true,
defaultExpanded = false,
+ headerEnd,
}: TaskErrorContentProps) {
const isCloudBrand = useIsCloudBrand();
const { openTaskDialog } = useTask();
@@ -100,10 +102,14 @@ export function TaskErrorContent({
}
const ossIconColumn = showHeader && !isCloudBrand;
+ const toggleAccordion = () =>
+ setAccordionValue((value) =>
+ value === "failed-files" ? "" : "failed-files",
+ );
const accordionSummary = (
- <div className="flex min-w-0 flex-1 items-center gap-1">
- <span className="text-xs">
+ <div className="flex min-w-0 flex-1 items-center gap-1 leading-4">
+ <span className="text-xs leading-4">
{ingestedSuccessCount} success
{warningCount > 0 ? ` · ${warningCount} warning` : ""}
{failedCount > 0 ? ` · ${failedCount} failed` : ""}
@@ -118,28 +124,24 @@ export function TaskErrorContent({
type="button"
aria-label="Open task details"
className="inline-flex shrink-0 items-center justify-center text-muted-foreground hover:text-foreground"
- onClick={() => openTaskDialog(task.task_id)}
+ onClick={(event) => {
+ event.stopPropagation();
+ openTaskDialog(task.task_id);
+ }}
>
<IncidentReporterIcon className="size-4" />
</button>
);
const accordionHeader = (
- <AccordionPrimitive.Header
- className={cn(
- "flex w-full min-w-0 items-center gap-2",
- ossIconColumn && "gap-2.5",
- )}
- >
+ <AccordionPrimitive.Header className="flex w-full min-w-0 items-center gap-2 leading-4">
{ossIconColumn ? <div className="size-5 shrink-0" aria-hidden /> : null}
<AccordionPrimitive.Trigger
- className={cn(
- "group inline-flex min-w-0 flex-1 items-center justify-start gap-1 px-0 py-0 text-sm text-muted-foreground transition-colors hover:text-foreground",
- )}
+ className="group inline-flex min-w-0 flex-1 items-center justify-start gap-1 p-0 text-sm text-muted-foreground transition-colors hover:text-foreground"
+ onClick={(event) => event.stopPropagation()}
>
{accordionSummary}
</AccordionPrimitive.Trigger>
- {openTaskDialogButton}
</AccordionPrimitive.Header>
);
@@ -154,41 +156,56 @@ export function TaskErrorContent({
? "border-t border-muted"
: "rounded-mmd border border-muted",
),
- !showHeader && "pt-2",
+ !showHeader && "pt-1",
)}
>
- <div className="flex w-full min-w-0 flex-col gap-1">
+ <div className="flex w-full min-w-0 flex-col">
{showHeader && (
<div
- className={cn("flex min-w-0 w-full", ossIconColumn && "gap-2.5")}
+ className="flex min-w-0 w-full cursor-pointer items-start gap-3"
+ role="button"
+ tabIndex={0}
+ aria-expanded={isExpanded}
+ onClick={toggleAccordion}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ toggleAccordion();
+ }
+ }}
>
{ossIconColumn &&
(isCancelledOnly ? (
<XCircle
- className="size-5 shrink-0 text-muted-foreground"
+ className="size-4 mt-0.5 shrink-0 text-muted-foreground"
aria-hidden
/>
) : isFailedStatus ? (
<XCircle
- className="size-5 shrink-0 text-destructive"
+ className="size-4 mt-1.5 shrink-0 text-destructive"
aria-hidden
/>
) : (
<AlertCircle
- className="size-5 shrink-0 text-brand-amber"
+ className="size-4 mt-0.5 shrink-0 text-brand-amber"
aria-hidden
/>
))}
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <div className="flex min-w-0 items-center justify-between gap-1.5">
- <p className="text-mmd truncate">
+ <div className="flex min-w-0 flex-1 flex-col gap-0">
+ <div className="flex min-w-0 items-center justify-between gap-1.5 leading-4">
+ <p className="truncate text-xs font-medium leading-4">
Task {task.task_id.slice(0, 8)}...
</p>
- {!isExpanded && (
- <p className={statusPillClassName}>{statusLabel}</p>
- )}
+ <div className="flex shrink-0 items-center gap-1.5">
+ {!isExpanded && (
+ <p className={statusPillClassName}>{statusLabel}</p>
+ )}
+ <span onClick={(event) => event.stopPropagation()}>
+ {headerEnd}
+ </span>
+ </div>
</div>
- <p className="min-h-4 text-xxs leading-4 text-muted-foreground whitespace-nowrap">
+ <p className="text-xs leading-4 text-muted-foreground">
{formatTaskTimestamp(timestamp, mode, nowMs)}
</p>
</div>
@@ -206,14 +223,15 @@ export function TaskErrorContent({
>
<AccordionItem value="failed-files" className="border-0 rounded-none">
{accordionHeader}
- <AccordionContent className="w-full p-0 pt-2">
- <div className="flex w-full flex-col gap-2">
+ <AccordionContent className="w-full p-1 pt-1">
+ <div className="flex w-full flex-col gap-1">
{issueEntries.map(([filePath, fileInfo], index) => {
const fileName = getTaskFileName(filePath, fileInfo);
const line = resolveTaskFileError(fileInfo, task.error);
const componentCause = formatApiComponent(fileInfo.component);
const isWarning = isTaskFileWarning(fileInfo);
const isCancelled = isFileCancelled(fileInfo);
+ const isFirst = index === 0;
return (
<div
@@ -230,7 +248,7 @@ export function TaskErrorContent({
: "border-l-destructive",
)
: cn(
- "flex flex-col gap-1 rounded py-mmd px-4",
+ "flex flex-col gap-1 rounded p-2",
isCancelled
? "border border-muted bg-muted/50"
: isWarning
@@ -239,18 +257,21 @@ export function TaskErrorContent({
),
)}
>
- <p
- className={cn(
- "w-full truncate text-xs",
- isCancelled
- ? "font-normal text-muted-foreground"
- : isCloudBrand
- ? "font-normal text-foreground"
- : "font-semibold text-failure-file",
- )}
- >
- {fileName}
- </p>
+ <div className="flex min-w-0 w-full items-center gap-1">
+ <p
+ className={cn(
+ "min-w-0 flex-1 truncate text-xs",
+ isCancelled
+ ? "font-normal text-muted-foreground"
+ : isCloudBrand
+ ? "font-normal text-foreground"
+ : "font-semibold text-failure-file",
+ )}
+ >
+ {fileName}
+ </p>
+ {isFirst && openTaskDialogButton}
+ </div>
<p
className={cn(
"w-full truncate text-xs",
diff --git a/frontend/components/task-notification-menu.test.tsx b/frontend/components/task-notification-menu.test.tsx
index 8da13ff3b..08d08ff72 100644
--- a/frontend/components/task-notification-menu.test.tsx
+++ b/frontend/components/task-notification-menu.test.tsx
@@ -1,7 +1,9 @@
import { act, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest";
import type { Task } from "@/app/api/queries/useGetTasksQuery";
-import { renderWithProviders, screen } from "@/test-utils/render";
+import { server } from "@/test-utils/msw/server";
+import { renderWithProviders, screen, userEvent } from "@/test-utils/render";
import { TaskNotificationMenu } from "./task-notification-menu";
/**
@@ -84,6 +86,43 @@ describe("TaskNotificationMenu — cancelled task display", () => {
});
});
+describe("TaskNotificationMenu — task deletion controls", () => {
+ it("shows delete buttons for completed, failed, and cancelled tasks", () => {
+ mockTasks = [
+ makeTask({ task_id: "completed-task", status: "completed" }),
+ makeTask({ task_id: "failed-task", status: "failed" }),
+ makeTask({ task_id: "cancelled-task", status: "cancelled" }),
+ ];
+
+ renderWithProviders(<TaskNotificationMenu />);
+
+ expect(screen.getAllByRole("button", { name: "Delete task" })).toHaveLength(
+ 3,
+ );
+ });
+
+ it("calls DELETE /api/tasks/:id for a cancelled task", async () => {
+ const user = userEvent.setup();
+ let deletedId: string | undefined;
+ server.use(
+ http.delete("/api/tasks/:taskId", ({ params }) => {
+ deletedId = params.taskId as string;
+ return HttpResponse.json({});
+ }),
+ );
+
+ mockTasks = [makeTask({ task_id: "t-cancelled", status: "cancelled" })];
+ renderWithProviders(<TaskNotificationMenu />);
+
+ const deleteBtn = screen.getByRole("button", { name: "Delete task" });
+ await user.click(deleteBtn);
+
+ await waitFor(() => {
+ expect(deletedId).toBe("t-cancelled");
+ });
+ });
+});
+
describe("TaskNotificationMenu — cancellingTaskIds cleanup useEffect", () => {
it("removes a task from cancellingTaskIds when it transitions to cancelled", async () => {
// Start with a running task.
@@ -126,3 +165,114 @@ describe("TaskNotificationMenu — cancellingTaskIds cleanup useEffect", () => {
});
});
});
+
+describe("TaskNotificationMenu — delete mutations", () => {
+ it("calls DELETE /api/tasks when 'Clear all' is clicked", async () => {
+ const user = userEvent.setup();
+ let deleteAllCalled = false;
+ server.use(
+ http.delete("/api/tasks", () => {
+ deleteAllCalled = true;
+ return HttpResponse.json({ deleted_ids: [] });
+ }),
+ );
+
+ // The "Clear all" button appears only when there is at least one owned
+ // (non-shared) terminal task.
+ mockTasks = [makeTask({ task_id: "t-done", status: "completed" })];
+ renderWithProviders(<TaskNotificationMenu />);
+
+ const clearAllBtn = screen.getByRole("button", {
+ name: "Clear all past tasks",
+ });
+ await user.click(clearAllBtn);
+
+ await waitFor(() => {
+ expect(deleteAllCalled).toBe(true);
+ });
+ });
+
+ it("calls DELETE /api/tasks/:id when the delete button is clicked on a regular terminal task", async () => {
+ const user = userEvent.setup();
+ let deletedId: string | undefined;
+ server.use(
+ http.delete("/api/tasks/:taskId", ({ params }) => {
+ deletedId = params.taskId as string;
+ return HttpResponse.json({});
+ }),
+ );
+
+ mockTasks = [makeTask({ task_id: "t-completed", status: "completed" })];
+ renderWithProviders(<TaskNotificationMenu />);
+
+ const deleteBtn = screen.getByRole("button", { name: "Delete task" });
+ await user.click(deleteBtn);
+
+ await waitFor(() => {
+ expect(deletedId).toBe("t-completed");
+ });
+ });
+
+ it("calls DELETE /api/tasks/:id when the delete button is clicked inside a TaskErrorContent row", async () => {
+ const user = userEvent.setup();
+ let deletedId: string | undefined;
+ server.use(
+ http.delete("/api/tasks/:taskId", ({ params }) => {
+ deletedId = params.taskId as string;
+ return HttpResponse.json({});
+ }),
+ );
+
+ // A failed task with file-level error details renders the TaskErrorContent row
+ // which embeds its own delete button as headerEnd.
+ mockTasks = [
+ makeTask({
+ task_id: "t-failed",
+ status: "failed",
+ failed_files: 1,
+ files: {
+ "doc.pdf": { status: "failed", error: "Parse error" },
+ },
+ }),
+ ];
+ renderWithProviders(<TaskNotificationMenu />);
+
+ // The delete button inside the TaskErrorContent headerEnd
+ const deleteBtns = screen.getAllByRole("button", { name: "Delete task" });
+ await user.click(deleteBtns[0]);
+
+ await waitFor(() => {
+ expect(deletedId).toBe("t-failed");
+ });
+ });
+
+ it("hides 'Clear all' when every terminal task is shared", () => {
+ // Only shared tasks — "Clear all" must not appear because the backend
+ // bulk-delete only removes tasks owned by the calling user.
+ mockTasks = [
+ makeTask({ task_id: "shared-1", status: "completed", is_shared: true }),
+ makeTask({ task_id: "shared-2", status: "failed", is_shared: true }),
+ ];
+
+ renderWithProviders(<TaskNotificationMenu />);
+
+ expect(
+ screen.queryByRole("button", { name: "Clear all past tasks" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows 'Clear all' when at least one owned terminal task exists alongside shared ones", () => {
+ // Mix of owned and shared — "Clear all" should be present because there
+ // is at least one task the bulk-delete will actually remove.
+ mockTasks = [
+ makeTask({ task_id: "shared-1", status: "completed", is_shared: true }),
+ makeTask({ task_id: "owned-1", status: "completed", is_shared: false }),
+ ];
+
+ renderWithProviders(<TaskNotificationMenu />);
+
+ expect(
+ screen.getByRole("button", { name: "Clear all past tasks" }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/components/task-notification-menu.tsx b/frontend/components/task-notification-menu.tsx
index da994a97f..f73224fb9 100644
--- a/frontend/components/task-notification-menu.tsx
+++ b/frontend/components/task-notification-menu.tsx
@@ -1,8 +1,19 @@
"use client";
-import { Bell, CheckCircle, Clock, Loader2, XCircle } from "lucide-react";
+import {
+ Bell,
+ CheckCircle,
+ ChevronDown,
+ Clock,
+ Loader2,
+ X,
+ XCircle,
+} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
-import { StatusIcon } from "@/components/console-status";
+import {
+ useDeleteAllTerminalTasksMutation,
+ useDeleteTaskMutation,
+} from "@/app/api/mutations/useDeleteTaskMutation";
import { IncidentReporterIcon } from "@/components/icons/incident-reporter-icon";
import { TaskCollapsibleSection } from "@/components/task-collapsible-section";
import { TaskErrorContent } from "@/components/task-error-content";
@@ -21,15 +32,14 @@ import {
CardTitle,
} from "@/components/ui/card";
import { useIsCloudBrand } from "@/contexts/brand-context";
-import { useConsoleStatus } from "@/contexts/console-status-context";
import { Task, useTask } from "@/contexts/task-context";
import { formatRelative } from "@/lib/status-utils";
+import { hasIssueFileEntries, isCompletedTotalFailure } from "@/lib/task-utils";
import {
- hasIssueFileEntries,
- isCompletedTotalFailure,
- isTerminalFailedTask,
-} from "@/lib/task-utils";
-import { parseTimestampMs } from "@/lib/time-utils";
+ formatTaskTimestamp,
+ parseTimestamp,
+ parseTimestampMs,
+} from "@/lib/time-utils";
import { cn } from "@/lib/utils";
const getTaskIcon = (
@@ -141,7 +151,7 @@ const getStatusBadge = (
: "bg-brand-amber-10 text-brand-amber border-brand-amber-30",
)}
>
- Complete
+ Completed
</Badge>
);
}
@@ -155,7 +165,7 @@ const getStatusBadge = (
: "border border-green-500/20 bg-green-500/10 text-green-500",
)}
>
- Complete
+ Completed
</Badge>
);
case "failed":
@@ -238,7 +248,8 @@ export function TaskNotificationMenu() {
closeMenu,
openTaskDialog,
} = useTask();
- const { problems, open: openConsoleStatus } = useConsoleStatus();
+ const deleteTaskMutation = useDeleteTaskMutation();
+ const deleteAllMutation = useDeleteAllTerminalTasksMutation();
const [isPastOpen, setIsPastOpen] = useState(true);
const [cancellingTaskIds, setCancellingTaskIds] = useState<Set<string>>(
new Set(),
@@ -357,46 +368,14 @@ export function TaskNotificationMenu() {
<div className="flex flex-col h-full">
<TaskPanelHeader
activeCount={activeTasks.length}
+ terminalCount={terminalTasks.filter((t) => !t.is_shared).length}
isFetching={isFetching}
onClose={closeMenu}
+ onClearAll={() => deleteAllMutation.mutate()}
/>
{/* Content */}
<div className="flex-1 overflow-y-auto">
- {/* System Status events — a container / service is degraded or down.
- Clicking an event opens the Console Status panel. */}
- {problems.length > 0 && (
- <div className="flex flex-col gap-2 p-4">
- <h4 className="text-sm font-medium text-muted-foreground">
- System Status
- </h4>
- {problems.map((component) => {
- const isDown = component.status === "unhealthy";
- return (
- <button
- key={component.name}
- type="button"
- data-testid="system-status-event"
- onClick={() => openConsoleStatus()}
- className="w-full rounded-lg border border-muted p-3 text-left transition-colors hover:bg-muted/60"
- >
- <div className="flex items-center gap-2">
- <StatusIcon status={component.status} size={16} />
- <span className="text-sm font-medium">
- {component.display_name}{" "}
- {isDown ? "is down" : `is ${component.status}`}
- </span>
- </div>
- <p className="mt-1 text-xs text-muted-foreground">
- {component.message ||
- "Open Console Status for more details."}
- </p>
- </button>
- );
- })}
- </div>
- )}
-
{/* Active Tasks */}
{activeTasks.length > 0 && (
<div className="flex flex-col gap-2 p-4">
@@ -577,33 +556,47 @@ export function TaskNotificationMenu() {
const progress = formatTaskProgress(task);
const hasFailedFiles = hasIssueFileEntries(task);
const isTotalFailure = isCompletedTotalFailure(task);
- const dur = formatDuration(task.duration_seconds);
const shouldExpandDetails = selectedTaskId === task.task_id;
- // Same full card as total failure; partial only differs inside (Complete pill / amber icon).
- // Exclude cancelled tasks from failure rendering to preserve the cancelled badge
+ // Render detailed failure content only when file-level details exist.
if (
task.status !== "cancelled" &&
- (isTerminalFailedTask(task) ||
- isTotalFailure ||
- hasFailedFiles)
+ (isTotalFailure || hasFailedFiles)
) {
return (
- <TaskErrorContent
- key={
- shouldExpandDetails
- ? `${task.task_id}-${selectedTaskTrigger}`
- : task.task_id
- }
- task={task}
- mode="past"
- defaultExpanded={shouldExpandDetails}
- />
+ <div key={task.task_id} className="group/row">
+ <TaskErrorContent
+ key={
+ shouldExpandDetails
+ ? `${task.task_id}-${selectedTaskTrigger}`
+ : task.task_id
+ }
+ task={task}
+ mode="past"
+ defaultExpanded={shouldExpandDetails}
+ headerEnd={
+ <button
+ type="button"
+ aria-label="Delete task"
+ onClick={(event) => {
+ event.stopPropagation();
+ deleteTaskMutation.mutate(task.task_id);
+ }}
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-100 hover:bg-muted hover:text-foreground transition-colors focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <X className="size-4" />
+ </button>
+ }
+ />
+ </div>
);
}
return (
- <div key={task.task_id} className={pastTaskRowClass}>
+ <div
+ key={task.task_id}
+ className={`${pastTaskRowClass} group/row`}
+ >
<div className="flex items-start gap-3">
{!isCloudBrand && getTaskIcon(task.status)}
<div className="flex-1 min-w-0">
@@ -611,8 +604,11 @@ export function TaskNotificationMenu() {
Task {task.task_id.substring(0, 8)}...
</div>
<div className="text-xs text-muted-foreground">
- {formatRelative(task.updated_at)}
- {dur && <span className="ml-2">• {dur}</span>}
+ {formatTaskTimestamp(
+ parseTimestamp(task.updated_at),
+ "past",
+ Date.now(),
+ )}
</div>
{task.status === "completed" && progress?.detailed && (
<div className="text-xs text-muted-foreground">
@@ -624,8 +620,19 @@ export function TaskNotificationMenu() {
</div>
)}
</div>
- <div className="self-start pt-0.5">
+ <div className="self-start pt-0.5 flex items-center gap-1.5 shrink-0">
{getStatusBadge(task.status, isCloudBrand)}
+ <button
+ type="button"
+ aria-label="Delete task"
+ onClick={(event) => {
+ event.stopPropagation();
+ deleteTaskMutation.mutate(task.task_id);
+ }}
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-100 hover:bg-muted hover:text-foreground transition-colors focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <X className="size-4" />
+ </button>
</div>
</div>
</div>
@@ -635,20 +642,18 @@ export function TaskNotificationMenu() {
</div>
{/* Empty State */}
- {activeTasks.length === 0 &&
- terminalTasks.length === 0 &&
- problems.length === 0 && (
- <div className="p-8 text-center">
- <Bell className="h-12 w-12 text-muted-foreground/50 mx-auto mb-4" />
- <h4 className="text-sm font-medium text-muted-foreground mb-2">
- No tasks yet
- </h4>
- <p className="text-xs text-muted-foreground">
- Task notifications will appear here when you upload files or
- sync connectors.
- </p>
- </div>
- )}
+ {activeTasks.length === 0 && terminalTasks.length === 0 && (
+ <div className="p-8 text-center">
+ <Bell className="h-12 w-12 text-muted-foreground/50 mx-auto mb-4" />
+ <h4 className="text-sm font-medium text-muted-foreground mb-2">
+ No tasks yet
+ </h4>
+ <p className="text-xs text-muted-foreground">
+ Task notifications will appear here when you upload files or
+ sync connectors.
+ </p>
+ </div>
+ )}
</div>
</div>
</div>
diff --git a/frontend/components/task-panel-header.tsx b/frontend/components/task-panel-header.tsx
index 495edb78a..cb0078e76 100644
--- a/frontend/components/task-panel-header.tsx
+++ b/frontend/components/task-panel-header.tsx
@@ -6,14 +6,18 @@ import { Button } from "@/components/ui/button";
interface TaskPanelHeaderProps {
activeCount?: number;
+ terminalCount?: number;
isFetching?: boolean;
onClose: () => void;
+ onClearAll?: () => void;
}
export function TaskPanelHeader({
activeCount = 0,
+ terminalCount = 0,
isFetching = false,
onClose,
+ onClearAll,
}: TaskPanelHeaderProps) {
return (
<div className="p-4 border-t border-muted" data-testid="tasks-panel-header">
@@ -32,15 +36,28 @@ export function TaskPanelHeader({
</Badge>
)}
</div>
- <Button
- variant="ghost"
- size="sm"
- className="h-8 w-8 p-0"
- onClick={onClose}
- aria-label="Close task panel"
- >
- <X className="h-4 w-4" />
- </Button>
+ <div className="flex items-center gap-1">
+ {onClearAll && terminalCount > 0 && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
+ onClick={onClearAll}
+ aria-label="Clear all past tasks"
+ >
+ Clear all
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 w-8 p-0"
+ onClick={onClose}
+ aria-label="Close task panel"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
</div>
</div>
);
diff --git a/frontend/tests/core/tasks-menu.spec.ts b/frontend/tests/core/tasks-menu.spec.ts
index 929ea6986..5b61d7cc7 100644
--- a/frontend/tests/core/tasks-menu.spec.ts
+++ b/frontend/tests/core/tasks-menu.spec.ts
@@ -126,7 +126,7 @@ test.describe("Tasks Menu Functionality @33219224 , @34581216", () => {
// Check task status for docling.pdf
let result1 = await tasksMenu.waitForTaskCompletionAndGetLog();
- if (result1.status === "Complete" || result1.status === "COMPLETED") {
+ if (result1.status === "Completed") {
logger.info(`✅ SUCCESS: ${file1} - ${result1.statusLine}`);
} else {
logger.info(`❌ FAILED: ${file1} - ${result1.statusLine}`);
@@ -173,7 +173,7 @@ test.describe("Tasks Menu Functionality @33219224 , @34581216", () => {
// Check task status for industry.csv
let result2 = await tasksMenu.waitForTaskCompletionAndGetLog();
- if (result2.status === "Complete" || result2.status === "COMPLETED") {
+ if (result2.status === "Completed") {
logger.info(`✅ SUCCESS: ${file2} - ${result2.statusLine}`);
} else {
logger.info(`❌ FAILED: ${file2} - ${result2.statusLine}`);
@@ -193,14 +193,8 @@ test.describe("Tasks Menu Functionality @33219224 , @34581216", () => {
// Close Tasks Menu
await tasksMenu.close();
- expect(
- result1.status === "Complete" || result1.status === "COMPLETED",
- result1.statusLine,
- ).toBe(true);
- expect(
- result2.status === "Complete" || result2.status === "COMPLETED",
- result2.statusLine,
- ).toBe(true);
+ expect(result1.status === "Completed", result1.statusLine).toBe(true);
+ expect(result2.status === "Completed", result2.statusLine).toBe(true);
});
// test('Negative: Cancel file upload from Tasks Menu and verify failed status', async ({ page, knowledge }) => {
diff --git a/frontend/tests/pages/TasksMenu.ts b/frontend/tests/pages/TasksMenu.ts
index c28274aa6..28b76f2e2 100644
--- a/frontend/tests/pages/TasksMenu.ts
+++ b/frontend/tests/pages/TasksMenu.ts
@@ -95,7 +95,7 @@ export class TasksMenu {
*/
async verifyTaskFailed(filename: string) {
const completedBadge = this.page
- .getByText("Complete", { exact: true })
+ .getByText("Completed", { exact: true })
.first();
const failedBadge = this.page.getByText("FAILED", { exact: true }).first();
@@ -126,14 +126,12 @@ export class TasksMenu {
* Waits for a task to complete (or fail) and returns the status and failure log (if any).
*/
async waitForTaskCompletionAndGetLog(): Promise<{
- status: "Complete" | "COMPLETED" | "FAILED";
+ status: "Completed" | "FAILED";
statusLine: string;
failureLog: string;
}> {
- // Match both "Complete" and "COMPLETED" (case-insensitive)
- const completedBadge = this.page
- .getByText(/^(Complete|COMPLETED)$/i)
- .first();
+ // Match "Completed" badge text (the UI renders "Completed", not "Complete")
+ const completedBadge = this.page.getByText(/^Completed$/i).first();
const failedBadge = this.page.getByText(/^(Failed|FAILED)$/i).first();
// Wait for either badge to appear - use .first() to avoid strict mode violation
@@ -179,11 +177,7 @@ export class TasksMenu {
}
return {
- status: isCompleted
- ? (((await completedBadge.textContent()) || "Complete") as
- | "Complete"
- | "COMPLETED")
- : "FAILED",
+ status: isCompleted ? "Completed" : "FAILED",
statusLine,
failureLog,
};
diff --git a/src/api/tasks.py b/src/api/tasks.py
index 928ad0efb..1b81acc5c 100644
--- a/src/api/tasks.py
+++ b/src/api/tasks.py
@@ -3,10 +3,27 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from dependencies import get_current_user, get_task_service
+from models.tasks import TaskDeleteResult
from session_manager import User
from utils.telemetry import Category, MessageId, TelemetryClient
+class _DeletedTaskResponse(BaseModel):
+ status: str = Field("deleted", description="Always 'deleted' on success.")
+ task_id: str = Field(description="ID of the deleted task.")
+
+
+class _TaskNotFoundResponse(BaseModel):
+ error: str = Field("Task not found", description="Task ID does not exist.")
+
+
+class _TaskInProgressResponse(BaseModel):
+ error: str = Field(
+ "Task is still in progress",
+ description="Task exists but has not reached a terminal state yet.",
+ )
+
+
async def task_status(
task_id: str,
task_service=Depends(get_task_service),
@@ -119,3 +136,28 @@ async def cancel_file(
await TelemetryClient.send_event(Category.TASK_OPERATIONS, MessageId.ORB_TASK_CANCELLED)
return JSONResponse({"status": "cancelled", "task_id": task_id, "file_path": body.file_path})
+
+
+async def delete_task(
+ task_id: str,
+ task_service=Depends(get_task_service),
+ user: User = Depends(get_current_user),
+):
+ """Permanently delete a terminal (completed/failed) task from the task store."""
+ result = task_service.delete_task(user.user_id, task_id)
+ if result is TaskDeleteResult.NOT_FOUND:
+ return JSONResponse({"error": "Task not found"}, status_code=404)
+ if result is TaskDeleteResult.IN_PROGRESS:
+ return JSONResponse({"error": "Task is still in progress"}, status_code=409)
+ return JSONResponse({"status": "deleted", "task_id": task_id})
+
+
+async def delete_all_terminal_tasks(
+ task_service=Depends(get_task_service),
+ user: User = Depends(get_current_user),
+):
+ """Delete all completed/failed tasks visible to the authenticated user."""
+ deleted_ids = task_service.delete_all_terminal_tasks(user.user_id)
+ return JSONResponse(
+ {"status": "deleted", "count": len(deleted_ids), "deleted_ids": deleted_ids}
+ )
diff --git a/src/app/routes/internal.py b/src/app/routes/internal.py
index d311eb580..22a435e84 100644
--- a/src/app/routes/internal.py
+++ b/src/app/routes/internal.py
@@ -131,6 +131,23 @@ def register_internal_routes(app: FastAPI):
methods=["POST"],
tags=["internal"],
)
+ app.add_api_route(
+ "/tasks/{task_id}",
+ tasks.delete_task,
+ methods=["DELETE"],
+ tags=["internal"],
+ responses={
+ 200: {"model": tasks._DeletedTaskResponse},
+ 404: {"model": tasks._TaskNotFoundResponse},
+ 409: {"model": tasks._TaskInProgressResponse},
+ },
+ )
+ app.add_api_route(
+ "/tasks",
+ tasks.delete_all_terminal_tasks,
+ methods=["DELETE"],
+ tags=["internal"],
+ )
app.add_api_route(
"/tasks/{task_id}/files/cancel",
tasks.cancel_file,
diff --git a/src/models/tasks.py b/src/models/tasks.py
index fac095e33..233bed351 100644
--- a/src/models/tasks.py
+++ b/src/models/tasks.py
@@ -20,6 +20,14 @@ class TaskStatus(Enum):
SKIPPED = "skipped"
+class TaskDeleteResult(Enum):
+ """Outcome of a single-task delete attempt."""
+
+ DELETED = "deleted"
+ NOT_FOUND = "not_found"
+ IN_PROGRESS = "in_progress"
+
+
class DoclingPhaseStatus(Enum):
"""Tracks the state of the Docling conversion sub-phase for a single file."""
diff --git a/src/services/task_service.py b/src/services/task_service.py
index a867c99f0..931eb9e6f 100644
--- a/src/services/task_service.py
+++ b/src/services/task_service.py
@@ -8,7 +8,14 @@ import uuid
from collections.abc import Coroutine
from typing import Any, TypeVar
-from models.tasks import DoclingPhaseStatus, FileTask, IngestionPhase, TaskStatus, UploadTask
+from models.tasks import (
+ DoclingPhaseStatus,
+ FileTask,
+ IngestionPhase,
+ TaskDeleteResult,
+ TaskStatus,
+ UploadTask,
+)
from session_manager import AnonymousUser
from utils.gpu_detection import get_worker_count
from utils.logging_config import get_logger
@@ -1458,6 +1465,8 @@ class TaskService:
"""
tasks_by_id = {}
+ is_shared = False
+
def add_tasks_from_store(store_user_id):
if store_user_id not in self.task_store:
return
@@ -1500,9 +1509,11 @@ class TaskService:
"updated_at": upload_task.updated_at,
"duration_seconds": upload_task.duration_seconds,
"files": file_statuses,
+ "is_shared": is_shared,
}
add_tasks_from_store(user_id)
+ is_shared = True
add_tasks_from_store(AnonymousUser().user_id)
tasks = list(tasks_by_id.values())
@@ -1518,6 +1529,8 @@ class TaskService:
"""
tasks_by_id = {}
+ is_shared = False
+
def add_tasks_from_store(store_user_id):
if store_user_id not in self.task_store:
return
@@ -1564,10 +1577,12 @@ class TaskService:
"updated_at": upload_task.updated_at,
"duration_seconds": upload_task.duration_seconds,
"files": file_statuses,
+ "is_shared": is_shared,
}
# First, add user-owned tasks; then shared anonymous;
add_tasks_from_store(user_id)
+ is_shared = True
add_tasks_from_store(AnonymousUser().user_id)
tasks = list(tasks_by_id.values())
@@ -1762,6 +1777,62 @@ class TaskService:
return True
+ def delete_task(self, user_id: str, task_id: str) -> TaskDeleteResult:
+ """Remove a terminal (completed/failed/cancelled) task from memory.
+
+ Deletes tasks owned by the calling user or shared anonymous tasks that
+ are visible to the user (same set exposed by get_all_tasks).
+
+ Returns:
+ TaskDeleteResult.DELETED – task found and removed.
+ TaskDeleteResult.NOT_FOUND – task ID does not exist for this user.
+ TaskDeleteResult.IN_PROGRESS – task exists but is not yet terminal.
+ """
+ resolved = self._resolve_upload_task_store(user_id, task_id)
+ if resolved is None:
+ return TaskDeleteResult.NOT_FOUND
+ store_user_id, upload_task = resolved
+ if upload_task.status not in [
+ TaskStatus.COMPLETED,
+ TaskStatus.FAILED,
+ TaskStatus.CANCELLED,
+ ]:
+ return TaskDeleteResult.IN_PROGRESS
+ self._cleanup_upload_temp_files(upload_task, force=True)
+ del self.task_store[store_user_id][task_id]
+ self._task_locks.pop(task_id, None)
+ if not self.task_store[store_user_id]:
+ del self.task_store[store_user_id]
+ return TaskDeleteResult.DELETED
+
+ def delete_all_terminal_tasks(self, user_id: str) -> list[str]:
+ """Remove all completed/failed/cancelled tasks owned by a user.
+
+ Only touches the calling user's own store. Shared tasks stored under
+ the anonymous key are intentionally excluded: they are visible to all
+ authenticated users, so a bulk clear by one user must not remove them
+ for everyone else. Those tasks are aged out by cleanup_old_tasks.
+
+ Returns the list of deleted task IDs.
+ """
+ if user_id not in self.task_store:
+ return []
+
+ to_delete = [
+ tid
+ for tid, t in self.task_store[user_id].items()
+ if t.status in [TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED]
+ ]
+ for tid in to_delete:
+ task = self.task_store[user_id][tid]
+ self._cleanup_upload_temp_files(task, force=True)
+ del self.task_store[user_id][tid]
+ self._task_locks.pop(tid, None)
+ if not self.task_store.get(user_id):
+ self.task_store.pop(user_id, None)
+
+ return to_delete
+
def _file_task_for_temp_path(self, upload_task: UploadTask, temp_path: str) -> FileTask | None:
"""Resolve the FileTask for a staged upload temp path."""
file_task = upload_task.file_tasks.get(temp_path)
diff --git a/tests/unit/test_task_service.py b/tests/unit/test_task_service.py
index 5ae68739a..62b787ef3 100644
--- a/tests/unit/test_task_service.py
+++ b/tests/unit/test_task_service.py
@@ -324,3 +324,140 @@ def test_enhanced_keeps_completed_files_for_preview_tasks(task_service):
assert "fileA" in files # completed retained for preview
assert files["fileA"]["status"] == "completed"
assert "fileB" in files
+
+
+# ---------------------------------------------------------------------------
+# delete_task
+# ---------------------------------------------------------------------------
+
+
+def _make_terminal_task(task_id: str, status: TaskStatus) -> UploadTask:
+ return UploadTask(
+ task_id=task_id,
+ total_files=1,
+ file_tasks={"f": FileTask(file_path="f", status=status)},
+ status=status,
+ )
+
+
+def test_delete_task_returns_deleted_for_completed(task_service):
+ task = _make_terminal_task("t1", TaskStatus.COMPLETED)
+ task_service.task_store["user1"] = {"t1": task}
+ from models.tasks import TaskDeleteResult
+
+ assert task_service.delete_task("user1", "t1") is TaskDeleteResult.DELETED
+ assert "t1" not in task_service.task_store.get("user1", {})
+
+
+def test_delete_task_returns_deleted_for_failed(task_service):
+ task = _make_terminal_task("t2", TaskStatus.FAILED)
+ task_service.task_store["user1"] = {"t2": task}
+ from models.tasks import TaskDeleteResult
+
+ assert task_service.delete_task("user1", "t2") is TaskDeleteResult.DELETED
+ assert "user1" not in task_service.task_store # store entry pruned when empty
+
+
+def test_delete_task_returns_not_found_for_absent_task(task_service):
+ from models.tasks import TaskDeleteResult
+
+ assert task_service.delete_task("user1", "nonexistent") is TaskDeleteResult.NOT_FOUND
+
+
+def test_delete_task_returns_in_progress_for_running_task(task_service):
+ task = _make_terminal_task("t3", TaskStatus.RUNNING)
+ task_service.task_store["user1"] = {"t3": task}
+ from models.tasks import TaskDeleteResult
+
+ assert task_service.delete_task("user1", "t3") is TaskDeleteResult.IN_PROGRESS
+ assert "t3" in task_service.task_store["user1"] # must not be removed
+
+
+def test_delete_task_returns_in_progress_for_pending_task(task_service):
+ task = _make_terminal_task("t4", TaskStatus.PENDING)
+ task_service.task_store["user1"] = {"t4": task}
+ from models.tasks import TaskDeleteResult
+
+ assert task_service.delete_task("user1", "t4") is TaskDeleteResult.IN_PROGRESS
+
+
+def test_delete_task_removes_lock(task_service):
+ import asyncio
+
+ task = _make_terminal_task("t5", TaskStatus.COMPLETED)
+ task_service.task_store["user1"] = {"t5": task}
+ task_service._task_locks["t5"] = asyncio.Lock()
+ from models.tasks import TaskDeleteResult
+
+ assert task_service.delete_task("user1", "t5") is TaskDeleteResult.DELETED
+ assert "t5" not in task_service._task_locks
+
+
+def test_delete_task_resolves_anonymous_shared_task(task_service):
+ """delete_task must find tasks stored under the anonymous key."""
+ from models.tasks import TaskDeleteResult
+ from session_manager import AnonymousUser
+
+ anon_id = AnonymousUser().user_id
+ task = _make_terminal_task("shared1", TaskStatus.COMPLETED)
+ task_service.task_store[anon_id] = {"shared1": task}
+ assert task_service.delete_task("real_user", "shared1") is TaskDeleteResult.DELETED
+ assert "shared1" not in task_service.task_store.get(anon_id, {})
+
+
+# ---------------------------------------------------------------------------
+# delete_all_terminal_tasks
+# ---------------------------------------------------------------------------
+
+
+def test_delete_all_terminal_tasks_removes_only_terminal(task_service):
+ completed = _make_terminal_task("c1", TaskStatus.COMPLETED)
+ failed = _make_terminal_task("f1", TaskStatus.FAILED)
+ running = _make_terminal_task("r1", TaskStatus.RUNNING)
+ task_service.task_store["user1"] = {"c1": completed, "f1": failed, "r1": running}
+
+ deleted = task_service.delete_all_terminal_tasks("user1")
+
+ assert set(deleted) == {"c1", "f1"}
+ assert "r1" in task_service.task_store["user1"]
+ assert "c1" not in task_service.task_store.get("user1", {})
+ assert "f1" not in task_service.task_store.get("user1", {})
+
+
+def test_delete_all_terminal_tasks_returns_empty_for_unknown_user(task_service):
+ assert task_service.delete_all_terminal_tasks("nobody") == []
+
+
+def test_delete_all_terminal_tasks_prunes_empty_user_store(task_service):
+ task = _make_terminal_task("c1", TaskStatus.COMPLETED)
+ task_service.task_store["user1"] = {"c1": task}
+ task_service.delete_all_terminal_tasks("user1")
+ assert "user1" not in task_service.task_store
+
+
+def test_delete_all_terminal_tasks_does_not_touch_anonymous_store(task_service):
+ """Bulk clear must not remove shared anonymous tasks — they are visible to
+ all authenticated users and are only aged out by cleanup_old_tasks."""
+ from session_manager import AnonymousUser
+
+ anon_id = AnonymousUser().user_id
+ anon_task = _make_terminal_task("anon1", TaskStatus.COMPLETED)
+ own_task = _make_terminal_task("own1", TaskStatus.COMPLETED)
+ task_service.task_store[anon_id] = {"anon1": anon_task}
+ task_service.task_store["user1"] = {"own1": own_task}
+
+ deleted = task_service.delete_all_terminal_tasks("user1")
+
+ assert deleted == ["own1"]
+ # shared anonymous task must still be present
+ assert "anon1" in task_service.task_store[anon_id]
+
+
+def test_delete_all_terminal_tasks_removes_lock(task_service):
+ import asyncio
+
+ task = _make_terminal_task("c2", TaskStatus.COMPLETED)
+ task_service.task_store["user1"] = {"c2": task}
+ task_service._task_locks["c2"] = asyncio.Lock()
+ task_service.delete_all_terminal_tasks("user1")
+ assert "c2" not in task_service._task_locks