Skip to content

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

Python

chore: FE query/mutation coverage (#2397)

Mike Fortman3fb98bb9953a
diff --git a/frontend/app/api/mutations/useConnectConnectorMutation.test.tsx b/frontend/app/api/mutations/useConnectConnectorMutation.test.tsx
new file mode 100644
index 000000000..29f00be5c
--- /dev/null
+++ b/frontend/app/api/mutations/useConnectConnectorMutation.test.tsx
@@ -0,0 +1,225 @@
+/**
+ * Tests for useConnectConnectorMutation: POSTs /api/auth/init and either
+ * redirects into an OAuth flow or, for direct-auth (bucket) connectors,
+ * refreshes the connector list in place.
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Connector } from "@/app/api/queries/useGetConnectorsQuery";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, createTestQueryClient } from "@/test-utils/render";
+import { useConnectConnectorMutation } from "./useConnectConnectorMutation";
+
+const toast = vi.hoisted(() => ({
+ error: vi.fn(),
+ success: vi.fn(),
+}));
+vi.mock("sonner", () => ({ toast }));
+
+function connector(overrides: Partial<Connector> = {}): Connector {
+ return {
+ id: "google_drive",
+ name: "Google Drive",
+ description: "desc",
+ icon: "google",
+ status: "not_connected",
+ type: "google_drive",
+ ...overrides,
+ };
+}
+
+describe("useConnectConnectorMutation", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ toast.error.mockClear();
+ toast.success.mockClear();
+ });
+
+ it("stores OAuth redirect state in localStorage and does not touch the connector cache", async () => {
+ server.use(
+ http.post("/api/auth/init", () =>
+ HttpResponse.json({
+ connection_id: "conn-1",
+ oauth_config: {
+ authorization_endpoint: "https://accounts.example.com/auth",
+ client_id: "client-1",
+ scopes: ["drive.readonly"],
+ redirect_uri: "http://localhost:3000/auth/callback",
+ },
+ }),
+ ),
+ );
+
+ const queryClient = createTestQueryClient();
+ queryClient.setDefaultOptions({
+ queries: {
+ retry: false,
+ staleTime: 0,
+ gcTime: 60_000,
+ refetchOnWindowFocus: false,
+ },
+ mutations: { retry: false },
+ });
+ queryClient.setQueryData(
+ ["connectors", false, false, false, false],
+ [connector()],
+ );
+
+ const { result } = renderHook(() => useConnectConnectorMutation(), {
+ wrapper: createQueryWrapper({ queryClient, providers: ["auth"] }),
+ });
+
+ act(() => {
+ result.current.mutate({
+ connector: connector(),
+ redirectUri: "http://localhost:3000/auth/callback",
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(localStorage.getItem("connecting_connector_id")).toBe("conn-1");
+ expect(localStorage.getItem("connecting_connector_type")).toBe(
+ "google_drive",
+ );
+ expect(localStorage.getItem("auth_purpose")).toBe("data_source");
+ // The optimistic snapshot is never restored on success, and the OAuth
+ // branch never invalidates — the cache should still hold the seed value.
+ expect(
+ queryClient.getQueryData(["connectors", false, false, false, false]),
+ ).toEqual([connector()]);
+ });
+
+ it("marks a 'test' purpose for the return-tab redirect", async () => {
+ server.use(
+ http.post("/api/auth/init", () =>
+ HttpResponse.json({
+ connection_id: "conn-2",
+ oauth_config: {
+ authorization_endpoint: "https://accounts.example.com/auth",
+ client_id: "client-1",
+ scopes: ["drive.readonly"],
+ redirect_uri: "http://localhost:3000/auth/callback",
+ },
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useConnectConnectorMutation(), {
+ wrapper: createQueryWrapper({ providers: ["auth"] }),
+ });
+
+ act(() => {
+ result.current.mutate({
+ connector: connector(),
+ redirectUri: "http://localhost:3000/auth/callback",
+ purpose: "test",
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(localStorage.getItem("auth_purpose")).toBe("test");
+ expect(localStorage.getItem("test_connection_return_tab")).toBe(
+ "connector-access",
+ );
+ });
+
+ it("invalidates the connector list for a direct-auth connector (no oauth_config)", async () => {
+ server.use(
+ http.post("/api/auth/init", () =>
+ HttpResponse.json({ connection_id: "conn-3" }),
+ ),
+ );
+
+ const queryClient = createTestQueryClient();
+ queryClient.setDefaultOptions({
+ queries: {
+ retry: false,
+ staleTime: 0,
+ gcTime: 60_000,
+ refetchOnWindowFocus: false,
+ },
+ mutations: { retry: false },
+ });
+ // Seed a cache entry that isConnectorsQuery would invalidate.
+ queryClient.setQueryData(
+ ["connectors", false, false, false, false],
+ [connector({ id: "aws_s3", type: "aws_s3", status: "configured" })],
+ );
+
+ const { result } = renderHook(() => useConnectConnectorMutation(), {
+ wrapper: createQueryWrapper({ queryClient, providers: ["auth"] }),
+ });
+
+ act(() => {
+ result.current.mutate({
+ connector: connector({ id: "aws_s3", type: "aws_s3" }),
+ redirectUri: "http://localhost:3000/auth/callback",
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ // invalidateQueries alone doesn't force a refetch without an active
+ // observer; assert on the cache being marked stale instead.
+ expect(
+ queryClient.getQueryState(["connectors", false, false, false, false])
+ ?.isInvalidated,
+ ).toBe(true);
+ });
+
+ it("restores the pre-mutation cache and toasts on failure", async () => {
+ let requestStarted = false;
+ let releaseResponse!: () => void;
+ const responseBlocked = new Promise<void>((resolve) => {
+ releaseResponse = resolve;
+ });
+ server.use(
+ http.post("/api/auth/init", async () => {
+ requestStarted = true;
+ await responseBlocked;
+ return HttpResponse.json(
+ { error: "provider unreachable" },
+ { status: 500 },
+ );
+ }),
+ );
+
+ const queryClient = createTestQueryClient();
+ queryClient.setDefaultOptions({
+ queries: {
+ retry: false,
+ staleTime: 0,
+ gcTime: 60_000,
+ refetchOnWindowFocus: false,
+ },
+ mutations: { retry: false },
+ });
+ const seed = [connector({ status: "configured" })];
+ queryClient.setQueryData(["connectors", false, false, false, false], seed);
+
+ const { result } = renderHook(() => useConnectConnectorMutation(), {
+ wrapper: createQueryWrapper({ queryClient, providers: ["auth"] }),
+ });
+
+ act(() => {
+ result.current.mutate({
+ connector: connector(),
+ redirectUri: "http://localhost:3000/auth/callback",
+ });
+ });
+
+ await waitFor(() => expect(requestStarted).toBe(true));
+ queryClient.setQueryData(
+ ["connectors", false, false, false, false],
+ [connector({ status: "not_connected" })],
+ );
+ releaseResponse();
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("provider unreachable");
+ expect(
+ queryClient.getQueryData(["connectors", false, false, false, false]),
+ ).toEqual(seed);
+ expect(toast.error).toHaveBeenCalledWith("provider unreachable");
+ });
+});
diff --git a/frontend/app/api/mutations/useOnboardingMutation.test.tsx b/frontend/app/api/mutations/useOnboardingMutation.test.tsx
new file mode 100644
index 000000000..9975c8131
--- /dev/null
+++ b/frontend/app/api/mutations/useOnboardingMutation.test.tsx
@@ -0,0 +1,200 @@
+/**
+ * Tests for useOnboardingMutation: POSTs the onboarding payload and, when the
+ * backend ingested sample data, persists the resulting filter ID through
+ * useUpdateOnboardingStateMutation.
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
+import { describe, expect, it, vi } from "vitest";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, createTestQueryClient } from "@/test-utils/render";
+import { useOnboardingMutation } from "./useOnboardingMutation";
+
+describe("useOnboardingMutation", () => {
+ it("posts the onboarding variables and resolves with the response", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.post("/api/onboarding", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json({ message: "done", edited: true });
+ }),
+ );
+
+ const { result } = renderHook(() => useOnboardingMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() =>
+ result.current.mutate({
+ llm_provider: "openai",
+ openai_api_key: "sk-test",
+ }),
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({
+ llm_provider: "openai",
+ openai_api_key: "sk-test",
+ });
+ });
+
+ it("persists openrag_docs_filter_id via the onboarding-state endpoint on success", async () => {
+ let stateBody: unknown;
+ server.use(
+ http.post("/api/onboarding", () =>
+ HttpResponse.json({
+ message: "done",
+ edited: true,
+ openrag_docs_filter_id: "filter-123",
+ }),
+ ),
+ http.post("/api/onboarding/state", async ({ request }) => {
+ stateBody = await request.json();
+ return HttpResponse.json({ success: true });
+ }),
+ );
+
+ const { result } = renderHook(() => useOnboardingMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ await waitFor(() =>
+ expect(stateBody).toEqual({ openrag_docs_filter_id: "filter-123" }),
+ );
+ });
+
+ it("calls the caller's onSuccess for a completed onboarding request", async () => {
+ const onSuccess = vi.fn();
+ const response = {
+ message: "done",
+ edited: true,
+ };
+ server.use(http.post("/api/onboarding", () => HttpResponse.json(response)));
+
+ const { result } = renderHook(() => useOnboardingMutation({ onSuccess }), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() =>
+ expect(onSuccess).toHaveBeenCalledWith(
+ response,
+ {},
+ undefined,
+ expect.anything(),
+ ),
+ );
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ it("calls the caller's onError when onboarding fails", async () => {
+ const onError = vi.fn();
+ server.use(
+ http.post("/api/onboarding", () =>
+ HttpResponse.json(
+ { error: "Could not complete onboarding" },
+ { status: 500 },
+ ),
+ ),
+ );
+
+ const { result } = renderHook(() => useOnboardingMutation({ onError }), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Could not complete onboarding");
+ expect(onError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: "Could not complete onboarding" }),
+ {},
+ undefined,
+ expect.anything(),
+ );
+ });
+
+ it("invalidates settings after onboarding settles", async () => {
+ const response = { message: "done", edited: true };
+ server.use(http.post("/api/onboarding", () => HttpResponse.json(response)));
+
+ const queryClient = createTestQueryClient();
+ queryClient.setQueryDefaults(["settings"], { gcTime: 60_000 });
+ queryClient.setQueryData(["settings"], { edited: false });
+ const { result } = renderHook(() => useOnboardingMutation(), {
+ wrapper: createQueryWrapper({ queryClient }),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(queryClient.getQueryState(["settings"])?.isInvalidated).toBe(true);
+ });
+
+ it("does not call the onboarding-state endpoint when there is no filter ID", async () => {
+ let stateCalled = false;
+ server.use(
+ http.post("/api/onboarding", () =>
+ HttpResponse.json({ message: "done", edited: true }),
+ ),
+ http.post("/api/onboarding/state", () => {
+ stateCalled = true;
+ return HttpResponse.json({ success: true });
+ }),
+ );
+
+ const { result } = renderHook(() => useOnboardingMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(stateCalled).toBe(false);
+ });
+
+ it("formats the backend error message on failure", async () => {
+ server.use(
+ http.post("/api/onboarding", () =>
+ HttpResponse.json(
+ { error: "Invalid provider configuration" },
+ {
+ status: 500,
+ },
+ ),
+ ),
+ );
+
+ const { result } = renderHook(() => useOnboardingMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe(
+ "Invalid provider configuration",
+ );
+ });
+
+ it("falls back to a default message when the error body has no error field", async () => {
+ server.use(
+ http.post("/api/onboarding", () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useOnboardingMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to complete onboarding");
+ });
+});
diff --git a/frontend/app/api/mutations/useRefreshOpenragDocs.test.ts b/frontend/app/api/mutations/useRefreshOpenragDocs.test.ts
new file mode 100644
index 000000000..8669fd776
--- /dev/null
+++ b/frontend/app/api/mutations/useRefreshOpenragDocs.test.ts
@@ -0,0 +1,136 @@
+/**
+ * Tests for useRefreshOpenragDocs: POSTs the refresh endpoint and, whatever
+ * the outcome, invalidates tasks/search/settings so the UI picks up the
+ * re-ingested sample docs.
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, createTestQueryClient } from "@/test-utils/render";
+import { useRefreshOpenragDocs } from "./useRefreshOpenragDocs";
+
+describe("useRefreshOpenragDocs", () => {
+ it("posts to /api/openrag-docs/refresh and resolves with the response", async () => {
+ server.use(
+ http.post("/api/openrag-docs/refresh", () =>
+ HttpResponse.json({ message: "refreshed", refreshed: true }),
+ ),
+ );
+
+ const { result } = renderHook(() => useRefreshOpenragDocs(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data).toEqual({
+ message: "refreshed",
+ refreshed: true,
+ });
+ });
+
+ it("invalidates tasks, search, and settings on settle, even on failure", async () => {
+ server.use(
+ http.post(
+ "/api/openrag-docs/refresh",
+ () => new HttpResponse(null, { status: 500 }),
+ ),
+ );
+
+ const queryClient = createTestQueryClient();
+ queryClient.setDefaultOptions({
+ queries: {
+ retry: false,
+ staleTime: 0,
+ gcTime: 60_000,
+ refetchOnWindowFocus: false,
+ },
+ mutations: { retry: false },
+ });
+ const seededKeys = [
+ ["tasks", "enhanced"],
+ ["search", "results"],
+ ["settings"],
+ ];
+ for (const key of seededKeys) queryClient.setQueryData(key, ["seed"]);
+
+ const { result } = renderHook(() => useRefreshOpenragDocs(), {
+ wrapper: createQueryWrapper(queryClient),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ for (const key of seededKeys) {
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true);
+ }
+ });
+
+ it("uses the response body's detail/error field as the failure message", async () => {
+ server.use(
+ http.post("/api/openrag-docs/refresh", () =>
+ HttpResponse.json(
+ { detail: "sample docs already refreshing" },
+ {
+ status: 409,
+ },
+ ),
+ ),
+ );
+
+ const { result } = renderHook(() => useRefreshOpenragDocs(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe(
+ "sample docs already refreshing",
+ );
+ });
+
+ it("falls back to a plain-text body when the response is not JSON", async () => {
+ server.use(
+ http.post(
+ "/api/openrag-docs/refresh",
+ () =>
+ new HttpResponse("upstream timed out", {
+ status: 504,
+ headers: { "content-type": "text/plain" },
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useRefreshOpenragDocs(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("upstream timed out");
+ });
+
+ it("falls back to the default message when the body is empty", async () => {
+ server.use(
+ http.post(
+ "/api/openrag-docs/refresh",
+ () => new HttpResponse(null, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useRefreshOpenragDocs(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe(
+ "Failed to refresh OpenRAG docs",
+ );
+ });
+});
diff --git a/frontend/app/api/mutations/useSyncConnector.test.ts b/frontend/app/api/mutations/useSyncConnector.test.ts
new file mode 100644
index 000000000..71afb7b21
--- /dev/null
+++ b/frontend/app/api/mutations/useSyncConnector.test.ts
@@ -0,0 +1,221 @@
+/**
+ * Tests for the four mutations in useSyncConnector.ts: syncing one connector
+ * or all of them, and previewing either sync before it runs.
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper } from "@/test-utils/render";
+import {
+ useSyncAllConnectors,
+ useSyncAllConnectorsPreview,
+ useSyncConnector,
+ useSyncConnectorPreview,
+} from "./useSyncConnector";
+
+describe("useSyncAllConnectors", () => {
+ it("posts to /api/connectors/sync-all and resolves with the response", async () => {
+ server.use(
+ http.post("/api/connectors/sync-all", () =>
+ HttpResponse.json({ status: "ok", message: "synced" }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncAllConnectors(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.message).toBe("synced");
+ });
+
+ it("throws the backend's error message when the response is not ok", async () => {
+ server.use(
+ http.post("/api/connectors/sync-all", () =>
+ HttpResponse.json(
+ { error: "no connectors configured" },
+ { status: 500 },
+ ),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncAllConnectors(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("no connectors configured");
+ });
+
+ it("falls back to a default message when the error body has no error field", async () => {
+ server.use(
+ http.post("/api/connectors/sync-all", () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncAllConnectors(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to sync connectors");
+ });
+});
+
+describe("useSyncConnector", () => {
+ it("posts to /api/connectors/:type/sync with the request body", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.post("/api/connectors/google_drive/sync", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json({ status: "ok", message: "synced" });
+ }),
+ );
+
+ const { result } = renderHook(() => useSyncConnector(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() =>
+ result.current.mutate({
+ connectorType: "google_drive",
+ body: { connection_id: "conn-1", max_files: 10 },
+ }),
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({ connection_id: "conn-1", max_files: 10 });
+ });
+
+ it("sends an empty object body when no body is given", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.post("/api/connectors/aws_s3/sync", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json({ status: "ok", message: "synced" });
+ }),
+ );
+
+ const { result } = renderHook(() => useSyncConnector(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({ connectorType: "aws_s3" }));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({});
+ });
+
+ it("throws a connector-specific default message on failure", async () => {
+ server.use(
+ http.post("/api/connectors/onedrive/sync", () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncConnector(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({ connectorType: "onedrive" }));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to sync onedrive");
+ });
+});
+
+describe("useSyncConnectorPreview", () => {
+ it("posts to /api/connectors/:type/sync-preview and resolves the preview", async () => {
+ server.use(
+ http.post("/api/connectors/google_drive/sync-preview", () =>
+ HttpResponse.json({
+ connector_type: "google_drive",
+ synced_count: 3,
+ orphans: [{ document_id: "d1", filename: "old.pdf" }],
+ orphans_available: true,
+ updates: [],
+ updates_available: true,
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncConnectorPreview(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate("google_drive"));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.orphans).toHaveLength(1);
+ expect(result.current.data?.orphans_available).toBe(true);
+ });
+
+ it("throws with a connector-specific message when the preview fails", async () => {
+ server.use(
+ http.post("/api/connectors/google_drive/sync-preview", () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncConnectorPreview(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate("google_drive"));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe(
+ "Failed to preview sync for google_drive",
+ );
+ });
+});
+
+describe("useSyncAllConnectorsPreview", () => {
+ it("posts to /api/connectors/sync-all-preview and resolves the aggregate preview", async () => {
+ server.use(
+ http.post("/api/connectors/sync-all-preview", () =>
+ HttpResponse.json({
+ orphans_by_type: { google_drive: [] },
+ synced_count_by_type: { google_drive: 5 },
+ orphans_available_by_type: { google_drive: true },
+ updates_by_type: { google_drive: [] },
+ updates_available_by_type: { google_drive: true },
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncAllConnectorsPreview(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.synced_count_by_type.google_drive).toBe(5);
+ });
+
+ it("throws a default message when the response has no error field", async () => {
+ server.use(
+ http.post("/api/connectors/sync-all-preview", () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useSyncAllConnectorsPreview(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate());
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to preview sync");
+ });
+});
diff --git a/frontend/app/api/mutations/useUpdateSettingsMutation.test.tsx b/frontend/app/api/mutations/useUpdateSettingsMutation.test.tsx
new file mode 100644
index 000000000..a2340b19e
--- /dev/null
+++ b/frontend/app/api/mutations/useUpdateSettingsMutation.test.tsx
@@ -0,0 +1,139 @@
+/**
+ * Tests for useUpdateSettingsMutation: POSTs /api/settings, invalidates the
+ * settings cache, and refetches the current provider's model list. The hook
+ * mounts useGetCurrentProviderModelsQuery internally, so /api/settings (GET)
+ * and the relevant /api/models/* endpoint must both be mocked even though
+ * this file is only testing the mutation.
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper } from "@/test-utils/render";
+import {
+ isEmbeddingProviderInUseError,
+ useUpdateSettingsMutation,
+} from "./useUpdateSettingsMutation";
+
+describe("useUpdateSettingsMutation", () => {
+ it("posts the settings payload and triggers a settings refetch on success", async () => {
+ let settingsFetchCount = 0;
+ let capturedBody: unknown;
+ server.use(
+ http.get("/api/settings", () => {
+ settingsFetchCount += 1;
+ return HttpResponse.json({ agent: { llm_provider: "openai" } });
+ }),
+ http.post("/api/settings", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json({
+ message: "saved",
+ settings: { agent: { llm_provider: "openai" } },
+ });
+ }),
+ http.post("/api/models/openai", () =>
+ HttpResponse.json({ language_models: [], embedding_models: [] }),
+ ),
+ );
+
+ const { result } = renderHook(() => useUpdateSettingsMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(settingsFetchCount).toBe(1));
+
+ act(() => result.current.mutate({ llm_model: "gpt-5.4" }));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({ llm_model: "gpt-5.4" });
+ // invalidateQueries refetches the mounted useGetSettingsQuery observer.
+ await waitFor(() => expect(settingsFetchCount).toBe(2));
+ });
+
+ it("calls the caller's onSuccess in addition to the hook's own side effects", async () => {
+ server.use(
+ http.get("/api/settings", () => HttpResponse.json({})),
+ http.post("/api/settings", () =>
+ HttpResponse.json({ message: "saved", settings: {} }),
+ ),
+ http.post("/api/models/openai", () =>
+ HttpResponse.json({ language_models: [], embedding_models: [] }),
+ ),
+ );
+
+ let onSuccessCalled = false;
+ const { result } = renderHook(
+ () =>
+ useUpdateSettingsMutation({
+ onSuccess: () => {
+ onSuccessCalled = true;
+ },
+ }),
+ { wrapper: createQueryWrapper() },
+ );
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(onSuccessCalled).toBe(true);
+ });
+
+ it("throws an UpdateSettingsError carrying the structured 409 payload", async () => {
+ server.use(
+ http.get("/api/settings", () => HttpResponse.json({})),
+ http.post("/api/settings", () =>
+ HttpResponse.json(
+ {
+ error: "Embedding provider still in use",
+ code: "embedding_provider_in_use",
+ affected_provider: "openai",
+ affected_models: [
+ { model: "text-embedding-3-small", doc_count: 4 },
+ ],
+ },
+ { status: 409 },
+ ),
+ ),
+ http.post("/api/models/openai", () =>
+ HttpResponse.json({ language_models: [], embedding_models: [] }),
+ ),
+ );
+
+ const { result } = renderHook(() => useUpdateSettingsMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({ remove_openai_config: true }));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(isEmbeddingProviderInUseError(result.current.error)).toBe(true);
+ if (isEmbeddingProviderInUseError(result.current.error)) {
+ expect(result.current.error.affectedProvider).toBe("openai");
+ expect(result.current.error.affectedModels).toEqual([
+ { model: "text-embedding-3-small", doc_count: 4 },
+ ]);
+ }
+ });
+
+ it("does not classify a plain 500 as the embedding-provider-in-use error", async () => {
+ server.use(
+ http.get("/api/settings", () => HttpResponse.json({})),
+ http.post("/api/settings", () =>
+ HttpResponse.json({ error: "database unavailable" }, { status: 500 }),
+ ),
+ http.post("/api/models/openai", () =>
+ HttpResponse.json({ language_models: [], embedding_models: [] }),
+ ),
+ );
+
+ const { result } = renderHook(() => useUpdateSettingsMutation(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ act(() => result.current.mutate({}));
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(isEmbeddingProviderInUseError(result.current.error)).toBe(false);
+ expect(result.current.error?.message).toBe("database unavailable");
+ });
+});
diff --git a/frontend/app/api/queries/useGetConnectorsQuery.test.ts b/frontend/app/api/queries/useGetConnectorsQuery.test.ts
new file mode 100644
index 000000000..0c323f512
--- /dev/null
+++ b/frontend/app/api/queries/useGetConnectorsQuery.test.ts
@@ -0,0 +1,299 @@
+/**
+ * Tests for useGetConnectorsQuery: fetching connector definitions, resolving
+ * each one's per-type status, and filtering by deployment/workspace policy.
+ *
+ * `brand` pulls in `auth` automatically (see test-utils/render.tsx), and the
+ * default scenario (oss brand, non-IBM auth) exercises the plain
+ * `isConnectorTypeVisible` filter without touching the workspace-policy
+ * fetch — that path gets its own test with an IBM auth scenario.
+ */
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { authPresets } from "@/test-utils/fixtures/auth";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, renderHook, waitFor } from "@/test-utils/render";
+import {
+ useGetConnectorAccessQuery,
+ useGetConnectorsQuery,
+ useUpdateConnectorAccessMutation,
+} from "./useGetConnectorsQuery";
+
+function connectorsPayload(
+ connectors: Record<string, Record<string, unknown>>,
+) {
+ return { connectors };
+}
+
+describe("useGetConnectorsQuery", () => {
+ it("marks a connector connected from an active, authenticated connection", async () => {
+ server.use(
+ http.get("/api/connectors", () =>
+ HttpResponse.json(
+ connectorsPayload({
+ google_drive: {
+ name: "Google Drive",
+ description: "desc",
+ icon: "google",
+ kind: "oauth",
+ available: true,
+ },
+ }),
+ ),
+ ),
+ http.get("/api/connectors/google_drive/status", () =>
+ HttpResponse.json({
+ connections: [
+ {
+ connection_id: "conn-1",
+ is_active: true,
+ is_authenticated: true,
+ created_at: "2026-01-01T00:00:00Z",
+ client_id: "client-1",
+ base_url: "https://drive.example.com",
+ },
+ ],
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorsQuery(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data).toEqual([
+ expect.objectContaining({
+ id: "google_drive",
+ status: "connected",
+ connectionId: "conn-1",
+ clientId: "client-1",
+ requiresOAuth: true,
+ }),
+ ]);
+ });
+
+ it("marks an oauth connector configured when only env credentials exist", async () => {
+ server.use(
+ http.get("/api/connectors", () =>
+ HttpResponse.json(
+ connectorsPayload({
+ onedrive: {
+ name: "OneDrive",
+ description: "desc",
+ icon: "onedrive",
+ kind: "oauth",
+ available: true,
+ },
+ }),
+ ),
+ ),
+ http.get("/api/connectors/onedrive/status", () =>
+ HttpResponse.json({ connections: [], has_env_credentials: true }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorsQuery(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.[0].status).toBe("configured");
+ });
+
+ it("defaults to not_connected when the status request itself fails", async () => {
+ server.use(
+ http.get("/api/connectors", () =>
+ HttpResponse.json(
+ connectorsPayload({
+ google_drive: {
+ name: "Google Drive",
+ description: "desc",
+ icon: "google",
+ kind: "oauth",
+ available: true,
+ },
+ }),
+ ),
+ ),
+ http.get(
+ "/api/connectors/google_drive/status",
+ () => new HttpResponse(null, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorsQuery(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.[0].status).toBe("not_connected");
+ });
+
+ it("filters out aws_s3 and ibm_cos for a non-IBM oss deployment", async () => {
+ server.use(
+ http.get("/api/connectors", () =>
+ HttpResponse.json(
+ connectorsPayload({
+ google_drive: {
+ name: "Google Drive",
+ description: "desc",
+ icon: "google",
+ kind: "oauth",
+ available: true,
+ },
+ aws_s3: {
+ name: "AWS S3",
+ description: "desc",
+ icon: "aws",
+ kind: "bucket",
+ available: true,
+ },
+ ibm_cos: {
+ name: "IBM COS",
+ description: "desc",
+ icon: "ibm",
+ kind: "bucket",
+ available: true,
+ },
+ }),
+ ),
+ ),
+ http.get(/\/api\/connectors\/.+\/status/, () =>
+ HttpResponse.json({ connections: [] }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorsQuery(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.map((c) => c.id)).toEqual(["google_drive"]);
+ });
+
+ it("applies workspace policy access instead of deployment visibility under IBM auth", async () => {
+ server.use(
+ http.get("/api/connectors", () =>
+ HttpResponse.json(
+ connectorsPayload({
+ google_drive: {
+ name: "Google Drive",
+ description: "desc",
+ icon: "google",
+ kind: "oauth",
+ available: true,
+ },
+ onedrive: {
+ name: "OneDrive",
+ description: "desc",
+ icon: "onedrive",
+ kind: "oauth",
+ available: true,
+ },
+ }),
+ ),
+ ),
+ http.get(/\/api\/connectors\/.+\/status/, () =>
+ HttpResponse.json({ connections: [] }),
+ ),
+ http.get("/api/connectors/workspace-policy", () =>
+ HttpResponse.json({ access: { onedrive: false } }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorsQuery(), {
+ wrapper: createQueryWrapper({
+ providers: ["brand"],
+ auth: authPresets.ibmAuthMode,
+ }),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ // onedrive explicitly denied by the workspace; google_drive falls back to
+ // isConnectorTypeVisible, which is true for a non-onedrive/non-bucket type.
+ expect(result.current.data?.map((c) => c.id)).toEqual(["google_drive"]);
+ });
+});
+
+describe("useGetConnectorAccessQuery", () => {
+ it("filters the returned list by deployment visibility", async () => {
+ server.use(
+ http.get("/api/connectors/user-access", () =>
+ HttpResponse.json({
+ connectors: [
+ { type: "google_drive", name: "Google Drive", enabled: true },
+ { type: "aws_s3", name: "AWS S3", enabled: true },
+ ],
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorAccessQuery(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.map((c) => c.type)).toEqual(["google_drive"]);
+ });
+
+ it("throws when the request fails", async () => {
+ server.use(
+ http.get(
+ "/api/connectors/user-access",
+ () => new HttpResponse(null, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetConnectorAccessQuery(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toMatch(
+ /Failed to fetch connectors permission/,
+ );
+ });
+});
+
+describe("useUpdateConnectorAccessMutation", () => {
+ it("PUTs the access map and returns the filtered, updated list", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.put("/api/connectors/user-access", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json({
+ connectors: [
+ { type: "google_drive", name: "Google Drive", enabled: false },
+ ],
+ });
+ }),
+ );
+
+ const { result } = renderHook(() => useUpdateConnectorAccessMutation(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ result.current.mutate({ google_drive: false });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({ access: { google_drive: false } });
+ expect(result.current.data?.[0].enabled).toBe(false);
+ });
+
+ it("throws the backend's error message on failure", async () => {
+ server.use(
+ http.put("/api/connectors/user-access", () =>
+ HttpResponse.json({ error: "not allowed" }, { status: 403 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useUpdateConnectorAccessMutation(), {
+ wrapper: createQueryWrapper({ providers: ["brand"] }),
+ });
+
+ result.current.mutate({ google_drive: false });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("not allowed");
+ });
+});
diff --git a/frontend/app/api/queries/useGetModelsQuery.test.tsx b/frontend/app/api/queries/useGetModelsQuery.test.tsx
new file mode 100644
index 000000000..b58cbe14a
--- /dev/null
+++ b/frontend/app/api/queries/useGetModelsQuery.test.tsx
@@ -0,0 +1,315 @@
+/**
+ * Tests for useGetModelsQuery.ts: the four per-provider model queries, the
+ * provider-switching dispatcher, and the static model catalogue query.
+ */
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, renderHook, waitFor } from "@/test-utils/render";
+import {
+ useGetAnthropicModelsQuery,
+ useGetCurrentProviderModelsQuery,
+ useGetIBMModelsQuery,
+ useGetModelCatalogQuery,
+ useGetOllamaModelsQuery,
+ useGetOpenAIModelsQuery,
+} from "./useGetModelsQuery";
+
+const models = {
+ language_models: [{ value: "gpt-5.4", label: "GPT-5.4", default: true }],
+ embedding_models: [{ value: "text-embedding-3-small", label: "Small" }],
+};
+
+describe("useGetOpenAIModelsQuery", () => {
+ it("omits api_key from the body when useEnvKey is true", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.post("/api/models/openai", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json(models);
+ }),
+ );
+
+ const { result } = renderHook(
+ () => useGetOpenAIModelsQuery({ apiKey: "sk-ignored", useEnvKey: true }),
+ { wrapper: createQueryWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({});
+ expect(result.current.data).toEqual(models);
+ });
+
+ it("sends the api_key in the body when provided and not using env key", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.post("/api/models/openai", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json(models);
+ }),
+ );
+
+ const { result } = renderHook(
+ () => useGetOpenAIModelsQuery({ apiKey: "sk-real" }),
+ { wrapper: createQueryWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({ api_key: "sk-real" });
+ });
+
+ it("formats the backend error message on failure", async () => {
+ server.use(
+ http.post("/api/models/openai", () =>
+ HttpResponse.json({ error: "Invalid API key" }, { status: 401 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetOpenAIModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Invalid API key");
+ });
+
+ it("falls back to a default message when the error body has no error field", async () => {
+ server.use(
+ http.post("/api/models/openai", () =>
+ HttpResponse.json({}, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetOpenAIModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to fetch OpenAI models");
+ });
+});
+
+describe("useGetAnthropicModelsQuery", () => {
+ it("resolves the model list on success", async () => {
+ server.use(
+ http.post("/api/models/anthropic", () => HttpResponse.json(models)),
+ );
+
+ const { result } = renderHook(() => useGetAnthropicModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data).toEqual(models);
+ });
+
+ it("surfaces the backend error message on failure", async () => {
+ server.use(
+ http.post("/api/models/anthropic", () =>
+ HttpResponse.json({ error: "rate limited" }, { status: 429 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetAnthropicModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("rate limited");
+ });
+});
+
+describe("useGetOllamaModelsQuery", () => {
+ it("appends the endpoint as a query param when given", async () => {
+ let capturedUrl = "";
+ server.use(
+ http.get("/api/models/ollama", ({ request }) => {
+ capturedUrl = request.url;
+ return HttpResponse.json(models);
+ }),
+ );
+
+ const { result } = renderHook(
+ () => useGetOllamaModelsQuery({ endpoint: "http://localhost:11434" }),
+ { wrapper: createQueryWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedUrl).toContain("endpoint=http%3A%2F%2Flocalhost%3A11434");
+ });
+
+ it("omits the query param when no endpoint is given", async () => {
+ let capturedUrl = "";
+ server.use(
+ http.get("/api/models/ollama", ({ request }) => {
+ capturedUrl = request.url;
+ return HttpResponse.json(models);
+ }),
+ );
+
+ const { result } = renderHook(() => useGetOllamaModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedUrl).not.toContain("endpoint=");
+ });
+});
+
+describe("useGetIBMModelsQuery", () => {
+ it("sends endpoint and project_id, omitting api_key when useEnvKey is true", async () => {
+ let capturedBody: unknown;
+ server.use(
+ http.post("/api/models/ibm", async ({ request }) => {
+ capturedBody = await request.json();
+ return HttpResponse.json(models);
+ }),
+ );
+
+ const { result } = renderHook(
+ () =>
+ useGetIBMModelsQuery({
+ endpoint: "https://ibm.example.com",
+ projectId: "proj-1",
+ apiKey: "ignored",
+ useEnvKey: true,
+ }),
+ { wrapper: createQueryWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(capturedBody).toEqual({
+ endpoint: "https://ibm.example.com",
+ project_id: "proj-1",
+ });
+ });
+
+ it("surfaces the backend error message on failure", async () => {
+ server.use(
+ http.post("/api/models/ibm", () =>
+ HttpResponse.json({ error: "endpoint unreachable" }, { status: 502 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetIBMModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("endpoint unreachable");
+ });
+});
+
+describe("useGetCurrentProviderModelsQuery", () => {
+ it("dispatches to the anthropic query when settings.agent.llm_provider is anthropic", async () => {
+ let anthropicCalled = false;
+ let openaiCalled = false;
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json({ agent: { llm_provider: "anthropic" } }),
+ ),
+ http.post("/api/models/anthropic", () => {
+ anthropicCalled = true;
+ return HttpResponse.json(models);
+ }),
+ http.post("/api/models/openai", () => {
+ openaiCalled = true;
+ return HttpResponse.json(models);
+ }),
+ );
+
+ const { result } = renderHook(() => useGetCurrentProviderModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(anthropicCalled).toBe(true);
+ expect(openaiCalled).toBe(false);
+ });
+
+ it("dispatches to the ollama query only once its endpoint is configured", async () => {
+ let ollamaCalled = false;
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json({
+ agent: { llm_provider: "ollama" },
+ providers: { ollama: { endpoint: "http://localhost:11434" } },
+ }),
+ ),
+ http.get("/api/models/ollama", () => {
+ ollamaCalled = true;
+ return HttpResponse.json(models);
+ }),
+ http.post("/api/models/openai", () => HttpResponse.json(models)),
+ );
+
+ const { result } = renderHook(() => useGetCurrentProviderModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(ollamaCalled).toBe(true);
+ });
+
+ it("defaults to the openai query when no provider is configured yet", async () => {
+ server.use(
+ http.get("/api/settings", () => HttpResponse.json({ agent: {} })),
+ http.post("/api/models/openai", () => HttpResponse.json(models)),
+ );
+
+ const { result } = renderHook(() => useGetCurrentProviderModelsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ // Falls through to the openai branch, but stays disabled because
+ // currentProvider !== "openai" — data never resolves.
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.data).toBeUndefined();
+ });
+});
+
+describe("useGetModelCatalogQuery", () => {
+ it("resolves the provider catalogue on success", async () => {
+ server.use(
+ http.get("/api/models/catalog", () =>
+ HttpResponse.json({
+ providers: [
+ {
+ key: "openai",
+ name: "OpenAI",
+ credential_fields: [],
+ model_placeholder: null,
+ models: [],
+ embedding_models: [],
+ },
+ ],
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetModelCatalogQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.providers[0].key).toBe("openai");
+ });
+
+ it("formats the backend error message on failure", async () => {
+ server.use(
+ http.get(
+ "/api/models/catalog",
+ () => new HttpResponse(null, { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetModelCatalogQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe(
+ "Failed to fetch the model catalogue",
+ );
+ });
+});
diff --git a/frontend/app/api/queries/useGetNudgesQuery.test.tsx b/frontend/app/api/queries/useGetNudgesQuery.test.tsx
new file mode 100644
index 000000000..8c9b91370
--- /dev/null
+++ b/frontend/app/api/queries/useGetNudgesQuery.test.tsx
@@ -0,0 +1,144 @@
+/**
+ * Tests for useGetNudgesQuery: gated on onboarding completion and LLM
+ * health, and parses the backend's newline-delimited `response` string into
+ * a list of nudges.
+ *
+ * The default settings/tasks handlers (see test-utils/msw/handlers.ts) leave
+ * onboarding finished and provider health disabled (settings.edited is
+ * falsy), so `useProviderHealthQuery` never fetches and `isLLMHealthy` stays
+ * optimistically true without mocking /api/provider/health.
+ */
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { makeSettings } from "@/test-utils/fixtures/settings";
+import { server } from "@/test-utils/msw/server";
+import {
+ createQueryWrapper,
+ createTestQueryClient,
+ renderHook,
+ waitFor,
+} from "@/test-utils/render";
+import { useGetNudgesQuery } from "./useGetNudgesQuery";
+
+describe("useGetNudgesQuery", () => {
+ it("splits the newline-delimited response into nudges", async () => {
+ server.use(
+ http.post("/api/nudges", () =>
+ HttpResponse.json({ response: "Try uploading a PDF\nAsk about X\n" }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetNudgesQuery(), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() =>
+ expect(result.current.data).toEqual([
+ "Try uploading a PDF",
+ "Ask about X",
+ ]),
+ );
+ });
+
+ it("returns an empty list when the response has no response field", async () => {
+ server.use(http.post("/api/nudges", () => HttpResponse.json({})));
+
+ const { result } = renderHook(() => useGetNudgesQuery(), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.data).toEqual([]);
+ });
+
+ it("swallows a non-abort error and returns an empty list instead of throwing", async () => {
+ server.use(
+ http.post("/api/nudges", () => new HttpResponse(null, { status: 500 })),
+ );
+
+ 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([]);
+ });
+
+ it("includes the chatId in the request path when given", async () => {
+ let capturedUrl = "";
+ server.use(
+ http.post("/api/nudges/chat-123", ({ request }) => {
+ capturedUrl = request.url;
+ return HttpResponse.json({ response: "" });
+ }),
+ );
+
+ renderHook(() => useGetNudgesQuery({ chatId: "chat-123" }), {
+ wrapper: createQueryWrapper({ providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(capturedUrl).not.toBe(""));
+ expect(capturedUrl).toContain("/api/nudges/chat-123");
+ });
+
+ it("stays disabled while onboarding is still in progress", async () => {
+ let nudgeRequests = 0;
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ onboarding: { current_step: 1 } })),
+ ),
+ http.post("/api/nudges", () => {
+ nudgeRequests += 1;
+ return HttpResponse.json({ response: "x" });
+ }),
+ );
+
+ const queryClient = createTestQueryClient();
+ const { result } = renderHook(() => useGetNudgesQuery(), {
+ wrapper: createQueryWrapper({ queryClient, providers: ["auth", "chat"] }),
+ });
+
+ // Wait for the in-progress onboarding settings to resolve and propagate
+ // to chat state, rather than sleeping for a fixed interval.
+ await waitFor(() =>
+ expect(
+ (
+ queryClient.getQueryData(["settings"]) as
+ | ReturnType<typeof makeSettings>
+ | undefined
+ )?.onboarding?.current_step,
+ ).toBe(1),
+ );
+ await waitFor(() =>
+ expect(queryClient.isFetching({ queryKey: ["settings"] })).toBe(0),
+ );
+
+ // Query is disabled: no request, no data, not loading.
+ expect(nudgeRequests).toBe(0);
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("cancel() drops the cached entry from the query client", async () => {
+ server.use(
+ http.post("/api/nudges", () =>
+ HttpResponse.json({ response: "Try this" }),
+ ),
+ );
+
+ const queryClient = createTestQueryClient();
+ const nudgesKey = ["nudges", undefined, undefined, undefined, undefined];
+
+ const { result } = renderHook(() => useGetNudgesQuery(), {
+ wrapper: createQueryWrapper({ queryClient, providers: ["auth", "chat"] }),
+ });
+
+ await waitFor(() => expect(result.current.data).toEqual(["Try this"]));
+ expect(queryClient.getQueryData(nudgesKey)).toEqual(["Try this"]);
+
+ result.current.cancel();
+
+ expect(queryClient.getQueryData(nudgesKey)).toBeUndefined();
+ });
+});
diff --git a/frontend/app/api/queries/useGetSettingsQuery.test.ts b/frontend/app/api/queries/useGetSettingsQuery.test.ts
new file mode 100644
index 000000000..38714f46a
--- /dev/null
+++ b/frontend/app/api/queries/useGetSettingsQuery.test.ts
@@ -0,0 +1,41 @@
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/test-utils/msw/server";
+import { createQueryWrapper, renderHook, waitFor } from "@/test-utils/render";
+import { useGetSettingsQuery } from "./useGetSettingsQuery";
+
+describe("useGetSettingsQuery", () => {
+ it("resolves /api/settings and returns the parsed body", async () => {
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json({
+ langflow_url: "http://localhost:7860",
+ edited: true,
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useGetSettingsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data).toEqual({
+ langflow_url: "http://localhost:7860",
+ edited: true,
+ });
+ });
+
+ it("throws a fixed error message when the backend responds non-ok", async () => {
+ server.use(
+ http.get("/api/settings", () => new HttpResponse(null, { status: 500 })),
+ );
+
+ const { result } = renderHook(() => useGetSettingsQuery(), {
+ wrapper: createQueryWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.error?.message).toBe("Failed to fetch settings");
+ });
+});
diff --git a/frontend/app/api/queries/useProviderHealthQuery.test.tsx b/frontend/app/api/queries/useProviderHealthQuery.test.tsx
new file mode 100644
index 000000000..60e582e0f
--- /dev/null
+++ b/frontend/app/api/queries/useProviderHealthQuery.test.tsx
@@ -0,0 +1,268 @@
+import { HttpResponse, http } from "msw";
+import { describe, expect, it } from "vitest";
+import { useAuth } from "@/contexts/auth-context";
+import { authPresets, withAuth } from "@/test-utils/fixtures/auth";
+import { makeSettings } from "@/test-utils/fixtures/settings";
+import { makeTask, makeTasksResponse } from "@/test-utils/fixtures/task";
+import { server } from "@/test-utils/msw/server";
+import {
+ createQueryWrapper,
+ createTestQueryClient,
+ renderHook,
+ waitFor,
+} from "@/test-utils/render";
+import { useGetSettingsQuery } from "./useGetSettingsQuery";
+import { useGetTasksQuery } from "./useGetTasksQuery";
+import { useProviderHealthQuery } from "./useProviderHealthQuery";
+
+/**
+ * `rbacDisabled` is the default auth scenario for this file: it makes
+ * `providerHealthAllowed` true unconditionally, which isolates the gate under
+ * test (settings.edited / onboarding / active-ingestion) from the separate
+ * `providers:read` RBAC gate covered explicitly below.
+ */
+function wrapper() {
+ return createQueryWrapper({
+ providers: ["auth", "chat"],
+ auth: authPresets.rbacDisabled,
+ });
+}
+
+describe("useProviderHealthQuery", () => {
+ it("stays disabled until settings.edited is true", async () => {
+ let healthRequests = 0;
+ server.use(
+ http.get("/api/settings", () => HttpResponse.json(makeSettings())),
+ http.get("/api/provider/health", () => {
+ healthRequests++;
+ return HttpResponse.json({ status: "healthy", message: "ok" });
+ }),
+ );
+
+ const queryClient = createTestQueryClient();
+ const { result } = renderHook(
+ () => ({
+ health: useProviderHealthQuery(),
+ settings: useGetSettingsQuery(),
+ tasks: useGetTasksQuery(),
+ }),
+ {
+ wrapper: createQueryWrapper({
+ providers: ["auth", "chat"],
+ auth: authPresets.rbacDisabled,
+ queryClient,
+ }),
+ },
+ );
+
+ await waitFor(() => expect(result.current.settings.isSuccess).toBe(true));
+ await waitFor(() => expect(result.current.tasks.isSuccess).toBe(true));
+ expect(result.current.settings.data?.edited).toBeFalsy();
+ expect(result.current.health.isEnabled).toBe(false);
+ expect(result.current.health.data).toBeUndefined();
+ expect(healthRequests).toBe(0);
+ });
+
+ it("fetches and returns a healthy response once enabled", async () => {
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ edited: true })),
+ ),
+ http.get("/api/provider/health", () =>
+ HttpResponse.json({
+ status: "healthy",
+ message: "ok",
+ provider: "openai",
+ }),
+ ),
+ );
+
+ const { result } = renderHook(() => useProviderHealthQuery(), {
+ wrapper: wrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isEnabled).toBe(true));
+ await waitFor(() => expect(result.current.data?.status).toBe("healthy"));
+ });
+
+ it("maps a 503 to an unhealthy status with the error details", async () => {
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ edited: true })),
+ ),
+ http.get(
+ "/api/provider/health",
+ () =>
+ new HttpResponse(
+ JSON.stringify({
+ message: "Provider validation failed",
+ provider: "openai",
+ llm_error: "Invalid API Key",
+ }),
+ { status: 503 },
+ ),
+ ),
+ );
+
+ const { result } = renderHook(() => useProviderHealthQuery(), {
+ wrapper: wrapper(),
+ });
+
+ await waitFor(() => expect(result.current.data?.status).toBe("unhealthy"));
+ expect(result.current.data?.llm_error).toBe("Invalid API Key");
+ });
+
+ it("maps any other non-ok status to an error status", async () => {
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ edited: true })),
+ ),
+ http.get(
+ "/api/provider/health",
+ () => new HttpResponse(JSON.stringify({}), { status: 500 }),
+ ),
+ );
+
+ const { result } = renderHook(() => useProviderHealthQuery(), {
+ wrapper: wrapper(),
+ });
+
+ await waitFor(() => expect(result.current.data?.status).toBe("error"));
+ expect(result.current.data?.message).toBe(
+ "Failed to check provider health",
+ );
+ });
+
+ it("maps a network failure to backend-unavailable", async () => {
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ edited: true })),
+ ),
+ http.get("/api/provider/health", () => HttpResponse.error()),
+ );
+
+ const { result } = renderHook(() => useProviderHealthQuery(), {
+ wrapper: wrapper(),
+ });
+
+ await waitFor(() =>
+ expect(result.current.data?.status).toBe("backend-unavailable"),
+ );
+ });
+
+ it.each([
+ "pending",
+ "running",
+ "processing",
+ ] as const)("stays disabled while a task is %s", async (status) => {
+ let healthRequests = 0;
+ let releaseSettings!: () => void;
+ const settingsBlocked = new Promise<void>((resolve) => {
+ releaseSettings = resolve;
+ });
+ server.use(
+ http.get("/api/settings", async () => {
+ await settingsBlocked;
+ return HttpResponse.json(makeSettings({ edited: true }));
+ }),
+ http.get("/api/tasks/enhanced", () => {
+ return HttpResponse.json(
+ makeTasksResponse([makeTask({ task_id: "t1", status })]),
+ );
+ }),
+ http.get("/api/provider/health", () => {
+ healthRequests++;
+ return HttpResponse.json({ status: "healthy", message: "ok" });
+ }),
+ );
+
+ const queryClient = createTestQueryClient();
+ const { result } = renderHook(
+ () => ({
+ health: useProviderHealthQuery(),
+ settings: useGetSettingsQuery(),
+ tasks: useGetTasksQuery(),
+ }),
+ {
+ wrapper: createQueryWrapper({
+ providers: ["auth", "chat"],
+ auth: authPresets.rbacDisabled,
+ queryClient,
+ }),
+ },
+ );
+
+ await waitFor(() =>
+ expect(result.current.tasks.data).toEqual([
+ expect.objectContaining({ status }),
+ ]),
+ );
+ releaseSettings();
+ await waitFor(() =>
+ expect(result.current.settings.data?.edited).toBe(true),
+ );
+ expect(result.current.health.isEnabled).toBe(false);
+ expect(healthRequests).toBe(0);
+ });
+
+ it("stays disabled without providers:read when RBAC is enforced", async () => {
+ let healthRequests = 0;
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ edited: true })),
+ ),
+ http.get("/api/provider/health", () => {
+ healthRequests++;
+ return HttpResponse.json({ status: "healthy", message: "ok" });
+ }),
+ );
+
+ const queryClient = createTestQueryClient();
+ const { result } = renderHook(
+ () => ({
+ health: useProviderHealthQuery(),
+ auth: useAuth(),
+ settings: useGetSettingsQuery(),
+ tasks: useGetTasksQuery(),
+ }),
+ {
+ wrapper: createQueryWrapper({
+ providers: ["auth", "chat"],
+ auth: withAuth(authPresets.viewer, {}),
+ queryClient,
+ }),
+ },
+ );
+
+ await waitFor(() =>
+ expect(result.current.auth.permissionsResolved).toBe(true),
+ );
+ await waitFor(() =>
+ expect(result.current.settings.data?.edited).toBe(true),
+ );
+ await waitFor(() => expect(result.current.tasks.isSuccess).toBe(true));
+ expect(result.current.health.isEnabled).toBe(false);
+ expect(healthRequests).toBe(0);
+ });
+
+ it("appends the provider query param when passed", async () => {
+ let capturedUrl: string | undefined;
+ server.use(
+ http.get("/api/settings", () =>
+ HttpResponse.json(makeSettings({ edited: true })),
+ ),
+ http.get("/api/provider/health", ({ request }) => {
+ capturedUrl = request.url;
+ return HttpResponse.json({ status: "healthy", message: "ok" });
+ }),
+ );
+
+ const { result } = renderHook(
+ () => useProviderHealthQuery({ provider: "watsonx" }),
+ { wrapper: wrapper() },
+ );
+
+ await waitFor(() => expect(result.current.data?.status).toBe("healthy"));
+ expect(capturedUrl).toContain("provider=watsonx");
+ });
+});