Skip to content

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

Python

fix: ignore axios cancellations in nudges and conversations queries (#2506)

VisveshJ484b8a398114
diff --git a/frontend/app/api/queries/useGetConversationsQuery.test.tsx b/frontend/app/api/queries/useGetConversationsQuery.test.tsx
new file mode 100644
index 000000000..2f9c2f78a
--- /dev/null
+++ b/frontend/app/api/queries/useGetConversationsQuery.test.tsx
@@ -0,0 +1,102 @@
+import axios from "axios";
+import { HttpResponse, http } from "msw";
+import { describe, expect, it, vi } from "vitest";
+import { apiClient } from "@/lib/api-client";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, renderHook, waitFor } from "@/test-utils/render";
+import { useGetConversationsQuery } from "./useGetConversationsQuery";
+
+describe("useGetConversationsQuery", () => {
+ it("returns conversations sorted by last_activity", async () => {
+ server.use(
+ http.get("/api/chat/history", () =>
+ HttpResponse.json({
+ conversations: [
+ {
+ response_id: "a",
+ title: "A",
+ endpoint: "chat",
+ messages: [],
+ total_messages: 0,
+ last_activity: "2024-01-02T00:00:00Z",
+ },
+ {
+ response_id: "b",
+ title: "B",
+ endpoint: "chat",
+ messages: [],
+ total_messages: 0,
+ last_activity: "2024-01-01T00:00:00Z",
+ },
+ ],
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConversationsQuery("chat"), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.data?.map((c) => c.response_id)).toEqual(["a", "b"]);
+ });
+
+ it("returns empty list on a server error without throwing", async () => {
+ server.use(
+ http.get(
+ "/api/chat/history",
+ () => new HttpResponse(null, { status: 500 }),
+ ),
+ );
+
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ try {
+ const { result } = renderHook(() => useGetConversationsQuery("chat"), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.isError).toBe(false);
+ expect(result.current.data).toEqual([]);
+ // Unlike a cancellation, a real failure is still logged.
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Failed to fetch conversations"),
+ );
+ } finally {
+ consoleSpy.mockRestore();
+ }
+ });
+
+ it("swallows an axios CanceledError and returns an empty list", async () => {
+ // Use mockImplementation with a URL check so the spy only rejects for the
+ // history endpoint — settings/auth GETs must still reach MSW.
+ const originalGet = apiClient.get.bind(apiClient);
+ const getSpy = vi
+ .spyOn(apiClient, "get")
+ .mockImplementation((url, config) => {
+ if (typeof url === "string" && url.includes("/history")) {
+ return Promise.reject(new axios.CanceledError("canceled"));
+ }
+ return originalGet(url as string, config);
+ });
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ try {
+ const { result } = renderHook(() => useGetConversationsQuery("chat"), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.isError).toBe(false);
+ expect(result.current.data).toEqual([]);
+ expect(consoleSpy).not.toHaveBeenCalledWith(
+ expect.stringContaining("conversations"),
+ expect.any(Error),
+ );
+ } finally {
+ consoleSpy.mockRestore();
+ getSpy.mockRestore();
+ }
+ });
+});
diff --git a/frontend/app/api/queries/useGetConversationsQuery.ts b/frontend/app/api/queries/useGetConversationsQuery.ts
index e263f721f..ba756ca48 100644
--- a/frontend/app/api/queries/useGetConversationsQuery.ts
+++ b/frontend/app/api/queries/useGetConversationsQuery.ts
@@ -5,7 +5,7 @@ import {
} from "@tanstack/react-query";
import type { EndpointType } from "@/contexts/chat-context";
import { useChat } from "@/contexts/chat-context";
-import { apiClient } from "@/lib/api-client";
+import { apiClient, isRequestCancelled } from "@/lib/api-client";
export interface RawConversation {
response_id: string;
@@ -57,6 +57,7 @@ export const useGetConversationsQuery = (
const queryClient = useQueryClient();
const { isOnboardingComplete } = useChat();
+ /** Fetches conversation history for the endpoint; silently returns [] on cancellation or error. */
async function getConversations(context: {
signal?: AbortSignal;
}): Promise<ChatConversation[]> {
@@ -96,7 +97,7 @@ export const useGetConversationsQuery = (
return conversations;
} catch (error) {
// Ignore abort errors - these are expected when requests are cancelled
- if (error instanceof Error && error.name === "AbortError") {
+ if (isRequestCancelled(error)) {
return [];
}
console.error(`Failed to fetch ${endpoint} conversations:`, error);
diff --git a/frontend/app/api/queries/useGetNudgesQuery.test.tsx b/frontend/app/api/queries/useGetNudgesQuery.test.tsx
index 8c9b91370..4a72b4307 100644
--- a/frontend/app/api/queries/useGetNudgesQuery.test.tsx
+++ b/frontend/app/api/queries/useGetNudgesQuery.test.tsx
@@ -8,8 +8,11 @@
* falsy), so `useProviderHealthQuery` never fetches and `isLLMHealthy` stays
* optimistically true without mocking /api/provider/health.
*/
+
+import axios from "axios";
import { HttpResponse, http } from "msw";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import { apiClient } from "@/lib/api-client";
import { makeSettings } from "@/test-utils/fixtures/settings";
import { server } from "@/test-utils/msw/server";
import {
@@ -120,6 +123,37 @@ describe("useGetNudgesQuery", () => {
expect(result.current.isLoading).toBe(false);
});
+ it("swallows an axios CanceledError and returns an empty list", async () => {
+ // Reject only the nudges request so any other POSTs still reach MSW.
+ const originalPost = apiClient.post.bind(apiClient);
+ const postSpy = vi
+ .spyOn(apiClient, "post")
+ .mockImplementation((url, data, config) => {
+ if (typeof url === "string" && url.startsWith("/nudges")) {
+ return Promise.reject(new axios.CanceledError("canceled"));
+ }
+ return originalPost(url, data, config);
+ });
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ try {
+ const { result } = renderHook(() => useGetNudgesQuery(), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.isError).toBe(false);
+ expect(result.current.data).toEqual([]);
+ expect(consoleSpy).not.toHaveBeenCalledWith(
+ "Error getting nudges",
+ expect.any(Error),
+ );
+ } finally {
+ consoleSpy.mockRestore();
+ postSpy.mockRestore();
+ }
+ });
+
it("cancel() drops the cached entry from the query client", async () => {
server.use(
http.post("/api/nudges", () =>
diff --git a/frontend/app/api/queries/useGetNudgesQuery.ts b/frontend/app/api/queries/useGetNudgesQuery.ts
index 8ee96a3a6..8b2fbb8cb 100644
--- a/frontend/app/api/queries/useGetNudgesQuery.ts
+++ b/frontend/app/api/queries/useGetNudgesQuery.ts
@@ -4,7 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import { useChat } from "@/contexts/chat-context";
-import { apiClient } from "@/lib/api-client";
+import { apiClient, isRequestCancelled } from "@/lib/api-client";
import { useProviderHealthQuery } from "./useProviderHealthQuery";
type Nudge = string;
@@ -49,6 +49,7 @@ export const useGetNudgesQuery = (
});
}
+ /** Fetches nudges for the given chat; silently returns the default list on cancellation or error. */
async function getNudges(context: {
signal?: AbortSignal;
}): Promise<Nudge[]> {
@@ -83,7 +84,7 @@ export const useGetNudgesQuery = (
return DEFAULT_NUDGES;
} catch (error) {
// Ignore abort errors - these are expected when requests are cancelled
- if (error instanceof Error && error.name === "AbortError") {
+ if (isRequestCancelled(error)) {
return DEFAULT_NUDGES;
}
console.error("Error getting nudges", error);
diff --git a/frontend/app/api/queries/useGetSearchQuery.ts b/frontend/app/api/queries/useGetSearchQuery.ts
index a0cddbacd..da4a0dd2e 100644
--- a/frontend/app/api/queries/useGetSearchQuery.ts
+++ b/frontend/app/api/queries/useGetSearchQuery.ts
@@ -4,7 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import type { ParsedQueryData } from "@/contexts/knowledge-filter-context";
-import { apiClient } from "@/lib/api-client";
+import { apiClient, isRequestCancelled } from "@/lib/api-client";
import { SEARCH_CONSTANTS } from "@/lib/constants";
import { buildSearchPayloadFilters } from "@/lib/filter-normalization";
@@ -261,7 +261,10 @@ export const useGetSearchQuery = (
return { files, warnings };
} catch (error) {
- console.error("Error getting files", error);
+ // Cancellation is expected (not an error); still re-throw it below
+ if (!isRequestCancelled(error)) {
+ console.error("Error getting files", error);
+ }
// Re-throw the error so React Query can handle it and trigger onError callbacks
throw error;
}
diff --git a/frontend/lib/api-client.test.ts b/frontend/lib/api-client.test.ts
index 0cc90a589..554196e80 100644
--- a/frontend/lib/api-client.test.ts
+++ b/frontend/lib/api-client.test.ts
@@ -96,3 +96,24 @@ describe("apiClient", () => {
expect(getUnauthorizedRedirectUrl("/\\evil.example/login")).toBe("/login");
});
});
+
+describe("isRequestCancelled", () => {
+ it("recognises Axios cancellations and native AbortErrors", async () => {
+ const axios = (await import("axios")).default;
+ const { isRequestCancelled } = await import("./api-client");
+
+ expect(isRequestCancelled(new axios.CanceledError("canceled"))).toBe(true);
+ // jsdom's DOMException isn't an `Error` in this realm, so use a plain one.
+ const abortError = new Error("aborted");
+ abortError.name = "AbortError";
+ expect(isRequestCancelled(abortError)).toBe(true);
+ });
+
+ it("does not treat other errors as cancellations", async () => {
+ const { isRequestCancelled } = await import("./api-client");
+
+ expect(isRequestCancelled(new Error("boom"))).toBe(false);
+ expect(isRequestCancelled("canceled")).toBe(false);
+ expect(isRequestCancelled(undefined)).toBe(false);
+ });
+});
diff --git a/frontend/lib/api-client.ts b/frontend/lib/api-client.ts
index c43c3aa90..91e37da6c 100644
--- a/frontend/lib/api-client.ts
+++ b/frontend/lib/api-client.ts
@@ -23,6 +23,20 @@ export const apiClient = axios.create({
validateStatus: () => true,
});
+/**
+ * True when a request failed because it was cancelled, not because it errored.
+ *
+ * Covers Axios cancellations (`CanceledError`, raised when React Query aborts a
+ * query's `signal`) and native `AbortError`s. Callers should skip error logging
+ * for these - cancellation is expected, e.g. when a query is removed or unmounted.
+ */
+export function isRequestCancelled(error: unknown): boolean {
+ return (
+ axios.isCancel(error) ||
+ (error instanceof Error && error.name === "AbortError")
+ );
+}
+
export function getUnauthorizedRedirectUrl(redirectUrl: unknown): string {
const fallback = withFrontendBasePath("/login");
if (typeof redirectUrl !== "string") return fallback;