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): offer Reconnect when a provider refused the saved credential (#15160)
Krzysztof Czerwinski4b1905c71918
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 8aee7426ef..a561cb5687 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@@ -34,7 +34,9 @@ const GRANT_FAILED_ERROR = "Couldn't grant access. Try again.";export function ConnectorRow({ row }: Props) {const [isDialogOpen, setDialogOpen] = useState(false);- const [awaitingGrant, setAwaitingGrant] = useState(false);+ // A sign-in finished without reporting its credential, so the account it+ // added is found by diffing the provider list against `knownIds`.+ const [awaitingNewAccount, setAwaitingNewAccount] = useState(false);const [grantError, setGrantError] = useState<string | null>(null);// A credential connected from this row while an expert is asking. It stays// here until its grant succeeds, so a failed grant is retried from the@@ -45,17 +47,39 @@ export function ConnectorRow({ row }: Props) {// `null` while the provider's accounts were still loading, where a diff// would call every account the user already had new.const knownIds = useRef<Set<string> | null>(null);+ // Credentials the user signed in with from this row, latest last. A re-auth+ // updates the account in place and keeps its id, so the id alone cannot tell+ // a renewed credential from the one the provider refused.+ const [renewedIds, setRenewedIds] = useState<string[]>([]);const allProviders = useContext(CredentialsProvidersContext);const { mutateAsync: grantCredentials, isPending: isGranting } =useGrantExpertCredentials();const expertGrant = row.expertGrant;const grantedCredentials = useExpertCredentialSelection(row, allProviders);+ const rejectedIds = row.rejectedCredentialIds.filter(+ (id) => !renewedIds.includes(id),+ );+ // Still on file, but refused: never one to select or offer as usable.+ const usableProviders = withoutCredentials(allProviders, rejectedIds);+ // Only this provider's own refused account makes the row a Reconnect. A+ // card's rejection reaches every row it asks for, and the account may have+ // been deleted since. While one is on file nothing is picked for the user,+ // not even after a sign-in whose account the list has yet to show: quietly+ // running on another of their accounts could post as someone else.+ const onFile = (ids: string[]) =>+ !expertGrant &&+ (allProviders?.[row.provider]?.savedCredentials ?? []).some((saved) =>+ ids.includes(saved.id),+ );+ const hasRefusedAccount = onFile(row.rejectedCredentialIds);+ const awaitingReconnect = onFile(rejectedIds);+const savedCredential = findSavedUserCredentialByProviderAndType(row.schema.credentials_provider ?? [],row.schema.credentials_types ?? [],row.schema.credentials_scopes,- allProviders,+ usableProviders,row.schema.discriminator_values,);@@ -105,29 +129,56 @@ export function ConnectorRow({ row }: Props) {useEffect(() => {if (expertGrant) {- if (!awaitingGrant || row.selected || !knownIds.current) return;+ if (!awaitingNewAccount || row.selected || !knownIds.current) return;const fresh = newlyConnectedCredential(row,allProviders,knownIds.current,);if (!fresh) return;- setAwaitingGrant(false);+ setAwaitingNewAccount(false);setConnected(fresh.grantable);void grant(fresh.grantable, fresh.account);return;}+ if (awaitingNewAccount && knownIds.current) {+ const fresh = newlyConnectedCredential(+ row,+ allProviders,+ knownIds.current,+ );+ if (fresh) {+ setAwaitingNewAccount(false);+ setRenewedIds((ids) => [...ids, fresh.grantable.id]);+ return;+ }+ }// 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.+ // would drop a good selection on every mount. A refused credential never+ // fits, which is what turns a row holding one back into a Reconnect.if (allProviders && row.selected && !selectedStillFits) {row.select(undefined);return;}- if (row.selected || !savedCredential) return;+ if (row.selected) return;+ // The account just signed in with wins over the others that also fit.+ // It is picked once the provider list has it, so it is judged on the+ // scopes the backend stored rather than on what the sign-in reported.+ const signedIn = pickable.find((c) => c.id === renewedIds.at(-1));+ if (signedIn) {+ row.select({+ id: signedIn.id,+ provider: row.provider,+ type: signedIn.type as CredentialsMetaInput["type"],+ title: signedIn.title,+ });+ return;+ }+ if (!savedCredential || hasRefusedAccount) return;row.select({id: savedCredential.id,provider: savedCredential.provider,@@ -139,8 +190,11 @@ export function ConnectorRow({ row }: Props) {savedCredential?.id,row.selected,allProviders,- awaitingGrant,+ awaitingNewAccount,expertGrant?.expertId,+ rejectedIds.join(),+ renewedIds.join(),+ hasRefusedAccount,]);// Several saved accounts can satisfy one row. Nothing picks between them for@@ -148,14 +202,17 @@ export function ConnectorRow({ row }: Props) {const pickable = expertGrant? []: filterSystemCredentials(- allProviders?.[row.provider]?.savedCredentials ?? [],+ usableProviders?.[row.provider]?.savedCredentials ?? [],).flatMap((saved) => grantableAmong(row, [saved]) ?? []);// The selected credential itself must still fit: that another account// does is no reason to keep this one and call it Connected.const selectedStillFits = pickable.some((credential) => credential.id === row.selected?.id,);- const hasChoice = !expertGrant && !row.selected && pickable.length > 1;+ const hasChoice =+ !expertGrant &&+ !row.selected &&+ pickable.length > (hasRefusedAccount ? 0 : 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@@ -193,7 +250,7 @@ export function ConnectorRow({ row }: Props) {!row.hasUnansweredTarget &&(expertGrant? grantedCredentials.isSelectionGranted- : Boolean(row.selected));+ : !!row.selected && !rejectedIds.includes(row.selected.id));function openDialog() {knownIds.current = allProviders@@ -202,7 +259,7 @@ export function ConnectorRow({ row }: Props) {): null;setGrantError(null);- setAwaitingGrant(false);+ setAwaitingNewAccount(false);setDialogOpen(true);}@@ -251,11 +308,11 @@ export function ConnectorRow({ row }: Props) {}onClick={openDialog}>- {grantableOptions.length > 0- ? "Grant access"- : hasChoice- ? "Choose account"- : "Connect"}+ {buttonLabel({+ canGrant: grantableOptions.length > 0,+ awaitingReconnect,+ hasChoice,+ })}</Button>)}@@ -295,13 +352,18 @@ export function ConnectorRow({ row }: Props) {onClose={() => setDialogOpen(false)}onConnected={(credential) => {if (!expertGrant) {- row.onConnected();+ // Without a reported credential nothing is known to be renewed,+ // so every refused account stays refused until the diff finds+ // the one this sign-in added.+ if (credential) setRenewedIds((ids) => [...ids, credential.id]);+ else setAwaitingNewAccount(true);+ row.onConnected(credential?.id);return;}// A flow that does not report its credential leaves the refresh to// find the new account.if (!credential) {- setAwaitingGrant(true);+ setAwaitingNewAccount(true);return;}// Grant the reported credential directly: a re-auth that upgraded@@ -346,6 +408,43 @@ function grantableAmong(: null;}+/** A refused account is named as such even when other accounts are offered+ * beside it: the dialog lists them and its Add new signs in again. */+function buttonLabel({+ canGrant,+ awaitingReconnect,+ hasChoice,+}: {+ canGrant: boolean;+ awaitingReconnect: boolean;+ hasChoice: boolean;+}) {+ if (canGrant) return "Grant access";+ if (awaitingReconnect) return "Reconnect";+ if (hasChoice) return "Choose account";+ return "Connect";+}++/** `allProviders` without the credentials in `ids`. Keeps the `null` loading+ * sentinel, and the list itself when there is nothing to drop. */+function withoutCredentials(+ allProviders: CredentialsProvidersContextType | null,+ ids: string[],+): CredentialsProvidersContextType | null {+ if (!allProviders || ids.length === 0) return allProviders;+ return Object.fromEntries(+ Object.entries(allProviders).map(([name, data]) => [+ name,+ data && {+ ...data,+ savedCredentials: data.savedCredentials.filter(+ (credential) => !ids.includes(credential.id),+ ),+ },+ ]),+ );+}+/** The API reports absent fields as null; the provider list omits them. */function toSavedCredential(credential: CredentialsMetaResponse,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 44d75f3a3b..5b7c2267a9 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@@ -81,6 +81,7 @@ function row(overrides: Partial<Row> = {}): Row {},selected: undefined,hasUnansweredTarget: false,+ rejectedCredentialIds: [],select: vi.fn(),onConnected: vi.fn(),...overrides,@@ -159,6 +160,28 @@ describe("ConnectorRow with several saved accounts for one provider", () => {});});+describe("ConnectorRow with a refused credential", () => {+ it("says Connect when the refused credential is not among this provider's", () => {+ // One card's rejection reaches every row it asks for, and the refused+ // account may since have been deleted: neither is this row's to renew.+ renderRow(row({ rejectedCredentialIds: ["cred-twitter"] }), []);++ expect(screen.getByRole("button", { name: "Connect" })).toBeDefined();+ });++ it("offers the other accounts and selects nothing on its own", () => {+ const current = row({ rejectedCredentialIds: ["cred-work"] });+ renderRow(current, [work, personal]);++ expect(current.select).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));++ expect(screen.getByText("purpose-choose")).toBeDefined();+ expect(screen.getByText("use-personal")).toBeDefined();+ expect(screen.queryByText("use-work")).toBeNull();+ });+});+describe("ConnectorRow when no saved account has the access a card needs", () => {const oauthRow = () =>row({diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsxindex 34b363858b..97337dda57 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsx@@ -198,6 +198,7 @@ function row(overrides: Partial<Row> = {}): Row {schema: { credentials_provider: ["github"], credentials_types: ["oauth2"] },selected: undefined,hasUnansweredTarget: false,+ rejectedCredentialIds: [],select: 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 731b523f10..8551055913 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,20 @@ describe("toConnectorRows", () => {expect(rows[0].provider).toBe("github");});+ it("keeps every credential a merged card reported refused, once each", () => {+ const rows = toConnectorRows(+ [+ connectorRequest({ id: "req-1", rejectedCredentialId: "cred-a" }),+ connectorRequest({ id: "req-2" }),+ connectorRequest({ id: "req-3", rejectedCredentialId: "cred-a" }),+ connectorRequest({ id: "req-4", rejectedCredentialId: "cred-b" }),+ ],+ [],+ );++ expect(rows[0].rejectedCredentialIds).toEqual(["cred-a", "cred-b"]);+ });+it("asks for the union of the scopes every card needs", () => {const first = connectorRequest({id: "req-1",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 c7f5ddd57e..62ac848c47 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@@ -68,8 +68,12 @@ export interface ConnectorRequest {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;+ * chat history. Carries the credential the sign-in reported, if it did. */+ onConnected: (credentialId?: string) => void;+ /** A saved credential the provider refused when the tool ran. It stays on+ * file, so without this the row would auto-select it and read Connected+ * with nothing to click. */+ rejectedCredentialId?: string;}export interface ConnectorRow {@@ -79,7 +83,7 @@ export interface ConnectorRow {schema: CredentialField[1];selected?: CredentialsMetaInput;select: (value?: CredentialsMetaInput) => void;- onConnected: () => void;+ onConnected: (credentialId?: string) => void;/** Set when an expert asked: an account credential only counts once the* expert has been granted it, so the connect dialog offers the account's* existing credentials first and a freshly connected one is granted. */@@ -88,6 +92,9 @@ export interface ConnectorRow {* reports the FIRST target's value, so without this a second card asking* for the same provider reads as answered while its field is still empty. */hasUnansweredTarget: boolean;+ /** Saved credentials a merged card reported refused. None is usable until+ * the user signs in to it again from this row. */+ rejectedCredentialIds: string[];}/** Flattens every request into one row per provider: two tools asking for@@ -150,10 +157,17 @@ export function toConnectorRows(hasUnansweredTarget: row.targets.some(({ request, key }) => request.selected[key]?.id !== row.selected?.id,),+ rejectedCredentialIds: [+ ...new Set(+ row.targets.flatMap(({ request }) =>+ request.rejectedCredentialId ? [request.rejectedCredentialId] : [],+ ),+ ),+ ],select: (value?: CredentialsMetaInput) =>row.targets.forEach(({ request, key }) => request.onChange(key, value)),- onConnected: () =>- row.targets.forEach(({ request }) => request.onConnected()),+ onConnected: (credentialId?: string) =>+ row.targets.forEach(({ request }) => request.onConnected(credentialId)),}));}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 4cbd490b03..3f70611517 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@@ -78,6 +78,10 @@ export function SetupRequirementsCard({>({});const [hasSent, setHasSent] = useState(false);const [justConnected, setJustConnected] = useState(false);+ // Credentials a sign-in on the chain's row reported. A renewal keeps the+ // credential's id, so this is how a renewed refused credential is told+ // apart from the refused one still being selected.+ const [renewedIds, setRenewedIds] = useState<string[]>([]);const [showAdvanced, setShowAdvanced] = useState(false);const { credentialFields, requiredCredentials } = coerceCredentialFields(@@ -203,9 +207,15 @@ export function SetupRequirementsCard({// eslint-disable-next-line react-hooks/exhaustive-deps -- handleRun captures latest state; claim guards re-entry}, [chainActions, canAutoDismiss, hasSent]);+ // Only a sign-in that renewed the refused credential itself lifts the+ // rejection; any other sign-in leaves it refused.+ const isRejectionRenewed = renewedIds.includes(+ rejection?.credential_id ?? "",+ );const canRun =checkCanRun(needsCredentials, isAllCredsComplete, isAllInputsDone) &&- !isRejectedCredentialSelected(rejection, inputCredentials);+ (isRejectionRenewed ||+ !isRejectedCredentialSelected(rejection, inputCredentials));// Inside a tool chain the card's own Proceed is replaced by the chain's// single Proceed step — register readiness + message with the chain.@@ -230,7 +240,11 @@ export function SetupRequirementsCard({fields: credentialFields,selected: inputCredentials,onChange: handleCredentialChange,- onConnected: () => setJustConnected(true),+ onConnected: (credentialId) => {+ setJustConnected(true);+ if (credentialId) setRenewedIds((ids) => [...ids, credentialId]);+ },+ rejectedCredentialId: rejection?.credential_id ?? undefined,}: undefined,inputs: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.tsxindex fee3316cdd..f0bad74b64 100644--- 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.tsx@@ -1,4 +1,5 @@import {+ act,render,screen,fireEvent,@@ -8,6 +9,10 @@ import {import { StrictMode } from "react";import { afterEach, describe, expect, it, vi } from "vitest";import { SetupRequirementsCard } from "../SetupRequirementsCard";+import {+ ChainActionsContext,+ type ChainActionEntry,+} from "../../ToolChain/chainActions";import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";import { useConnectedProvidersStore } from "../../../connectedProvidersStore";@@ -753,4 +758,55 @@ describe("SetupRequirementsCard (rejected credential)", () => {expect(screen.queryByRole("alert")).toBeNull();});++ describe("inside a chain", () => {+ function renderInChain() {+ const entries: ChainActionEntry[] = [];+ render(+ <ChainActionsContext.Provider+ value={{+ register: (entry) => entries.push(entry),+ unregister: vi.fn(),+ }}+ >+ <SetupRequirementsCard+ output={makeOutput({+ missingCredentials: {+ api_key: { provider: "openai", types: ["api_key"] },+ },+ rejection,+ })}+ />+ </ChainActionsContext.Provider>,+ );+ const latest = () => entries[entries.length - 1];+ // Holding the refused credential is the state a sign-in has to clear.+ act(() =>+ latest().connectors!.onChange("api_key", {+ id: "cred-api_key",+ provider: "openai",+ type: "api_key",+ }),+ );+ return latest;+ }++ it("stays unready when the sign-in reported a different credential", () => {+ const latest = renderInChain();++ act(() => latest().connectors!.onConnected("cred-someone-else"));++ expect(latest().justConnected).toBe(true);+ expect(latest().ready).toBe(false);+ });++ it("is ready once the sign-in renewed the refused credential itself", () => {+ const latest = renderInChain();+ expect(latest().ready).toBe(false);++ act(() => latest().connectors!.onConnected("cred-api_key"));++ expect(latest().ready).toBe(true);+ });+ });});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 433cc5e9ef..1a0b55dca7 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@@ -848,6 +848,254 @@ describe("copilot Connect card, a card that arrives after the first connection",});});+describe("copilot Connect card, a saved credential the provider refused", () => {+ // The credential the provider refused. It stays on file and still has every+ // scope the card asks for, which is what made the row read Connected.+ const refused = oauthCredential("cred-refused", [REQUIRED_SCOPE]);+ let picked: Record<string, string> | null = null;++ beforeEach(() => {+ requestedScopes = null;+ upgradedCredentialID = null;+ picked = null;+ savedCredentials = [refused];+ 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",+ });+ }),+ // A re-auth aimed at an account updates it in place: same id, new token.+ http.post("*/api/integrations/github/callback", () =>+ HttpResponse.json(refused),+ ),+ http.put(+ "*/api/chat/sessions/:sessionId/credential-selection",+ async ({ request }) => {+ picked = ((await request.json()) as { selections: typeof picked })+ .selections;+ return HttpResponse.json({});+ },+ ),+ );+ });++ afterEach(resetStores);++ function renderRefusedChain() {+ const onSend = vi.fn();+ render(+ <CredentialsProvider>+ <CopilotChatActionsProvider onSend={onSend}>+ <ToolChain+ parts={[refusedRequirementsPart("cred-refused")]}+ isStreaming={false}+ />+ </CopilotChatActionsProvider>+ </CredentialsProvider>,+ );+ return { onSend };+ }++ async function reconnect() {+ const user = userEvent.setup();+ await user.click(await screen.findByRole("button", { name: "Reconnect" }));+ await user.click(await screen.findByText("OAuth"));+ await user.click(await screen.findByRole("button", { name: "Continue" }));+ }++ it("offers Reconnect instead of calling the refused credential Connected", async () => {+ const { onSend } = renderRefusedChain();++ // A Connected row renders no button, so it would leave nothing to click.+ await screen.findByRole("button", { name: "Reconnect" });+ expect(screen.queryByText("Connected")).toBeNull();+ expect(onSend).not.toHaveBeenCalled();+ });++ it("renews the refused account in place and continues the chat", async () => {+ const { onSend } = renderRefusedChain();++ await reconnect();++ await waitFor(() => expect(upgradedCredentialID).toBe("cred-refused"));+ // The renewal keeps the credential's id, so a card that kept treating that+ // id as refused would never send.+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(picked).toEqual({ github: "cred-refused" });+ await screen.findByText("Connected. Continuing…");+ });++ it("runs on the new credential, not the refused one, when the sign-in adds one", async () => {+ server.use(+ http.post("*/api/integrations/github/callback", () => {+ const added = oauthCredential("cred-new", [REQUIRED_SCOPE]);+ savedCredentials = [refused, added];+ return HttpResponse.json(added);+ }),+ );+ const { onSend } = renderRefusedChain();++ await reconnect();++ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(picked).toEqual({ github: "cred-new" });+ });++ it("keeps asking when the sign-in comes back without the access needed", async () => {+ // A narrower grant is stored beside the refused account, not over it.+ server.use(+ http.post("*/api/integrations/github/callback", () => {+ const short = oauthCredential("cred-short", []);+ savedCredentials = [refused, short];+ return HttpResponse.json(short);+ }),+ );+ const { onSend } = renderRefusedChain();++ await reconnect();++ await waitFor(() => expect(savedCredentials).toHaveLength(2));+ await screen.findByRole("button", { name: "Reconnect" });+ expect(onSend).not.toHaveBeenCalled();+ });++ it("finds the new account when the sign-in does not report it", async () => {+ // Any 2xx other than 200 reaches the dialog as a success with no+ // credential, which is how a credential-less approval looks to the row.+ server.use(+ http.post("*/api/integrations/github/callback", () => {+ const added = oauthCredential("cred-new", [REQUIRED_SCOPE]);+ savedCredentials = [refused, added];+ return HttpResponse.json(added, { status: 201 });+ }),+ );+ const { onSend } = renderRefusedChain();++ await reconnect();++ // Nothing says the refused account was renewed, so it must not be the+ // one the chat runs on.+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(picked).toEqual({ github: "cred-new" });+ });++ describe("when another saved account still works", () => {+ const other = {+ ...oauthCredential("cred-other", [REQUIRED_SCOPE]),+ title: "Work",+ };++ beforeEach(() => {+ savedCredentials = [refused, other];+ });++ it("asks instead of quietly running on the other account", async () => {+ const { onSend } = renderRefusedChain();+ const user = userEvent.setup();++ // A different account can mean posting as someone else, so the row+ // waits for the user rather than calling the other one Connected.+ await user.click(+ await screen.findByRole("button", { name: "Reconnect" }),+ );+ expect(screen.queryByText("Connected")).toBeNull();+ // Only the account that still works is offered; the refused one is+ // renewed through Add new.+ expect(screen.queryByRole("radio", { name: /GitHub/ })).toBeNull();+ await user.click(await screen.findByRole("radio", { name: /Work/ }));+ await user.click(+ screen.getByRole("button", { name: "Use this account" }),+ );++ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(picked).toEqual({ github: "cred-other" });+ });++ it("runs on the renewed account once the user signs in to it again", async () => {+ const { onSend } = renderRefusedChain();+ const user = userEvent.setup();++ await user.click(+ await screen.findByRole("button", { name: "Reconnect" }),+ );+ 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" }));++ // Both accounts now fit; the one just signed in to is the one meant.+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(picked).toEqual({ github: "cred-refused" });+ });++ it("waits for a newly added account rather than falling back to the other", async () => {+ // The first list fetched after the sign-in predates it, as when the+ // provider list lags the callback.+ let staleFetches = 0;+ server.use(+ http.post("*/api/integrations/github/callback", () => {+ const added = oauthCredential("cred-new", [REQUIRED_SCOPE]);+ savedCredentials = [refused, other, added];+ staleFetches = 1;+ return HttpResponse.json(added);+ }),+ http.get("*/api/integrations/credentials", () => {+ if (staleFetches === 0) return HttpResponse.json(savedCredentials);+ staleFetches -= 1;+ return HttpResponse.json([refused, other]);+ }),+ );+ const { onSend } = renderRefusedChain();+ const user = userEvent.setup();++ await user.click(+ await screen.findByRole("button", { name: "Reconnect" }),+ );+ 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" }));++ // Until the list shows the new account, the other one is the only+ // usable match; picking it then would run on an account nobody chose.+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(picked).toEqual({ github: "cred-new" });+ });+ });+});++function refusedRequirementsPart(credentialID: string): MessagePart {+ const part = setupRequirementsPart() as unknown as {+ output: Record<string, unknown>;+ };+ return {+ ...part,+ output: {+ ...part.output,+ message: "The saved Github credential 'GitHub' could not be refreshed.",+ rejection: {+ provider: "github",+ detail: "invalid_grant",+ status_code: null,+ credential_id: credentialID,+ credential_title: "GitHub",+ },+ },+ } as unknown as MessagePart;+}+function renderChain() {const onSend = vi.fn();const utils = render(