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): stop managed, stale and trigger credentials breaking the Connect card (#14327)
Reinier van der Leer369fe1509339
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsxindex 2ae9a00dcc..89efebc281 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ChainActionCard.tsx@@ -22,6 +22,9 @@ interface Props {mcp: McpConnectorRequest[];inputs: InputsRequest[];questions: QuestionRequest[];+ /** A card opted out of auto-sending, so the stack needs a Proceed even with+ * no inputs of its own. */+ manualProceed: boolean;isReady: boolean;onProceed: () => void;}@@ -36,6 +39,7 @@ export function ChainActionCard({mcp,inputs,questions,+ manualProceed,isReady,onProceed,}: Props) {@@ -114,7 +118,7 @@ export function ChainActionCard({</div>)}- {hasInputs && !hasQuestions && (+ {(hasInputs || manualProceed) && !hasQuestions && (<Buttonvariant="primary"size="small"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 0b311fe4cc..0dca7fc774 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@@ -35,6 +35,16 @@ export function ConnectorRow({ row }: Props) {);useEffect(() => {+ // Cards stream in one commit at a time, so a row's schema can widen after+ // it auto-selected: a selection that no longer satisfies it must go, or+ // the row reads Connected while Proceed sends a credential missing the+ // scopes the later card asked for. `null` is the provider context's+ // "still loading" sentinel, where every lookup misses — clearing then+ // would drop a good selection on every mount.+ if (allProviders && row.selected && !savedCredential) {+ row.select(undefined);+ return;+ }if (row.selected || !savedCredential) return;row.select({id: savedCredential.id,@@ -43,7 +53,7 @@ export function ConnectorRow({ row }: Props) {title: savedCredential.title ?? undefined,});// eslint-disable-next-line react-hooks/exhaustive-deps -- row.select is rebuilt each render by the card- }, [savedCredential?.id, row.selected]);+ }, [savedCredential?.id, row.selected, allProviders]);return (<div className="flex items-center gap-3 px-4 py-3">@@ -94,13 +104,17 @@ export function ConnectorRow({ row }: Props) {/** 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. */+ * exactly one account exists — otherwise picking one would be a guess.+ * Managed and system credentials are excluded: the backend refuses to upgrade+ * either, so offering one turns every Connect click into a 400. */function upgradableCredentialID(provider: string,allProviders: CredentialsProvidersContextType | null,) {const oauthCredentials = filterSystemCredentials(allProviders?.[provider]?.savedCredentials ?? [],- ).filter((credential) => credential.type === "oauth2");+ ).filter(+ (credential) => credential.type === "oauth2" && !credential.is_managed,+ );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 9b32780bf4..fbc5cb3593 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@@ -138,6 +138,7 @@ function renderCard(mcp={[]}inputs={[]}questions={[]}+ manualProceed={false}isReadyonProceed={onProceed}{...overrides}@@ -201,6 +202,81 @@ describe("ChainActionCard", () => {expect(screen.queryByText("Connect")).toBeNull();});+ it("keeps a selection while the providers context is still loading", async () => {+ const selected = {+ id: "saved-1",+ provider: "github",+ type: "api_key" as const,+ };+ const request = connectorRequest({ selected: { credentials: selected } });++ render(+ // `null` is the provider context's "still loading" sentinel, so every+ // credential lookup misses — clearing then drops a good selection.+ <CredentialsProvidersContext.Provider value={null}>+ <ChainActionCard+ connectors={[request]}+ mcp={[]}+ inputs={[]}+ questions={[]}+ manualProceed={false}+ isReady+ onProceed={vi.fn()}+ />+ </CredentialsProvidersContext.Provider>,+ );++ await screen.findByText("GitHub");+ expect(request.onChange).not.toHaveBeenCalled();+ });++ it("clears the selection once loading reveals no matching credential", async () => {+ const selected = {+ id: "saved-1",+ provider: "github",+ type: "api_key" as const,+ };+ const request = connectorRequest({ selected: { credentials: selected } });+ const loadedWithNoMatch = {+ github: { savedCredentials: [] },+ } as unknown as CredentialsProvidersContextType;++ const { rerender } = render(+ <CredentialsProvidersContext.Provider value={null}>+ <ChainActionCard+ connectors={[request]}+ mcp={[]}+ inputs={[]}+ questions={[]}+ manualProceed={false}+ isReady+ onProceed={vi.fn()}+ />+ </CredentialsProvidersContext.Provider>,+ );+ expect(request.onChange).not.toHaveBeenCalled();++ rerender(+ <CredentialsProvidersContext.Provider value={loadedWithNoMatch}>+ <ChainActionCard+ connectors={[request]}+ mcp={[]}+ inputs={[]}+ questions={[]}+ manualProceed={false}+ isReady+ onProceed={vi.fn()}+ />+ </CredentialsProvidersContext.Provider>,+ );++ // Neither the credential nor the selection changed across this+ // transition, so only `allProviders` can re-run the effect.+ await waitFor(() =>+ expect(request.onChange).toHaveBeenCalledWith("credentials", undefined),+ );+ });+it("auto-selects a saved credential from the providers context", async () => {const request = connectorRequest();const providers = {@@ -223,6 +299,7 @@ describe("ChainActionCard", () => {mcp={[]}inputs={[]}questions={[]}+ manualProceed={false}isReadyonProceed={vi.fn()}/>@@ -378,6 +455,7 @@ describe("ChainActionCard", () => {mcp={[]}inputs={[inputsRequest()]}questions={[]}+ manualProceed={false}isReadyonProceed={onProceed}/>,@@ -975,6 +1053,7 @@ describe("ChainActionCard", () => {mcp={[]}inputs={[]}questions={[{ ...request, answers: { region: "Europe" } }]}+ manualProceed={false}isReadyonProceed={onProceed}/>,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 390b549b1e..731b523f10 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@@ -60,6 +60,50 @@ describe("toConnectorRows", () => {expect(rows[0].provider).toBe("github");});+ it("asks for the union of the scopes every card needs", () => {+ const first = connectorRequest({+ id: "req-1",+ fields: [+ [+ "credentials",+ {+ credentials_provider: ["github"],+ credentials_types: ["oauth2"],+ credentials_scopes: ["repo"],+ },+ ],+ ],+ });+ const second = connectorRequest({+ id: "req-2",+ fields: [+ [+ "credentials",+ {+ credentials_provider: ["github"],+ credentials_types: ["oauth2"],+ credentials_scopes: ["repo", "workflow"],+ },+ ],+ ],+ });++ const [row] = toConnectorRows([first, second], []);++ // Keeping only the first card's scopes leaves the second permanently+ // unsatisfiable, and with auto-proceed it never sends.+ expect(row.schema.credentials_scopes).toEqual(["repo", "workflow"]);+ });++ it("leaves the schema alone when no card asks for scopes", () => {+ const first = connectorRequest({ id: "req-1" });+ const second = connectorRequest({ id: "req-2" });++ const [row] = toConnectorRows([first, second], []);++ expect(row.schema.credentials_scopes).toBeUndefined();+ });+it("fans a selection out to every request asking for the provider", () => {const first = connectorRequest({ id: "req-1" });const second = connectorRequest({ id: "req-2" });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 2ec647f7bc..ef24af3aa4 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@@ -98,10 +98,23 @@ export function toConnectorRows(for (const [key, schema] of request.fields) {const provider = schema.credentials_provider?.[0];if (!provider) continue;- const row = rows.get(provider) ?? { schema, targets: [] };+ const row = rows.get(provider);+ if (!row) {+ rows.set(provider, {+ schema,+ targets: [{ request, key }],+ selected: request.selected[key],+ });+ continue;+ }+ // One row answers every card that asked for this provider, so it must+ // request the union of their scopes — keeping only the first card's+ // leaves the others permanently unsatisfiable. Scopes only: merging+ // `credentials_types` would offer a method some cards cannot accept, and+ // that needs a per-card row rather than a wider one.+ row.schema = withUnionedScopes(row.schema, schema);row.targets.push({ request, key });row.selected = row.selected ?? request.selected[key];- rows.set(provider, row);}}@@ -118,3 +131,18 @@ export function toConnectorRows(row.targets.forEach(({ request }) => request.onConnected()),}));}++/** Merges `incoming`'s scopes into `kept`, leaving every other schema field+ * as the first card set it. */+function withUnionedScopes(+ kept: CredentialField[1],+ incoming: CredentialField[1],+): CredentialField[1] {+ const scopes = [+ ...new Set([+ ...(kept.credentials_scopes ?? []),+ ...(incoming.credentials_scopes ?? []),+ ]),+ ];+ return scopes.length > 0 ? { ...kept, credentials_scopes: scopes } : kept;+}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 7a1212159e..adf31e03b4 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@@ -101,6 +101,7 @@ export function SetupRequirementsCard({}, [initialValuesKey]);const isEditMode = inputsMode === "edit";+ const isTriggerMode = inputsMode === "trigger";const hasAdvancedFields =isEditMode && expectedInputs.some((i) => i.advanced);@@ -147,8 +148,15 @@ export function SetupRequirementsCard({const requestedProviders = getRequestedProviders(credentialFields);const alreadyConnected = useAreAllConnected(sessionID, requestedProviders);const hasUserActionableInputs = isEditMode && needsInputs;+ // A trigger card's message carries the account its webhook registers under,+ // which the backend requires the user to have picked — so neither auto path+ // may send it, and the chain gives it a Proceed instead.+ const needsManualPick = isTriggerMode;const canAutoDismiss =- needsCredentials && alreadyConnected && !hasUserActionableInputs;+ needsCredentials &&+ alreadyConnected &&+ !hasUserActionableInputs &&+ !needsManualPick;// 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@@ -158,7 +166,8 @@ export function SetupRequirementsCard({Boolean(chainActions) &&justConnected &&isAllCredsComplete &&- !hasUserActionableInputs;+ !hasUserActionableInputs &&+ !needsManualPick;// 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@@ -201,6 +210,7 @@ export function SetupRequirementsCard({chainActions.register({id: actionId,ready: canRun,+ manualProceed: needsManualPick,buildMessage: () => buildProceedMessage(),onSent: markSent,connectors: needsCredentials@@ -249,7 +259,7 @@ export function SetupRequirementsCard({}function buildProceedMessage() {- return inputsMode === "trigger"+ return isTriggerMode? buildTriggerSetupMessage(inputCredentials): isEditMode? buildRunMessage(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsxindex daf4fdf243..4313fcb69a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx@@ -165,6 +165,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {const questionRequests = pendingActions.map((entry) => entry.questions).filter((request) => request !== undefined);+ const manualProceed = pendingActions.some((entry) => entry.manualProceed);const hasCardWork =connectorRequests.length > 0 ||mcpRequests.length > 0 ||@@ -343,6 +344,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {mcp={mcpRequests}inputs={inputRequests}questions={questionRequests}+ manualProceed={manualProceed}isReady={allActionsReady}onProceed={handleProceed}/>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.tsxindex 671c231a32..f6d101cddf 100644--- 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.tsx@@ -117,13 +117,7 @@ describe("copilot Connect card", () => {);});- 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);- });+ afterEach(resetStores);it("asks the consent screen for the scopes the block requires", async () => {renderChain();@@ -146,7 +140,7 @@ describe("copilot Connect card", () => {expect(onSend.mock.calls[0][0]).toContain("I've configured the required credentials.",);- expect(await screen.findByText("Connected. Continuing…")).toBeDefined();+ await screen.findByText("Connected. Continuing…");});it("offers the existing account for upgrade instead of a fresh grant", async () => {@@ -176,15 +170,239 @@ describe("copilot Connect card", () => {await completeConnectFlow();await waitFor(() => expect(savedCredentials).toHaveLength(2));- expect(- await screen.findByRole("button", { name: "Connect" }),- ).toBeDefined();+ await screen.findByRole("button", { name: "Connect" });+ expect(onSend).not.toHaveBeenCalled();+ });+});++describe("copilot Connect card, cards that owe more than a credential", () => {+ beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;+ savedCredentials = [];+ server.use(+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([{ name: "github", description: "Repositories" }]),+ ),+ http.get("*/api/integrations/providers/system", () =>+ HttpResponse.json([]),+ ),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json(savedCredentials),+ ),+ http.get("*/api/integrations/github/login", ({ request }) => {+ requestedScopes = new URL(request.url).searchParams.get("scopes") ?? "";+ return HttpResponse.json({+ login_url: "https://github.com/login/oauth/authorize",+ state_token: "state-token",+ });+ }),+ http.post("*/api/integrations/github/callback", () => {+ savedCredentials = [oauthCredential("cred-new", [REQUIRED_SCOPE])];+ return HttpResponse.json(savedCredentials[0]);+ }),+ );+ });++ afterEach(resetStores);++ it("waits for the user when the card also collects run inputs", async () => {+ const onSend = vi.fn();+ render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain parts={[partWithInputs()]} isStreaming={false} />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );++ await completeConnectFlow();++ // Auto-sending here would run the block with the inputs the user has not+ // filled in yet, discarding them. Wait on the row resolving, not on the+ // MSW handler: `savedCredentials` is set inside the handler, before the+ // query invalidates or the auto-send effect could run.+ await screen.findByText("Connected");+ expect(onSend).not.toHaveBeenCalled();+ });++ it("gives a trigger card a Proceed instead of auto-sending it", async () => {+ const onSend = vi.fn();+ render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain parts={[triggerPart()]} isStreaming={false} />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );++ await completeConnectFlow();++ // buildTriggerSetupMessage carries the credential the webhook registers+ // under, so the account must be chosen rather than auto-picked — but+ // excluding the auto-send without adding a button leaves the card with no+ // way forward at all, which is worse than sending the wrong account.+ // The Proceed button is the positive signal that the card has finished+ // reacting, so it has to come before the negative assertion.+ await screen.findByRole("button", { name: "Proceed" });+ expect(onSend).not.toHaveBeenCalled();+ });++ it("gives a trigger card a Proceed when a sibling already connected its provider", async () => {+ // The auto-dismiss path fires before any account is selected and sends+ // `credentials={}`; the backend then re-issues the card, the re-issued one+ // has already lost the dedupe claim, and the chat waits forever.+ savedCredentials = [oauthCredential("cred-existing", [REQUIRED_SCOPE])];+ useConnectedProvidersStore+ .getState()+ .markConnected({ sessionID: SESSION_ID, providers: ["github"] });++ const onSend = vi.fn();+ render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain parts={[triggerPart()]} isStreaming={false} />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );++ await screen.findByRole("button", { name: "Proceed" });expect(onSend).not.toHaveBeenCalled();});});+describe("copilot Connect card, a row whose schema widens mid-stream", () => {+ beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;+ // Satisfies the first card's `repo` but not the second card's `workflow`.+ savedCredentials = [oauthCredential("cred-repo", [REQUIRED_SCOPE])];+ server.use(+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([{ name: "github", description: "Repositories" }]),+ ),+ http.get("*/api/integrations/providers/system", () =>+ HttpResponse.json([]),+ ),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json(savedCredentials),+ ),+ );+ });++ afterEach(resetStores);++ it("drops a selection the widened schema no longer satisfies", async () => {+ const onSend = vi.fn();+ const { rerender } = render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain parts={[setupRequirementsPart()]} isStreaming={true} />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );+ await screen.findByText("Connected");++ rerender(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain+ parts={[setupRequirementsPart(), widerScopePart()]}+ isStreaming={false}+ />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );++ // Cards stream in one commit at a time. Leaving the stale selection in+ // place renders "Connected" and lets Proceed send a credential missing+ // the scope the second card asked for.+ await screen.findByRole("button", { name: "Connect" });+ expect(onSend).not.toHaveBeenCalled();+ });+});++describe("copilot Connect card, upgrade-target selection", () => {+ beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;+ savedCredentials = [];+ server.use(+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([{ name: "github", description: "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",+ });+ }),+ http.post("*/api/integrations/github/callback", () =>+ HttpResponse.json({ id: "cred-new", provider: "github" }),+ ),+ );+ });++ afterEach(resetStores);++ it("picks no upgrade target when two accounts could be the one", async () => {+ savedCredentials = [+ oauthCredential("cred-a", ["notifications"]),+ oauthCredential("cred-b", ["read:user"]),+ ];++ renderChain();+ await completeConnectFlow();++ // Choosing between them would be a guess; the backend upgrades in place,+ // so guessing wrong silently broadens the wrong account.+ await waitFor(() => expect(requestedScopes).toBe(REQUIRED_SCOPE));+ expect(upgradedCredentialID).toBeNull();+ });++ it("does not offer a managed account, which the backend refuses to upgrade", async () => {+ savedCredentials = [+ {+ ...oauthCredential("cred-managed", ["notifications"]),+ is_managed: true,+ },+ ];++ renderChain();+ await completeConnectFlow();++ // _prepare_scope_upgrade 400s a managed credential, so offering one makes+ // every Connect click fail and the row permanently unconnectable.+ await waitFor(() => expect(requestedScopes).toBe(REQUIRED_SCOPE));+ expect(upgradedCredentialID).toBeNull();+ });++ it("does not offer an API-key account for an OAuth upgrade", async () => {+ savedCredentials = [+ { id: "cred-key", provider: "github", type: "api_key", title: "GitHub" },+ ];++ renderChain();+ await completeConnectFlow();++ await waitFor(() => expect(requestedScopes).toBe(REQUIRED_SCOPE));+ expect(upgradedCredentialID).toBeNull();+ });+});+describe("copilot Connect card, API-key provider", () => {beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;savedCredentials = [];server.use(http.get("*/api/integrations/providers", () =>@@ -209,11 +427,7 @@ describe("copilot Connect card, API-key provider", () => {);});- afterEach(() => {- cleanup();- useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });- useConnectedProvidersStore.getState().clearSession(SESSION_ID);- });+ afterEach(resetStores);it("continues the chat after an API key is saved", async () => {const onSend = vi.fn();@@ -243,6 +457,8 @@ describe("copilot Connect card, API-key provider", () => {describe("copilot Connect card, already satisfied", () => {beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;// 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 = [@@ -277,16 +493,12 @@ describe("copilot Connect card, already satisfied", () => {);});- afterEach(() => {- cleanup();- useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });- useConnectedProvidersStore.getState().clearSession(SESSION_ID);- });+ afterEach(resetStores);it("stays silent when a finished card re-mounts from chat history", async () => {const { onSend } = renderChain();- await settle();+ await settle({ connectedRows: 1 });expect(onSend).not.toHaveBeenCalled();});@@ -304,7 +516,7 @@ describe("copilot Connect card, already satisfied", () => {</CredentialsProvider>,);- await settle();+ await settle({ connectedRows: 2 });// The auto-send claim is keyed by provider set, so two cards are two// claims — each would fire its own message on mount.@@ -362,11 +574,14 @@ function setupRequirementsPart(): MessagePart {} 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));+/** Waits on a positive signal — every row resolved against the refreshed+ * credential list — so a "nothing was sent" assertion cannot pass merely+ * because nothing has mounted yet. */+async function settle({ connectedRows }: { connectedRows: number }) {+ await screen.findByText("Plug in what this needs");+ await waitFor(() =>+ expect(screen.getAllByText("Connected")).toHaveLength(connectedRows),+ );}function slackRequirementsPart(): MessagePart {@@ -415,3 +630,66 @@ function apiKeyRequirementsPart(): MessagePart {},} as unknown as MessagePart;}+function oauthCredential(id: string, scopes: string[]) {+ return { id, provider: "github", type: "oauth2", title: "GitHub", scopes };+}+function resetStores() {+ 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);+}+function partWithInputs(): MessagePart {+ const base = setupRequirementsPart() as unknown as Record<string, unknown>;+ const output = base.output as Record<string, unknown>;+ const setup = output.setup_info as Record<string, unknown>;+ return {+ ...base,+ output: {+ ...output,+ setup_info: {+ ...setup,+ requirements: {+ inputs: [+ { name: "url", title: "URL", type: "string", required: true },+ ],+ },+ },+ },+ } as unknown as MessagePart;+}++function triggerPart(): MessagePart {+ const base = setupRequirementsPart() as unknown as Record<string, unknown>;+ return {+ ...base,+ type: "tool-setup_agent_webhook_trigger",+ toolCallId: "call-setup_agent_webhook_trigger",+ } as unknown as MessagePart;+}+function widerScopePart(): MessagePart {+ const base = setupRequirementsPart() as unknown as Record<string, unknown>;+ const output = base.output as Record<string, unknown>;+ const setup = output.setup_info as Record<string, unknown>;+ return {+ ...base,+ toolCallId: "call-run_block-wider",+ output: {+ ...output,+ setup_info: {+ ...setup,+ user_readiness: {+ has_all_credentials: false,+ missing_credentials: {+ credentials: {+ provider: "github",+ types: ["oauth2"],+ scopes: [REQUIRED_SCOPE, "workflow"],+ },+ },+ },+ },+ },+ } as unknown as MessagePart;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.tsindex 9e70de4595..1b60148224 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts@@ -17,6 +17,9 @@ export interface ChainActionEntry {ready: boolean;buildMessage: () => string | null;onSent?: () => void;+ /** This card's reply must be reviewed before it is sent, so the chain owes+ * it a Proceed even when it asks for nothing but credentials. */+ manualProceed?: boolean;/** Credentials this card needs. The chain merges every entry's request* into the single connectors table it renders underneath itself. */connectors?: ConnectorRequest;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 e323edb248..ecf2460079 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@@ -53,10 +53,7 @@ export function ConnectCredentialDialog({reset,} = useConnectCredentialDialog({provider,- onConnected: () => {- onConnected?.();- onClose();- },+ onConnected: handleConnected,scopes: schema.credentials_scopes,credentialID,});@@ -66,14 +63,19 @@ export function ConnectCredentialDialog({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();+ // The hook has already reset by the time it calls this.+ function handleConnected() {onConnected?.();onClose();}+ // Device auth completes inside ConnectMethodView, bypassing the hook, so+ // this is the only place its reset can happen.+ function handleDeviceAuthSuccess() {+ reset();+ handleConnected();+ }+const connectable: ConnectableProvider = {id: provider,name: displayName,diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.tsindex 77449668b2..66c0fe672f 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/useOAuthConnect.test.ts@@ -409,3 +409,117 @@ describe("useOAuthConnect — popup window lifecycle", () => {await first;});});++describe("useOAuthConnect — login request shape", () => {+ afterEach(() => vi.clearAllMocks());++ async function connectWith(args: {+ scopes?: string[];+ credentialID?: string;+ }) {+ await setupSuccessfulPopup();+ await mockInitiateOk();+ const { postV1ExchangeOauthCodeForTokens } = await import(+ "@/app/api/__generated__/endpoints/integrations/integrations"+ );+ vi.mocked(postV1ExchangeOauthCodeForTokens).mockResolvedValue({+ status: 200,+ data: { id: "cred-1" },+ } as never);++ const { result } = renderHook(() =>+ useOAuthConnect({ provider: "github", onSuccess: vi.fn(), ...args }),+ );+ await result.current.connect();++ const { getV1InitiateOauthFlow } = await import(+ "@/app/api/__generated__/endpoints/integrations/integrations"+ );+ return vi.mocked(getV1InitiateOauthFlow).mock.calls[0];+ }++ it("sends no query at all for a provider-level connect", async () => {+ // The four existing callers pass no scopes; they must be unaffected.+ expect(await connectWith({})).toEqual(["github", undefined]);+ });++ it("omits the query for an empty scope list", async () => {+ expect(await connectWith({ scopes: [] })).toEqual(["github", undefined]);+ });++ it("joins scopes with commas, as the endpoint parses them", async () => {+ expect(await connectWith({ scopes: ["repo", "read:org"] })).toEqual([+ "github",+ { scopes: "repo,read:org" },+ ]);+ });++ it("carries the upgrade target alongside the scopes", async () => {+ expect(+ await connectWith({ scopes: ["repo"], credentialID: "cred-old" }),+ ).toEqual(["github", { scopes: "repo", credential_id: "cred-old" }]);+ });++ it("does not retry a 404 that is not about the upgrade target", async () => {+ await setupSuccessfulPopup();+ const { getV1InitiateOauthFlow } = await import(+ "@/app/api/__generated__/endpoints/integrations/integrations"+ );+ vi.mocked(getV1InitiateOauthFlow).mockRejectedValue(+ makeApiError(404, { detail: "Provider 'foo' does not support OAuth" }),+ );++ const { result } = renderHook(() =>+ useOAuthConnect({+ provider: "foo",+ onSuccess: vi.fn(),+ scopes: ["repo"],+ credentialID: "cred-1",+ }),+ );+ await result.current.connect();++ // That 404 is raised before the endpoint reads the upgrade target, so+ // re-sending without it fails identically.+ expect(vi.mocked(getV1InitiateOauthFlow)).toHaveBeenCalledTimes(1);+ });++ it("retries without the upgrade target when the backend 404s it", async () => {+ await setupSuccessfulPopup();+ const { getV1InitiateOauthFlow, postV1ExchangeOauthCodeForTokens } =+ await import(+ "@/app/api/__generated__/endpoints/integrations/integrations"+ );+ vi.mocked(getV1InitiateOauthFlow)+ .mockRejectedValueOnce(+ makeApiError(404, { detail: "Credential to upgrade not found" }),+ )+ .mockResolvedValueOnce({+ status: 200,+ data: {+ login_url: "https://github.com/login/oauth",+ state_token: "state-token",+ },+ } as never);+ vi.mocked(postV1ExchangeOauthCodeForTokens).mockResolvedValue({+ status: 200,+ data: { id: "cred-1" },+ } as never);++ const { result } = renderHook(() =>+ useOAuthConnect({+ provider: "github",+ onSuccess: vi.fn(),+ scopes: ["repo"],+ credentialID: "deleted-in-another-tab",+ }),+ );+ await result.current.connect();++ // A stale id must degrade to a fresh grant, not a dead Connect button.+ expect(vi.mocked(getV1InitiateOauthFlow).mock.calls).toEqual([+ ["github", { scopes: "repo", credential_id: "deleted-in-another-tab" }],+ ["github", { scopes: "repo" }],+ ]);+ });+});diff --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 279a88cb2d..b409ece055 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@@ -53,12 +53,11 @@ 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.+ // 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.+ // Narrow by shape, not status code, so a 201 ↔ 200 swap cannot break+ // this; only the success payload carries an id.onSuccess("id" in created.data ? created.data : undefined);} catch (error) {toast({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 bfd3686bf8..d576b6fddd 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@@ -80,9 +80,13 @@ export function useOAuthConnect({try {// Without the scopes the consent screen grants provider defaults, and// a credential missing a required scope never satisfies the caller.- const initiateResponse = await getV1InitiateOauthFlow(+ const initiateResponse = await initiateLogin(provider,- buildLoginParams(scopes, credentialID),+ scopes,+ credentialID,+ // The list that produced the dead id is stale; refresh it now so a+ // cancelled popup does not make every later click pay the retry too.+ () => credentialsActions?.reload(),);// customMutator rejects non-2xx, so this branch is unreachable at// runtime — it exists only to narrow the discriminated union so the@@ -173,3 +177,42 @@ function buildLoginParams(scopes?: string[], credentialID?: string) {if (credentialID) params.credential_id = credentialID;return Object.keys(params).length > 0 ? params : undefined;}++/** The upgrade target comes from an in-memory list that can be stale — the+ * very staleness this flow exists to survive — and the backend 404s an id it+ * cannot find. Fall back to a fresh grant rather than leaving a dead button.+ * Only that 404 retries: the endpoint also 404s a provider without OAuth+ * support, before it ever reads the upgrade target, and re-sending that+ * fails identically. */+async function initiateLogin(+ provider: string,+ scopes?: string[],+ credentialID?: string,+ onStaleCredential?: () => void,+) {+ try {+ return await getV1InitiateOauthFlow(+ provider,+ buildLoginParams(scopes, credentialID),+ );+ } catch (error) {+ if (!credentialID || !isMissingUpgradeTarget(error)) throw error;+ onStaleCredential?.();+ return getV1InitiateOauthFlow(provider, buildLoginParams(scopes));+ }+}++/** Matches only `_prepare_scope_upgrade`'s "Credential to upgrade not found".+ * If the backend rewords it the retry stops happening and the original 404+ * surfaces — the behaviour before the retry existed. */+function isMissingUpgradeTarget(error: unknown) {+ const { status, response } = (error ?? {}) as {+ status?: number;+ response?: { detail?: unknown };+ };+ return (+ status === 404 &&+ typeof response?.detail === "string" &&+ response.detail.toLowerCase().includes("upgrade")+ );+}