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): MCP OAuth popup fails with 'Sign-in window was closed' on COOP providers (#14141)
Ubbed1f62979ca49
diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.test.ts b/autogpt_platform/frontend/src/lib/oauth-popup.test.tsindex f87a56a819..6def02e291 100644--- a/autogpt_platform/frontend/src/lib/oauth-popup.test.ts+++ b/autogpt_platform/frontend/src/lib/oauth-popup.test.ts@@ -23,7 +23,7 @@ function setupPopup(stub: ReturnType<typeof makePopupStub> | null) {.mockImplementation(() => stub as unknown as Window);}-describe("openOAuthPopup popup-close grace window", () => {+describe("openOAuthPopup popup-close handling", () => {beforeEach(() => {vi.useFakeTimers();localStorage.clear();@@ -35,7 +35,7 @@ describe("openOAuthPopup popup-close grace window", () => {vi.unstubAllGlobals();});- test("rejects with WINDOW_CLOSED after grace if no result arrives", async () => {+ test("cross-origin flow survives a COOP-severed handle reporting closed", async () => {const popup = makePopupStub();setupPopup(popup);@@ -43,30 +43,40 @@ describe("openOAuthPopup popup-close grace window", () => {stateToken: "tok-1",useCrossOriginListeners: true,});+ const onResolve = vi.fn();const onReject = vi.fn();- promise.catch(onReject);+ promise.then(onResolve, onReject);- // User closes the popup.+ // Providers serving COOP: same-origin (e.g. Stripe) trigger a+ // browsing-context-group swap when the popup navigates to them — the+ // parent's handle is severed and ``closed`` flips to true while the+ // window is still open and the user hasn't signed in yet.popup.closed = true;- // First closed-poll tick (500ms) observes closed and starts the 3s grace.- await vi.advanceTimersByTimeAsync(500);- expect(onReject).not.toHaveBeenCalled();-- // Mid-grace: still pending.- await vi.advanceTimersByTimeAsync(1500);+ // The user takes far longer than any close-based deadline to authorize.+ await vi.advanceTimersByTimeAsync(30_000);expect(onReject).not.toHaveBeenCalled();- // Grace expires (total +3000ms after close-detect) → reject fires.- await vi.advanceTimersByTimeAsync(1600);- expect(onReject).toHaveBeenCalledTimes(1);- expect(onReject.mock.calls[0][0]).toBeInstanceOf(Error);- expect((onReject.mock.calls[0][0] as Error).message).toBe(- OAUTH_ERROR_WINDOW_CLOSED,+ // The callback page finally lands the result via localStorage.+ localStorage.setItem(+ "oauth_popup_result_tok-1",+ JSON.stringify({+ message_type: "mcp_oauth_result",+ success: true,+ code: "late-auth-code",+ state: "tok-1",+ }),);+ await vi.advanceTimersByTimeAsync(500);++ expect(onReject).not.toHaveBeenCalled();+ expect(onResolve).toHaveBeenCalledWith({+ code: "late-auth-code",+ state: "tok-1",+ });});- test("final localStorage sweep resolves when result lands after close", async () => {+ test("cross-origin localStorage poll resolves the flow", async () => {const popup = makePopupStub();setupPopup(popup);@@ -78,9 +88,8 @@ describe("openOAuthPopup popup-close grace window", () => {const onReject = vi.fn();promise.then(onResolve, onReject);- // Result lands in scoped localStorage just before the user closes the- // popup — the BroadcastChannel listener never fired (storage partitioning)- // and the periodic poll hasn't ticked yet.+ // The BroadcastChannel listener never fires, so the callback page leaves+ // the result in scoped localStorage for the periodic poll to read.localStorage.setItem("oauth_popup_result_tok-2",JSON.stringify({@@ -90,10 +99,8 @@ describe("openOAuthPopup popup-close grace window", () => {state: "tok-2",}),);- popup.closed = true;- // First closed-poll tick runs the synchronous final-storage check,- // which resolves the promise before the grace timer even arms.+ // The next periodic localStorage poll resolves the flow.await vi.advanceTimersByTimeAsync(500);expect(onReject).not.toHaveBeenCalled();@@ -105,7 +112,7 @@ describe("openOAuthPopup popup-close grace window", () => {expect(localStorage.getItem("oauth_popup_result_tok-2")).toBeNull();});- test("result arriving during grace window cancels the WINDOW_CLOSED reject", async () => {+ test("result arriving after the handle reports closed still resolves", async () => {const popup = makePopupStub();setupPopup(popup);@@ -117,11 +124,11 @@ describe("openOAuthPopup popup-close grace window", () => {const onReject = vi.fn();promise.then(onResolve, onReject);- // User closes popup before the result lands.+ // Handle reports closed before the result lands.popup.closed = true;- await vi.advanceTimersByTimeAsync(500); // close-detect fires, grace armed+ await vi.advanceTimersByTimeAsync(500);- // Result lands ~1s into the grace via localStorage (polled every 500ms).+ // Result lands ~1s later via localStorage (polled every 500ms).localStorage.setItem("oauth_popup_result_tok-3",JSON.stringify({@@ -138,12 +145,12 @@ describe("openOAuthPopup popup-close grace window", () => {state: "tok-3",});- // Run out the rest of the grace window — must NOT reject after the fact.+ // Keep advancing — must NOT reject after the fact.await vi.advanceTimersByTimeAsync(3000);expect(onReject).not.toHaveBeenCalled();});- test("abort during grace window tears down the grace timer", async () => {+ test("abort after the handle reports closed rejects with CANCELED", async () => {const popup = makePopupStub();setupPopup(popup);@@ -155,9 +162,9 @@ describe("openOAuthPopup popup-close grace window", () => {promise.catch(onReject);popup.closed = true;- await vi.advanceTimersByTimeAsync(500); // grace armed+ await vi.advanceTimersByTimeAsync(500);- // Caller aborts (e.g. component unmount) before grace expires.+ // Caller aborts (e.g. component unmount).cleanup.abort();await vi.advanceTimersByTimeAsync(10);@@ -167,8 +174,7 @@ describe("openOAuthPopup popup-close grace window", () => {OAUTH_ERROR_FLOW_CANCELED,);- // Advancing past the original grace deadline must not produce a second- // reject — the grace setTimeout was cleared by the abort listener.+ // Advancing further must not produce a second reject.await vi.advanceTimersByTimeAsync(5000);expect(onReject).toHaveBeenCalledTimes(1);});diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.ts b/autogpt_platform/frontend/src/lib/oauth-popup.tsindex 5641ffabbc..ef1a952774 100644--- a/autogpt_platform/frontend/src/lib/oauth-popup.ts+++ b/autogpt_platform/frontend/src/lib/oauth-popup.ts@@ -257,91 +257,35 @@ export function openOAuthPopup();}- // Detect popup closed without completing sign-in.+ // Detect popup closed without completing sign-in — same-origin flows+ // only.//- // Three timeouts apply to the OAuth flow, only the outermost bounds- // user time:- // 1. ``timeout`` (default 5 min) — overall deadline; rejects with- // OAUTH_ERROR_FLOW_TIMED_OUT if the user never finishes signing- // in. This is the only timeout that limits how long the user- // has to log in.- // 2. 500 ms polling on ``popup.closed`` — only fires after the- // popup window actually goes away (user closed it OR callback- // page self-closed). Doesn't run while the popup is open.- // 3. POPUP_CLOSE_GRACE_MS (3000 ms) — only starts after step 2- // observes a closed popup; gives in-flight result messages a- // chance to land before we declare failure.+ // Cross-origin flows (``useCrossOriginListeners``) must not poll+ // ``popup.closed``: providers that serve+ // ``Cross-Origin-Opener-Policy: same-origin`` (e.g. Stripe's MCP+ // authorize pages) trigger a browsing-context-group swap when the popup+ // navigates to them, severing this handle — ``closed`` then reports+ // ``true`` while the window is still open and the user is minutes away+ // from finishing sign-in. Rejecting on it (with any grace period)+ // kills the flow and tears down the BroadcastChannel/localStorage+ // listeners before the callback page can post its result, surfacing a+ // bogus "Sign-in window was closed" error on a successful sign-in.+ // Those flows rely on the callback result, the outer ``timeout``, and+ // the caller's explicit abort instead — the same reasoning the+ // popup-blocked new-tab fallback above applies.//- // Why the grace at all? The callback page (see- // ``frontend/src/app/(platform)/auth/integrations/mcp_callback/route.ts``)- // does:- // bc.postMessage(...); localStorage.setItem(...); setTimeout(close, 1500)- // BroadcastChannel delivery is async across-origin; the parent's- // localStorage poll fires every 500 ms. Without a grace window the- // ``popup.closed`` rejection can win the race against a successful- // result that's a few hundred ms behind, surfacing the bogus- // "Sign-in window was closed" error John screenshotted.- //- // On detected close we ALSO do one synchronous final localStorage- // read — covers the case where the BroadcastChannel listener never- // fired (storage-partitioning / BCG isolation) and the poll tick- // hasn't run yet. The grace then handles any remaining- // post-message latency.- //- // The setTimeout lives in a plain JS closure, not React state — it- // does NOT stack across re-renders, and the AbortController cleanup- // tears it down if the caller aborts before grace expires.- // Skip the close-poll entirely when the popup was blocked. The fallback- // WindowProxy is retained so an explicit abort can close it, but COOP can- // make that handle appear closed while the new tab is still usable.- // Polling it would therefore risk rejecting a successful sign-in before- // its BroadcastChannel/localStorage result arrives.- if (popup && !popupBlocked) {- // Grace window only applies to cross-origin flows. Same-origin- // OAuth resolves via ``window.opener.postMessage`` which the- // parent receives synchronously on the same event-loop tick the- // popup posts it — there's no async delivery race to wait for,- // and adding 3 s of fake spinner after a manual close hurts UX.- const POPUP_CLOSE_GRACE_MS = useCrossOriginListeners ? 3000 : 0;- const finalLocalStorageCheck = () => {- if (!useCrossOriginListeners || handled) return;- try {- const stored = localStorage.getItem(scopedLocalStorageKey);- if (stored) {- const data = JSON.parse(stored);- localStorage.removeItem(scopedLocalStorageKey);- handleResult(data);- }- } catch {}- };-+ // Same-origin flows resolve via ``window.opener.postMessage``, which+ // the parent receives synchronously on the tick the popup posts before+ // closing — by the time ``closed`` is observed, any successful result+ // has already been handled, so rejecting immediately is safe and spares+ // the user a fake spinner after a manual close.+ if (popup && !popupBlocked && !useCrossOriginListeners) {const closedPollInterval = setInterval(() => {if (popup.closed && !handled) {clearInterval(closedPollInterval);- finalLocalStorageCheck();- if (handled) return;- if (POPUP_CLOSE_GRACE_MS === 0) {- // Same-origin path: the ``window.addEventListener("message", …)``- // at line 149 fires synchronously when the popup posts before- // closing, so any successful result has already been handled- // by the time ``popup.closed`` flips. Reject immediately —- // no async-delivery race to wait for.- handled = true;- reject(new Error(OAUTH_ERROR_WINDOW_CLOSED));- controller.abort("popup_closed");- return;- }- const graceTimeout = setTimeout(() => {- if (handled) return;- finalLocalStorageCheck();- if (handled) return;- handled = true;- reject(new Error(OAUTH_ERROR_WINDOW_CLOSED));- controller.abort("popup_closed");- }, POPUP_CLOSE_GRACE_MS);- controller.signal.addEventListener("abort", () =>- clearTimeout(graceTimeout),- );+ handled = true;+ reject(new Error(OAUTH_ERROR_WINDOW_CLOSED));+ controller.abort("popup_closed");}}, 500);controller.signal.addEventListener("abort", () =>