AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend/copilot): make completing a Connect card actually connect (#14316)
Reinier van der Leerbb917df100c4
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsxindex cc3f3e1461..0b311fe4cc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx@@ -4,9 +4,13 @@ import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { ConnectCredentialDialog } from "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog";import { findSavedUserCredentialByProviderAndType } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";+import { filterSystemCredentials } from "@/components/contextual/CredentialsInput/helpers";import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";-import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";+import {+ CredentialsProvidersContext,+ type CredentialsProvidersContextType,+} from "@/providers/agent-credentials/credentials-provider";import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";import { useContext, useEffect, useState } from "react";import type { ConnectorRow as Row } from "./helpers";@@ -78,9 +82,25 @@ export function ConnectorRow({ row }: Props) {schema={row.schema}provider={row.provider}displayName={row.displayName}+ credentialID={upgradableCredentialID(row.provider, allProviders)}open={isDialogOpen}onClose={() => setDialogOpen(false)}+ onConnected={row.onConnected}/></div>);}++/** The account a re-auth should upgrade in place. Signing in without it can+ * grant narrower scopes than the user already had and leave a second row for+ * the same provider, which no ConnectorRow can ever resolve. Only safe when+ * exactly one account exists — otherwise picking one would be a guess. */+function upgradableCredentialID(+ provider: string,+ allProviders: CredentialsProvidersContextType | null,+) {+ const oauthCredentials = filterSystemCredentials(+ allProviders?.[provider]?.savedCredentials ?? [],+ ).filter((credential) => credential.type === "oauth2");+ return oauthCredentials.length === 1 ? oauthCredentials[0].id : undefined;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsxindex 176e4ea617..9b32780bf4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx@@ -80,6 +80,7 @@ function connectorRequest(],selected: {},onChange: vi.fn(),+ onConnected: vi.fn(),...overrides,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.tsindex 0e4a4d73e5..390b549b1e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.test.ts@@ -22,6 +22,7 @@ function connectorRequest(],selected: {},onChange: vi.fn(),+ onConnected: vi.fn(),...overrides,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.tsindex 2a9375a31d..2ec647f7bc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts@@ -61,6 +61,10 @@ export interface ConnectorRequest {fields: CredentialField[];selected: Record<string, CredentialsMetaInput | undefined>;onChange: (key: string, value?: CredentialsMetaInput) => void;+ /** The user finished a sign-in on this row. Distinct from a credential+ * merely being present, which is also true of a card re-rendered from+ * chat history. */+ onConnected: () => void;}export interface ConnectorRow {@@ -70,6 +74,7 @@ export interface ConnectorRow {schema: CredentialField[1];selected?: CredentialsMetaInput;select: (value?: CredentialsMetaInput) => void;+ onConnected: () => void;}/** Flattens every request into one row per provider: two tools asking for@@ -109,5 +114,7 @@ export function toConnectorRows(selected: row.selected,select: (value?: CredentialsMetaInput) =>row.targets.forEach(({ request, key }) => request.onChange(key, value)),+ onConnected: () =>+ row.targets.forEach(({ request }) => request.onConnected()),}));}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.tsxindex 7b338c8de2..7a1212159e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx@@ -74,6 +74,7 @@ export function SetupRequirementsCard({Record<string, CredentialsMetaInput | undefined>>({});const [hasSent, setHasSent] = useState(false);+ const [justConnected, setJustConnected] = useState(false);const [showAdvanced, setShowAdvanced] = useState(false);const { credentialFields, requiredCredentials } = coerceCredentialFields(@@ -148,6 +149,16 @@ export function SetupRequirementsCard({const hasUserActionableInputs = isEditMode && needsInputs;const canAutoDismiss =needsCredentials && alreadyConnected && !hasUserActionableInputs;+ // Inside a chain this card renders no Proceed of its own — the chain only+ // renders one for inputs/questions — so a completed sign-in is the sole "go"+ // signal; without this the chain stalls after the user connects. It must be+ // the sign-in and not merely a satisfied credential: every card in the chat+ // history re-mounts on load with its credential already in place.+ const canAutoProceed =+ Boolean(chainActions) &&+ justConnected &&+ isAllCredsComplete &&+ !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@@ -163,7 +174,7 @@ export function SetupRequirementsCard({// (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 ((!canAutoDismiss && !canAutoProceed) || hasSent) return;if (!sessionID || requestedProviders.length === 0) return;const claimed = useConnectedProvidersStore.getState()@@ -174,7 +185,7 @@ export function SetupRequirementsCard({}handleRun();// eslint-disable-next-line react-hooks/exhaustive-deps -- handleRun captures latest state; claim guards re-entry- }, [canAutoDismiss, hasSent]);+ }, [canAutoDismiss, canAutoProceed, hasSent]);const canRun = checkCanRun(needsCredentials,@@ -185,7 +196,7 @@ export function SetupRequirementsCard({// Inside a tool chain the card's own Proceed is replaced by the chain's// single Proceed step — register readiness + message with the chain.useEffect(() => {- if (!chainActions || hasSent || canAutoDismiss) return;+ if (!chainActions || hasSent || canAutoDismiss || canAutoProceed) return;if (!needsCredentials && !needsInputs) return;chainActions.register({id: actionId,@@ -198,6 +209,7 @@ export function SetupRequirementsCard({fields: credentialFields,selected: inputCredentials,onChange: handleCredentialChange,+ onConnected: () => setJustConnected(true),}: undefined,inputs:@@ -221,6 +233,7 @@ export function SetupRequirementsCard({chainActions,hasSent,canAutoDismiss,+ canAutoProceed,canRun,actionId,needsCredentials,@@ -231,7 +244,7 @@ export function SetupRequirementsCard({showAdvanced,]);- if (hasSent || canAutoDismiss) {+ if (hasSent || canAutoDismiss || canAutoProceed) {return <ContentMessage>Connected. Continuing…</ContentMessage>;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsxnew file mode 100644index 0000000000..671c231a32--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/connect-card-flow.test.tsx@@ -0,0 +1,417 @@+/**+ * End-to-end regression for the copilot's Connect card.+ *+ * Every layer of this path had tests and every layer passed, yet composing+ * them produced a card that could never be completed. So this test drives the+ * whole path, mocking only its two ends:+ *+ * ToolChain → SetupRequirementsCard → ChainActionCard → ConnectorRow+ * → ConnectCredentialDialog → useOAuthConnect → the API+ *+ * The API is MSW rather than a live backend, and the consent screen is the one+ * unavoidable fake — no CI job can have a human approve a real OAuth grant.+ * Every component in between is the real one.+ */++import CredentialsProvider from "@/providers/agent-credentials/credentials-provider";+import userEvent from "@testing-library/user-event";+import { HttpResponse, http } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { server } from "@/mocks/mock-server";+import {+ cleanup,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { useConnectedProvidersStore } from "@/app/(platform)/copilot/connectedProvidersStore";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import type { MessagePart } from "../../ChatMessagesContainer/helpers";+import { ToolChain } from "../ToolChain";++// CredentialsProvider only fetches for a signed-in user; the shared setup+// signs everyone out.+vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isLoggedIn: true, isUserLoading: false, user: null }),+}));++// The popup is the consent screen; nothing else about the flow is faked.+// It resolves with the code the real callback handler would receive.+vi.mock("@/lib/oauth-popup", () => ({+ OAUTH_ERROR_POPUP_BLOCKED: "popup blocked",+ preOpenOAuthPopup: () => null,+ openOAuthPopup: () => ({+ promise: Promise.resolve({ code: "oauth-code", state: "state-token" }),+ cleanup: { abort: () => undefined },+ popupBlocked: false,+ fallbackBlocked: false,+ }),+}));++const REQUIRED_SCOPE = "repo";+const SESSION_ID = "session-1";++// The scopes the browser actually asked the consent screen for. `null` means+// the login endpoint was never called; `""` means it was called without them.+let requestedScopes: string | null = null;+// The account the sign-in asked to upgrade, if any.+let upgradedCredentialID: string | null = null;+let savedCredentials: Record<string, unknown>[] = [];++describe("copilot Connect card", () => {+ beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;+ // The user already has GitHub connected, but without the scope this block+ // needs — the exact state in which the card is surfaced.+ savedCredentials = [+ {+ id: "cred-old",+ provider: "github",+ type: "oauth2",+ title: "GitHub",+ scopes: ["notifications", "read:user"],+ },+ ];+ server.use(+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([+ {+ name: "github",+ description: "Issues, pull requests, repositories",+ },+ ]),+ ),+ http.get("*/api/integrations/providers/system", () =>+ HttpResponse.json([]),+ ),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json(savedCredentials),+ ),+ http.get("*/api/integrations/github/login", ({ request }) => {+ const query = new URL(request.url).searchParams;+ requestedScopes = query.get("scopes") ?? "";+ upgradedCredentialID = query.get("credential_id");+ return HttpResponse.json({+ login_url: "https://github.com/login/oauth/authorize",+ state_token: "state-token",+ });+ }),+ // The real backend grants what the login URL asked for, so the scopes+ // the frontend dropped are the scopes the new credential lacks.+ http.post("*/api/integrations/github/callback", () => {+ const granted = requestedScopes ? requestedScopes.split(",") : [];+ savedCredentials = [+ ...savedCredentials,+ {+ id: "cred-new",+ provider: "github",+ type: "oauth2",+ title: "GitHub",+ scopes: granted,+ },+ ];+ return HttpResponse.json(savedCredentials.at(-1));+ }),+ );+ });++ afterEach(() => {+ cleanup();+ useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });+ // The auto-send claim is a module singleton keyed by session id, so a+ // later test reusing SESSION_ID would silently dismiss its own card.+ useConnectedProvidersStore.getState().clearSession(SESSION_ID);+ });++ it("asks the consent screen for the scopes the block requires", async () => {+ renderChain();++ await completeConnectFlow();++ // Pre-fix this was "" — the chain initiated OAuth with no scopes at all,+ // so the granted credential could never satisfy the card that asked for it.+ await waitFor(() => expect(requestedScopes).toBe(REQUIRED_SCOPE));+ });++ it("marks the row connected and continues the chat once connected", async () => {+ const { onSend } = renderChain();++ await completeConnectFlow();++ // The chain renders no Proceed for a connectors-only card, so without an+ // automatic follow-up turn the chat stalls with the credential connected.+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(onSend.mock.calls[0][0]).toContain(+ "I've configured the required credentials.",+ );+ expect(await screen.findByText("Connected. Continuing…")).toBeDefined();+ });++ it("offers the existing account for upgrade instead of a fresh grant", async () => {+ renderChain();++ await completeConnectFlow();++ // Without this the backend cannot union scopes, and a narrower grant is+ // stored as a second row that no ConnectorRow can ever resolve.+ await waitFor(() => expect(upgradedCredentialID).toBe("cred-old"));+ });++ it("leaves the row unconnected when the grant comes back short", async () => {+ // A provider that silently downgrades the grant must not read as connected+ // — that was the shape of the original "Connected, then 401" report.+ server.use(+ http.get("*/api/integrations/github/login", () => {+ requestedScopes = "";+ return HttpResponse.json({+ login_url: "https://github.com/login/oauth/authorize",+ state_token: "state-token",+ });+ }),+ );+ const { onSend } = renderChain();++ await completeConnectFlow();++ await waitFor(() => expect(savedCredentials).toHaveLength(2));+ expect(+ await screen.findByRole("button", { name: "Connect" }),+ ).toBeDefined();+ expect(onSend).not.toHaveBeenCalled();+ });+});++describe("copilot Connect card, API-key provider", () => {+ beforeEach(() => {+ savedCredentials = [];+ server.use(+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([{ name: "openai", description: "Models" }]),+ ),+ http.get("*/api/integrations/providers/system", () =>+ HttpResponse.json([]),+ ),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json(savedCredentials),+ ),+ http.post("*/api/integrations/openai/credentials", async () => {+ const stored = {+ id: "cred-key",+ provider: "openai",+ type: "api_key",+ title: "My key",+ };+ savedCredentials = [...savedCredentials, stored];+ return HttpResponse.json(stored);+ }),+ );+ });++ afterEach(() => {+ cleanup();+ useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });+ useConnectedProvidersStore.getState().clearSession(SESSION_ID);+ });++ it("continues the chat after an API key is saved", async () => {+ const onSend = vi.fn();+ render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain parts={[apiKeyRequirementsPart()]} isStreaming={false} />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );++ const user = userEvent.setup();+ await user.click(await screen.findByRole("button", { name: "Connect" }));+ await user.click(await screen.findByText("API Key"));+ await user.type(await screen.findByLabelText("Name"), "My key");+ await user.type(+ await screen.findByPlaceholderText("sk-..."),+ "sk-test-value",+ );+ await user.click(await screen.findByRole("button", { name: "Continue" }));++ // The OAuth branch was fixed first; this is the same stall on the other+ // button of the same dialog.+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ });+});++describe("copilot Connect card, already satisfied", () => {+ beforeEach(() => {+ // The state a chat is in after the user connected and later reopened it:+ // every card in the history re-mounts with its credential already there.+ savedCredentials = [+ {+ id: "cred-ok",+ provider: "github",+ type: "oauth2",+ title: "GitHub",+ scopes: [REQUIRED_SCOPE],+ },+ {+ id: "cred-slack",+ provider: "slack",+ type: "oauth2",+ title: "Slack",+ scopes: ["chat:write"],+ },+ ];+ server.use(+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([+ { name: "github", description: "Issues, pull requests" },+ { name: "slack", description: "Messages" },+ ]),+ ),+ http.get("*/api/integrations/providers/system", () =>+ HttpResponse.json([]),+ ),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json(savedCredentials),+ ),+ );+ });++ afterEach(() => {+ cleanup();+ useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });+ useConnectedProvidersStore.getState().clearSession(SESSION_ID);+ });++ it("stays silent when a finished card re-mounts from chat history", async () => {+ const { onSend } = renderChain();++ await settle();++ expect(onSend).not.toHaveBeenCalled();+ });++ it("stays silent for two finished cards asking for different services", async () => {+ const onSend = vi.fn();+ render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain+ parts={[setupRequirementsPart(), slackRequirementsPart()]}+ isStreaming={false}+ />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );++ await settle();++ // The auto-send claim is keyed by provider set, so two cards are two+ // claims — each would fire its own message on mount.+ expect(onSend).not.toHaveBeenCalled();+ });+});++function renderChain() {+ const onSend = vi.fn();+ const utils = render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain parts={[setupRequirementsPart()]} isStreaming={false} />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );+ return { onSend, ...utils };+}++async function completeConnectFlow() {+ const user = userEvent.setup();+ await user.click(await screen.findByRole("button", { name: "Connect" }));+ await user.click(await screen.findByText("OAuth"));+ await user.click(await screen.findByRole("button", { name: "Continue" }));+}++/** What the backend returns when a block needs a credential the user's+ * connected account doesn't cover — here GitHub without the `repo` scope. */+function setupRequirementsPart(): MessagePart {+ return {+ type: "tool-run_block",+ toolCallId: "call-run_block",+ state: "output-available",+ input: { block_name: "GithubReadPullRequestBlock" },+ output: {+ type: "setup_requirements",+ message: "Connect GitHub to continue.",+ session_id: SESSION_ID,+ setup_info: {+ agent_id: "block-1",+ agent_name: "Github Read Pull Request",+ requirements: {},+ user_readiness: {+ has_all_credentials: false,+ missing_credentials: {+ credentials: {+ provider: "github",+ types: ["oauth2"],+ scopes: [REQUIRED_SCOPE],+ },+ },+ },+ },+ },+ } as unknown as MessagePart;+}++/** Long enough for the credential list, the row's auto-select and the+ * auto-send effect to have all run had they been going to. */+async function settle() {+ await waitFor(() => expect(screen.queryByText("Connect")).toBeDefined());+ await new Promise((resolve) => setTimeout(resolve, 800));+}++function slackRequirementsPart(): MessagePart {+ const github = setupRequirementsPart() as unknown as Record<string, unknown>;+ return {+ ...github,+ toolCallId: "call-run_block-slack",+ output: {+ ...(github.output as Record<string, unknown>),+ setup_info: {+ agent_id: "block-2",+ agent_name: "Slack Post Message",+ requirements: {},+ user_readiness: {+ has_all_credentials: false,+ missing_credentials: {+ credentials: {+ provider: "slack",+ types: ["oauth2"],+ scopes: ["chat:write"],+ },+ },+ },+ },+ },+ } as unknown as MessagePart;+}+function apiKeyRequirementsPart(): MessagePart {+ const github = setupRequirementsPart() as unknown as Record<string, unknown>;+ return {+ ...github,+ toolCallId: "call-run_block-openai",+ output: {+ ...(github.output as Record<string, unknown>),+ setup_info: {+ agent_id: "block-3",+ agent_name: "OpenAI Completion",+ requirements: {},+ user_readiness: {+ has_all_credentials: false,+ missing_credentials: {+ credentials: { provider: "openai", types: ["api_key"] },+ },+ },+ },+ },+ } as unknown as MessagePart;+}diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsxindex e37b83cc88..e323edb248 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx@@ -20,8 +20,12 @@ interface Props {schema: BlockIOCredentialsSubSchema;provider: string;displayName: string;+ /** Existing account to upgrade in place rather than signing in afresh. */+ credentialID?: string;open: boolean;onClose: () => void;+ /** Fires only on a completed sign-in, unlike onClose. */+ onConnected?: () => void;}/** The onboarding connect flow (logo pair, "Connect AutoGPT to X",@@ -32,8 +36,10 @@ export function ConnectCredentialDialog({schema,provider,displayName,+ credentialID,open,onClose,+ onConnected,}: Props) {const {selectedMethod,@@ -45,13 +51,29 @@ export function ConnectCredentialDialog({isConnecting,handleContinue,reset,- } = useConnectCredentialDialog({ provider, onConnected: onClose });+ } = useConnectCredentialDialog({+ provider,+ onConnected: () => {+ onConnected?.();+ onClose();+ },+ scopes: schema.credentials_scopes,+ credentialID,+ });function handleClose() {reset();onClose();}+ // Device auth completes inside ConnectMethodView, so it never passes through+ // the hook's success path and has to report the connection itself.+ function handleDeviceAuthSuccess() {+ reset();+ onConnected?.();+ onClose();+ }+const connectable: ConnectableProvider = {id: provider,name: displayName,@@ -79,7 +101,7 @@ export function ConnectCredentialDialog({onSelectMethod={setSelectedMethod}apiKeyForm={apiKeyForm}onApiKeySubmit={handleApiKeySubmit}- onDeviceAuthSuccess={handleClose}+ onDeviceAuthSuccess={handleDeviceAuthSuccess}/><div className="flex items-center justify-end gap-3"><Button variant="secondary" size="small" onClick={handleClose}>diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.tsindex 95c68a3be4..131ccb9367 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts@@ -11,12 +11,24 @@ import { useState } from "react";interface Args {provider: string;onConnected: () => void;+ scopes?: string[];+ credentialID?: string;}-export function useConnectCredentialDialog({ provider, onConnected }: Args) {+export function useConnectCredentialDialog({+ provider,+ onConnected,+ scopes,+ credentialID,+}: Args) {const [selectedMethod, setSelectedMethod] = useState<AuthMethod | null>(null);- const oauth = useOAuthConnect({ provider, onSuccess: handleConnected });+ const oauth = useOAuthConnect({+ provider,+ onSuccess: handleConnected,+ scopes,+ credentialID,+ });const apiKey = useApiKeyConnectForm({ provider, onSuccess: handleConnected });// The dialog stays mounted while closed, so a half-filled key or adiff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.tsindex 9fa1a99794..279a88cb2d 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useContext, useState } from "react";import { zodResolver } from "@hookform/resolvers/zod";import { useForm } from "react-hook-form";import { useQueryClient } from "@tanstack/react-query";@@ -9,6 +9,7 @@ import { postV1CreateCredentials } from "@/app/api/__generated__/endpoints/integimport type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { toast } from "@/components/molecules/Toast/use-toast";import { invalidateConnectionQueries } from "@/lib/react-query/invalidateConnections";+import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";import { apiKeyConnectSchema, type ApiKeyConnectFormValues } from "./schema";@@ -26,6 +27,7 @@ function toUnixSeconds(value: string | undefined): number | undefined {export function useApiKeyConnectForm({ provider, onSuccess }: Args) {const queryClient = useQueryClient();+ const credentialsActions = useContext(CredentialsActionsContext);const [isPending, setIsPending] = useState(false);const form = useForm<ApiKeyConnectFormValues>({@@ -51,6 +53,9 @@ export function useApiKeyConnectForm({ provider, onSuccess }: Args) {toast({ title: "API key saved", variant: "success" });await invalidateConnectionQueries(queryClient);+ // Same reason as the OAuth branch: invalidation emits no cache event+ // unless something already subscribed to the credentials query.+ credentialsActions?.reload();// Narrow by shape rather than by status code: the comment above keeps// this flow indifferent to a 201 ↔ 200 swap, and only the success// payload carries an id.diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.tsindex abb974b69d..bfd3686bf8 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts@@ -1,6 +1,6 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useContext, useEffect, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import {@@ -15,16 +15,29 @@ import {openOAuthPopup,preOpenOAuthPopup,} from "@/lib/oauth-popup";+import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";import { getOAuthErrorMessage } from "./helpers";interface Args {provider: string;onSuccess: (credential?: CredentialsMetaResponse) => void;+ /** Scopes the requesting block needs. Omit for a provider-level connect,+ * where the provider's default scopes are the whole ask. */+ scopes?: string[];+ /** Existing account to upgrade. The backend unions its scopes with the+ * requested ones, so a re-auth cannot narrow what the user already had. */+ credentialID?: string;}-export function useOAuthConnect({ provider, onSuccess }: Args) {+export function useOAuthConnect({+ provider,+ onSuccess,+ scopes,+ credentialID,+}: Args) {const queryClient = useQueryClient();+ const credentialsActions = useContext(CredentialsActionsContext);const [isPending, setIsPending] = useState(false);const isPendingRef = useRef(false);const abortRef = useRef<(() => void) | null>(null);@@ -65,7 +78,12 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {const preOpenedWindow = preOpenOAuthPopup();preOpenedWindowRef.current = preOpenedWindow;try {- const initiateResponse = await getV1InitiateOauthFlow(provider);+ // Without the scopes the consent screen grants provider defaults, and+ // a credential missing a required scope never satisfies the caller.+ const initiateResponse = await getV1InitiateOauthFlow(+ provider,+ buildLoginParams(scopes, credentialID),+ );// customMutator rejects non-2xx, so this branch is unreachable at// runtime — it exists only to narrow the discriminated union so the// 200-only LoginResponse shape is accessible below.@@ -116,6 +134,10 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {toast({ title: "Connected via OAuth", variant: "success" });await invalidateConnectionQueries(queryClient);+ // The provider's in-memory list only reloads off a React Query cache+ // event, which invalidation never emits unless something already+ // subscribed to that query — so ask it directly.+ credentialsActions?.reload();// customMutator rejects non-2xx, so a 200 is the only way to get here;// the check narrows the union rather than guarding a real branch.onSuccess(exchanged.status === 200 ? exchanged.data : undefined);@@ -144,3 +166,10 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {return { connect, isPending };}++function buildLoginParams(scopes?: string[], credentialID?: string) {+ const params: { scopes?: string; credential_id?: string } = {};+ if (scopes?.length) params.scopes = scopes.join(",");+ if (credentialID) params.credential_id = credentialID;+ return Object.keys(params).length > 0 ? params : undefined;+}