diff --git a/docs/guide/mcp.md b/docs/guide/mcp.md index f44b4552ae..1340b574a6 100644 --- a/docs/guide/mcp.md +++ b/docs/guide/mcp.md @@ -97,7 +97,7 @@ explicit, model-selected MCP tool path can run alongside the separate automatic OpenViking memory backend; it does not replace automatic turn capture or recall. See the [OpenViking MCP tools configuration](../../backend/docs/MCP_SERVER.md#openviking-mcp-tools). -The Gateway can adapt an MCP server's ordinary `submit` / `status` / `cancel` tools into durable background tasks. The Agent sees only the configured submit tool and a DeerFlow-local task ID; remote IDs are persisted before the submit call returns, while status and cancel stay internal to the runtime. Polling uses cross-worker leases, exponential retry backoff, scoped MCP sessions, bounded result storage, and restart recovery. A status-tool `isError` is retained as a bounded diagnostic and retried; servers report a permanent remote-task outcome through a normal structured result with `status: "failed"`. Remote poll hints are finite positive numbers capped at 24 hours, artifact-reference JSON is limited to 64 KiB, and task/server identifiers are validated against their durable SQL column limits before persistence. Input-required and terminal updates wake the current chat through idempotent Agent runs, while `list_background_tasks` and `cancel_background_task` let the Agent manage tasks without asking users for remote handles. Current-thread tasks are available through `GET /api/threads/{thread_id}/mcp-tasks`, its detail endpoint, and `POST /api/threads/{thread_id}/mcp-tasks/{task_id}/cancel`; when the task runtime actually starts, the Web UI exposes the same safe local view from the chat header with live status refresh, cancellation, and on-demand result, artifact, input-request, status-error, and cancellation-retry details. Default-disabled and memory-backend deployments hide that UI and do not poll the task endpoints. A failed remote cancellation remains queued with backoff, and its latest bounded error and attempt count stay visible in the expanded task card. Enable `mcp_tasks` in `config.yaml`, configure `task_toolsets` with exact raw tool names in `extensions_config.json`, and use a SQL database backend (`sqlite` or `postgres`). Task-enabled server connection, authentication, interceptor, timeout, or binding changes require a Gateway restart so Agent tool discovery and background calls cannot use different configuration versions. `input_required` is notification-only for now: DeerFlow can display the request but cannot yet submit the user's answer back to the remote task. +The Gateway can adapt an MCP server's ordinary `submit` / `status` / `cancel` tools into durable background tasks. The Agent sees only the configured submit tool and a DeerFlow-local task ID; remote IDs are persisted before the submit call returns, while status and cancel stay internal to the runtime. Polling uses cross-worker leases, exponential retry backoff, scoped MCP sessions, bounded result storage, and restart recovery. A status-tool `isError` is retained as a bounded diagnostic and retried; servers report a permanent remote-task outcome through a normal structured result with `status: "failed"`. Remote poll hints are finite positive numbers capped at 24 hours, artifact-reference JSON is limited to 64 KiB, and task/server identifiers are validated against their durable SQL column limits before persistence. Input-required and terminal updates wake the current chat through idempotent Agent runs, while `list_background_tasks` and `cancel_background_task` let the Agent manage tasks without asking users for remote handles. Current-thread tasks are available through `GET /api/threads/{thread_id}/mcp-tasks`, its detail endpoint, and `POST /api/threads/{thread_id}/mcp-tasks/{task_id}/cancel`; when the task runtime actually starts, the Web UI exposes the same safe local view from the chat header with live status refresh, cancellation, and on-demand result, artifact, input-request, status-error, and cancellation-retry details. Confirmed Web UI cancellations remain visible when older task-list or detail requests finish, including after the task panel closes. Cancelling one task aborts its older list/detail requests while other task details continue loading. Default-disabled and memory-backend deployments hide that UI and do not poll the task endpoints. A failed remote cancellation remains queued with backoff, and its latest bounded error and attempt count stay visible in the expanded task card. Enable `mcp_tasks` in `config.yaml`, configure `task_toolsets` with exact raw tool names in `extensions_config.json`, and use a SQL database backend (`sqlite` or `postgres`). Task-enabled server connection, authentication, interceptor, timeout, or binding changes require a Gateway restart so Agent tool discovery and background calls cannot use different configuration versions. `input_required` is notification-only for now: DeerFlow can display the request but cannot yet submit the user's answer back to the remote task. For deployment-level HTTP/SSE servers with `task_toolsets`, discovery, ordinary tools, and background task calls share OAuth token state within one Gateway diff --git a/frontend/src/core/background-tasks/AGENTS.md b/frontend/src/core/background-tasks/AGENTS.md index 77496c4c28..48a6da23bd 100644 --- a/frontend/src/core/background-tasks/AGENTS.md +++ b/frontend/src/core/background-tasks/AGENTS.md @@ -1,6 +1,13 @@ # Background-task queries (`core/background-tasks/`) -A poll that started before a cancel was answered must not undo the cancel. The -mutation drops the thread's background-task reads first, then seeds the -confirmed detail and list entry, then invalidates the list. `core/memory` -follows the same order. Test it with a real `QueryClient`. +On a successful cancel, await cancellation of the exact thread list and target +detail queries before writing the confirmed result to either cache. Then +invalidate only the exact list. Other task details keep loading. Both GETs pass +TanStack Query's `AbortSignal` to `fetch`. Callers that omit the signal keep the +single-argument `fetch` call. `core/memory` follows the same cache update order. + +`frontend/tests/unit/core/background-tasks/hooks.dom.test.tsx` exercises the +cache updates with a real `QueryClient`. The sibling `cancellation-http.dom.test.tsx` +covers closed panels, HTTP aborts, cached and initial reads, isolation between +tasks and threads, and failed cancellations. An uncached list stays undefined +until a fresh list GET succeeds. diff --git a/frontend/src/core/background-tasks/api.ts b/frontend/src/core/background-tasks/api.ts index 8345e56d15..bccd59f31f 100644 --- a/frontend/src/core/background-tasks/api.ts +++ b/frontend/src/core/background-tasks/api.ts @@ -10,8 +10,11 @@ function threadTasksUrl(threadId: string, path = ""): string { export async function fetchBackgroundTasks( threadId: string, + signal?: AbortSignal, ): Promise { - const response = await fetch(`${threadTasksUrl(threadId)}?limit=20`); + const url = `${threadTasksUrl(threadId)}?limit=20`; + // Preserve the single-argument fetch call for callers that omit the signal. + const response = signal ? await fetch(url, { signal }) : await fetch(url); if (!response.ok) { await throwGatewayApiError( response, @@ -24,10 +27,11 @@ export async function fetchBackgroundTasks( export async function fetchBackgroundTask( threadId: string, taskId: string, + signal?: AbortSignal, ): Promise { - const response = await fetch( - threadTasksUrl(threadId, `/${encodeURIComponent(taskId)}`), - ); + const url = threadTasksUrl(threadId, `/${encodeURIComponent(taskId)}`); + // Preserve the single-argument fetch call for callers that omit the signal. + const response = signal ? await fetch(url, { signal }) : await fetch(url); if (!response.ok) { await throwGatewayApiError( response, diff --git a/frontend/src/core/background-tasks/hooks.ts b/frontend/src/core/background-tasks/hooks.ts index 5a2a2fe022..c9d775a452 100644 --- a/frontend/src/core/background-tasks/hooks.ts +++ b/frontend/src/core/background-tasks/hooks.ts @@ -25,7 +25,7 @@ export function useBackgroundTasks( ) { return useQuery({ queryKey: backgroundTasksQueryKey(threadId), - queryFn: () => fetchBackgroundTasks(threadId), + queryFn: ({ signal }) => fetchBackgroundTasks(threadId, signal), enabled: options.enabled !== false && Boolean(threadId), refetchInterval: (query) => query.state.data?.some(isActiveBackgroundTask) ? 3000 : 15000, @@ -40,7 +40,7 @@ export function useBackgroundTask( ) { return useQuery({ queryKey: backgroundTaskQueryKey(threadId, taskId), - queryFn: () => fetchBackgroundTask(threadId, taskId), + queryFn: ({ signal }) => fetchBackgroundTask(threadId, taskId, signal), enabled: options.enabled !== false && Boolean(threadId) && Boolean(taskId), refetchInterval: (query) => query.state.data && shouldPollBackgroundTaskDetail(query.state.data) @@ -56,13 +56,18 @@ export function useCancelBackgroundTask(threadId: string) { return useMutation({ mutationFn: (taskId: string) => cancelBackgroundTask(threadId, taskId), onSuccess: async (task) => { - // This thread's task list and detail reads poll the same caches the - // confirmation is about to seed. A read that started before the cancel - // answered must not land afterwards and put the card back to "working" - // (#7177); same ordering contract as the memory mutations (#6959). - await queryClient.cancelQueries({ - queryKey: backgroundTasksQueryKey(threadId), - }); + // Fence older reads before seeding either cache, including queries whose + // panels closed while cancellation was in flight. + await Promise.all([ + queryClient.cancelQueries({ + queryKey: backgroundTasksQueryKey(threadId), + exact: true, + }), + queryClient.cancelQueries({ + queryKey: backgroundTaskQueryKey(threadId, task.task_id), + exact: true, + }), + ]); queryClient.setQueryData( backgroundTaskQueryKey(threadId, task.task_id), task, @@ -83,6 +88,7 @@ export function useCancelBackgroundTask(threadId: string) { ); void queryClient.invalidateQueries({ queryKey: backgroundTasksQueryKey(threadId), + exact: true, }); }, onError: (error: Error) => { diff --git a/frontend/tests/unit/core/background-tasks/cancellation-http.dom.test.tsx b/frontend/tests/unit/core/background-tasks/cancellation-http.dom.test.tsx new file mode 100644 index 0000000000..edc1faf8ef --- /dev/null +++ b/frontend/tests/unit/core/background-tasks/cancellation-http.dom.test.tsx @@ -0,0 +1,243 @@ +import { afterEach, expect, rs, test } from "@rstest/core"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import type { ReactNode } from "react"; + +import { fetch } from "@/core/api/fetcher"; +import { + backgroundTaskQueryKey, + backgroundTasksQueryKey, + useBackgroundTask, + useBackgroundTasks, + useCancelBackgroundTask, +} from "@/core/background-tasks/hooks"; +import type { BackgroundTaskDetail } from "@/core/background-tasks/types"; + +rs.mock("@/core/api/fetcher", () => ({ fetch: rs.fn() })); +rs.mock("@/core/config", () => ({ getBackendBaseURL: () => "" })); +rs.mock("@/core/i18n/hooks", () => ({ + useI18n: () => ({ + t: { backgroundTasks: { cancelFailed: "Cancel failed" } }, + }), +})); +rs.mock("sonner", () => ({ toast: { error: rs.fn() } })); + +const working: BackgroundTaskDetail = { + task_id: "task-1", + task_name: "Generate report", + status: "working", + created_at: "2026-08-08T00:00:00Z", + updated_at: "2026-08-08T00:00:01Z", + error: null, + tracking_degraded: false, + cancel_requested: false, + last_polled_at: null, + last_poll_error: null, + last_cancel_error: null, + cancel_attempt_count: 0, + notification_status: "none", + notification_error: null, + notification_attempt_count: 0, + result: null, + result_preview: null, + result_truncated: false, + result_artifact: null, + input_required: null, +}; +const cancelled: BackgroundTaskDetail = { + ...working, + status: "cancelled", + cancel_requested: true, +}; + +function jsonResponse(value: unknown, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +const clients: QueryClient[] = []; +function setupClient() { + const client = new QueryClient({ + defaultOptions: { + queries: { retry: false, gcTime: Infinity }, + mutations: { retry: false, gcTime: Infinity }, + }, + }); + clients.push(client); + function wrapper({ children }: { children: ReactNode }) { + return ( + {children} + ); + } + return { client, wrapper }; +} + +afterEach(() => { + cleanup(); + for (const client of clients.splice(0)) client.clear(); + rs.resetAllMocks(); +}); + +for (const { scope, cached } of [ + { scope: "detail", cached: true }, + { scope: "detail", cached: false }, + { scope: "list", cached: true }, + { scope: "list", cached: false }, +] as const) { + test(`a delayed ${cached ? "cached" : "initial"} ${scope} read cannot undo cancellation after the panel closes`, async () => { + const delayed = deferred(); + const before = scope === "detail" ? working : [working]; + const confirmed = scope === "detail" ? cancelled : [cancelled]; + // An unloaded list is populated only by a fresh list GET. + const expectedAfterCancel = + scope === "list" && !cached ? undefined : confirmed; + rs.mocked(fetch).mockImplementation((_url, init) => + init?.method === "POST" + ? Promise.resolve(jsonResponse(cancelled)) + : delayed.promise, + ); + const { client, wrapper } = setupClient(); + const key = + scope === "detail" + ? backgroundTaskQueryKey("thread-1", working.task_id) + : backgroundTasksQueryKey("thread-1"); + if (cached) client.setQueryData(key, before); + const { result, rerender } = renderHook( + ({ enabled }) => ({ + detail: useBackgroundTask("thread-1", working.task_id, { + enabled: enabled && scope === "detail", + }), + list: useBackgroundTasks("thread-1", { + enabled: enabled && scope === "list", + }), + cancel: useCancelBackgroundTask("thread-1"), + }), + { initialProps: { enabled: true }, wrapper }, + ); + await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1)); + // The cancel request can finish after the user closes the panel. Disabled + // queries are not refetched by invalidation, so it cannot fence this GET. + rerender({ enabled: false }); + await act(async () => { + await result.current.cancel.mutateAsync(working.task_id); + }); + expect(client.getQueryData(key)).toEqual(expectedAfterCancel); + + await act(async () => { + // Deliberately ignore transport abort to verify the cache fence as well. + delayed.resolve(jsonResponse(before)); + await delayed.promise; + }); + expect(client.getQueryData(key)).toEqual(expectedAfterCancel); + + // A later legitimate refresh still updates the cache. + rs.mocked(fetch).mockResolvedValue(jsonResponse(confirmed)); + rerender({ enabled: true }); + await waitFor(() => expect(fetch).toHaveBeenCalledTimes(3)); + await waitFor(() => + expect(client.getQueryState(key)?.fetchStatus).toBe("idle"), + ); + expect(client.getQueryData(key)).toEqual(confirmed); + }); +} + +test("cancellation aborts both HTTP reads and preserves sibling tasks and other threads", async () => { + const delayedReads: { + url: string; + signal: AbortSignal | null | undefined; + resolve: (value: Response) => void; + }[] = []; + rs.mocked(fetch).mockImplementation((url, init) => { + if (init?.method === "POST") + return Promise.resolve(jsonResponse(cancelled)); + const read = deferred(); + delayedReads.push({ + url: typeof url === "string" ? url : url.url, + signal: init?.signal, + resolve: read.resolve, + }); + return read.promise; + }); + const { client, wrapper } = setupClient(); + const otherKey = backgroundTaskQueryKey("other-thread", working.task_id); + client.setQueryData(otherKey, working); + const { result } = renderHook( + () => ({ + detail: useBackgroundTask("thread-1", working.task_id), + list: useBackgroundTasks("thread-1"), + other: useBackgroundTask("other-thread", working.task_id), + sibling: useBackgroundTask("thread-1", "task-2"), + cancel: useCancelBackgroundTask("thread-1"), + }), + { wrapper }, + ); + await waitFor(() => expect(delayedReads).toHaveLength(4)); + expect(delayedReads.every((read) => read.signal instanceof AbortSignal)).toBe( + true, + ); + await act(async () => { + await result.current.cancel.mutateAsync(working.task_id); + }); + expect(delayedReads[0]!.signal!.aborted).toBe(true); + expect(delayedReads[1]!.signal!.aborted).toBe(true); + expect(delayedReads[2]!.signal!.aborted).toBe(false); + expect(delayedReads[3]!.signal!.aborted).toBe(false); + // Only the list starts a replacement GET. The confirmed detail is already + // authoritative, and unrelated initial detail loads must remain in flight. + expect(delayedReads).toHaveLength(5); + expect(client.getQueryData(otherKey)).toEqual(working); + expect( + client.getQueryData(backgroundTaskQueryKey("thread-1", working.task_id)), + ).toEqual(cancelled); + await act(async () => { + for (const read of delayedReads) { + const value = read.url.includes("?limit=") ? [cancelled] : working; + read.resolve(jsonResponse(value)); + } + }); + expect( + client.getQueryData(backgroundTaskQueryKey("thread-1", working.task_id)), + ).toEqual(cancelled); + await waitFor(() => expect(result.current.sibling.data).toEqual(working)); +}); + +test("failed cancellation allows a pending detail refresh to finish", async () => { + const delayed = deferred(); + rs.mocked(fetch).mockImplementation((_url, init) => + init?.method === "POST" + ? Promise.resolve(jsonResponse({ detail: "Unavailable" }, 503)) + : delayed.promise, + ); + const { client, wrapper } = setupClient(); + const key = backgroundTaskQueryKey("thread-1", working.task_id); + client.setQueryData(key, working); + const { result } = renderHook( + () => ({ + detail: useBackgroundTask("thread-1", working.task_id), + cancel: useCancelBackgroundTask("thread-1"), + }), + { wrapper }, + ); + await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1)); + await act(async () => { + await expect( + result.current.cancel.mutateAsync(working.task_id), + ).rejects.toThrow("Unavailable"); + }); + expect(client.getQueryData(key)).toEqual(working); + const completed = { ...working, status: "completed" }; + await act(async () => { + delayed.resolve(jsonResponse(completed)); + }); + await waitFor(() => expect(result.current.detail.data).toEqual(completed)); +});