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): pre-open OAuth window synchronously to unblock iOS Safari (#13592)

Ubbe380b864a65d9
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
index 841ed964a2..ee66bcf7b7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
@@ -321,6 +321,7 @@ describe("MCPSetupCard", () => {
promise: Promise.reject(new Error("OAuth flow timed out")),
cleanup: { abort: vi.fn(), signal: new AbortController().signal },
popupBlocked: false,
+ fallbackBlocked: false,
});
render(<MCPSetupCard output={makeSetupOutput()} />);
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx
index 0902954b3e..3aaeb27ab7 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx
@@ -20,17 +20,21 @@ vi.mock("@/components/molecules/Toast/use-toast", () => ({
}));
vi.mock("@/lib/oauth-popup", () => ({
openOAuthPopup: vi.fn(),
+ preOpenOAuthPopup: vi.fn(() => null),
OAUTH_ERROR_WINDOW_CLOSED: "Sign-in window was closed",
OAUTH_ERROR_FLOW_CANCELED: "OAuth flow was canceled",
OAUTH_ERROR_FLOW_TIMED_OUT: "OAuth flow timed out",
+ OAUTH_ERROR_POPUP_BLOCKED:
+ "Popup blocked — the sign-in window opened in a new tab instead. If you don't see it, allow popups for this site and retry.",
}));
vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
postV2InitiateOauthLoginForAnMcpServer: vi.fn(),
}));
+import { toast } from "@/components/molecules/Toast/use-toast";
import useCredentials from "@/hooks/useCredentials";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-import { openOAuthPopup } from "@/lib/oauth-popup";
+import { openOAuthPopup, preOpenOAuthPopup } from "@/lib/oauth-popup";
const mockUseCredentials = useCredentials as unknown as ReturnType<
typeof vi.fn
@@ -39,6 +43,10 @@ const mockUseBackendAPI = useBackendAPI as unknown as ReturnType<typeof vi.fn>;
const mockOpenOAuthPopup = openOAuthPopup as unknown as ReturnType<
typeof vi.fn
>;
+const mockPreOpenOAuthPopup = preOpenOAuthPopup as unknown as ReturnType<
+ typeof vi.fn
+>;
+const mockToast = toast as unknown as ReturnType<typeof vi.fn>;
const baseSchema: BlockIOCredentialsSubSchema = {
credentials_provider: ["google"],
@@ -139,4 +147,243 @@ describe("CredentialsInput – OAuth flow", () => {
);
});
});
+
+ it("pre-opens the window before the oAuthLogin await and passes it to openOAuthPopup", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const callOrder: string[] = [];
+ mockPreOpenOAuthPopup.mockImplementation(() => {
+ callOrder.push("preOpen");
+ return fakeWindow;
+ });
+
+ const oAuthLoginMock = vi.fn().mockImplementation(async () => {
+ callOrder.push("initiate");
+ return {
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-xyz",
+ };
+ });
+ mockUseBackendAPI.mockReturnValue(
+ makeBackendAPI({ oAuthLogin: oAuthLoginMock }),
+ );
+ mockUseCredentials.mockReturnValue(makeCredentialsReturn());
+ mockOpenOAuthPopup.mockReturnValue({
+ promise: Promise.resolve({ code: "code-2", state: "state-xyz" }),
+ cleanup: { abort: vi.fn() },
+ popupBlocked: false,
+ fallbackBlocked: false,
+ });
+
+ render(
+ <CredentialsInput
+ schema={baseSchema}
+ onSelectCredentials={vi.fn()}
+ showTitle={false}
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /add account/i }),
+ );
+ await waitFor(() => expect(mockOpenOAuthPopup).toHaveBeenCalled());
+
+ // The window must be opened synchronously, before the login-URL request —
+ // after an await iOS Safari blocks every window.open().
+ expect(callOrder).toEqual(["preOpen", "initiate"]);
+ expect(mockOpenOAuthPopup).toHaveBeenCalledWith(
+ "https://accounts.google.com/o/oauth2/auth",
+ expect.objectContaining({
+ stateToken: "state-xyz",
+ preOpenedWindow: fakeWindow,
+ useCrossOriginListeners: true,
+ }),
+ );
+ });
+
+ it("shows the blocked-popup toast and modal copy when the popup is blocked", async () => {
+ mockPreOpenOAuthPopup.mockReturnValue(null);
+ mockUseCredentials.mockReturnValue(makeCredentialsReturn());
+ mockOpenOAuthPopup.mockReturnValue({
+ promise: new Promise(() => {}), // flow stays in flight
+ cleanup: { abort: vi.fn() },
+ popupBlocked: true,
+ fallbackBlocked: false,
+ });
+
+ render(
+ <CredentialsInput
+ schema={baseSchema}
+ onSelectCredentials={vi.fn()}
+ showTitle={false}
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /add account/i }),
+ );
+
+ await waitFor(() =>
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Popup blocked" }),
+ ),
+ );
+ // The waiting modal must direct the user to the fallback tab instead of
+ // to a popup that doesn't exist.
+ expect(
+ await screen.findByText(/blocked the sign-in window/i),
+ ).toBeDefined();
+ });
+
+ it("closes the pre-opened window when the login-URL request fails", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ mockPreOpenOAuthPopup.mockReturnValue(fakeWindow);
+
+ const oAuthLoginMock = vi
+ .fn()
+ .mockRejectedValue(new Error("provider not configured"));
+ mockUseBackendAPI.mockReturnValue(
+ makeBackendAPI({ oAuthLogin: oAuthLoginMock }),
+ );
+ mockUseCredentials.mockReturnValue(makeCredentialsReturn());
+
+ render(
+ <CredentialsInput
+ schema={baseSchema}
+ onSelectCredentials={vi.fn()}
+ showTitle={false}
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /add account/i }),
+ );
+
+ // The failure happens before openOAuthPopup adopts the window, so the
+ // flow still owns the dangling about:blank window and must close it.
+ await waitFor(() => expect(fakeWindow.close).toHaveBeenCalled());
+ expect(mockOpenOAuthPopup).not.toHaveBeenCalled();
+ });
+
+ it("closes the pre-opened window and skips adoption when unmounted mid-initiation", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ mockPreOpenOAuthPopup.mockReturnValue(fakeWindow);
+
+ let resolveLogin: (value: unknown) => void = () => {};
+ const oAuthLoginMock = vi.fn().mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveLogin = resolve;
+ }),
+ );
+ mockUseBackendAPI.mockReturnValue(
+ makeBackendAPI({ oAuthLogin: oAuthLoginMock }),
+ );
+ mockUseCredentials.mockReturnValue(makeCredentialsReturn());
+ mockOpenOAuthPopup.mockReturnValue({
+ promise: Promise.resolve({ code: "code-2", state: "state-xyz" }),
+ cleanup: { abort: vi.fn() },
+ });
+
+ const { unmount } = render(
+ <CredentialsInput
+ schema={baseSchema}
+ onSelectCredentials={vi.fn()}
+ showTitle={false}
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /add account/i }),
+ );
+ await waitFor(() => expect(oAuthLoginMock).toHaveBeenCalled());
+
+ // Unmount while the login-URL request is still in flight — the cleanup
+ // must close the pre-opened window immediately.
+ unmount();
+ expect(fakeWindow.close).toHaveBeenCalled();
+
+ // When the request resolves, the stale continuation must not adopt the
+ // window into a new OAuth popup.
+ resolveLogin({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-xyz",
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(mockOpenOAuthPopup).not.toHaveBeenCalled();
+ });
+
+ it("a superseded flow does not clear the newer flow's abort handler", async () => {
+ const windowA = { closed: false, close: vi.fn() };
+ const windowB = { closed: false, close: vi.fn() };
+ mockPreOpenOAuthPopup
+ .mockReturnValueOnce(windowA)
+ .mockReturnValueOnce(windowB);
+
+ let resolveA: (value: unknown) => void = () => {};
+ let resolveB: (value: unknown) => void = () => {};
+ const oAuthLoginMock = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveA = resolve;
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveB = resolve;
+ }),
+ );
+ mockUseBackendAPI.mockReturnValue(
+ makeBackendAPI({ oAuthLogin: oAuthLoginMock }),
+ );
+ mockUseCredentials.mockReturnValue(makeCredentialsReturn());
+
+ const abortB = vi.fn();
+ mockOpenOAuthPopup.mockReturnValue({
+ promise: new Promise(() => {}), // flow stays in flight
+ cleanup: { abort: abortB },
+ });
+
+ const { unmount } = render(
+ <CredentialsInput
+ schema={baseSchema}
+ onSelectCredentials={vi.fn()}
+ showTitle={false}
+ />,
+ );
+
+ const addAccountButton = await screen.findByRole("button", {
+ name: /add account/i,
+ });
+
+ // Flow A starts, then flow B supersedes it while A's request is pending.
+ fireEvent.click(addAccountButton);
+ await waitFor(() => expect(oAuthLoginMock).toHaveBeenCalledTimes(1));
+ fireEvent.click(addAccountButton);
+ await waitFor(() => expect(oAuthLoginMock).toHaveBeenCalledTimes(2));
+
+ // Starting B closes A's still-pending pre-opened window.
+ expect(windowA.close).toHaveBeenCalled();
+
+ // B's request resolves first and registers its abort handler.
+ resolveB({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-xyz",
+ });
+ await waitFor(() => expect(mockOpenOAuthPopup).toHaveBeenCalledTimes(1));
+
+ // A's request resolves late — its continuation must bail without
+ // nulling B's abort handler in its finally block.
+ resolveA({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-xyz",
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // Unmount must still reach B's abort — i.e. A's finally did not clear it.
+ unmount();
+ expect(abortB).toHaveBeenCalled();
+ });
});
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/OAuthWaitingModal/OAuthWaitingModal.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/OAuthWaitingModal/OAuthWaitingModal.tsx
index cf7c679f31..2e87faeb1b 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/OAuthWaitingModal/OAuthWaitingModal.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/OAuthWaitingModal/OAuthWaitingModal.tsx
@@ -32,7 +32,7 @@ export function OAuthFlowWaitingModal({
<Dialog.Content>
{popupBlocked ? (
<p className="text-sm text-zinc-600">
- Your browser blocked the sign-in popup, so we opened it in a new
+ Your browser blocked the sign-in window, so we opened it in a new
tab. Switch to that tab and complete sign-in there.
<br />
If you don&apos;t see the tab, allow popups for this site, close
@@ -40,7 +40,7 @@ export function OAuthFlowWaitingModal({
</p>
) : (
<p className="text-sm text-zinc-600">
- Complete the sign-in process in the pop-up window.
+ Complete the sign-in process in the sign-in window.
<br />
Closing this dialog will cancel the sign-in process.
</p>
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
index a2fc8aaa37..73bf253965 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
@@ -12,6 +12,7 @@ import {
OAUTH_ERROR_POPUP_BLOCKED,
OAUTH_ERROR_WINDOW_CLOSED,
openOAuthPopup,
+ preOpenOAuthPopup,
} from "@/lib/oauth-popup";
import { useEffect, useRef, useState } from "react";
import {
@@ -70,12 +71,22 @@ export function useCredentialsInput({
const credentials = useCredentials(schema, siblingInputs);
const hasAttemptedAutoSelect = useRef(false);
const oauthAbortRef = useRef<((reason?: string) => void) | null>(null);
+ const oauthFlowIdRef = useRef(0);
+ const preOpenedWindowRef = useRef<Window | null>(null);
const [isDeletingCredential, setIsDeletingCredential] = useState(false);
// Clean up on unmount
useEffect(() => {
return () => {
+ // Invalidate any in-flight flow so its continuation bails instead of
+ // adopting the window, and close a window pre-opened by a flow that
+ // never reached openOAuthPopup (its abort isn't registered yet).
+ oauthFlowIdRef.current += 1;
oauthAbortRef.current?.();
+ if (preOpenedWindowRef.current && !preOpenedWindowRef.current.closed) {
+ preOpenedWindowRef.current.close();
+ }
+ preOpenedWindowRef.current = null;
};
}, []);
@@ -173,8 +184,29 @@ export function useCredentialsInput({
async function executeOAuthFlow(credentialID?: string) {
setOAuthError(null);
- // Abort any previous OAuth flow
+ // Abort any previous OAuth flow, and close the window of one that was
+ // still initiating (its abort wasn't registered yet, so the abort above
+ // can't reach it).
oauthAbortRef.current?.();
+ if (preOpenedWindowRef.current && !preOpenedWindowRef.current.closed) {
+ preOpenedWindowRef.current.close();
+ }
+ preOpenedWindowRef.current = null;
+
+ // Generation marker — lets this flow's continuation detect that it was
+ // superseded (new flow, or unmount) while awaiting the login URL.
+ // Re-entrancy contract: SUPERSEDE — the newest call wins because it may
+ // target a different credential (add account vs scope upgrade).
+ // Deliberately different from useOAuthConnect.connect, which BLOCKS
+ // re-entry (single flow target). Reconcile the two explicitly if this
+ // lifecycle is ever extracted into a shared hook.
+ const flowId = ++oauthFlowIdRef.current;
+
+ // Open the sign-in window synchronously, before the first await — iOS
+ // Safari discards the tap's user-gesture context at any async break and
+ // then blocks every window.open(), including the new-tab fallback.
+ const preOpenedWindow = preOpenOAuthPopup();
+ preOpenedWindowRef.current = preOpenedWindow;
// MCP uses dynamic OAuth discovery per server URL
const isMCP = provider === "mcp" && !!discriminatorValue;
@@ -197,26 +229,37 @@ export function useCredentialsInput({
));
}
+ // A newer flow (or an unmount) superseded this one while the login
+ // URL was being fetched — the superseding path already closed the
+ // pre-opened window; don't adopt it or touch state.
+ if (flowId !== oauthFlowIdRef.current) return;
+
setOAuth2FlowInProgress(true);
setOAuthPopupBlocked(false);
- const { promise, cleanup, popupBlocked } = openOAuthPopup(login_url, {
- stateToken: state_token,
- // Always enable BroadcastChannel + localStorage listeners — they are
- // the only path that works when the popup is blocked and we fall back
- // to a new tab (window.opener can be severed by cross-origin COOP).
- useCrossOriginListeners: true,
- acceptMessageTypes: isMCP
- ? ["mcp_oauth_result"]
- : ["oauth_popup_result"],
- });
+ const { promise, cleanup, popupBlocked, fallbackBlocked } =
+ openOAuthPopup(login_url, {
+ stateToken: state_token,
+ preOpenedWindow,
+ // Always enable BroadcastChannel + localStorage listeners — they are
+ // the only path that works when the popup is blocked and we fall back
+ // to a new tab (window.opener can be severed by cross-origin COOP).
+ useCrossOriginListeners: true,
+ acceptMessageTypes: isMCP
+ ? ["mcp_oauth_result"]
+ : ["oauth_popup_result"],
+ });
+ // Ownership transferred — the helper closes the window on abort now.
+ preOpenedWindowRef.current = null;
// The blank popup window was rejected by the browser — the helper has
// already fallen back to opening the login URL in a new tab, but that
// tab is easy to miss. Track the state so the waiting modal can
// change its copy and direct the user to the right place, and emit a
// toast in case they've already dismissed the modal.
- if (popupBlocked) {
+ // Skip when the fallback was blocked too — the promise has already
+ // rejected and the error below carries the correct retry message.
+ if (popupBlocked && !fallbackBlocked) {
setOAuthPopupBlocked(true);
toast({
title: "Popup blocked",
@@ -259,6 +302,18 @@ export function useCredentialsInput({
provider,
});
} catch (error) {
+ // Close the dangling about:blank window only while this flow still
+ // owns it — i.e. the error occurred before openOAuthPopup adopted the
+ // window. After handoff the ref is nulled and the helper closes the
+ // window itself on abort, so it's no longer ours to close.
+ if (preOpenedWindowRef.current === preOpenedWindow) {
+ preOpenedWindowRef.current = null;
+ if (preOpenedWindow && !preOpenedWindow.closed) {
+ preOpenedWindow.close();
+ }
+ }
+ // A superseded flow must not surface its errors over the newer flow.
+ if (flowId !== oauthFlowIdRef.current) return;
const message = error instanceof Error ? error.message : String(error);
if (
message === OAUTH_ERROR_WINDOW_CLOSED ||
@@ -271,8 +326,13 @@ export function useCredentialsInput({
setOAuthError(`OAuth error: ${message}`);
}
} finally {
- setOAuth2FlowInProgress(false);
- oauthAbortRef.current = null;
+ // A superseded flow must not tear down the newer flow's state —
+ // nulling oauthAbortRef here would orphan the newer popup's abort
+ // handler, and resetting the in-progress flag would close its UI.
+ if (flowId === oauthFlowIdRef.current) {
+ setOAuth2FlowInProgress(false);
+ oauthAbortRef.current = null;
+ }
}
}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx
index 144f50a1ef..946547ac34 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx
@@ -23,8 +23,8 @@ export function OAuthConnectButton({
return (
<div className="flex flex-col gap-3">
<Text variant="body" className="text-[#505057]">
- We&apos;ll open {providerName} in a popup. After approving, you&apos;ll
- come right back.
+ We&apos;ll open a {providerName} sign-in window. Approve access there to
+ finish connecting.
</Text>
<Button
type="button"
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts
index a85241b10a..9bb8375284 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts
@@ -10,6 +10,9 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/lib/oauth-popup", () => ({
openOAuthPopup: vi.fn(),
+ preOpenOAuthPopup: vi.fn(() => null),
+ OAUTH_ERROR_POPUP_BLOCKED:
+ "Popup blocked — the sign-in window opened in a new tab instead. If you don't see it, allow popups for this site and retry.",
}));
vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
@@ -43,6 +46,8 @@ async function setupSuccessfulPopup() {
vi.mocked(openOAuthPopup).mockReturnValue({
promise: Promise.resolve({ code: "auth-code", state: "state-token" }),
cleanup: { abort: vi.fn() },
+ popupBlocked: false,
+ fallbackBlocked: false,
} as unknown as ReturnType<typeof openOAuthPopup>);
}
@@ -175,3 +180,230 @@ describe("useOAuthConnect — error toast", () => {
await waitFor(() => expect(toastMock).toHaveBeenCalled());
});
});
+
+describe("useOAuthConnect — popup window lifecycle", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("pre-opens the window before the initiate await and passes it to openOAuthPopup", async () => {
+ await setupSuccessfulPopup();
+
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const callOrder: string[] = [];
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockImplementation(() => {
+ callOrder.push("preOpen");
+ return fakeWindow as unknown as Window;
+ });
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockImplementation(async () => {
+ callOrder.push("initiate");
+ return {
+ status: 200,
+ data: {
+ login_url: "https://github.com/login/oauth",
+ state_token: "state-token",
+ },
+ } as never;
+ });
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ await result.current.connect();
+
+ // The window must be opened synchronously, before the initiate request —
+ // after an await iOS Safari blocks every window.open().
+ expect(callOrder).toEqual(["preOpen", "initiate"]);
+ expect(vi.mocked(openOAuthPopup)).toHaveBeenCalledWith(
+ "https://github.com/login/oauth",
+ expect.objectContaining({
+ stateToken: "state-token",
+ preOpenedWindow: fakeWindow,
+ useCrossOriginListeners: true,
+ }),
+ );
+ });
+
+ it("closes the pre-opened window when the initiate request fails", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { preOpenOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockRejectedValue(
+ makeApiError(501, { detail: { message: "not configured" } }),
+ );
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ await result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+ expect(fakeWindow.close).toHaveBeenCalled();
+ });
+
+ it("closes the pre-opened window and skips adoption when unmounted mid-initiation", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+
+ let resolveInitiate: (value: unknown) => void = () => {};
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveInitiate = resolve;
+ }) as never,
+ );
+
+ const { result, unmount } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ void result.current.connect();
+
+ // Unmount while the initiate request is still in flight — the cleanup
+ // must close the pre-opened window immediately.
+ unmount();
+ expect(fakeWindow.close).toHaveBeenCalled();
+
+ // When the request resolves, the stale continuation must not adopt the
+ // window or surface anything.
+ resolveInitiate({
+ status: 200,
+ data: {
+ login_url: "https://github.com/login/oauth",
+ state_token: "state-token",
+ },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(vi.mocked(openOAuthPopup)).not.toHaveBeenCalled();
+ expect(toastMock).not.toHaveBeenCalled();
+ });
+
+ it("warns the user when the browser blocked the popup", async () => {
+ await mockInitiateOk();
+
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(null);
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: new Promise(() => {}), // flow stays in flight
+ cleanup: { abort: vi.fn() },
+ popupBlocked: true,
+ fallbackBlocked: false,
+ } as unknown as ReturnType<typeof openOAuthPopup>);
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ // The mocked popup promise never settles, so connect() stays in flight —
+ // don't await it; just wait for the warning toast it fires synchronously
+ // after openOAuthPopup returns.
+ void result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+ const arg = toastMock.mock.calls[0][0] as { title: string };
+ expect(arg.title).toBe("Popup blocked");
+ });
+
+ it("shows only the failure toast when both popup and fallback tab are blocked", async () => {
+ await mockInitiateOk();
+
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(null);
+ vi.mocked(openOAuthPopup).mockImplementation(
+ () =>
+ ({
+ promise: Promise.reject(
+ new Error(
+ "Popup blocked — allow popups for this site and try again.",
+ ),
+ ),
+ cleanup: { abort: vi.fn() },
+ popupBlocked: true,
+ fallbackBlocked: true,
+ }) as unknown as ReturnType<typeof openOAuthPopup>,
+ );
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ await result.current.connect();
+
+ await waitFor(() => expect(toastMock).toHaveBeenCalled());
+ // Exactly one toast — the "opened in a new tab" hint would contradict it.
+ expect(toastMock).toHaveBeenCalledTimes(1);
+ const arg = toastMock.mock.calls[0][0] as {
+ title: string;
+ description: string;
+ };
+ expect(arg.title).toBe("OAuth connection failed");
+ expect(arg.description).toBe(
+ "Popup blocked — allow popups for this site and try again.",
+ );
+ });
+
+ it("ignores a re-entrant connect() while a flow is in flight", async () => {
+ const { preOpenOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(null);
+
+ let resolveInitiate: (value: unknown) => void = () => {};
+ const { getV1InitiateOauthFlow } = await import(
+ "@/app/api/__generated__/endpoints/integrations/integrations"
+ );
+ vi.mocked(getV1InitiateOauthFlow).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveInitiate = resolve;
+ }) as never,
+ );
+
+ const { result } = renderHook(() =>
+ useOAuthConnect({ provider: "github", onSuccess: vi.fn() }),
+ );
+
+ // A rapid double-click fires the second call while the first is still
+ // awaiting the initiate request — it must return without side effects.
+ const first = result.current.connect();
+ await result.current.connect();
+
+ expect(vi.mocked(preOpenOAuthPopup)).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(getV1InitiateOauthFlow)).toHaveBeenCalledTimes(1);
+
+ // Let the first flow finish so the test doesn't leak a pending flow.
+ await setupSuccessfulPopup();
+ resolveInitiate({
+ status: 200,
+ data: {
+ login_url: "https://github.com/login/oauth",
+ state_token: "state-token",
+ },
+ });
+ await first;
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts
index 6bf1c5f614..e538be752f 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts
@@ -9,7 +9,11 @@ import {
postV1ExchangeOauthCodeForTokens,
} from "@/app/api/__generated__/endpoints/integrations/integrations";
import { toast } from "@/components/molecules/Toast/use-toast";
-import { openOAuthPopup } from "@/lib/oauth-popup";
+import {
+ OAUTH_ERROR_POPUP_BLOCKED,
+ openOAuthPopup,
+ preOpenOAuthPopup,
+} from "@/lib/oauth-popup";
import { getOAuthErrorMessage } from "./helpers";
@@ -21,19 +25,44 @@ interface Args {
export function useOAuthConnect({ provider, onSuccess }: Args) {
const queryClient = useQueryClient();
const [isPending, setIsPending] = useState(false);
+ const isPendingRef = useRef(false);
const abortRef = useRef<(() => void) | null>(null);
const isUnmountedRef = useRef(false);
+ const preOpenedWindowRef = useRef<Window | null>(null);
useEffect(() => {
isUnmountedRef.current = false;
return () => {
isUnmountedRef.current = true;
abortRef.current?.();
+ // Close a window pre-opened by a flow still fetching the login URL —
+ // its abort isn't registered yet, so the line above can't reach it.
+ if (preOpenedWindowRef.current && !preOpenedWindowRef.current.closed) {
+ preOpenedWindowRef.current.close();
+ }
+ preOpenedWindowRef.current = null;
};
}, []);
async function connect() {
+ // Ignore re-entry while a flow is in flight: a rapid double-click fires
+ // again before the pending state re-renders the button, and a second
+ // concurrent flow would overwrite preOpenedWindowRef/abortRef. State
+ // isn't readable synchronously here, so track it in a ref.
+ // Re-entrancy contract: BLOCK — this button has a single flow target, so
+ // a second call is always a duplicate. Deliberately different from
+ // useCredentialsInput.executeOAuthFlow, which SUPERSEDES (its next call
+ // may target a different credential). Reconcile the two explicitly if
+ // this lifecycle is ever extracted into a shared hook.
+ if (isPendingRef.current) return;
+ isPendingRef.current = true;
setIsPending(true);
+ // Open the sign-in window synchronously, before the first await — iOS
+ // Safari discards the tap's user-gesture context at any async break and
+ // then blocks every window.open(), including the new-tab fallback, so
+ // nothing would open at all.
+ const preOpenedWindow = preOpenOAuthPopup();
+ preOpenedWindowRef.current = preOpenedWindow;
try {
const initiateResponse = await getV1InitiateOauthFlow(provider);
// customMutator rejects non-2xx, so this branch is unreachable at
@@ -44,11 +73,36 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {
}
const { login_url, state_token } = initiateResponse.data;
- const { promise, cleanup } = openOAuthPopup(login_url, {
- stateToken: state_token,
- });
+ // Unmounted while the login URL was being fetched — the cleanup
+ // already closed the window; don't adopt it.
+ if (isUnmountedRef.current) return;
+
+ const { promise, cleanup, popupBlocked, fallbackBlocked } =
+ openOAuthPopup(login_url, {
+ stateToken: state_token,
+ preOpenedWindow,
+ // BroadcastChannel + localStorage listeners are the only delivery
+ // path when the flow runs in a tab without window.opener (the iOS
+ // fallback) — the callback page already writes to both.
+ useCrossOriginListeners: true,
+ acceptMessageTypes: ["oauth_popup_result"],
+ });
+ // Ownership transferred — the helper closes the window on abort now.
+ preOpenedWindowRef.current = null;
abortRef.current = () => cleanup.abort("unmounted");
+ // The browser blocked even the synchronous window.open but the new-tab
+ // fallback opened — that tab is easy to miss, so tell the user. Skip
+ // the hint when the fallback was blocked too: the promise has already
+ // rejected and the catch below shows the correct allow-popups-and-retry
+ // message — showing both would contradict each other.
+ if (popupBlocked && !fallbackBlocked) {
+ toast({
+ title: "Popup blocked",
+ description: OAUTH_ERROR_POPUP_BLOCKED,
+ });
+ }
+
const { code, state } = await promise;
abortRef.current = null;
@@ -63,6 +117,16 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {
});
onSuccess();
} catch (error) {
+ // Close the dangling about:blank window only while this flow still
+ // owns it — i.e. the error occurred before openOAuthPopup adopted the
+ // window. After handoff the ref is nulled and the helper closes the
+ // window itself on abort, so it's no longer ours to close.
+ if (preOpenedWindowRef.current === preOpenedWindow) {
+ preOpenedWindowRef.current = null;
+ if (preOpenedWindow && !preOpenedWindow.closed) {
+ preOpenedWindow.close();
+ }
+ }
if (isUnmountedRef.current) return;
toast({
title: "OAuth connection failed",
@@ -70,6 +134,7 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {
variant: "destructive",
});
} finally {
+ isPendingRef.current = false;
setIsPending(false);
}
}
diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.test.ts b/autogpt_platform/frontend/src/lib/oauth-popup.test.ts
index 4202c0e715..848d8b3762 100644
--- a/autogpt_platform/frontend/src/lib/oauth-popup.test.ts
+++ b/autogpt_platform/frontend/src/lib/oauth-popup.test.ts
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
OAUTH_ERROR_FLOW_CANCELED,
+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB,
OAUTH_ERROR_WINDOW_CLOSED,
openOAuthPopup,
+ preOpenOAuthPopup,
} from "./oauth-popup";
// Minimal popup stub — window.open returns this. `closed` flips when the
@@ -243,3 +245,142 @@ describe("openOAuthPopup popup-close grace window", () => {
cleanup.abort();
});
});
+
+describe("preOpenedWindow option", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ localStorage.clear();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ test("navigates the pre-opened window instead of calling window.open again", () => {
+ const openSpy = vi.spyOn(window, "open");
+ const preOpened = makePopupStub();
+
+ const { promise, cleanup, popupBlocked, fallbackBlocked } = openOAuthPopup(
+ "https://example.com/oauth",
+ {
+ stateToken: "tok-pre",
+ preOpenedWindow: preOpened as unknown as Window,
+ },
+ );
+ promise.catch(() => {});
+
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(preOpened.location.href).toBe("https://example.com/oauth");
+ expect(popupBlocked).toBe(false);
+ expect(fallbackBlocked).toBe(false);
+
+ // After adoption the helper owns the window: aborting must close it —
+ // callers no longer close an adopted window themselves.
+ cleanup.abort();
+ expect(preOpened.close).toHaveBeenCalled();
+ });
+
+ test("already-closed preOpenedWindow goes to the new-tab fallback", () => {
+ const openSpy = setupPopup(makePopupStub());
+ const preOpened = makePopupStub();
+ preOpened.closed = true;
+
+ const { promise, cleanup, popupBlocked, fallbackBlocked } = openOAuthPopup(
+ "https://example.com/oauth",
+ {
+ stateToken: "tok-pre-closed",
+ preOpenedWindow: preOpened as unknown as Window,
+ },
+ );
+ promise.catch(() => {});
+
+ expect(popupBlocked).toBe(true);
+ expect(fallbackBlocked).toBe(false);
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ expect(openSpy).toHaveBeenCalledWith("https://example.com/oauth", "_blank");
+
+ cleanup.abort();
+ });
+
+ test("null preOpenedWindow goes straight to the new-tab fallback", () => {
+ const openSpy = setupPopup(makePopupStub());
+
+ const { promise, cleanup, popupBlocked, fallbackBlocked } = openOAuthPopup(
+ "https://example.com/oauth",
+ {
+ stateToken: "tok-null",
+ preOpenedWindow: null,
+ },
+ );
+ promise.catch(() => {});
+
+ expect(popupBlocked).toBe(true);
+ expect(fallbackBlocked).toBe(false);
+ // Only the fallback open fires, with the real login URL.
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ expect(openSpy).toHaveBeenCalledWith("https://example.com/oauth", "_blank");
+
+ cleanup.abort();
+ });
+
+ test("preOpenOAuthPopup opens a blank popup window", () => {
+ const popup = makePopupStub();
+ const openSpy = setupPopup(popup);
+
+ const result = preOpenOAuthPopup();
+
+ expect(result).toBe(popup);
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ expect(openSpy.mock.calls[0][0]).toBe("about:blank");
+ });
+
+ test("rejects immediately when the new-tab fallback is blocked too", async () => {
+ // iOS Safari case: the synchronous pre-open was already blocked, and the
+ // fallback open after the async break has no gesture context either.
+ setupPopup(null);
+
+ const { promise, popupBlocked, fallbackBlocked } = openOAuthPopup(
+ "https://example.com/oauth",
+ {
+ stateToken: "tok-blocked",
+ preOpenedWindow: null,
+ },
+ );
+ const onReject = vi.fn();
+ promise.catch(onReject);
+
+ await vi.advanceTimersByTimeAsync(10);
+
+ expect(popupBlocked).toBe(true);
+ expect(fallbackBlocked).toBe(true);
+ expect(onReject).toHaveBeenCalledTimes(1);
+ expect((onReject.mock.calls[0][0] as Error).message).toBe(
+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB,
+ );
+ });
+
+ test("rejects immediately when window.open is blocked for both attempts", async () => {
+ // No preOpenedWindow — the inline open is blocked, and so is the
+ // fallback (e.g. aggressive popup blocker). Must not wait for timeout.
+ setupPopup(null);
+
+ const { promise, popupBlocked, fallbackBlocked } = openOAuthPopup(
+ "https://example.com/oauth",
+ {
+ stateToken: "tok-blocked-2",
+ },
+ );
+ const onReject = vi.fn();
+ promise.catch(onReject);
+
+ await vi.advanceTimersByTimeAsync(10);
+
+ expect(popupBlocked).toBe(true);
+ expect(fallbackBlocked).toBe(true);
+ expect(onReject).toHaveBeenCalledTimes(1);
+ expect((onReject.mock.calls[0][0] as Error).message).toBe(
+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB,
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.ts b/autogpt_platform/frontend/src/lib/oauth-popup.ts
index 9e17f1e3d9..ac1a83cc8e 100644
--- a/autogpt_platform/frontend/src/lib/oauth-popup.ts
+++ b/autogpt_platform/frontend/src/lib/oauth-popup.ts
@@ -12,7 +12,9 @@ export const OAUTH_ERROR_WINDOW_CLOSED = "Sign-in window was closed";
export const OAUTH_ERROR_FLOW_CANCELED = "OAuth flow was canceled";
export const OAUTH_ERROR_FLOW_TIMED_OUT = "OAuth flow timed out";
export const OAUTH_ERROR_POPUP_BLOCKED =
- "Popup blocked — sign-in opened in a new tab. If you don't see it, allow popups for this site and retry.";
+ "Popup blocked — the sign-in window opened in a new tab instead. If you don't see it, allow popups for this site and retry.";
+export const OAUTH_ERROR_POPUP_BLOCKED_NO_TAB =
+ "Popup blocked — allow popups for this site and try again.";
export type OAuthPopupResult = {
code: string;
@@ -22,6 +24,17 @@ export type OAuthPopupResult = {
export type OAuthPopupOptions = {
/** State token to validate against incoming messages */
stateToken: string;
+ /**
+ * A window pre-opened via {@link preOpenOAuthPopup} synchronously inside the
+ * user-gesture handler, before any `await`. iOS Safari discards the gesture
+ * context at the first async break, so a `window.open()` issued after an
+ * `await` (e.g. after fetching the login URL) is always blocked — callers
+ * that need to do async work before knowing the login URL must pre-open the
+ * window and pass it here. `null` means the browser blocked even the
+ * synchronous open; the new-tab fallback is used. When omitted, the window
+ * is opened inline as before.
+ */
+ preOpenedWindow?: Window | null;
/**
* Use BroadcastChannel + localStorage polling on top of postMessage. Needed
* whenever `window.opener` may not survive (cross-origin OAuth providers
@@ -45,11 +58,30 @@ type Cleanup = {
signal: AbortSignal;
};
+/**
+ * Opens the blank OAuth window synchronously and returns its handle (null when
+ * the browser blocks it). Must be called directly from a user-gesture handler
+ * (click/tap), before any `await` — browsers, most strictly iOS Safari, block
+ * `window.open()` once the gesture context is lost across an async break.
+ */
+export function preOpenOAuthPopup(): Window | null {
+ const width = 500;
+ const height = 700;
+ const left = window.screenX + (window.outerWidth - width) / 2;
+ const top = window.screenY + (window.outerHeight - height) / 2;
+ return window.open(
+ "about:blank",
+ "_blank",
+ `width=${width},height=${height},left=${left},top=${top},popup=true,scrollbars=yes`,
+ );
+}
+
/**
* Opens an OAuth popup and sets up listeners for the callback result.
*
- * Opens a blank popup synchronously (to avoid popup blockers), then navigates
- * it to the login URL. Returns a promise that resolves with the OAuth code/state.
+ * Opens a blank popup synchronously (to avoid popup blockers) — or adopts the
+ * caller's `preOpenedWindow` when given — then navigates it to the login URL.
+ * Returns a promise that resolves with the OAuth code/state.
*
* @param loginUrl - The OAuth authorization URL to navigate to
* @param options - Configuration for message handling
@@ -67,9 +99,17 @@ export function openOAuthPopup(
* tab can be easy to miss) and offer a retry path.
*/
popupBlocked: boolean;
+ /**
+ * True iff the new-tab fallback was refused too — no window exists at all
+ * and the promise has already rejected. Callers must NOT show the
+ * popupBlocked "opened in a new tab" hint in this case; the rejection
+ * already carries the correct allow-popups-and-retry message.
+ */
+ fallbackBlocked: boolean;
} {
const {
stateToken,
+ preOpenedWindow,
useCrossOriginListeners = false,
broadcastChannelName = "oauth_popup",
localStorageKey = "oauth_popup_result",
@@ -79,25 +119,28 @@ export function openOAuthPopup(
const controller = new AbortController();
- // Open popup synchronously (before any async work) to avoid browser popup blockers
- const width = 500;
- const height = 700;
- const left = window.screenX + (window.outerWidth - width) / 2;
- const top = window.screenY + (window.outerHeight - height) / 2;
- const popup = window.open(
- "about:blank",
- "_blank",
- `width=${width},height=${height},left=${left},top=${top},popup=true,scrollbars=yes`,
- );
+ // Adopt the caller's pre-opened window when given (required on iOS Safari,
+ // where window.open only works synchronously inside the gesture handler);
+ // otherwise open it now — still synchronous from the caller's perspective,
+ // so the gesture context is intact when openOAuthPopup itself is called
+ // straight from a click handler.
+ const popup =
+ preOpenedWindow !== undefined ? preOpenedWindow : preOpenOAuthPopup();
let popupBlocked = false;
+ let fallbackBlocked = false;
if (popup && !popup.closed) {
popup.location.href = loginUrl;
} else {
// Popup was blocked — open in new tab as fallback so the OAuth flow can
// still complete via postMessage / BroadcastChannel / localStorage poll.
popupBlocked = true;
- window.open(loginUrl, "_blank");
+ const fallback = window.open(loginUrl, "_blank");
+ // The fallback open can be blocked too — iOS Safari blocks every
+ // window.open() after an async break, so when the caller pre-opened
+ // (and lost) the window, this open has no gesture context either. No
+ // window exists at all then, so no result can ever arrive.
+ fallbackBlocked = !fallback || fallback.closed;
}
// Close popup on abort
@@ -121,6 +164,17 @@ export function openOAuthPopup(
const promise = new Promise<OAuthPopupResult>((resolve, reject) => {
let handled = false;
+ // Both the popup and the new-tab fallback were blocked — no window
+ // exists, so no result can ever arrive. Fail fast instead of hanging
+ // until the timeout while the UI claims a tab opened. Retrying from a
+ // fresh tap (the connect button is re-enabled once this rejects) gets a
+ // new user-gesture context.
+ if (fallbackBlocked) {
+ handled = true;
+ reject(new Error(OAUTH_ERROR_POPUP_BLOCKED_NO_TAB));
+ return;
+ }
+
const handleResult = (data: any) => {
if (handled) return; // Prevent double-handling
@@ -301,5 +355,6 @@ export function openOAuthPopup(
signal: controller.signal,
},
popupBlocked,
+ fallbackBlocked,
};
}