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): stop device auth reporting a new credential as removed (#14177)
Nicholas Tindle6751f0440da5
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/__tests__/AyrshareConnectButton.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/__tests__/AyrshareConnectButton.test.tsxindex 150dfd0627..c75f18d930 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/__tests__/AyrshareConnectButton.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/__tests__/AyrshareConnectButton.test.tsx@@ -31,7 +31,7 @@ function renderWithActions(reload: () => void) {vi.fn(() => ({}) as Window),);return render(- <CredentialsActionsContext.Provider value={{ reload }}>+ <CredentialsActionsContext.Provider value={{ reload, upsert: vi.fn() }}><AyrshareConnectButton /></CredentialsActionsContext.Provider>,);diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.ts b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.tsindex 6b7e8f3bcd..df8602e6d2 100644--- a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.ts@@ -1,4 +1,5 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";import { act, renderHook, waitFor } from "@testing-library/react";import { createElement, type ReactNode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -38,12 +39,22 @@ function initiated(overrides: Record<string, unknown> = {}) {} as never;}+const upsertSpy = vi.fn();+function makeWrapper() {const client = new QueryClient({defaultOptions: { queries: { retry: false } },});return function Wrapper({ children }: { children: ReactNode }) {- return createElement(QueryClientProvider, { client }, children);+ return createElement(+ QueryClientProvider,+ { client },+ createElement(+ CredentialsActionsContext.Provider,+ { value: { reload: vi.fn(), upsert: upsertSpy } },+ children,+ ),+ );};}@@ -349,4 +360,41 @@ describe("useDeviceAuthConnect", () => {await waitFor(() => expect(onSuccess).toHaveBeenCalledWith(undefined));expect(result.current.phase).toBe("done");});++ it("seeds the credentials store so a new credential is not reported as removed", async () => {+ // Invalidating the react-query key does not reach CredentialsProvidersContext+ // — that is separate state filled by loadCredentials. Without seeding it the+ // caller selects an id the store has never seen, and useCredentialsInput+ // flags the brand-new credential as *removed* and deselects it, so the user+ // is told their connection was removed immediately after connecting. The+ // OAuth path gets this for free via oAuthCallback.+ initiate.mockResolvedValue(initiated());+ poll.mockResolvedValue({+ status: 200,+ data: {+ status: "approved",+ credentials: {+ id: "cred-new",+ provider: "stripe_link",+ type: "oauth2",+ title: "Stripe Link",+ },+ },+ } as never);++ const { result } = render();+ await act(async () => {+ await result.current.connect();+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5_000);+ });++ await waitFor(() =>+ expect(upsertSpy).toHaveBeenCalledWith(+ "stripe_link",+ expect.objectContaining({ id: "cred-new" }),+ ),+ );+ });});diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.tsindex bc857f78fb..f66ee19dd4 100644--- a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useContext, useEffect, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import {@@ -9,7 +9,9 @@ import {} from "@/app/api/__generated__/endpoints/integrations/integrations";import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { toast } from "@/components/molecules/Toast/use-toast";+import type { CredentialsProviderName } from "@/lib/autogpt-server-api/types";import { invalidateConnectionQueries } from "@/lib/react-query/invalidateConnections";+import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";interface Args {provider: string;@@ -27,6 +29,7 @@ const MAX_CONSECUTIVE_POLL_FAILURES = 3;export function useDeviceAuthConnect({ provider, onSuccess }: Args) {const queryClient = useQueryClient();+ const credentialsActions = useContext(CredentialsActionsContext);const [phase, setPhase] = useState<Phase>("idle");const [userCode, setUserCode] = useState("");const [verificationUrl, setVerificationUrl] = useState("");@@ -83,6 +86,18 @@ export function useDeviceAuthConnect({ provider, onSuccess }: Args) {stopPolling();toast({ title: "Connected via device auth", variant: "success" });await invalidateConnectionQueries(queryClient);+ // Seed the credentials store directly. Invalidating the query keys+ // does not reach it — it is separate state filled by loadCredentials+ // — so without this the caller selects an id the store has never+ // seen, and `useCredentialsInput` reports the brand-new credential+ // as removed and deselects it. The OAuth path gets this for free+ // via `oAuthCallback`.+ if (credentials) {+ credentialsActions?.upsert(+ provider as CredentialsProviderName,+ credentials,+ );+ }onSuccess(credentials ?? undefined);return;}@@ -138,7 +153,7 @@ export function useDeviceAuthConnect({ provider, onSuccess }: Args) {});}},- [provider, onSuccess, queryClient, stopPolling],+ [provider, onSuccess, queryClient, stopPolling, credentialsActions],);async function connect() {diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsxindex 786476cdcc..89a8fb5f7a 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider-auth.test.tsx@@ -9,6 +9,7 @@ const { apiMock, errorHandlerMock, isLoggedIn, onFailToastMock, useAuthMock } =return {apiMock: {listCredentials: vi.fn().mockResolvedValue([]),+ deleteCredentials: vi.fn().mockResolvedValue({ deleted: true }),listProviders: vi.fn().mockResolvedValue(["google"]),listSystemProviders: vi.fn().mockResolvedValue([]),},@@ -32,8 +33,11 @@ vi.mock("@/components/molecules/Toast/use-toast", () => ({}));import CredentialsProvider, {+ CredentialsActionsContext,CredentialsProvidersContext,+ mergePendingCredentials,} from "../credentials-provider";+import type { CredentialsMetaResponse } from "@/lib/autogpt-server-api";const queryClient = new QueryClient();@@ -64,6 +68,46 @@ function deferred<T>() {return { promise, resolve };}+/**+ * Exposes `upsert` and the resulting saved-credential ids, so a test can drive+ * the same sequence device auth does: mint a credential outside a list+ * response, then let a reload land.+ */+function UpsertProbe({ provider }: { provider: string }) {+ const providers = useContext(CredentialsProvidersContext);+ const actions = useContext(CredentialsActionsContext);+ const saved = providers?.[provider]?.savedCredentials ?? [];+ return (+ <div>+ <button+ data-testid="do-upsert"+ onClick={() =>+ actions?.upsert(provider, {+ id: "cred-device",+ provider,+ type: "oauth2",+ title: "Device Auth Credential",+ } as never)+ }+ >+ upsert+ </button>+ <button data-testid="do-reload" onClick={() => actions?.reload()}>+ reload+ </button>+ <button+ data-testid="do-delete"+ onClick={() =>+ providers?.[provider]?.deleteCredentials("cred-device", true)+ }+ >+ delete+ </button>+ <span data-testid="saved-ids">{saved.map((c) => c.id).join(",")}</span>+ </div>+ );+}+describe("CredentialsProvider authentication", () => {beforeEach(() => {vi.clearAllMocks();@@ -146,3 +190,177 @@ describe("CredentialsProvider authentication", () => {expect(apiMock.listCredentials).not.toHaveBeenCalled();});});++describe("CredentialsProvider device-auth upserts", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ queryClient.clear();+ isLoggedIn.value = true;+ apiMock.listCredentials.mockResolvedValue([]);+ apiMock.listProviders.mockResolvedValue(["stripe_link"]);+ apiMock.listSystemProviders.mockResolvedValue([]);+ useAuthMock.mockImplementation(() => ({ isLoggedIn: isLoggedIn.value }));+ });++ const deviceCred = {+ id: "cred-device",+ provider: "stripe_link",+ type: "oauth2",+ title: "Device Auth Credential",+ };++ function savedIds() {+ return (screen.getByTestId("saved-ids").textContent ?? "")+ .split(",")+ .filter(Boolean);+ }++ async function mountProbe() {+ render(+ <CredentialsProvider>+ <UpsertProbe provider="stripe_link" />+ </CredentialsProvider>,+ { wrapper: TestWrapper },+ );+ await waitFor(() => expect(apiMock.listCredentials).toHaveBeenCalled());+ }++ /** Click reload and wait for that specific request to have been issued. */+ async function reloadAndSettle() {+ const before = apiMock.listCredentials.mock.calls.length;+ await act(async () => {+ screen.getByTestId("do-reload").click();+ });+ await waitFor(() =>+ expect(apiMock.listCredentials.mock.calls.length).toBeGreaterThan(before),+ );+ // Let the response publish.+ await act(async () => undefined);+ }++ it("survives a reload whose response predates the credential", async () => {+ // The device-auth race: the credential is minted server-side by the poll,+ // and a listCredentials() call that started before it existed resolves+ // afterwards. Publishing that stale response unmodified drops the+ // credential, and useCredentialsInput then tells the user their brand-new+ // connection was removed.+ await mountProbe();++ await act(async () => {+ screen.getByTestId("do-upsert").click();+ });+ expect(savedIds()).toContain("cred-device");++ apiMock.listCredentials.mockResolvedValue([] as never);+ await reloadAndSettle();++ expect(savedIds()).toContain("cred-device");+ });++ it("retires the pending entry once the server returns it", async () => {+ await mountProbe();+ await act(async () => {+ screen.getByTestId("do-upsert").click();+ });++ // Server catches up: present exactly once, not duplicated by the pending copy.+ apiMock.listCredentials.mockResolvedValue([deviceCred] as never);+ await reloadAndSettle();+ expect(savedIds().filter((i) => i === "cred-device")).toHaveLength(1);++ // The proof that it was actually retired rather than merely deduped: a+ // later empty reload must now drop it, because nothing is pending.+ apiMock.listCredentials.mockResolvedValue([] as never);+ await reloadAndSettle();+ expect(savedIds()).not.toContain("cred-device");+ });++ it("does not carry a pending credential across a logout", async () => {+ // pendingUpsertsRef outlives a session unless cleared. Left in place it+ // would be merged into the next user's list on the same mounted provider,+ // exposing the previous account's credential metadata.+ await mountProbe();+ await act(async () => {+ screen.getByTestId("do-upsert").click();+ });+ expect(savedIds()).toContain("cred-device");++ isLoggedIn.value = false;+ await act(async () => {+ screen.getByTestId("do-reload").click();+ });++ isLoggedIn.value = true;+ apiMock.listCredentials.mockResolvedValue([] as never);+ await reloadAndSettle();++ expect(savedIds()).not.toContain("cred-device");+ });++ it("does not resurrect a credential deleted while still pending", async () => {+ await mountProbe();+ await act(async () => {+ screen.getByTestId("do-upsert").click();+ });++ apiMock.deleteCredentials.mockResolvedValue({ deleted: true });+ await act(async () => {+ screen.getByTestId("do-delete").click();+ });++ apiMock.listCredentials.mockResolvedValue([] as never);+ await reloadAndSettle();++ expect(savedIds()).not.toContain("cred-device");+ });++ it("ignores a list response a newer request has superseded", async () => {+ await mountProbe();+ await act(async () => {+ screen.getByTestId("do-upsert").click();+ });++ const stale = deferred<never[]>();+ const fresh = deferred<never[]>();+ apiMock.listCredentials+ .mockReturnValueOnce(stale.promise)+ .mockReturnValueOnce(fresh.promise);++ await act(async () => {+ screen.getByTestId("do-reload").click();+ screen.getByTestId("do-reload").click();+ });++ // The newer request lands first and retires the pending entry. The older+ // one predates the credential, so without the generation guard it+ // republishes a list without it and the connection reads as removed again.+ await act(async () => {+ fresh.resolve([deviceCred] as never);+ await fresh.promise;+ });+ await act(async () => {+ stale.resolve([] as never);+ await stale.promise;+ });++ expect(savedIds()).toContain("cred-device");+ });++ it("keeps the server's copy of a credential it has caught up on", () => {+ // The pending copy is a snapshot from the moment of the upsert; once the+ // server returns the id, its copy carries any change made since.+ const pendingCopy: CredentialsMetaResponse = {+ id: "cred-device",+ provider: "stripe_link",+ type: "oauth2",+ title: "Device Auth Credential",+ };+ const merged = mergePendingCredentials(+ [{ ...pendingCopy, title: "Renamed elsewhere" }],+ [pendingCopy],+ );++ expect(merged).toHaveLength(1);+ expect(merged[0].title).toBe("Renamed elsewhere");+ });+});diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.tsindex 48f4378811..861247cc01 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts@@ -6,6 +6,7 @@ import type {import {upsertProviderCredentials,type CredentialsProvidersContextType,+ mergePendingCredentials,} from "../credentials-provider";function makeCred(@@ -122,3 +123,26 @@ describe("upsertProviderCredentials", () => {expect(prev.google?.savedCredentials).toEqual([]);});});++describe("mergePendingCredentials", () => {+ const loaded = { id: "a", provider: "stripe_link", type: "oauth2" } as never;+ const fresh = { id: "b", provider: "stripe_link", type: "oauth2" } as never;++ it("returns the loaded list untouched when nothing is pending", () => {+ expect(mergePendingCredentials([loaded], undefined)).toEqual([loaded]);+ expect(mergePendingCredentials([loaded], [])).toEqual([loaded]);+ });++ it("keeps a credential a stale list response would have dropped", () => {+ // The listCredentials() call was already in flight when device auth minted+ // `fresh`, so the response predates it. Publishing it unmodified drops the+ // credential and useCredentialsInput reports it as removed.+ const merged = mergePendingCredentials([loaded], [fresh]);+ expect(merged.map((c: { id: string }) => c.id).sort()).toEqual(["a", "b"]);+ });++ it("does not duplicate a credential the server has caught up on", () => {+ const merged = mergePendingCredentials([loaded, fresh], [fresh]);+ expect(merged.map((c: { id: string }) => c.id).sort()).toEqual(["a", "b"]);+ });+});diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsxindex 3c3c3a226b..4d791f9def 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx@@ -1,4 +1,5 @@import { useToastOnFail } from "@/components/molecules/Toast/use-toast";+import type { CredentialsMetaResponse as GeneratedCredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import {APIKeyCredentials,CredentialsDeleteNeedConfirmationResponse,@@ -17,7 +18,7 @@ import { useBackendAPI } from "@/lib/autogpt-server-api/context";import { useAuth } from "@/lib/auth/hooks/useAuth";import { toDisplayName } from "@/providers/agent-credentials/helper";import { hashKey, useQueryClient } from "@tanstack/react-query";-import { createContext, useCallback, useEffect, useState } from "react";+import { createContext, useCallback, useEffect, useState, useRef } from "react";type APIKeyCredentialsCreatable = Omit<APIKeyCredentials,@@ -109,6 +110,21 @@ export function upsertProviderCredentials(};}+/**+ * Append credentials a freshly-loaded list does not carry yet: a+ * `listCredentials()` request already in flight when one is created predates+ * it, and publishing that response unmodified drops it. An id the list does+ * carry needs no pending copy: the caller retires it in the same pass.+ */+export function mergePendingCredentials(+ loaded: CredentialsMetaResponse[],+ pending: CredentialsMetaResponse[] | undefined,+): CredentialsMetaResponse[] {+ if (!pending?.length) return loaded;+ const loadedIds = new Set(loaded.map((c) => c.id));+ return [...loaded, ...pending.filter((c) => !loadedIds.has(c.id))];+}+/*** Imperative actions on the credentials context. Split out so the data* context can stay read-only for consumers that only render the list —@@ -117,6 +133,15 @@ export function upsertProviderCredentials(*/export const CredentialsActionsContext = createContext<{reload: () => void;+ /**+ * Add a just-created credential without waiting for a re-fetch. A flow that+ * mints one outside this provider (device auth polls the backend directly)+ * must call this, or `useCredentialsInput` reports it as *removed*.+ */+ upsert: (+ provider: CredentialsProviderName,+ credentials: GeneratedCredentialsMetaResponse,+ ) => void;} | null>(null);export default function CredentialsProvider({@@ -135,11 +160,27 @@ export default function CredentialsProvider({const onFailToast = useToastOnFail();const queryClient = useQueryClient();+ // Held until a load returns them: the store can still be null when the upsert+ // lands, and an in-flight list can resolve with a list that predates it.+ const pendingUpsertsRef = useRef<+ Partial<Record<CredentialsProviderName, CredentialsMetaResponse[]>>+ >({});+ // Only the newest list request may publish or retire; an older one can+ // resolve last with a response that predates an upsert.+ const loadGenerationRef = useRef(0);+const upsertCredentials = useCallback((provider: CredentialsProviderName,credentials: CredentialsMetaResponse,) => {+ const pending = pendingUpsertsRef.current[provider] ?? [];+ pendingUpsertsRef.current[provider] = [+ ...pending.filter(+ (c: CredentialsMetaResponse) => c.id !== credentials.id,+ ),+ credentials,+ ];setProviders((prev) =>upsertProviderCredentials(prev, provider, credentials),);@@ -147,6 +188,23 @@ export default function CredentialsProvider({[setProviders],);+ /**+ * Upsert a credential straight off the API. The generated model marks several+ * fields nullable where the store's model uses `undefined`.+ */+ function upsertFromApi(+ provider: CredentialsProviderName,+ credentials: GeneratedCredentialsMetaResponse,+ ) {+ upsertCredentials(provider, {+ ...credentials,+ title: credentials.title ?? undefined,+ scopes: credentials.scopes ?? undefined,+ username: credentials.username ?? undefined,+ host: credentials.host ?? undefined,+ } as CredentialsMetaResponse);+ }+/** Wraps `BackendAPI.oAuthCallback`, and adds the result to the internal credentials store. */const oAuthCallback = useCallback(async (@@ -298,6 +356,22 @@ export default function CredentialsProvider({if (!result.deleted) {return result;}+ // A list request that started before the delete would otherwise+ // resolve afterwards with the deleted credential and republish it.+ loadGenerationRef.current += 1;+ // A credential deleted while still pending would otherwise be merged+ // straight back into the picker by the next load.+ const pendingForProvider = pendingUpsertsRef.current[provider];+ if (pendingForProvider?.length) {+ const kept = pendingForProvider.filter(+ (c: CredentialsMetaResponse) => c.id !== id,+ );+ if (kept.length) {+ pendingUpsertsRef.current[provider] = kept;+ } else {+ delete pendingUpsertsRef.current[provider];+ }+ }setProviders((prev) => {if (!prev || !prev[provider]) return prev;@@ -321,6 +395,14 @@ export default function CredentialsProvider({);const loadCredentials = useCallback(() => {+ if (!isLoggedIn) {+ // Left in place these would be merged into the *next* user's list,+ // exposing the previous account's credential metadata.+ pendingUpsertsRef.current = {};+ // Retire any in-flight request so its response cannot publish over the+ // logged-out state.+ loadGenerationRef.current += 1;+ }if (!isLoggedIn || providerNames.length === 0) {// null is the sole "still loading" sentinel; an empty object means// "loaded, and this user has no providers". Keeping those distinct@@ -341,9 +423,14 @@ export default function CredentialsProvider({return;}+ const generation = ++loadGenerationRef.current;+api.listCredentials().then((response) => {+ // Stale: publishing would overwrite fresher state, and retiring from+ // it would strand credentials the newer response has not returned.+ if (generation !== loadGenerationRef.current) return;const credentialsByProvider = response.reduce((acc, cred) => {if (!acc[cred.provider]) {@@ -359,7 +446,28 @@ export default function CredentialsProvider({...prev,...Object.fromEntries(providerNames.map((provider) => {- const providerCredentials = credentialsByProvider[provider] ?? [];+ const loaded = credentialsByProvider[provider] ?? [];+ const pending = pendingUpsertsRef.current[provider];+ // One predicate drives both the merge and the retirement: an id+ // the server returned is caught up, so its pending copy is+ // neither merged in nor kept.+ const loadedIds = new Set(+ loaded.map((c: CredentialsMetaResponse) => c.id),+ );+ const stillPending = pending?.filter(+ (c: CredentialsMetaResponse) => !loadedIds.has(c.id),+ );+ const providerCredentials = mergePendingCredentials(+ loaded,+ stillPending,+ );+ if (pending?.length) {+ if (stillPending?.length) {+ pendingUpsertsRef.current[provider] = stillPending;+ } else {+ delete pendingUpsertsRef.current[provider];+ }+ }return [provider,@@ -460,7 +568,9 @@ export default function CredentialsProvider({}, [queryClient, loadCredentials]);return (- <CredentialsActionsContext.Provider value={{ reload: loadCredentials }}>+ <CredentialsActionsContext.Provider+ value={{ reload: loadCredentials, upsert: upsertFromApi }}+ ><CredentialsProvidersContext.Provider value={providers}>{children}</CredentialsProvidersContext.Provider>