Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend/integrations): show OAuth connect error toast with a readable message (#13282)

Void&Nulle6818e77a4b8
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..bba24591e9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/__tests__/helpers.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+
+import { getOAuthErrorMessage } from "../helpers";
+
+function apiError(response: unknown, message = "[object Object]") {
+ const err = new Error(message) as Error & { response: unknown };
+ err.name = "ApiError";
+ err.response = response;
+ return err;
+}
+
+describe("getOAuthErrorMessage", () => {
+ it("reads a string detail from response", () => {
+ expect(getOAuthErrorMessage(apiError({ detail: "boom" }))).toBe("boom");
+ });
+
+ it("joins msg fields from a validation array", () => {
+ const err = apiError({
+ detail: [{ msg: "Field required" }, { msg: "Too short" }],
+ });
+ expect(getOAuthErrorMessage(err)).toBe("Field required, Too short");
+ });
+
+ it("combines message and hint from a dict detail", () => {
+ const err = apiError({
+ detail: { message: "not configured", hint: "set keys" },
+ });
+ expect(getOAuthErrorMessage(err)).toBe("not configured set keys");
+ });
+
+ it("returns message alone when the dict has no hint", () => {
+ expect(
+ getOAuthErrorMessage(apiError({ detail: { message: "nope" } })),
+ ).toBe("nope");
+ });
+
+ it("falls back to detail on the error itself when there is no response", () => {
+ const err = new Error("[object Object]") as Error & { detail: unknown };
+ err.detail = "direct detail";
+ expect(getOAuthErrorMessage(err)).toBe("direct detail");
+ });
+
+ it("uses error.message when no usable detail is present", () => {
+ expect(getOAuthErrorMessage(new Error("plain failure"))).toBe(
+ "plain failure",
+ );
+ });
+
+ it("falls back to a generic message when message is the coerced object string", () => {
+ expect(getOAuthErrorMessage(apiError({ detail: { code: 1 } }))).toBe(
+ "Something went wrong. Please try again.",
+ );
+ });
+
+ it("falls back to a generic message for non-error values", () => {
+ expect(getOAuthErrorMessage("just a string")).toBe(
+ "Something went wrong. Please try again.",
+ );
+ expect(getOAuthErrorMessage(null)).toBe(
+ "Something went wrong. Please try again.",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts
new file mode 100644
index 0000000000..a85241b10a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts
@@ -0,0 +1,177 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { StrictMode } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { useOAuthConnect } from "../useOAuthConnect";
+
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
+}));
+
+vi.mock("@/lib/oauth-popup", () => ({
+ openOAuthPopup: vi.fn(),
+}));
+
+vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
+ getV1InitiateOauthFlow: vi.fn(),
+ postV1ExchangeOauthCodeForTokens: vi.fn(),
+ getGetV1ListCredentialsQueryKey: vi.fn(() => ["credentials"]),
+}));
+
+const toastMock = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: (args: unknown) => toastMock(args),
+}));
+
+type ApiErrorShape = Error & { status: number; response: unknown };
+
+function makeApiError(status: number, response: unknown): ApiErrorShape {
+ // Reproduces customMutator: `new ApiError(errorMessage, status, responseData)`
+ // where errorMessage = responseData.detail. When detail is a non-string
+ // (FastAPI 422 array / dict), Error coerces it to "[object Object]".
+ const detail = (response as { detail?: unknown })?.detail;
+ const message = typeof detail === "string" ? detail : String(detail);
+ const err = new Error(message) as ApiErrorShape;
+ err.name = "ApiError";
+ err.status = status;
+ err.response = response;
+ return err;
+}
+
+async function setupSuccessfulPopup() {
+ const { openOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: Promise.resolve({ code: "auth-code", state: "state-token" }),
+ cleanup: { abort: vi.fn() },
+ } as unknown as ReturnType<typeof openOAuthPopup>);
+}
+
+async function mockInitiateOk() {
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockResolvedValue({
+ status: 200,
+ data: {
+ login_url: "https://github.com/login/oauth",
+ state_token: "state-token",
+ },
+ } as never);
+}
+
+describe("useOAuthConnect — error toast", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("shows the FastAPI 422 validation message, not [object Object]", async () => {
+ await setupSuccessfulPopup();
+ await mockInitiateOk();
+
+ const { postV1ExchangeOauthCodeForTokens } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(postV1ExchangeOauthCodeForTokens).mockRejectedValue(
+ makeApiError(422, {
+ detail: [
+ {
+ type: "missing",
+ loc: ["body", "state_token"],
+ msg: "Field required",
+ input: null,
+ },
+ ],
+ }),
+ );
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ await result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+
+ const arg = toastMock.mock.calls[0][0] as {
+ title: string;
+ description: string;
+ };
+ expect(arg.title).toBe("OAuth connection failed");
+ expect(arg.description).not.toBe("[object Object]");
+ expect(arg.description).toContain("Field required");
+ });
+
+ it("shows a string detail message unchanged", async () => {
+ await setupSuccessfulPopup();
+ await mockInitiateOk();
+
+ const { postV1ExchangeOauthCodeForTokens } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(postV1ExchangeOauthCodeForTokens).mockRejectedValue(
+ makeApiError(400, {
+ detail: "OAuth2 callback failed to exchange code for tokens",
+ }),
+ );
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ await result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+
+ const arg = toastMock.mock.calls[0][0] as { description: string };
+ expect(arg.description).toBe(
+ "OAuth2 callback failed to exchange code for tokens",
+ );
+ });
+
+ it("shows the 501 dict detail message for an unconfigured provider", async () => {
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockRejectedValue(
+ makeApiError(501, {
+ detail: {
+ message: "Integration with provider 'github' is not configured.",
+ hint: "Set client ID and secret in the application's deployment environment",
+ },
+ }),
+ );
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ await result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+
+ const arg = toastMock.mock.calls[0][0] as { description: string };
+ expect(arg.description).not.toBe("[object Object]");
+ expect(arg.description).toContain("is not configured");
+ });
+
+ it("still fires the toast after a StrictMode mount→cleanup→remount", async () => {
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockRejectedValue(
+ makeApiError(501, { detail: { message: "not configured" } }),
+ );
+
+ // StrictMode runs the mount effect, its cleanup, then the effect again on
+ // the same instance. The cleanup sets isUnmountedRef to true, so without a
+ // reset on (re)mount the catch guard silently swallows the toast.
+ const { result } = renderHook(
+ () => useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ { wrapper: StrictMode },
+ );
+
+ await result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/helpers.ts
new file mode 100644
index 0000000000..6898af46c9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/helpers.ts
@@ -0,0 +1,54 @@
+type ValidationDetailItem = { msg?: unknown };
+
+function readDetail(value: unknown): string | null {
+ if (typeof value !== "object" || value === null) return null;
+ const detail = (value as { detail?: unknown }).detail;
+
+ if (typeof detail === "string" && detail.length > 0) return detail;
+
+ if (Array.isArray(detail)) {
+ const messages = detail
+ .map((item: ValidationDetailItem) =>
+ typeof item?.msg === "string" ? item.msg : null,
+ )
+ .filter((msg): msg is string => msg !== null);
+ if (messages.length > 0) return messages.join(", ");
+ }
+
+ if (typeof detail === "object" && detail !== null) {
+ const message = (detail as { message?: unknown }).message;
+ if (typeof message === "string" && message.length > 0) {
+ const hint = (detail as { hint?: unknown }).hint;
+ return typeof hint === "string" && hint.length > 0
+ ? `${message} ${hint}`
+ : message;
+ }
+ }
+
+ return null;
+}
+
+// Extracts a human-readable message from an error thrown by the API client.
+// The mutator builds `ApiError` via `new Error(detail)`, so when the backend
+// returns a non-string `detail` (FastAPI 422 array, or a dict), `error.message`
+// is coerced to the useless string "[object Object]". Prefer the structured
+// `response.detail` and only fall back to `error.message` when it's usable.
+export function getOAuthErrorMessage(error: unknown): string {
+ if (typeof error === "object" && error !== null) {
+ const fromResponse = readDetail((error as { response?: unknown }).response);
+ if (fromResponse) return fromResponse;
+
+ const fromError = readDetail(error);
+ if (fromError) return fromError;
+ }
+
+ if (
+ error instanceof Error &&
+ error.message &&
+ error.message !== "[object Object]"
+ ) {
+ return error.message;
+ }
+
+ return "Something went wrong. Please try again.";
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts
index f7f95b7b0b..6bf1c5f614 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts
@@ -11,6 +11,8 @@ import {
import { toast } from "@/components/molecules/Toast/use-toast";
import { openOAuthPopup } from "@/lib/oauth-popup";
+import { getOAuthErrorMessage } from "./helpers";
+
interface Args {
provider: string;
onSuccess: () => void;
@@ -23,6 +25,7 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {
const isUnmountedRef = useRef(false);
useEffect(() => {
+ isUnmountedRef.current = false;
return () => {
isUnmountedRef.current = true;
abortRef.current?.();
@@ -63,8 +66,7 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {
if (isUnmountedRef.current) return;
toast({
title: "OAuth connection failed",
- description:
- error instanceof Error ? error.message : "Unexpected error",
+ description: getOAuthErrorMessage(error),
variant: "destructive",
});
} finally {