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): ask which account to update instead of adding a duplicate (SECRT-2660) (#14745)
Bentlyc3b2eda182d2
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 1ac5c988ab..8aee7426ef 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@@ -156,6 +156,20 @@ export function ConnectorRow({ row }: Props) {(credential) => credential.id === row.selected?.id,);const hasChoice = !expertGrant && !row.selected && pickable.length > 1;+ // No saved account fits, and there are several that a fresh sign-in could+ // widen. Signing in without naming one requests only this card's scopes,+ // which the backend cannot merge into an account that holds others, so it+ // stored yet another credential beside them. The user names the account+ // instead; with exactly one, `upgradableCredentialID` already does. Only+ // where the row takes an OAuth credential at all: a card asking for an API+ // key runs no sign-in to aim, so naming an account there picks one the key+ // form then ignores.+ const updatable =+ expertGrant ||+ pickable.length > 0 ||+ !(row.schema.credentials_types ?? []).includes("oauth2")+ ? []+ : updatableAccounts(row, allProviders);async function pick(credential: Grantable): Promise<boolean> {row.select({@@ -266,7 +280,16 @@ export function ConnectorRow({ row }: Props) {error: null,purpose: "choose",}- : undefined+ : updatable.length > 1+ ? {+ credentials: updatable,+ // The dialog runs the sign-in itself for this purpose.+ onUse: async () => false,+ isPending: false,+ error: null,+ purpose: "update",+ }+ : undefined}open={isDialogOpen}onClose={() => setDialogOpen(false)}@@ -354,6 +377,33 @@ function newlyConnectedCredential(return account ? { grantable, account } : null;}+/** The user's own OAuth accounts for a provider: the ones a fresh sign-in can+ * widen. API keys have nothing to re-authorise, and managed and system+ * credentials are refused by the backend. The one-click upgrade and the+ * account picker must agree on this set, or a provider counted one way and+ * offered the other leaves the user with no path that upgrades in place. */+function updatableCredentials(+ provider: string,+ allProviders: CredentialsProvidersContextType | null,+) {+ return filterSystemCredentials(+ allProviders?.[provider]?.savedCredentials ?? [],+ ).filter(+ (credential) => credential.type === "oauth2" && !credential.is_managed,+ );+}++function updatableAccounts(+ row: Row,+ allProviders: CredentialsProvidersContextType | null,+): Grantable[] {+ return updatableCredentials(row.provider, allProviders).map((credential) => ({+ id: credential.id,+ title: credential.title ?? credential.username ?? row.displayName,+ type: credential.type,+ }));+}+/** 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@@ -364,10 +414,6 @@ function upgradableCredentialID(provider: string,allProviders: CredentialsProvidersContextType | null,) {- const oauthCredentials = filterSystemCredentials(- allProviders?.[provider]?.savedCredentials ?? [],- ).filter(- (credential) => credential.type === "oauth2" && !credential.is_managed,- );+ const oauthCredentials = updatableCredentials(provider, allProviders);return oauthCredentials.length === 1 ? oauthCredentials[0].id : undefined;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.choice.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.choice.test.tsxindex 426edf18d8..44d75f3a3b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.choice.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.choice.test.tsx@@ -33,6 +33,7 @@ vi.mock(}) =>open ? (<div data-testid="connect-dialog">+ {existing?.purpose && <span>{`purpose-${existing.purpose}`}</span>}{existing?.credentials.map((credential) => (<buttonkey={credential.id}@@ -157,3 +158,56 @@ describe("ConnectorRow with several saved accounts for one provider", () => {expect(screen.queryByText("Choose account")).toBeNull();});});++describe("ConnectorRow when no saved account has the access a card needs", () => {+ const oauthRow = () =>+ row({+ schema: {+ credentials_provider: ["github"],+ credentials_types: ["oauth2"],+ credentials_scopes: ["repo", "read:org"],+ },+ });+ const oauth = (id: string, title: string) => ({+ id,+ provider: "github",+ type: "oauth2",+ title,+ scopes: ["repo"],+ });++ it("asks which account to update when there are several", () => {+ renderRow(oauthRow(), [+ oauth("cred-a", "work"),+ oauth("cred-b", "personal"),+ ] as never);++ fireEvent.click(screen.getByText("Connect"));++ expect(screen.getByText("purpose-update")).toBeDefined();+ expect(screen.getByText("use-work")).toBeDefined();+ expect(screen.getByText("use-personal")).toBeDefined();+ });++ it("does not ask with a single account, which is upgraded in place already", () => {+ renderRow(oauthRow(), [oauth("cred-a", "work")] as never);++ fireEvent.click(screen.getByText("Connect"));++ expect(screen.queryByText("purpose-update")).toBeNull();+ });++ it("does not ask when the card takes an API key, which no sign-in widens", () => {+ // Several OAuth accounts exist, but this row only accepts an API key:+ // naming one of them changes nothing about the key form that follows.+ renderRow(row(), [+ oauth("cred-a", "work"),+ oauth("cred-b", "personal"),+ ] as never);++ fireEvent.click(screen.getByText("Connect"));++ expect(screen.queryByText("purpose-update")).toBeNull();+ expect(screen.queryByText("use-work")).toBeNull();+ });+});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 edbafc7c8c..433cc5e9ef 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@@ -51,6 +51,14 @@ vi.mock("@/lib/oauth-popup", () => ({}),}));+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: vi.fn(),+ useToast: () => ({ toast: vi.fn() }),+ useToastOnFail: () => () => {},+}));++import { toast } from "@/components/molecules/Toast/use-toast";+const REQUIRED_SCOPE = "repo";const SESSION_ID = "session-1";@@ -404,21 +412,89 @@ describe("copilot Connect card, upgrade-target selection", () => {afterEach(resetStores);- it("picks no upgrade target when two accounts could be the one", async () => {+ it("asks which account to update when two could be the one", async () => {savedCredentials = [oauthCredential("cred-a", ["notifications"]),oauthCredential("cred-b", ["read:user"]),];renderChain();- await completeConnectFlow();+ const user = userEvent.setup();+ await user.click(await screen.findByRole("button", { name: "Connect" }));++ // Choosing between them on the user's behalf would be a guess, and the+ // backend upgrades in place, so a wrong guess silently broadens the wrong+ // account. Signing in without a target stored a third credential instead.+ // So the user names the account.+ expect(await screen.findByText("Update a GitHub account")).toBeDefined();+ expect(requestedScopes).toBeNull();++ const accounts = await screen.findAllByRole("radio");+ await user.click(accounts[1]);+ await user.click(+ screen.getByRole("button", { name: "Update this account" }),+ );+ await user.click(await screen.findByText("OAuth"));+ await user.click(await screen.findByRole("button", { name: "Continue" }));++ await waitFor(() => expect(upgradedCredentialID).toBe("cred-b"));+ });++ it("adds a new account beside two existing ones when asked to", async () => {+ savedCredentials = [+ oauthCredential("cred-a", ["notifications"]),+ oauthCredential("cred-b", ["read:user"]),+ ];++ renderChain();+ const user = userEvent.setup();+ await user.click(await screen.findByRole("button", { name: "Connect" }));+ await user.click(await screen.findByRole("button", { name: "Add new" }));+ await user.click(await screen.findByText("OAuth"));+ await user.click(await screen.findByRole("button", { name: "Continue" }));- // 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("surfaces the backend's refusal when the sign-in is a different user", async () => {+ savedCredentials = [+ oauthCredential("cred-a", ["notifications"]),+ oauthCredential("cred-b", ["read:user"]),+ ];+ server.use(+ http.post("*/api/integrations/github/callback", () =>+ HttpResponse.json(+ { detail: "Username mismatch: authenticated as a different user" },+ { status: 400 },+ ),+ ),+ );++ renderChain();+ const user = userEvent.setup();+ await user.click(await screen.findByRole("button", { name: "Connect" }));+ const accounts = await screen.findAllByRole("radio");+ await user.click(accounts[1]);+ await user.click(+ screen.getByRole("button", { name: "Update this account" }),+ );+ await user.click(await screen.findByText("OAuth"));+ await user.click(await screen.findByRole("button", { name: "Continue" }));++ // The sign-in was aimed at cred-b, and a different user behind it is+ // refused rather than stored as yet another account.+ await waitFor(() => expect(upgradedCredentialID).toBe("cred-b"));+ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ description: "Username mismatch: authenticated as a different user",+ variant: "destructive",+ }),+ ),+ );+ });+it("does not offer a managed account, which the backend refuses to upgrade", async () => {savedCredentials = [{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 3a78f1beec..7f92573272 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@@ -59,6 +59,9 @@ export function ConnectCredentialDialog({}: Props) {const [addingNew, setAddingNew] = useState(false);const [chosenId, setChosenId] = useState<string | null>(null);+ // The account the user chose to sign in to again. It becomes the upgrade+ // target, so the sign-in widens that account rather than adding another.+ const [updatingId, setUpdatingId] = useState<string | null>(null);const {selectedMethod,setSelectedMethod,@@ -76,12 +79,13 @@ export function ConnectCredentialDialog({// Add new asks for a second account, not a re-auth: keeping the upgrade// target would sign the user back into the very account they are trying// to add another alongside.- credentialID: addingNew ? undefined : credentialID,+ credentialID: addingNew ? undefined : (updatingId ?? credentialID),});const offered = existing?.credentials ?? [];- const showExisting = offered.length > 0 && !addingNew;- const isChoosing = existing?.purpose === "choose";+ const showExisting = offered.length > 0 && !addingNew && !updatingId;+ const isUpdating = existing?.purpose === "update";+ const isChoosing = existing?.purpose === "choose" || isUpdating;// Handing an expert one of several accounts defaults to the first; choosing// which of your own accounts to run on starts with none picked.const chosen =@@ -92,6 +96,7 @@ export function ConnectCredentialDialog({reset();setAddingNew(false);setChosenId(null);+ setUpdatingId(null);}function handleClose() {@@ -103,6 +108,7 @@ export function ConnectCredentialDialog({function handleConnected(credential?: CredentialsMetaResponse) {setAddingNew(false);setChosenId(null);+ setUpdatingId(null);onConnected?.(credential);onClose();}@@ -116,6 +122,11 @@ export function ConnectCredentialDialog({async function handleUseExisting() {if (!existing || !chosen) return;+ if (isUpdating) {+ // Nothing is usable yet: move on to the sign-in, aimed at this account.+ setUpdatingId(chosen.id);+ return;+ }if (await existing.onUse(chosen)) handleClose();}@@ -195,9 +206,11 @@ export function ConnectCredentialDialog({>{existing?.isPending? "Granting…"- : isChoosing- ? "Use this account"- : "Use existing"}+ : isUpdating+ ? "Update this account"+ : isChoosing+ ? "Use this account"+ : "Use existing"}</Button></>) : (diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsxindex 6ae3433d22..f787efa931 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx@@ -513,4 +513,40 @@ describe("ConnectCredentialDialog with existing accounts", () => {"true",);});++ it("signs in to the account the user chose to update, not a fresh one", () => {+ const existing = { ...offer(), purpose: "update" as const };+ renderDialog({ existing });++ expect(screen.getByText("Update a GitHub account")).toBeDefined();+ for (const radio of screen.getAllByRole("radio")) {+ expect(radio.getAttribute("aria-checked")).toBe("false");+ }+ expect(+ screen.getByText("Update this account").closest("button")?.disabled,+ ).toBe(true);++ fireEvent.click(screen.getByText("Personal GitHub"));+ fireEvent.click(screen.getByText("Update this account"));++ // The list gives way to the sign-in, aimed at that account, so the+ // backend widens it in place instead of storing another beside it.+ expect(screen.getByTestId("connect-method-view")).toBeDefined();+ const flow = mockUseOAuthConnect.mock.calls.at(-1)?.[0] as {+ credentialID?: string;+ };+ expect(flow.credentialID).toBe("cred-2");+ expect(existing.onUse).not.toHaveBeenCalled();+ });++ it("adds a new account when the user asks for one instead of updating", () => {+ renderDialog({ existing: { ...offer(), purpose: "update" as const } });++ fireEvent.click(screen.getByText("Add new"));++ const flow = mockUseOAuthConnect.mock.calls.at(-1)?.[0] as {+ credentialID?: string;+ };+ expect(flow.credentialID).toBeUndefined();+ });});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/components/ExistingCredentialsView/ExistingCredentialsView.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/components/ExistingCredentialsView/ExistingCredentialsView.tsxindex 16fd2fe142..1a1b9071bc 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/components/ExistingCredentialsView/ExistingCredentialsView.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/components/ExistingCredentialsView/ExistingCredentialsView.tsx@@ -13,9 +13,24 @@ interface Props {credentials: ExistingCredential[];selectedId: string | null;onSelect: (id: string) => void;- purpose?: "grant" | "choose";+ purpose?: "grant" | "choose" | "update";}+const TITLES = {+ grant: (name: string) => `Give this expert access to ${name}`,+ choose: (name: string) => `Choose a ${name} account`,+ update: (name: string) => `Update a ${name} account`,+};++const DESCRIPTIONS = {+ grant:+ "Your account is already connected, but this expert can't use it yet. Pick an account to share, or add a new one.",+ choose:+ "You have more than one account connected. Pick the one this chat should use, or add a new one.",+ update:+ "None of your connected accounts has the access this needs. Pick the one to sign in to again, or add a new one.",+};+// The step before the connect methods when the account already has a// credential the expert lacks: pick which one to hand over. Mirrors the// method radio cards so switching to Add new feels like the same dialog.@@ -48,14 +63,10 @@ export function ExistingCredentialsView({<div className="flex flex-col gap-1.5 text-center"><Text variant="h3" className="!text-[1.25rem] text-zinc-900">- {purpose === "choose"- ? `Choose a ${displayName} account`- : `Give this expert access to ${displayName}`}+ {TITLES[purpose](displayName)}</Text><Text variant="body" className="!text-zinc-500">- {purpose === "choose"- ? "You have more than one account connected. Pick the one this chat should use, or add a new one."- : "Your account is already connected, but this expert can't use it yet. Pick an account to share, or add a new one."}+ {DESCRIPTIONS[purpose]}</Text></div>diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/helpers.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/helpers.tsindex dcbc5c29d6..3cf8431fa2 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/helpers.ts+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/helpers.ts@@ -14,7 +14,9 @@ export interface ExistingCredentialsOffer {isPending: boolean;error: string | null;/** Why the accounts are offered. "grant" hands one to an expert that lacks- * it; "choose" picks which of the user's own accounts a chat runs on, where- * nothing is pre-selected because the choice is the whole point. */- purpose?: "grant" | "choose";+ * it; "choose" picks which of the user's own accounts a chat runs on;+ * "update" picks which account to sign in to again for wider access, so the+ * sign-in upgrades that account instead of adding another beside it. The+ * last two pre-select nothing, because the choice is the whole point. */+ purpose?: "grant" | "choose" | "update";}