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(platform/copilot): Unify & debug credential UX (card + prompt + session store + popup recovery) (#13088)
Ubbe7ae7b17f9c03
diff --git a/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.py b/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.pyindex 352f14df5a..cf1c0ea58e 100644--- a/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.py@@ -1128,3 +1128,164 @@ class TestUpgradeExistingCredentialDoesNotMutateCaller:"https://www.googleapis.com/auth/calendar.readonly",}mock_mgr.update.assert_called_once()+++class TestExplicitUpgradeScopeGuard:+ """Explicit scope upgrade (`credential_id` set on the OAuth state) must+ enforce the same scope-coverage guard as the implicit-merge path.++ Without the guard a narrowed re-auth — the user lands on the provider's+ consent screen and only grants some of the requested scopes — would+ overwrite the existing credential's ``access_token`` with a narrower+ token while merging the wider scope set onto the record. The+ credential matcher then routes AutoPilot tools to that record believing+ it covers scopes its token does not actually grant, and the tool fails+ with opaque 401/403s on the missing scopes. Users perceive this as+ "AutoPilot keeps picking the old creds" because the loop never breaks.+ """++ def _make_state_with_credential_id(+ self,+ credential_id: str,+ scopes: list[str] | None = None,+ provider: str = "google",+ ) -> OAuthState:+ return OAuthState(+ token="state-token",+ provider=provider,+ expires_at=9999999999,+ scopes=(+ scopes+ if scopes is not None+ else [+ "https://www.googleapis.com/auth/gmail.readonly",+ "https://www.googleapis.com/auth/calendar.readonly",+ ]+ ),+ credential_id=credential_id,+ )++ def test_explicit_upgrade_skipped_when_new_scopes_narrower(self):+ """The user re-auths to upgrade scopes but the provider returns a+ narrower token than what the existing record advertises. The+ existing credential must stay intact (its old token still grants+ the lost scopes) and the new (narrower) credential is persisted+ alongside it."""+ existing = _make_google_oauth2_cred(+ scopes=[+ "https://www.googleapis.com/auth/gmail.readonly",+ "https://www.googleapis.com/auth/calendar.readonly",+ ],+ )+ # The user only granted Gmail on the consent screen — narrower+ # than the existing record's claimed Gmail + Calendar.+ new_cred = _make_google_oauth2_cred(+ cred_id="new-cred-id",+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],+ )+ state = self._make_state_with_credential_id(+ "google-cred-1",+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],+ )+ handler = MagicMock()+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)+ handler.handle_default_scopes.return_value = state.scopes++ with (+ patch(+ "backend.api.features.integrations.router._get_provider_oauth_handler",+ return_value=handler,+ ),+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,+ ):+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)+ mock_mgr.create = AsyncMock()+ mock_mgr.update = AsyncMock()++ resp = client.post(+ "/google/callback",+ json={"code": "auth-code", "state_token": "state-token"},+ )++ assert resp.status_code == 200+ # No mutation of the existing record — keep its wider token intact.+ mock_mgr.update.assert_not_called()+ # The narrower credential is persisted as a new record so the user+ # ends up with both: the AutoPilot matcher will now pick the one+ # that actually grants the requested scopes for each tool call.+ mock_mgr.create.assert_called_once()++ def test_explicit_upgrade_proceeds_when_new_scopes_are_superset(self):+ """Typical happy path: the OAuth flow asked for existing ∪ new and+ the user authorised everything. The new token covers the wider+ set, so merging into the existing record is safe."""+ existing = _make_google_oauth2_cred(+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],+ )+ new_cred = _make_google_oauth2_cred(+ cred_id="new-cred-id",+ scopes=[+ "https://www.googleapis.com/auth/gmail.readonly",+ "https://www.googleapis.com/auth/calendar.readonly",+ ],+ )+ state = self._make_state_with_credential_id("google-cred-1")+ handler = MagicMock()+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)+ handler.handle_default_scopes.return_value = state.scopes++ with (+ patch(+ "backend.api.features.integrations.router._get_provider_oauth_handler",+ return_value=handler,+ ),+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,+ ):+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)+ mock_mgr.create = AsyncMock()+ mock_mgr.update = AsyncMock()++ resp = client.post(+ "/google/callback",+ json={"code": "auth-code", "state_token": "state-token"},+ )++ assert resp.status_code == 200+ mock_mgr.update.assert_called_once()+ mock_mgr.create.assert_not_called()++ def test_explicit_upgrade_with_equal_scopes_still_merges(self):+ """Re-auth with the same scope set (e.g. user refreshed an expired+ token by going through the OAuth flow again) is the same as+ ``new ⊇ existing`` — merging into the existing record updates+ the access_token without scope drift."""+ scopes = ["https://www.googleapis.com/auth/gmail.readonly"]+ existing = _make_google_oauth2_cred(scopes=scopes)+ new_cred = _make_google_oauth2_cred(cred_id="new-cred-id", scopes=scopes)+ state = self._make_state_with_credential_id("google-cred-1", scopes=scopes)+ handler = MagicMock()+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)+ handler.handle_default_scopes.return_value = state.scopes++ with (+ patch(+ "backend.api.features.integrations.router._get_provider_oauth_handler",+ return_value=handler,+ ),+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,+ ):+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)+ mock_mgr.create = AsyncMock()+ mock_mgr.update = AsyncMock()++ resp = client.post(+ "/google/callback",+ json={"code": "auth-code", "state_token": "state-token"},+ )++ assert resp.status_code == 200+ mock_mgr.update.assert_called_once()+ mock_mgr.create.assert_not_called()diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex d99cf7444d..cfb166a317 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -799,8 +799,39 @@ async def _merge_or_create_credential(When *credential_id* is set (explicit upgrade), merges scopes and updatesthe existing credential. Otherwise, checks for an implicit merge (sameprovider + username) before falling back to creating a new credential.++ Both paths enforce a scope-coverage guard: a "merge" only happens when+ the freshly-minted token covers every scope the existing record already+ advertises. Without that guard a narrowed re-auth would overwrite the+ stored ``access_token`` with a token whose grant is smaller than the+ ``scopes`` list — the record would claim authorizations the token does+ not grant, the credential matcher would happily route AutoPilot tools+ to that "more capable" credential, and the tool would fail with opaque+ 401/403s on the missing scopes ("AutoPilot keeps picking the old+ creds" symptom). On a narrowing re-auth we keep the existing+ credential intact and persist the new one alongside it instead."""if credential_id:+ existing = await creds_manager.store.get_creds_by_id(user_id, credential_id)+ # Gate the scope-coverage guard on the same defense-in-depth invariants+ # that `_upgrade_existing_credential` enforces — provider drift, missing+ # records, and non-OAuth2 targets must still raise via the upgrade path+ # instead of being silently bypassed by the new-credential fallback.+ if (+ existing+ and isinstance(existing, OAuth2Credentials)+ and not existing.is_managed+ and not is_system_credential(existing.id)+ and provider_matches(existing.provider, credentials.provider)+ and not set(credentials.scopes).issuperset(set(existing.scopes))+ ):+ # Narrowing re-auth: keep existing intact, persist new alongside.+ # The frontend `executeOAuthFlow` has already pre-screened that+ # the new credential covers the scopes the card asked for; the+ # mismatch here is with the *existing* record's wider scope set,+ # which the explicit-upgrade path tried to preserve via union.+ await creds_manager.create(user_id, credentials)+ return credentialsreturn await _upgrade_existing_credential(user_id, credential_id, credentials)# Implicit merge: check for existing credential with same provider+username.diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.pyindex 909091d91b..7ee3b3454c 100644--- a/autogpt_platform/backend/backend/copilot/prompting.py+++ b/autogpt_platform/backend/backend/copilot/prompting.py@@ -232,6 +232,34 @@ object (with its hidden credentials field attached), you MAY pass thatobject through as-is to a downstream `run_block`; do not strip ormodify its fields.+### Credentials & sign-in surfacing — CRITICAL++When the user asks to run something that needs credentials (a block, an+agent, an MCP server, or an authenticated web request) and the user may+not have them yet, three rules apply:++**1. Surface the sign-in card EAGERLY — in the same turn, before+collecting other inputs.** Call `connect_integration(provider=...)`+(or `run_agent` / `run_block`) immediately. Do not wait until you have+the URL / resource ID / other parameters. The user can connect in+parallel with answering follow-up questions. A frequent failure mode is+asking "what URL should I use?" without ever emitting the card the user+is supposed to click.++**2. NEVER claim a card has appeared if you didn't just emit one.**+Sentences like "a sign-in card has appeared in the chat", "I've added a+connect button above", or "please connect it there" are CLAIMS about+the actual UI state. You may only write such a sentence in the SAME+turn that you have just called `connect_integration`, `run_agent`,+`run_block`, or `run_mcp_tool` AND received a `setup_requirements`+(or compatible) response. If you have not made that tool call yet, do+not promise a card — call the tool first, then describe it.++**3. Prefer the tool over verbal coaching.** If you would write+"please connect your GitHub account", instead just call+`connect_integration(provider="github")`. The card the tool surfaces+does the job better than the sentence.+### Pre-flight with `validate_only``run_block(id, {})` is NOT always a safe probe — for blocks with nodiff --git a/autogpt_platform/backend/backend/copilot/prompting_test.py b/autogpt_platform/backend/backend/copilot/prompting_test.pyindex ae115c0508..e5ee040553 100644--- a/autogpt_platform/backend/backend/copilot/prompting_test.py+++ b/autogpt_platform/backend/backend/copilot/prompting_test.py@@ -32,6 +32,27 @@ class TestGetSdkSupplementStaticPlaceholder:assert "<session-id>" not in result+class TestCredentialsSurfacingGuardrails:+ """The system prompt must instruct the model to (a) surface sign-in cards+ eagerly via tool calls and (b) never claim a card has appeared unless one+ was just emitted in the same turn. Both behaviours prevent the user from+ being stranded waiting for a card that was never produced.+ """++ def test_local_prompt_contains_eager_surfacing_rule(self):+ result = prompting.get_sdk_supplement(use_e2b=False)+ assert "Surface the sign-in card EAGERLY" in result++ def test_e2b_prompt_contains_eager_surfacing_rule(self):+ result = prompting.get_sdk_supplement(use_e2b=True)+ assert "Surface the sign-in card EAGERLY" in result++ def test_prompt_contains_anti_hallucination_guardrail(self):+ result = prompting.get_sdk_supplement(use_e2b=False)+ assert "NEVER claim a card has appeared" in result+ assert "call the tool first" in result++class TestToolDiscoveryPriorityAntiPattern:"""The Tool Discovery Priority section must forbid claiming a capabilitygap without calling ``find_block`` first — this is the regression thediff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration.pyindex 6ebef104bc..71377f8dd1 100644--- a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py@@ -6,7 +6,7 @@ setup card in the chat — the same UI that appears when a GitHub block runswithout configured credentials."""-from typing import Any, TypedDict+from typing import Any, castfrom backend.copilot.model import ChatSessionfrom backend.copilot.providers import SUPPORTED_PROVIDERS, get_provider_auth_types@@ -18,34 +18,13 @@ from backend.copilot.tools.models import (ToolResponseBase,UserReadiness,)+from backend.copilot.tools.utils import build_missing_credentials_from_field_info+from backend.data.model import CredentialsFieldInfo, CredentialsType+from backend.integrations.providers import ProviderNamefrom .base import BaseTool-class _CredentialEntry(TypedDict):- """Shape of each entry inside SetupRequirementsResponse.user_readiness.missing_credentials.-- Partially overlaps with :class:`~backend.data.model.CredentialsMetaInput`- (``id``, ``title``, ``provider``) but carries extra UI-facing fields- (``types``, ``scopes``) that the frontend ``SetupRequirementsCard`` needs- to render the inline credential setup card.-- Display name is derived from :data:`SUPPORTED_PROVIDERS` at build time- rather than stored here — eliminates the old ``provider_name`` field.- ``types`` replaces the old singular ``type`` field; the frontend already- prefers ``types`` and only fell back to ``type`` for compatibility.- """-- id: str- title: str- # Slug used as the credential key (e.g. "github").- provider: str- # All supported credential types the user can choose from (e.g. ["api_key", "oauth2"]).- # The first element is the default/primary type.- types: list[str]- scopes: list[str]--class ConnectIntegrationTool(BaseTool):"""Surface the credentials setup UI when an integration is not connected."""@@ -166,14 +145,30 @@ class ConnectIntegrationTool(BaseTool):if reason:message_parts.append(reason)- credential_entry: _CredentialEntry = {- "id": field_key,- "title": f"{display_name} Credentials",- "provider": provider,- "types": supported_types,- "scopes": merged_scopes,- }- missing_credentials: dict[str, _CredentialEntry] = {field_key: credential_entry}+ # Route the single-provider entry through the shared serializer+ # used by run_block / run_agent so the payload shape (sorted scopes,+ # type+types fields, optional discriminator) stays in lockstep across+ # all three credential-surfacing tools. The casts narrow the runtime+ # strings — already validated upstream — to the typed enum/literal+ # the generic constructor expects.+ provider_enum = ProviderName(provider)+ typed_types: frozenset[CredentialsType] = cast(+ frozenset[CredentialsType], frozenset(supported_types)+ )+ field_info = CredentialsFieldInfo[ProviderName, CredentialsType](+ credentials_provider=frozenset([provider_enum]),+ credentials_types=typed_types,+ credentials_scopes=(frozenset(merged_scopes) if merged_scopes else None),+ )+ missing_credentials: dict[str, Any] = build_missing_credentials_from_field_info(+ credential_fields={field_key: field_info},+ matched_keys=set(),+ )+ # Preserve the registry's display name (e.g. "GitHub Credentials")+ # rather than the title-cased slug ("Github Credentials") that the+ # generic serializer produces from `field_key`.+ missing_credentials[field_key]["title"] = f"{display_name} Credentials"+ missing_credentials[field_key]["provider_name"] = display_namereturn SetupRequirementsResponse(type=ResponseType.SETUP_REQUIREMENTS,diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/mcp_callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/mcp_callback/route.tsindex 326f42e049..8786a1b78c 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/mcp_callback/route.ts+++ b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/mcp_callback/route.ts@@ -49,8 +49,8 @@ export async function GET(request: Request) {// Method 1: BroadcastChannel (reliable across tabs/popups, no opener needed)try {- var bc = new BroadcastChannel("mcp_oauth");- bc.postMessage({ type: "mcp_oauth_result", success: msg.success, code: msg.code, state: msg.state, message: msg.message });+ var bc = new BroadcastChannel("oauth_popup");+ bc.postMessage({ message_type: "mcp_oauth_result", success: msg.success, code: msg.code, state: msg.state, message: msg.message });bc.close();sent = true;} catch(e) { /* BroadcastChannel not supported */ }@@ -66,10 +66,14 @@ export async function GET(request: Request) {}} catch(e) { /* opener not available (COOP) */ }- // Method 3: localStorage (most reliable cross-tab fallback)+ // Method 3: localStorage (most reliable cross-tab fallback).+ // Key is scoped by state token so concurrent OAuth flows don't race+ // for a single shared slot (poller destructively reads its own key).try {- localStorage.setItem("mcp_oauth_result", JSON.stringify(msg));- sent = true;+ if (msg.state) {+ localStorage.setItem("oauth_popup_result_" + msg.state, JSON.stringify({ message_type: "mcp_oauth_result", ...msg }));+ sent = true;+ }} catch(e) { /* localStorage not available */ }var statusEl = document.getElementById("status");diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.tsindex fd67519957..239085f39a 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts+++ b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts@@ -33,19 +33,44 @@ export async function GET(request: Request) {console.debug("Sending message to opener:", message);- // Return a response with the message as JSON and a script to close the window- // Use safeJsonStringify to prevent XSS by escaping <, >, and & characters+ // Emit via three channels so the result reaches the originating page+ // regardless of how the OAuth flow was opened:+ // 1. BroadcastChannel — works across tabs/popups even when COOP headers+ // have severed window.opener, and is the only channel that works for+ // the popup-blocked → new-tab fallback path.+ // 2. window.opener.postMessage — fast path for same-origin popups.+ // 3. localStorage — most reliable cross-tab fallback when both above fail.+ // Key is scoped by state token so concurrent flows don't clobber each+ // other's slots. BroadcastChannel/postMessage are pub/sub-style so the+ // listener's state-token filter already prevents cross-talk for them.return new NextResponse(- `- <html>- <body>- <script>- window.opener.postMessage(${safeJsonStringify(message)});- window.close();- </script>- </body>- </html>- `,+ `<!DOCTYPE html>+<html>+ <body>+ <script>+ (function() {+ var msg = ${safeJsonStringify(message)};+ var state = ${safeJsonStringify(state)};+ try {+ var bc = new BroadcastChannel("oauth_popup");+ bc.postMessage(msg);+ bc.close();+ } catch(e) {}+ try {+ if (window.opener && !window.opener.closed) {+ window.opener.postMessage(msg, window.location.origin);+ }+ } catch(e) {}+ try {+ if (state) {+ localStorage.setItem("oauth_popup_result_" + state, JSON.stringify(msg));+ }+ } catch(e) {}+ window.close();+ })();+ </script>+ </body>+</html>`,{headers: { "Content-Type": "text/html" },},diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/connectedProvidersStore.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/connectedProvidersStore.test.tsnew file mode 100644index 0000000000..f05f00d90b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/connectedProvidersStore.test.ts@@ -0,0 +1,223 @@+import { renderHook, act } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import {+ useAreAllConnected,+ useConnectedProvidersStore,+} from "../connectedProvidersStore";++afterEach(() => {+ // Reset the store so tests are isolated.+ useConnectedProvidersStore.setState({+ connected: new Set(),+ autoDismissedKeys: new Set(),+ });+});++describe("connectedProvidersStore", () => {+ it("marks providers connected within a session", () => {+ const { result } = renderHook(() =>+ useAreAllConnected("sess-1", ["github"]),+ );+ expect(result.current).toBe(false);++ act(() => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["github"] });+ });+ expect(result.current).toBe(true);+ });++ it("scopes connections per session", () => {+ act(() => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["github"] });+ });++ const sameSession = renderHook(() =>+ useAreAllConnected("sess-1", ["github"]),+ );+ const otherSession = renderHook(() =>+ useAreAllConnected("sess-2", ["github"]),+ );+ expect(sameSession.result.current).toBe(true);+ expect(otherSession.result.current).toBe(false);+ });++ it("returns false until ALL required providers are connected", () => {+ const { result } = renderHook(() =>+ useAreAllConnected("sess-1", ["github", "openai"]),+ );++ act(() => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["github"] });+ });+ expect(result.current).toBe(false);++ act(() => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });+ });+ expect(result.current).toBe(true);+ });++ it("returns false when sessionID is null", () => {+ act(() => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["github"] });+ });++ const { result } = renderHook(() => useAreAllConnected(null, ["github"]));+ expect(result.current).toBe(false);+ });++ it("returns false when no providers are requested", () => {+ const { result } = renderHook(() => useAreAllConnected("sess-1", []));+ expect(result.current).toBe(false);+ });++ it("clearSession removes only that session's marks", () => {+ act(() => {+ const store = useConnectedProvidersStore.getState();+ store.markConnected({ sessionID: "sess-1", providers: ["github"] });+ store.markConnected({ sessionID: "sess-2", providers: ["openai"] });+ });++ act(() => {+ useConnectedProvidersStore.getState().clearSession("sess-1");+ });++ const s1 = renderHook(() => useAreAllConnected("sess-1", ["github"]));+ const s2 = renderHook(() => useAreAllConnected("sess-2", ["openai"]));+ expect(s1.result.current).toBe(false);+ expect(s2.result.current).toBe(true);+ });++ it("ignores empty/falsy providers in markConnected", () => {+ act(() => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["", "github"] });+ });+ expect(useConnectedProvidersStore.getState().connected.size).toBe(1);+ });++ describe("tryClaimAutoDismiss", () => {+ it("returns true on first claim and false on subsequent claims", () => {+ const store = useConnectedProvidersStore.getState();+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github"],+ }),+ ).toBe(true);+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github"],+ }),+ ).toBe(false);+ });++ it("treats different provider sets in the same session as separate slots", () => {+ const store = useConnectedProvidersStore.getState();+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github"],+ }),+ ).toBe(true);+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["openai"],+ }),+ ).toBe(true);+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github", "openai"],+ }),+ ).toBe(true);+ });++ it("treats the same provider set in different sessions as separate slots", () => {+ const store = useConnectedProvidersStore.getState();+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github"],+ }),+ ).toBe(true);+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-2",+ providers: ["github"],+ }),+ ).toBe(true);+ });++ it("ignores provider order when matching slots", () => {+ const store = useConnectedProvidersStore.getState();+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github", "openai"],+ }),+ ).toBe(true);+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["openai", "github"],+ }),+ ).toBe(false);+ });++ it("returns false when sessionID is empty or providers list is empty", () => {+ const store = useConnectedProvidersStore.getState();+ expect(+ store.tryClaimAutoDismiss({ sessionID: "", providers: ["github"] }),+ ).toBe(false);+ expect(+ store.tryClaimAutoDismiss({ sessionID: "sess-1", providers: [] }),+ ).toBe(false);+ });++ it("clearSession releases auto-dismiss slots scoped to that session", () => {+ act(() => {+ const store = useConnectedProvidersStore.getState();+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github"],+ });+ store.tryClaimAutoDismiss({+ sessionID: "sess-2",+ providers: ["github"],+ });+ });++ act(() => {+ useConnectedProvidersStore.getState().clearSession("sess-1");+ });++ const store = useConnectedProvidersStore.getState();+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-1",+ providers: ["github"],+ }),+ ).toBe(true);+ expect(+ store.tryClaimAutoDismiss({+ sessionID: "sess-2",+ providers: ["github"],+ }),+ ).toBe(false);+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/FeedbackModal.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/FeedbackModal.tsxindex fe0e47de10..7e212c6336 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/FeedbackModal.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/FeedbackModal.tsx@@ -1,7 +1,7 @@"use client";+import { Button } from "@/components/atoms/Button/Button";import { Dialog } from "@/components/molecules/Dialog/Dialog";-import { Button } from "@/components/ui/button";import { Textarea } from "@/components/ui/textarea";import { useState } from "react";@@ -53,11 +53,11 @@ export function FeedbackModal({ isOpen, onSubmit, onCancel }: Props) {{comment.length}/2000</p><div className="flex gap-2">- <Button variant="outline" size="sm" onClick={handleClose}>+ <Button variant="outline" size="small" onClick={handleClose}>Cancel</Button><Button- size="sm"+ size="small"onClick={handleSubmit}disabled={!comment.trim()}>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsxindex 1e50408661..8da708b80a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx@@ -109,8 +109,14 @@ export function MessagePartRenderer({const reasoningText ="text" in part && typeof part.text === "string" ? part.text : "";if (!reasoningText.trim()) return null;+ // AI SDK reasoning parts carry an optional `state: "streaming" | "done"`.+ // We pulse the indicator only while streaming so a finalized reasoning+ // block doesn't keep looking like the model is still thinking.+ const reasoningState =+ "state" in part && typeof part.state === "string" ? part.state : null;+ const isActive = reasoningState === "streaming";return (- <ReasoningCollapse key={key}>+ <ReasoningCollapse key={key} isActive={isActive}><pre className="whitespace-pre-wrap text-sm text-zinc-700">{reasoningText}</pre>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsxindex 6e2e8b4b2d..53e01ba9a8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx@@ -1,29 +1,60 @@"use client";+import { Button } from "@/components/atoms/Button/Button";import {Accordion,AccordionContent,AccordionItem,- AccordionTrigger,} from "@/components/molecules/Accordion/Accordion";+import { cn } from "@/lib/utils";import { LightbulbIcon } from "@phosphor-icons/react";+import * as AccordionPrimitive from "@radix-ui/react-accordion";+import { useState } from "react";interface Props {children: React.ReactNode;+ /**+ * True while the reasoning is still being produced by the model. Drives+ * the pulse animation on the trigger — once the part is done streaming+ * the indicator stops pulsing so it doesn't look like the chat is still+ * "thinking" when it isn't.+ */+ isActive?: boolean;}-export function ReasoningCollapse({ children }: Props) {+export function ReasoningCollapse({ children, isActive = false }: Props) {+ const [value, setValue] = useState("");+return (- <Accordion type="single" collapsible className="my-1">+ <Accordion+ type="single"+ collapsible+ className="my-1"+ value={value}+ onValueChange={(newValue) => setValue(newValue === value ? "" : newValue)}+ ><AccordionItem value="reasoning" className="border-none">- <AccordionTrigger className="justify-start gap-1.5 py-1 text-xs font-medium text-zinc-500 hover:no-underline">- <span className="flex items-center gap-1.5">+ <AccordionPrimitive.Header className="flex">+ <AccordionPrimitive.Trigger+ className={cn(+ "flex items-center gap-1.5 py-1 text-xs font-medium text-zinc-500 transition-colors hover:text-zinc-700 focus-visible:outline-none",+ isActive && "animate-pulse",+ )}+ ><LightbulbIcon size={14} weight="bold" className="shrink-0" />Reasoning- </span>- </AccordionTrigger>- <AccordionContent className="pb-1 pl-5 pt-0 text-xs text-zinc-500 [&_pre]:m-0 [&_pre]:whitespace-pre-wrap [&_pre]:bg-transparent [&_pre]:p-0 [&_pre]:text-xs [&_pre]:text-zinc-500">+ </AccordionPrimitive.Trigger>+ </AccordionPrimitive.Header>+ <AccordionContent className="pb-1 pt-0 text-xs text-zinc-500 [&_pre]:m-0 [&_pre]:whitespace-pre-wrap [&_pre]:bg-transparent [&_pre]:p-0 [&_pre]:text-xs [&_pre]:text-zinc-500">{children}+ <Button+ variant="secondary"+ size="small"+ className="mt-2"+ onClick={() => setValue("")}+ >+ Collapse+ </Button></AccordionContent></AccordionItem></Accordion>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsxindex 3eaa27341d..3792675b43 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx@@ -1,4 +1,10 @@-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { ReasoningCollapse } from "../ReasoningCollapse";@@ -26,6 +32,40 @@ describe("ReasoningCollapse", () => {expect(screen.queryByTestId("reasoning-body")).toBeNull();});+ it("applies a pulse animation class to the trigger ONLY while active", () => {+ const inactive = render(+ <ReasoningCollapse>+ <span>thought</span>+ </ReasoningCollapse>,+ );+ expect(+ inactive.getByRole("button", { name: /reasoning/i }).className,+ ).not.toContain("animate-pulse");+ inactive.unmount();++ const active = render(+ <ReasoningCollapse isActive>+ <span>thought</span>+ </ReasoningCollapse>,+ );+ expect(+ active.getByRole("button", { name: /reasoning/i }).className,+ ).toContain("animate-pulse");+ });++ it("renders no chevron / extra svg inside the trigger", () => {+ render(+ <ReasoningCollapse>+ <span>thought</span>+ </ReasoningCollapse>,+ );++ const trigger = screen.getByRole("button", { name: /reasoning/i });+ // The bulb icon is mocked to a <span>; the previous design appended a+ // <ChevronDown /> svg. After the redesign no svg should remain.+ expect(trigger.querySelector("svg")).toBeNull();+ });+it("reveals the reasoning body when the trigger is clicked", async () => {render(<ReasoningCollapse>@@ -37,4 +77,20 @@ describe("ReasoningCollapse", () => {expect(await screen.findByTestId("reasoning-body")).toBeDefined();});++ it("collapses back when the inner Collapse button is clicked", async () => {+ render(+ <ReasoningCollapse>+ <span data-testid="reasoning-body">secret thoughts</span>+ </ReasoningCollapse>,+ );++ fireEvent.click(screen.getByRole("button", { name: /reasoning/i }));+ expect(await screen.findByTestId("reasoning-body")).toBeDefined();++ fireEvent.click(screen.getByRole("button", { name: /collapse/i }));+ await waitFor(() => {+ expect(screen.queryByTestId("reasoning-body")).toBeNull();+ });+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsxnew file mode 100644index 0000000000..697f2cbc65--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx@@ -0,0 +1,298 @@+"use client";++import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { CredentialsGroupedView } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView";+import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";+import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";+import { useEffect, useMemo, useState } from "react";+import {+ useAreAllConnected,+ useConnectedProvidersStore,+} from "../../connectedProvidersStore";+import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";+import {+ ContentBadge,+ ContentCardDescription,+ ContentCardTitle,+ ContentMessage,+} from "../ToolAccordion/AccordionContent";+import {+ buildExpectedInputsSchema,+ buildPreviewRunMessage,+ buildRunMessage,+ buildSiblingInputsFromCredentials,+ checkAllCredentialsComplete,+ checkAllInputsComplete,+ checkCanRun,+ coerceCredentialFields,+ coerceExpectedInputs,+ extractInitialValues,+ getRequestedProviders,+ mergeInputValues,+} from "./helpers";++/**+ * Single credential/setup card rendered inline in copilot chats.+ *+ * Used by the run_block, run_agent and connect_integration tool renderers.+ * MCP has its own card (different OAuth route) and lives separately.+ *+ * - `inputsMode = "edit"` (default): renders inputs as an editable RJSF form,+ * and `Proceed` sends the form values back to the chat. Used by run_block+ * and connect_integration.+ * - `inputsMode = "preview"`: renders inputs as a read-only list+ * (name • type, Required/Optional badge). Used by run_agent because graph+ * inputs are set in the graph definition, not from the chat.+ */+interface Props {+ output: SetupRequirementsResponse;+ retryInstruction?: string;+ credentialsLabel?: string;+ inputsMode?: "edit" | "preview";+ onComplete?: () => void;+}++export function SetupRequirementsCard({+ output,+ retryInstruction,+ credentialsLabel,+ inputsMode = "edit",+ onComplete,+}: Props) {+ const { onSend } = useCopilotChatActions();++ const [inputCredentials, setInputCredentials] = useState<+ Record<string, CredentialsMetaInput | undefined>+ >({});+ const [hasSent, setHasSent] = useState(false);+ const [showAdvanced, setShowAdvanced] = useState(false);++ const { credentialFields, requiredCredentials } = coerceCredentialFields(+ output.setup_info.user_readiness?.missing_credentials,+ );++ const expectedInputs = coerceExpectedInputs(+ (output.setup_info.requirements as Record<string, unknown>)?.inputs,+ );++ const initialValues = useMemo(+ () => extractInitialValues(expectedInputs),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- stabilise on the raw prop+ [output.setup_info.requirements],+ );++ const [inputValues, setInputValues] =+ useState<Record<string, unknown>>(initialValues);++ const initialValuesKey = JSON.stringify(initialValues);+ useEffect(() => {+ setInputValues((prev) => mergeInputValues(initialValues, prev));+ // eslint-disable-next-line react-hooks/exhaustive-deps -- sync when serialised values change+ }, [initialValuesKey]);++ const isEditMode = inputsMode === "edit";++ const hasAdvancedFields =+ isEditMode && expectedInputs.some((i) => i.advanced);+ const inputSchema = isEditMode+ ? buildExpectedInputsSchema(expectedInputs, showAdvanced)+ : null;++ // Build siblingInputs for credential modal host prefill. In edit mode we also+ // include the live form values; in preview mode there is no form so only+ // discriminator-derived values contribute.+ const siblingInputs = useMemo(() => {+ const fromCreds = buildSiblingInputsFromCredentials(+ output.setup_info.user_readiness?.missing_credentials,+ );+ return isEditMode ? { ...inputValues, ...fromCreds } : fromCreds;+ }, [+ output.setup_info.user_readiness?.missing_credentials,+ inputValues,+ isEditMode,+ ]);++ function handleCredentialChange(key: string, value?: CredentialsMetaInput) {+ setInputCredentials((prev) => ({ ...prev, [key]: value }));+ }++ const needsCredentials = credentialFields.length > 0;+ const isAllCredsComplete = checkAllCredentialsComplete(+ requiredCredentials,+ inputCredentials,+ );++ const needsInputs = expectedInputs.length > 0;+ const isAllInputsDone = isEditMode+ ? checkAllInputsComplete(expectedInputs, inputValues)+ : true;++ // Session-scoped dismissal: when an earlier card in the same chat already+ // satisfied every provider this card asks for AND the card has nothing+ // else for the user to do, treat it as already sent. The `hasUserActionableInputs`+ // gate keeps the card visible when there are RJSF inputs the user still+ // needs to fill in (edit mode) — otherwise the chat hangs because+ // `handleRun` never fires and no message gets sent.+ const sessionID = output.session_id ?? null;+ const requestedProviders = getRequestedProviders(credentialFields);+ const alreadyConnected = useAreAllConnected(sessionID, requestedProviders);+ const hasUserActionableInputs = isEditMode && needsInputs;+ const canAutoDismiss =+ needsCredentials && alreadyConnected && !hasUserActionableInputs;++ // Auto-send when dismissing so the AI receives the run message and the+ // chat doesn't hang waiting for a confirmation that the user can no longer+ // provide (the Proceed button is hidden behind the early return below).+ //+ // `tryClaimAutoDismiss` provides the atomicity guarantee: only the first+ // card per `(sessionID, providers)` slot wins the claim and runs+ // `handleRun`; later cards (whether parallel siblings or StrictMode's+ // dev-mode re-mount of the same card) see `claimed === false`, set their+ // local `hasSent`, and dismiss silently — no chat spam, no double-send.+ // We deliberately call `handleRun` synchronously: a microtask + cleanup+ // pattern would leak the claim across StrictMode's double-invoke+ // (cleanup cancels the first microtask, but the claim is still held, so+ // the second effect run can't re-claim and the send never fires).+ useEffect(() => {+ if (!canAutoDismiss || hasSent) return;+ if (!sessionID || requestedProviders.length === 0) return;+ const claimed = useConnectedProvidersStore+ .getState()+ .tryClaimAutoDismiss({ sessionID, providers: requestedProviders });+ if (!claimed) {+ setHasSent(true);+ return;+ }+ handleRun();+ // eslint-disable-next-line react-hooks/exhaustive-deps -- handleRun captures latest state; claim guards re-entry+ }, [canAutoDismiss, hasSent]);++ if (hasSent || canAutoDismiss) {+ return <ContentMessage>Connected. Continuing…</ContentMessage>;+ }++ const canRun = checkCanRun(+ needsCredentials,+ isAllCredsComplete,+ isAllInputsDone,+ );++ function handleRun() {+ setHasSent(true);+ if (sessionID && requestedProviders.length > 0) {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID, providers: requestedProviders });+ }+ onComplete?.();+ const message = isEditMode+ ? buildRunMessage(+ needsCredentials,+ needsInputs,+ inputValues,+ retryInstruction,+ )+ : buildPreviewRunMessage(needsCredentials);+ onSend(message);+ if (isEditMode) setInputValues({});+ }++ return (+ <div className="grid gap-2">+ <ContentMessage>{output.message}</ContentMessage>++ {needsCredentials && (+ <div className="rounded-2xl border bg-background p-3">+ <Text variant="small" className="w-fit border-b text-zinc-500">+ {credentialsLabel ??+ (isEditMode ? "Credentials" : "Agent credentials")}+ </Text>+ <div className="mt-6">+ <CredentialsGroupedView+ credentialFields={credentialFields}+ requiredCredentials={requiredCredentials}+ inputCredentials={inputCredentials}+ inputValues={siblingInputs}+ onCredentialChange={handleCredentialChange}+ />+ </div>+ </div>+ )}++ {isEditMode && (inputSchema || hasAdvancedFields) && (+ <div className="rounded-2xl border bg-background p-3 pt-4">+ <Text variant="small" className="w-fit border-b text-zinc-500">+ Inputs+ </Text>+ {inputSchema && (+ <FormRenderer+ jsonSchema={inputSchema}+ className="mb-3 mt-3"+ handleChange={(v) =>+ setInputValues((prev) => ({ ...prev, ...(v.formData ?? {}) }))+ }+ uiSchema={{+ "ui:submitButtonOptions": { norender: true },+ }}+ initialValues={inputValues}+ formContext={{+ showHandles: false,+ size: "small",+ }}+ />+ )}+ {hasAdvancedFields && (+ <button+ type="button"+ className="text-xs text-muted-foreground underline"+ onClick={() => setShowAdvanced((v) => !v)}+ >+ {showAdvanced ? "Hide advanced fields" : "Show advanced fields"}+ </button>+ )}+ </div>+ )}++ {!isEditMode && expectedInputs.length > 0 && (+ <div className="rounded-2xl border bg-background p-3">+ <ContentCardTitle className="text-xs">+ Expected inputs+ </ContentCardTitle>+ <div className="mt-2 grid gap-2">+ {expectedInputs.map((input) => (+ <div key={input.name} className="rounded-xl border p-2">+ <div className="flex items-center justify-between gap-2">+ <ContentCardTitle className="text-xs">+ {input.title}+ </ContentCardTitle>+ <ContentBadge>+ {input.required ? "Required" : "Optional"}+ </ContentBadge>+ </div>+ {input.description && (+ <ContentCardDescription className="mt-1">+ {input.description}+ </ContentCardDescription>+ )}+ </div>+ ))}+ </div>+ </div>+ )}++ {(needsCredentials || needsInputs) && (+ <Button+ variant="primary"+ size="small"+ className="mt-4 w-fit"+ disabled={!canRun}+ onClick={handleRun}+ >+ Proceed+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsxnew file mode 100644index 0000000000..9fdbc7ea1c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx@@ -0,0 +1,605 @@+import {+ render,+ screen,+ fireEvent,+ cleanup,+ waitFor,+} from "@testing-library/react";+import { StrictMode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { SetupRequirementsCard } from "../SetupRequirementsCard";+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";+import { useConnectedProvidersStore } from "../../../connectedProvidersStore";++const mockOnSend = vi.fn();+vi.mock("../../CopilotChatActionsProvider/useCopilotChatActions", () => ({+ useCopilotChatActions: () => ({ onSend: mockOnSend }),+}));++vi.mock(+ "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView",+ () => ({+ CredentialsGroupedView: () => (+ <div data-testid="credentials-grouped-view">Credentials</div>+ ),+ }),+);++vi.mock("@/components/renderers/InputRenderer/FormRenderer", () => ({+ FormRenderer: ({+ handleChange,+ }: {+ handleChange: (e: { formData?: Record<string, unknown> }) => void;+ }) => (+ <div data-testid="form-renderer">+ <button+ data-testid="form-change"+ onClick={() => handleChange({ formData: { url: "https://test.com" } })}+ >+ Fill+ </button>+ </div>+ ),+}));++afterEach(() => {+ cleanup();+ mockOnSend.mockReset();+ useConnectedProvidersStore.setState({+ connected: new Set(),+ autoDismissedKeys: new Set(),+ });+});++function makeOutput(+ overrides: {+ message?: string;+ missingCredentials?: Record<string, unknown>;+ inputs?: unknown[];+ } = {},+): SetupRequirementsResponse {+ const {+ message = "Please configure credentials",+ missingCredentials,+ inputs,+ } = overrides;+ return {+ type: "setup_requirements",+ message,+ session_id: "sess-1",+ setup_info: {+ agent_id: "agent-1",+ agent_name: "Test Agent",+ user_readiness: {+ has_all_credentials: !missingCredentials,+ missing_credentials: missingCredentials ?? {},+ ready_to_run: !missingCredentials && !inputs,+ },+ requirements: {+ credentials: [],+ inputs: inputs ?? [],+ execution_modes: ["immediate"],+ },+ },+ graph_id: null,+ graph_version: null,+ } as SetupRequirementsResponse;+}++describe("SetupRequirementsCard (edit mode)", () => {+ it("renders the setup message", () => {+ render(<SetupRequirementsCard output={makeOutput()} />);+ expect(screen.getByText("Please configure credentials")).toBeDefined();+ });++ it("renders credential section when missing credentials are provided", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: {+ provider: "openai",+ types: ["api_key"],+ },+ },+ })}+ />,+ );+ expect(screen.getByTestId("credentials-grouped-view")).toBeDefined();+ });++ it("uses custom credentials label when provided", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ credentialsLabel="API Keys"+ />,+ );+ expect(screen.getByText("API Keys")).toBeDefined();+ });++ it("renders input form when inputs are provided", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ { name: "url", title: "URL", type: "string", required: true },+ ],+ })}+ />,+ );+ expect(screen.getByTestId("form-renderer")).toBeDefined();+ expect(screen.getByText("Inputs")).toBeDefined();+ });++ it("renders Proceed button that is enabled when inputs are filled", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ {+ name: "url",+ title: "URL",+ type: "string",+ required: true,+ value: "https://prefilled.com",+ },+ ],+ })}+ />,+ );+ const proceed = screen.getByText("Proceed");+ expect(proceed.closest("button")?.disabled).toBe(false);+ });++ it("calls onSend and shows Connected message when Proceed is clicked", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ {+ name: "url",+ title: "URL",+ type: "string",+ required: true,+ value: "https://prefilled.com",+ },+ ],+ })}+ />,+ );+ fireEvent.click(screen.getByText("Proceed"));+ expect(mockOnSend).toHaveBeenCalledOnce();+ expect(screen.getByText(/Connected. Continuing/)).toBeDefined();+ });++ it("calls onComplete callback when Proceed is clicked", () => {+ const onComplete = vi.fn();+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ {+ name: "url",+ title: "URL",+ type: "string",+ required: true,+ value: "https://prefilled.com",+ },+ ],+ })}+ onComplete={onComplete}+ />,+ );+ fireEvent.click(screen.getByText("Proceed"));+ expect(onComplete).toHaveBeenCalledOnce();+ });++ it("renders advanced toggle when advanced inputs exist", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ {+ name: "debug",+ title: "Debug Mode",+ type: "boolean",+ advanced: true,+ },+ ],+ })}+ />,+ );+ expect(screen.getByText("Show advanced fields")).toBeDefined();+ });++ it("toggles advanced fields visibility", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ { name: "url", title: "URL", type: "string", required: false },+ { name: "debug", title: "Debug", type: "boolean", advanced: true },+ ],+ })}+ />,+ );+ const toggle = screen.getByText("Show advanced fields");+ fireEvent.click(toggle);+ expect(screen.getByText("Hide advanced fields")).toBeDefined();+ });++ it("includes retryInstruction in onSend message when no inputs needed", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ retryInstruction="Retry the agent now"+ />,+ );+ // With credentials required but no auto-filling mechanism in the mock,+ // Proceed is disabled, but we're testing render only here+ expect(screen.getByText("Proceed")).toBeDefined();+ });++ it("does not render Proceed when neither credentials nor inputs are needed", () => {+ render(<SetupRequirementsCard output={makeOutput()} />);+ expect(screen.queryByText("Proceed")).toBeNull();+ });+});++describe("SetupRequirementsCard (preview mode)", () => {+ it("renders inputs as read-only list, not a form", () => {+ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ {+ name: "query",+ title: "Search Query",+ type: "string",+ required: true,+ description: "What to search for",+ },+ ],+ })}+ />,+ );+ expect(screen.queryByTestId("form-renderer")).toBeNull();+ expect(screen.getByText("Expected inputs")).toBeDefined();+ expect(screen.getByText("Search Query")).toBeDefined();+ expect(screen.getByText("What to search for")).toBeDefined();+ expect(screen.getByText("Required")).toBeDefined();+ // Technical bits — internal field name and JSON-schema type — must NOT+ // leak into the user-facing preview.+ expect(screen.queryByText(/query/)).toBeNull();+ expect(screen.queryByText(/string/)).toBeNull();+ });++ it("omits the description block entirely when no description is provided", () => {+ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ { name: "url", title: "URL", type: "string", required: true },+ ],+ })}+ />,+ );+ expect(screen.getByText("URL")).toBeDefined();+ // No "url • string" leakage and no empty description container.+ expect(screen.queryByText(/url • string/i)).toBeNull();+ });++ it("labels credentials section as 'Agent credentials' by default", () => {+ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ />,+ );+ expect(screen.getByText("Agent credentials")).toBeDefined();+ });++ it("does not render advanced toggle even when advanced inputs exist", () => {+ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ {+ name: "debug",+ title: "Debug",+ type: "boolean",+ advanced: true,+ },+ ],+ })}+ />,+ );+ expect(screen.queryByText("Show advanced fields")).toBeNull();+ });++ it("renders enabled Proceed with inputs only (preserves legacy run_agent behavior)", () => {+ // Proceed is rendered when needsCredentials || needsInputs — preserves+ // legacy run_agent behaviour where Proceed is shown alongside the input+ // preview and gated only by credentials.+ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ { name: "query", title: "Query", type: "string", required: true },+ ],+ })}+ />,+ );+ const proceed = screen.queryByText("Proceed");+ expect(proceed).not.toBeNull();+ expect(proceed!.closest("button")?.disabled).toBe(false);+ });++ it("sends the legacy run_agent message on Proceed", () => {+ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ { name: "query", title: "Query", type: "string", required: true },+ ],+ })}+ />,+ );+ fireEvent.click(screen.getByText("Proceed"));+ expect(mockOnSend).toHaveBeenCalledWith(+ "Please proceed with running the agent.",+ );+ });+});++describe("SetupRequirementsCard (session-scoped dismissal)", () => {+ it("auto-dismisses when all requested providers are already connected in this session", async () => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ render(+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ />,+ );++ expect(screen.queryByText("Proceed")).toBeNull();+ expect(screen.getByText(/Connected. Continuing/)).toBeDefined();+ // Auto-dismiss must also fire onSend, otherwise the AI's tool call sits+ // unanswered and the chat hangs (regression: Sentry bug prediction).+ await waitFor(() => expect(mockOnSend).toHaveBeenCalledOnce());+ });++ it("auto-dismiss in preview mode sends the legacy run_agent message", async () => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ { name: "url", title: "URL", type: "string", required: true },+ ],+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ />,+ );++ await waitFor(() =>+ expect(mockOnSend).toHaveBeenCalledWith(+ "I've configured the required credentials. Please check if everything is ready and proceed with running the agent.",+ ),+ );+ });++ it("auto-dismiss invokes onComplete callback", async () => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });+ const onComplete = vi.fn();++ render(+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ onComplete={onComplete}+ />,+ );++ await waitFor(() => expect(onComplete).toHaveBeenCalledOnce());+ });++ it("does not auto-dismiss when only some providers are connected", () => {+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ render(+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ gh: { provider: "github", types: ["api_key"] },+ },+ })}+ />,+ );++ expect(screen.queryByText(/Connected. Continuing/)).toBeNull();+ expect(screen.getByText("Proceed")).toBeDefined();+ });++ it("marks providers connected in the store when Proceed is clicked", () => {+ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ {+ name: "url",+ title: "URL",+ type: "string",+ required: true,+ value: "https://prefilled.com",+ },+ ],+ missingCredentials: {+ // Use a credential that auto-fills via system credentials would be+ // ideal, but for this test we just need Proceed to be clickable —+ // an inputs-only card with no creds is the simplest path.+ },+ })}+ />,+ );++ fireEvent.click(screen.getByText("Proceed"));+ // No credentials in this output, so no providers should be marked.+ expect(useConnectedProvidersStore.getState().connected.size).toBe(0);+ });++ it("does NOT auto-dismiss when the card has user-fillable inputs pending", () => {+ // Regression: a run_block card with both already-connected creds AND+ // unfilled user inputs must keep showing the form — otherwise handleRun+ // never fires and the chat hangs waiting for input that can't be sent.+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ render(+ <SetupRequirementsCard+ output={makeOutput({+ inputs: [+ { name: "url", title: "URL", type: "string", required: true },+ ],+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ />,+ );++ expect(screen.queryByText(/Connected. Continuing/)).toBeNull();+ expect(screen.getByText("Proceed")).toBeDefined();+ });++ it("still auto-dismisses in preview mode even when inputs exist (read-only)", () => {+ // Preview-mode inputs aren't user-fillable, so a creds-only "Proceed"+ // would just be confirming pre-set values — auto-dismiss is still the+ // right call to avoid duplicate prompts.+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ render(+ <SetupRequirementsCard+ inputsMode="preview"+ output={makeOutput({+ inputs: [+ { name: "url", title: "URL", type: "string", required: true },+ ],+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ />,+ );++ expect(screen.getByText(/Connected. Continuing/)).toBeDefined();+ });++ it("only one card auto-sends when multiple parallel cards share a provider set", async () => {+ // Regression test for Sentry bug prediction: when N parallel+ // SetupRequirementsCard instances all require the same provider, after+ // one card connects the provider the others all flip to canAutoDismiss+ // simultaneously. Without coordination each card's useEffect would fire+ // onSend, producing N identical "Please proceed" messages and spamming+ // the chat. The store-level claim must allow only the first auto-dismiss+ // to send.+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ const output = makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ });++ render(+ <>+ <SetupRequirementsCard output={output} />+ <SetupRequirementsCard output={output} />+ <SetupRequirementsCard output={output} />+ </>,+ );++ // All three cards must visually dismiss.+ await waitFor(() =>+ expect(screen.getAllByText(/Connected. Continuing/)).toHaveLength(3),+ );+ // But only one auto-send fires for the whole provider set.+ expect(mockOnSend).toHaveBeenCalledOnce();+ });++ it("auto-send survives StrictMode's double-invoke of effects", async () => {+ // Regression test for Sentry bug prediction: in React StrictMode, the+ // auto-dismiss effect runs twice in quick succession (mount → cleanup →+ // re-mount). A previous version of this effect scheduled the send via a+ // microtask and cancelled it in cleanup, which leaked the store claim+ // across the double-invoke — the first effect's microtask got cancelled,+ // the second effect couldn't re-claim, and `handleRun` never fired.+ // Today the claim itself provides atomicity and we call `handleRun`+ // synchronously; this test pins the behaviour against a StrictMode+ // remount.+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });++ render(+ <StrictMode>+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ })}+ />+ </StrictMode>,+ );++ // The card must dismiss AND the auto-send must fire exactly once+ // (not zero — the previous bug; not two — the original double-invoke+ // risk that the microtask used to guard against).+ expect(screen.getByText(/Connected. Continuing/)).toBeDefined();+ await waitFor(() => expect(mockOnSend).toHaveBeenCalledOnce());+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.tssimilarity index 100%rename from autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/__tests__/helpers.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.tsdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.tssimilarity index 86%rename from autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.tsindex b4b54be28e..8bba692f7c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts@@ -71,6 +71,28 @@ export function coerceCredentialFields(rawMissingCredentials: unknown): {return { credentialFields, requiredCredentials };}+/**+ * Extract the unique provider slugs the card is asking the user to connect.+ *+ * Used by the session-scoped connected-providers store to decide whether a+ * later card in the same chat can self-dismiss because the user has already+ * connected every provider it requires.+ */+export function getRequestedProviders(+ credentialFields: CredentialField[],+): string[] {+ const providers = new Set<string>();+ for (const [, schema] of credentialFields) {+ const provs = (schema as { credentials_provider?: unknown })+ .credentials_provider;+ if (!Array.isArray(provs)) continue;+ for (const p of provs) {+ if (typeof p === "string" && p) providers.add(p);+ }+ }+ return [...providers];+}+/*** Build a sibling-inputs dict from the missing_credentials discriminator values.*@@ -78,9 +100,6 @@ export function coerceCredentialFields(rawMissingCredentials: unknown): {* SendAuthenticatedWebRequestBlock), it adds the target URL to* `discriminator_values`. The credential modal uses `siblingInputs`* to extract the host and prefill the "Host Pattern" field.- *- * This function builds that mapping from the `discriminator` field name- * and the first `discriminator_values` entry for each credential.*/export function buildSiblingInputsFromCredentials(rawMissingCredentials: unknown,@@ -110,7 +129,7 @@ export function buildSiblingInputsFromCredentials(return result;}-interface ExpectedInput {+export interface ExpectedInput {name: string;title: string;type: string;@@ -120,8 +139,7 @@ interface ExpectedInput {value?: unknown;// Any additional JSON-schema fields (format, json_schema_extra entries,// custom widget configs, etc.) are preserved verbatim so the generic- // custom-field dispatch on the frontend can read them. Keeps this- // layer free of widget-specific knowledge.+ // custom-field dispatch on the frontend can read them.[key: string]: unknown;}@@ -164,9 +182,6 @@ export function coerceExpectedInputs(rawInputs: unknown): ExpectedInput[] {if (input.value !== undefined && input.value !== null) {item.value = input.value;}- // Preserve any additional schema fields (format, custom widget- // configs, etc.) verbatim — dispatch is handled by the generic- // custom-field layer in FormRenderer.for (const [key, value] of Object.entries(input)) {if (RESERVED_EXPECTED_INPUT_KEYS.has(key)) continue;if (value === undefined) continue;@@ -180,11 +195,10 @@ export function coerceExpectedInputs(rawInputs: unknown): ExpectedInput[] {/*** Build an RJSF schema from expected inputs so they can be rendered- * as a dynamic form via FormRenderer.+ * as a dynamic form via FormRenderer (used in "edit" mode).** When ``showAdvanced`` is false (default), fields marked ``advanced``- * are excluded — matching the builder behaviour where advanced fields- * are hidden behind a toggle.+ * are excluded — matching the builder behaviour.*/export function buildExpectedInputsSchema(expectedInputs: ExpectedInput[],@@ -218,8 +232,6 @@ export function buildExpectedInputsSchema(};if (input.description) prop.description = input.description;if (input.value !== undefined) prop.default = input.value;- // Pass through any additional schema fields (format, custom widget- // configs, etc.) so the generic custom-field dispatch can use them.for (const [key, value] of Object.entries(input)) {if (RESERVED_EXPECTED_INPUT_KEYS.has(key)) continue;if (value === undefined) continue;@@ -236,10 +248,6 @@ export function buildExpectedInputsSchema(};}-/**- * Extract initial form values from expected inputs that have a- * prefilled ``value`` from the backend.- */export function extractInitialValues(expectedInputs: ExpectedInput[],): Record<string, unknown> {@@ -324,3 +332,14 @@ export function buildRunMessage(return parts.join(" ");}++/**+ * Message variant for "preview" mode (run_agent): graph inputs are defined+ * inside the graph and not editable from the chat, so the message just+ * confirms credential setup and asks the agent to proceed.+ */+export function buildPreviewRunMessage(needsCredentials: boolean): string {+ return needsCredentials+ ? "I've configured the required credentials. Please check if everything is ready and proceed with running the agent."+ : "Please proceed with running the agent.";+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/connectedProvidersStore.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/connectedProvidersStore.tsnew file mode 100644index 0000000000..8f9665ec6a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/connectedProvidersStore.ts@@ -0,0 +1,102 @@+import { create } from "zustand";++/**+ * Session-scoped record of credential providers the user has connected+ * during the current chat. Lets credential cards self-dismiss when an+ * earlier card in the same session has already satisfied the requirement,+ * killing the "duplicate sign-in card" UX problem and obsoleting the local+ * `isDismissed` workarounds that callers used to add to survive remounts.+ *+ * Entries are keyed by `${sessionID}::${provider}` so multiple chats can+ * coexist without cross-contamination, and so a different chat reading the+ * same provider name does not falsely auto-dismiss.+ */+interface ConnectedProvidersState {+ connected: Set<string>;+ /**+ * Tracks `(sessionID, sortedProviders)` combinations that have already+ * triggered an auto-dismiss send. Prevents N parallel cards for the same+ * provider-set from each firing an identical "Please proceed" message+ * when one card connects the provider and the others re-render.+ */+ autoDismissedKeys: Set<string>;+ markConnected(args: { sessionID: string; providers: string[] }): void;+ /**+ * Atomically claim the auto-dismiss slot for `(sessionID, providers)`.+ * Returns `true` on the first call (caller should send the proceed+ * message) and `false` on subsequent calls (caller should silently+ * dismiss the card without sending).+ */+ tryClaimAutoDismiss(args: {+ sessionID: string;+ providers: string[];+ }): boolean;+ clearSession(sessionID: string): void;+}++function makeKey(sessionID: string, provider: string) {+ return `${sessionID}::${provider}`;+}++function makeAutoDismissKey(sessionID: string, providers: string[]) {+ const sorted = [...providers].sort().join(",");+ return `${sessionID}::${sorted}`;+}++export const useConnectedProvidersStore = create<ConnectedProvidersState>(+ (set) => ({+ connected: new Set<string>(),+ autoDismissedKeys: new Set<string>(),+ markConnected({ sessionID, providers }) {+ if (!sessionID || providers.length === 0) return;+ set((state) => {+ const next = new Set(state.connected);+ for (const p of providers) {+ if (p) next.add(makeKey(sessionID, p));+ }+ return { connected: next };+ });+ },+ tryClaimAutoDismiss({ sessionID, providers }) {+ if (!sessionID || providers.length === 0) return false;+ const key = makeAutoDismissKey(sessionID, providers);+ let claimed = false;+ set((state) => {+ if (state.autoDismissedKeys.has(key)) return state;+ claimed = true;+ const next = new Set(state.autoDismissedKeys);+ next.add(key);+ return { autoDismissedKeys: next };+ });+ return claimed;+ },+ clearSession(sessionID) {+ if (!sessionID) return;+ set((state) => {+ const prefix = `${sessionID}::`;+ const nextConnected = new Set<string>();+ for (const k of state.connected) {+ if (!k.startsWith(prefix)) nextConnected.add(k);+ }+ const nextAutoDismissed = new Set<string>();+ for (const k of state.autoDismissedKeys) {+ if (!k.startsWith(prefix)) nextAutoDismissed.add(k);+ }+ return {+ connected: nextConnected,+ autoDismissedKeys: nextAutoDismissed,+ };+ });+ },+ }),+);++export function useAreAllConnected(+ sessionID: string | null | undefined,+ providers: string[],+) {+ return useConnectedProvidersStore((state) => {+ if (!sessionID || providers.length === 0) return false;+ return providers.every((p) => state.connected.has(makeKey(sessionID, p)));+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.tsindex 800e944008..9156bdf2cb 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.ts@@ -1,6 +1,7 @@import { Chat } from "@ai-sdk/react";import type { UIMessage } from "ai";import { create } from "zustand";+import { useConnectedProvidersStore } from "./connectedProvidersStore";import { useCopilotStreamStore } from "./copilotStreamStore";import {createCopilotTransport,@@ -131,6 +132,7 @@ export function shouldReloadCopilotChatRuntime(sessionId: string) {export function resetCopilotChatRuntime(sessionId: string) {copilotChatRuntimes.delete(sessionId);useCopilotStreamStore.getState().clearSession(sessionId);+ useConnectedProvidersStore.getState().clearSession(sessionId);useCopilotChatRuntimeStore.getState().clearNeedsReload(sessionId);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsxindex 1be760e2f0..2ddd47f28b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx@@ -2,10 +2,8 @@import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";import type { ToolUIPart } from "ai";-import { useState } from "react";import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";-import { ContentMessage } from "../../components/ToolAccordion/AccordionContent";-import { SetupRequirementsCard } from "../RunBlock/components/SetupRequirementsCard/SetupRequirementsCard";+import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";type Props = {part: ToolUIPart;@@ -39,9 +37,6 @@ function parseError(raw: unknown): string | null {}export function ConnectIntegrationTool({ part }: Props) {- // Persist dismissed state here so SetupRequirementsCard remounts don't re-enable Proceed.- const [isDismissed, setIsDismissed] = useState(false);-const isStreaming =part.state === "input-streaming" || part.state === "input-available";const isError = part.state === "output-error";@@ -87,16 +82,11 @@ export function ConnectIntegrationTool({ part }: Props) {{output && (<div className="mt-2">- {isDismissed ? (- <ContentMessage>Connected. Continuing…</ContentMessage>- ) : (- <SetupRequirementsCard- output={output}- credentialsLabel={`${output.setup_info?.agent_name ?? providerName} credentials`}- retryInstruction="I've connected my account. Please continue."- onComplete={() => setIsDismissed(true)}- />- )}+ <SetupRequirementsCard+ output={output}+ credentialsLabel={`${output.setup_info?.agent_name ?? providerName} credentials`}+ retryInstruction="I've connected my account. Please continue."+ /></div>)}</div>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsxindex f61fd27cf1..fb57637345 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx@@ -24,7 +24,7 @@ import {} from "./helpers";import { ExecutionStartedCard } from "./components/ExecutionStartedCard/ExecutionStartedCard";import { AgentDetailsCard } from "./components/AgentDetailsCard/AgentDetailsCard";-import { SetupRequirementsCard } from "./components/SetupRequirementsCard/SetupRequirementsCard";+import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";import { ErrorCard } from "./components/ErrorCard/ErrorCard";export interface RunAgentToolPart {@@ -107,7 +107,10 @@ export function RunAgentTool({ part }: Props) {{setupRequirementsOutput && (<div className="mt-2">- <SetupRequirementsCard output={setupRequirementsOutput} />+ <SetupRequirementsCard+ output={setupRequirementsOutput}+ inputsMode="preview"+ /></div>)}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/SetupRequirementsCard.tsxdeleted file mode 100644index e61744ba50..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/SetupRequirementsCard.tsx+++ /dev/null@@ -1,118 +0,0 @@-"use client";--import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";-import { Button } from "@/components/atoms/Button/Button";-import { Text } from "@/components/atoms/Text/Text";-import { CredentialsGroupedView } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView";-import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";-import { useState } from "react";-import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";-import {- ContentBadge,- ContentCardDescription,- ContentCardTitle,- ContentMessage,-} from "../../../../components/ToolAccordion/AccordionContent";-import { coerceCredentialFields, coerceExpectedInputs } from "./helpers";--interface Props {- output: SetupRequirementsResponse;-}--export function SetupRequirementsCard({ output }: Props) {- const { onSend } = useCopilotChatActions();-- const [inputCredentials, setInputCredentials] = useState<- Record<string, CredentialsMetaInput | undefined>- >({});- const [hasSent, setHasSent] = useState(false);-- const { credentialFields, requiredCredentials } = coerceCredentialFields(- output.setup_info.user_readiness?.missing_credentials,- );-- const expectedInputs = coerceExpectedInputs(- (output.setup_info.requirements as Record<string, unknown>)?.inputs,- );-- function handleCredentialChange(key: string, value?: CredentialsMetaInput) {- setInputCredentials((prev) => ({ ...prev, [key]: value }));- }-- const needsCredentials = credentialFields.length > 0;- const isAllCredentialsComplete =- needsCredentials &&- [...requiredCredentials].every((key) => !!inputCredentials[key]);-- const canProceed =- !hasSent && (!needsCredentials || isAllCredentialsComplete);-- function handleProceed() {- setHasSent(true);- const message = needsCredentials- ? "I've configured the required credentials. Please check if everything is ready and proceed with running the agent."- : "Please proceed with running the agent.";- onSend(message);- }-- return (- <div className="grid gap-2">- <ContentMessage>{output.message}</ContentMessage>-- {needsCredentials && (- <div className="rounded-2xl border bg-background p-3">- <Text variant="small" className="w-fit border-b text-zinc-500">- Agent credentials- </Text>- <div className="mt-6">- <CredentialsGroupedView- credentialFields={credentialFields}- requiredCredentials={requiredCredentials}- inputCredentials={inputCredentials}- inputValues={{}}- onCredentialChange={handleCredentialChange}- />- </div>- </div>- )}-- {expectedInputs.length > 0 && (- <div className="rounded-2xl border bg-background p-3">- <ContentCardTitle className="text-xs">- Expected inputs- </ContentCardTitle>- <div className="mt-2 grid gap-2">- {expectedInputs.map((input) => (- <div key={input.name} className="rounded-xl border p-2">- <div className="flex items-center justify-between gap-2">- <ContentCardTitle className="text-xs">- {input.title}- </ContentCardTitle>- <ContentBadge>- {input.required ? "Required" : "Optional"}- </ContentBadge>- </div>- <ContentCardDescription className="mt-1">- {input.name} • {input.type}- {input.description ? ` \u2022 ${input.description}` : ""}- </ContentCardDescription>- </div>- ))}- </div>- </div>- )}-- {(needsCredentials || expectedInputs.length > 0) && (- <Button- variant="primary"- size="small"- className="mt-4 w-fit"- disabled={!canProceed}- onClick={handleProceed}- >- Proceed- </Button>- )}- </div>- );-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.tsdeleted file mode 100644index 0d94b80095..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts+++ /dev/null@@ -1,112 +0,0 @@-import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";--const VALID_CREDENTIAL_TYPES = new Set([- "api_key",- "oauth2",- "user_password",- "host_scoped",-]);--/**- * Transforms raw missing_credentials from SetupRequirementsResponse- * into CredentialField[] tuples compatible with CredentialsGroupedView.- *- * Each CredentialField is [key, schema] where schema matches- * BlockIOCredentialsSubSchema shape.- */-export function coerceCredentialFields(rawMissingCredentials: unknown): {- credentialFields: CredentialField[];- requiredCredentials: Set<string>;-} {- const missing =- rawMissingCredentials && typeof rawMissingCredentials === "object"- ? (rawMissingCredentials as Record<string, unknown>)- : {};-- const credentialFields: CredentialField[] = [];- const requiredCredentials = new Set<string>();-- Object.entries(missing).forEach(([key, value]) => {- if (!value || typeof value !== "object") return;- const cred = value as Record<string, unknown>;-- const provider =- typeof cred.provider === "string" ? cred.provider.trim() : "";- if (!provider) return;-- const types =- Array.isArray(cred.types) && cred.types.length > 0 ? cred.types : [];-- const credentialTypes = types- .map((t) => (typeof t === "string" ? t.trim() : ""))- .filter((t) => VALID_CREDENTIAL_TYPES.has(t));-- if (credentialTypes.length === 0) return;-- const scopes = Array.isArray(cred.scopes)- ? cred.scopes.filter((s): s is string => typeof s === "string")- : undefined;-- const schema = {- type: "object" as const,- properties: {},- credentials_provider: [provider],- credentials_types: credentialTypes,- credentials_scopes: scopes,- };-- credentialFields.push([key, schema]);- requiredCredentials.add(key);- });-- return { credentialFields, requiredCredentials };-}--export function coerceExpectedInputs(rawInputs: unknown): Array<{- name: string;- title: string;- type: string;- description?: string;- required: boolean;-}> {- if (!Array.isArray(rawInputs)) return [];- const results: Array<{- name: string;- title: string;- type: string;- description?: string;- required: boolean;- }> = [];-- rawInputs.forEach((value, index) => {- if (!value || typeof value !== "object") return;- const input = value as Record<string, unknown>;-- const name =- typeof input.name === "string" && input.name.trim()- ? input.name.trim()- : `input-${index}`;- const title =- typeof input.title === "string" && input.title.trim()- ? input.title.trim()- : name;- const type = typeof input.type === "string" ? input.type : "unknown";- const description =- typeof input.description === "string" && input.description.trim()- ? input.description.trim()- : undefined;- const required = Boolean(input.required);-- const item: {- name: string;- title: string;- type: string;- description?: string;- required: boolean;- } = { name, title, type, required };- if (description) item.description = description;- results.push(item);- });-- return results;-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsxindex 92610b5adb..1ff238a0cf 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx@@ -7,7 +7,7 @@ import { BlockDetailsCard } from "./components/BlockDetailsCard/BlockDetailsCardimport { BlockInputCard } from "./components/BlockInputCard/BlockInputCard";import { BlockOutputCard } from "./components/BlockOutputCard/BlockOutputCard";import { ErrorCard } from "./components/ErrorCard/ErrorCard";-import { SetupRequirementsCard } from "./components/SetupRequirementsCard/SetupRequirementsCard";+import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";import {getAccordionMeta,getAnimationText,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsxdeleted file mode 100644index 7b2e0c339d..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx+++ /dev/null@@ -1,188 +0,0 @@-"use client";--import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";-import { Button } from "@/components/atoms/Button/Button";-import { Text } from "@/components/atoms/Text/Text";-import { CredentialsGroupedView } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView";-import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";-import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";-import { useEffect, useMemo, useState } from "react";-import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";-import { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";-import {- buildExpectedInputsSchema,- buildRunMessage,- buildSiblingInputsFromCredentials,- checkAllCredentialsComplete,- checkAllInputsComplete,- checkCanRun,- coerceCredentialFields,- coerceExpectedInputs,- extractInitialValues,- mergeInputValues,-} from "./helpers";--interface Props {- output: SetupRequirementsResponse;- retryInstruction?: string;- credentialsLabel?: string;- onComplete?: () => void;-}--export function SetupRequirementsCard({- output,- retryInstruction,- credentialsLabel,- onComplete,-}: Props) {- const { onSend } = useCopilotChatActions();-- const [inputCredentials, setInputCredentials] = useState<- Record<string, CredentialsMetaInput | undefined>- >({});- const [hasSent, setHasSent] = useState(false);- const [showAdvanced, setShowAdvanced] = useState(false);-- const { credentialFields, requiredCredentials } = coerceCredentialFields(- output.setup_info.user_readiness?.missing_credentials,- );-- const expectedInputs = coerceExpectedInputs(- (output.setup_info.requirements as Record<string, unknown>)?.inputs,- );-- const initialValues = useMemo(- () => extractInitialValues(expectedInputs),- // eslint-disable-next-line react-hooks/exhaustive-deps -- stabilise on the raw prop- [output.setup_info.requirements],- );-- const [inputValues, setInputValues] =- useState<Record<string, unknown>>(initialValues);-- const initialValuesKey = JSON.stringify(initialValues);- useEffect(() => {- setInputValues((prev) => mergeInputValues(initialValues, prev));- // eslint-disable-next-line react-hooks/exhaustive-deps -- sync when serialised values change- }, [initialValuesKey]);-- const hasAdvancedFields = expectedInputs.some((i) => i.advanced);- const inputSchema = buildExpectedInputsSchema(expectedInputs, showAdvanced);-- // Build siblingInputs for credential modal host prefill.- // Prefer discriminator_values from the credential response, but also- // include values from input_data (e.g. url field) so the host pattern- // can be extracted even when discriminator_values is empty.- const siblingInputs = useMemo(() => {- const fromCreds = buildSiblingInputsFromCredentials(- output.setup_info.user_readiness?.missing_credentials,- );- return { ...inputValues, ...fromCreds };- }, [output.setup_info.user_readiness?.missing_credentials, inputValues]);-- function handleCredentialChange(key: string, value?: CredentialsMetaInput) {- setInputCredentials((prev) => ({ ...prev, [key]: value }));- }-- const needsCredentials = credentialFields.length > 0;- const isAllCredsComplete = checkAllCredentialsComplete(- requiredCredentials,- inputCredentials,- );-- const needsInputs = expectedInputs.length > 0;- const isAllInputsDone = checkAllInputsComplete(expectedInputs, inputValues);-- if (hasSent) {- return <ContentMessage>Connected. Continuing…</ContentMessage>;- }-- const canRun = checkCanRun(- needsCredentials,- isAllCredsComplete,- isAllInputsDone,- );-- function handleRun() {- setHasSent(true);- onComplete?.();- onSend(- buildRunMessage(- needsCredentials,- needsInputs,- inputValues,- retryInstruction,- ),- );- setInputValues({});- }-- return (- <div className="grid gap-2">- <ContentMessage>{output.message}</ContentMessage>-- {needsCredentials && (- <div className="rounded-2xl border bg-background p-3">- <Text variant="small" className="w-fit border-b text-zinc-500">- {credentialsLabel ?? "Credentials"}- </Text>- <div className="mt-6">- <CredentialsGroupedView- credentialFields={credentialFields}- requiredCredentials={requiredCredentials}- inputCredentials={inputCredentials}- inputValues={siblingInputs}- onCredentialChange={handleCredentialChange}- />- </div>- </div>- )}-- {(inputSchema || hasAdvancedFields) && (- <div className="rounded-2xl border bg-background p-3 pt-4">- <Text variant="small" className="w-fit border-b text-zinc-500">- Inputs- </Text>- {inputSchema && (- <FormRenderer- jsonSchema={inputSchema}- className="mb-3 mt-3"- handleChange={(v) =>- setInputValues((prev) => ({ ...prev, ...(v.formData ?? {}) }))- }- uiSchema={{- "ui:submitButtonOptions": { norender: true },- }}- initialValues={inputValues}- formContext={{- showHandles: false,- size: "small",- }}- />- )}- {hasAdvancedFields && (- <button- type="button"- className="text-xs text-muted-foreground underline"- onClick={() => setShowAdvanced((v) => !v)}- >- {showAdvanced ? "Hide advanced fields" : "Show advanced fields"}- </button>- )}- </div>- )}-- {(needsCredentials || needsInputs) && (- <Button- variant="primary"- size="small"- className="mt-4 w-fit"- disabled={!canRun}- onClick={handleRun}- >- Proceed- </Button>- )}- </div>- );-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsxdeleted file mode 100644index 3ef0e6d82e..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx+++ /dev/null@@ -1,247 +0,0 @@-import { render, screen, fireEvent, cleanup } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";-import { SetupRequirementsCard } from "../SetupRequirementsCard";-import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";--const mockOnSend = vi.fn();-vi.mock(- "../../../../../components/CopilotChatActionsProvider/useCopilotChatActions",- () => ({- useCopilotChatActions: () => ({ onSend: mockOnSend }),- }),-);--vi.mock(- "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView",- () => ({- CredentialsGroupedView: () => (- <div data-testid="credentials-grouped-view">Credentials</div>- ),- }),-);--vi.mock("@/components/renderers/InputRenderer/FormRenderer", () => ({- FormRenderer: ({- handleChange,- }: {- handleChange: (e: { formData?: Record<string, unknown> }) => void;- }) => (- <div data-testid="form-renderer">- <button- data-testid="form-change"- onClick={() => handleChange({ formData: { url: "https://test.com" } })}- >- Fill- </button>- </div>- ),-}));--afterEach(() => {- cleanup();- mockOnSend.mockReset();-});--function makeOutput(- overrides: {- message?: string;- missingCredentials?: Record<string, unknown>;- inputs?: unknown[];- } = {},-): SetupRequirementsResponse {- const {- message = "Please configure credentials",- missingCredentials,- inputs,- } = overrides;- return {- type: "setup_requirements",- message,- session_id: "sess-1",- setup_info: {- agent_id: "agent-1",- agent_name: "Test Agent",- user_readiness: {- has_all_credentials: !missingCredentials,- missing_credentials: missingCredentials ?? {},- ready_to_run: !missingCredentials && !inputs,- },- requirements: {- credentials: [],- inputs: inputs ?? [],- execution_modes: ["immediate"],- },- },- graph_id: null,- graph_version: null,- } as SetupRequirementsResponse;-}--describe("SetupRequirementsCard", () => {- it("renders the setup message", () => {- render(<SetupRequirementsCard output={makeOutput()} />);- expect(screen.getByText("Please configure credentials")).toBeDefined();- });-- it("renders credential section when missing credentials are provided", () => {- render(- <SetupRequirementsCard- output={makeOutput({- missingCredentials: {- api_key: {- provider: "openai",- types: ["api_key"],- },- },- })}- />,- );- expect(screen.getByTestId("credentials-grouped-view")).toBeDefined();- });-- it("uses custom credentials label when provided", () => {- render(- <SetupRequirementsCard- output={makeOutput({- missingCredentials: {- api_key: { provider: "openai", types: ["api_key"] },- },- })}- credentialsLabel="API Keys"- />,- );- expect(screen.getByText("API Keys")).toBeDefined();- });-- it("renders input form when inputs are provided", () => {- render(- <SetupRequirementsCard- output={makeOutput({- inputs: [- { name: "url", title: "URL", type: "string", required: true },- ],- })}- />,- );- expect(screen.getByTestId("form-renderer")).toBeDefined();- expect(screen.getByText("Inputs")).toBeDefined();- });-- it("renders Proceed button that is enabled when inputs are filled", () => {- render(- <SetupRequirementsCard- output={makeOutput({- inputs: [- {- name: "url",- title: "URL",- type: "string",- required: true,- value: "https://prefilled.com",- },- ],- })}- />,- );- const proceed = screen.getByText("Proceed");- expect(proceed.closest("button")?.disabled).toBe(false);- });-- it("calls onSend and shows Connected message when Proceed is clicked", () => {- render(- <SetupRequirementsCard- output={makeOutput({- inputs: [- {- name: "url",- title: "URL",- type: "string",- required: true,- value: "https://prefilled.com",- },- ],- })}- />,- );- fireEvent.click(screen.getByText("Proceed"));- expect(mockOnSend).toHaveBeenCalledOnce();- expect(screen.getByText(/Connected. Continuing/)).toBeDefined();- });-- it("calls onComplete callback when Proceed is clicked", () => {- const onComplete = vi.fn();- render(- <SetupRequirementsCard- output={makeOutput({- inputs: [- {- name: "url",- title: "URL",- type: "string",- required: true,- value: "https://prefilled.com",- },- ],- })}- onComplete={onComplete}- />,- );- fireEvent.click(screen.getByText("Proceed"));- expect(onComplete).toHaveBeenCalledOnce();- });-- it("renders advanced toggle when advanced inputs exist", () => {- render(- <SetupRequirementsCard- output={makeOutput({- inputs: [- {- name: "debug",- title: "Debug Mode",- type: "boolean",- advanced: true,- },- ],- })}- />,- );- expect(screen.getByText("Show advanced fields")).toBeDefined();- });-- it("toggles advanced fields visibility", () => {- render(- <SetupRequirementsCard- output={makeOutput({- inputs: [- { name: "url", title: "URL", type: "string", required: false },- { name: "debug", title: "Debug", type: "boolean", advanced: true },- ],- })}- />,- );- const toggle = screen.getByText("Show advanced fields");- fireEvent.click(toggle);- expect(screen.getByText("Hide advanced fields")).toBeDefined();- });-- it("includes retryInstruction in onSend message when no inputs needed", () => {- render(- <SetupRequirementsCard- output={makeOutput({- missingCredentials: {- api_key: { provider: "openai", types: ["api_key"] },- },- })}- retryInstruction="Retry the agent now"- />,- );- // With credentials required but no auto-filling mechanism in the mock,- // Proceed is disabled, but we're testing render only here- expect(screen.getByText("Proceed")).toBeDefined();- });-- it("does not render Proceed when neither credentials nor inputs are needed", () => {- render(<SetupRequirementsCard output={makeOutput()} />);- expect(screen.queryByText("Proceed")).toBeNull();- });-});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsxindex 461102d7eb..f927d782df 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx@@ -82,6 +82,7 @@ export function CredentialsInput({isHostScopedCredentialsModalOpen,isCredentialTypeSelectorOpen,isOAuth2FlowInProgress,+ oAuthPopupBlocked,cancelOAuthFlow,actionButtonText,setAPICredentialsModalOpen,@@ -168,6 +169,7 @@ export function CredentialsInput({open={isOAuth2FlowInProgress}onClose={cancelOAuthFlow}providerName={providerName}+ popupBlocked={oAuthPopupBlocked}/>)}{supportsUserPassword && (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.tsxindex 10fb5e00d7..cf7c679f31 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@@ -4,9 +4,20 @@ type Props = {open: boolean;onClose: () => void;providerName: string;+ /**+ * Set when the browser blocked the OAuth popup window and the helper+ * fell back to opening the login URL in a new tab. Changes the copy+ * to direct the user there instead of to a popup that doesn't exist.+ */+ popupBlocked?: boolean;};-export function OAuthFlowWaitingModal({ open, onClose, providerName }: Props) {+export function OAuthFlowWaitingModal({+ open,+ onClose,+ providerName,+ popupBlocked = false,+}: Props) {return (<Dialogtitle={`Waiting on ${providerName} sign-in process...`}@@ -19,11 +30,21 @@ export function OAuthFlowWaitingModal({ open, onClose, providerName }: Props) {onClose={onClose}><Dialog.Content>- <p className="text-sm text-zinc-600">- Complete the sign-in process in the pop-up window.- <br />- Closing this dialog will cancel the sign-in process.- </p>+ {popupBlocked ? (+ <p className="text-sm text-zinc-600">+ Your browser blocked the sign-in popup, so we opened it in a new+ tab. Switch to that tab and complete sign-in there.+ <br />+ If you don't see the tab, allow popups for this site, close+ this dialog, and try connecting again.+ </p>+ ) : (+ <p className="text-sm text-zinc-600">+ Complete the sign-in process in the pop-up window.+ <br />+ Closing this dialog will cancel the sign-in process.+ </p>+ )}</Dialog.Content></Dialog>);diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.tsindex 0f63d4237a..a2fc8aaa37 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts@@ -9,6 +9,7 @@ import { postV2InitiateOauthLoginForAnMcpServer } from "@/app/api/__generated__/import {OAUTH_ERROR_FLOW_CANCELED,OAUTH_ERROR_FLOW_TIMED_OUT,+ OAUTH_ERROR_POPUP_BLOCKED,OAUTH_ERROR_WINDOW_CLOSED,openOAuthPopup,} from "@/lib/oauth-popup";@@ -55,6 +56,7 @@ export function useCredentialsInput({const [isCredentialTypeSelectorOpen, setCredentialTypeSelectorOpen] =useState(false);const [isOAuth2FlowInProgress, setOAuth2FlowInProgress] = useState(false);+ const [oAuthPopupBlocked, setOAuthPopupBlocked] = useState(false);const [oAuthError, setOAuthError] = useState<string | null>(null);const [credentialToDelete, setCredentialToDelete] = useState<{id: string;@@ -196,16 +198,32 @@ export function useCredentialsInput({}setOAuth2FlowInProgress(true);+ setOAuthPopupBlocked(false);- const { promise, cleanup } = openOAuthPopup(login_url, {+ const { promise, cleanup, popupBlocked } = openOAuthPopup(login_url, {stateToken: state_token,- useCrossOriginListeners: isMCP,- // Standard OAuth uses "oauth_popup_result", MCP uses "mcp_oauth_result"+ // 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"],});+ // 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) {+ setOAuthPopupBlocked(true);+ toast({+ title: "Popup blocked",+ description: OAUTH_ERROR_POPUP_BLOCKED,+ });+ }+oauthAbortRef.current = cleanup.abort;const result = await promise;@@ -385,6 +403,7 @@ export function useCredentialsInput({isHostScopedCredentialsModalOpen,isCredentialTypeSelectorOpen,isOAuth2FlowInProgress,+ oAuthPopupBlocked,cancelOAuthFlow,credentialToDelete,deleteWarningMessage,diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.ts b/autogpt_platform/frontend/src/lib/oauth-popup.tsindex 235dc59e0b..178ea32f85 100644--- a/autogpt_platform/frontend/src/lib/oauth-popup.ts+++ b/autogpt_platform/frontend/src/lib/oauth-popup.ts@@ -11,6 +11,8 @@ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutesexport 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.";export type OAuthPopupResult = {code: string;@@ -21,13 +23,14 @@ export type OAuthPopupOptions = {/** State token to validate against incoming messages */stateToken: string;/**- * Use BroadcastChannel + localStorage polling for cross-origin OAuth (MCP).- * Standard OAuth only uses postMessage via window.opener.+ * Use BroadcastChannel + localStorage polling on top of postMessage. Needed+ * whenever `window.opener` may not survive (cross-origin OAuth providers+ * stripped by COOP headers, popup-blocked → new-tab fallback, etc.).*/useCrossOriginListeners?: boolean;- /** BroadcastChannel name (default: "mcp_oauth") */+ /** BroadcastChannel name (default: "oauth_popup") */broadcastChannelName?: string;- /** localStorage key for cross-origin fallback (default: "mcp_oauth_result") */+ /** localStorage key for cross-origin fallback (default: "oauth_popup_result") */localStorageKey?: string;/** Message types to accept (default: ["oauth_popup_result", "mcp_oauth_result"]) */acceptMessageTypes?: string[];@@ -55,12 +58,21 @@ type Cleanup = {export function openOAuthPopup(loginUrl: string,options: OAuthPopupOptions,-): { promise: Promise<OAuthPopupResult>; cleanup: Cleanup } {+): {+ promise: Promise<OAuthPopupResult>;+ cleanup: Cleanup;+ /**+ * True iff the browser refused the popup and we fell back to opening the+ * login URL in a new tab. Callers should surface a hint to the user (the+ * tab can be easy to miss) and offer a retry path.+ */+ popupBlocked: boolean;+} {const {stateToken,useCrossOriginListeners = false,- broadcastChannelName = "mcp_oauth",- localStorageKey = "mcp_oauth_result",+ broadcastChannelName = "oauth_popup",+ localStorageKey = "oauth_popup_result",acceptMessageTypes = ["oauth_popup_result", "mcp_oauth_result"],timeout = DEFAULT_TIMEOUT_MS,} = options;@@ -78,10 +90,13 @@ export function openOAuthPopup(`width=${width},height=${height},left=${left},top=${top},popup=true,scrollbars=yes`,);+ let popupBlocked = false;if (popup && !popup.closed) {popup.location.href = loginUrl;} else {- // Popup was blocked — open in new tab as fallback+ // 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");}@@ -90,10 +105,16 @@ export function openOAuthPopup(if (popup && !popup.closed) popup.close();});- // Clear any stale localStorage entry+ // Scope the localStorage key by stateToken so concurrent OAuth flows do+ // not race for a single shared slot. Each flow only reads/writes its own+ // key, so a poller cannot destructively consume a result intended for a+ // different flow. BroadcastChannel is pub/sub so it doesn't need scoping.+ const scopedLocalStorageKey = `${localStorageKey}_${stateToken}`;++ // Clear any stale localStorage entry for this specific flow only.if (useCrossOriginListeners) {try {- localStorage.removeItem(localStorageKey);+ localStorage.removeItem(scopedLocalStorageKey);} catch {}}@@ -147,10 +168,10 @@ export function openOAuthPopup(// Listener: localStorage polling (most reliable cross-tab fallback)const pollInterval = setInterval(() => {try {- const stored = localStorage.getItem(localStorageKey);+ const stored = localStorage.getItem(scopedLocalStorageKey);if (stored) {const data = JSON.parse(stored);- localStorage.removeItem(localStorageKey);+ localStorage.removeItem(scopedLocalStorageKey);handleResult(data);}} catch {}@@ -200,5 +221,6 @@ export function openOAuthPopup(abort: (reason?: string) => controller.abort(reason || "canceled"),signal: controller.signal,},+ popupBlocked,};}