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.
feat(platform/copilot): use the credential the user picked, and ask instead of guessing (#14677)
Bentlyffa7ceeb81ad
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 062137888e..2670e38fc8 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -30,6 +30,7 @@ from backend.copilot.computer import (open_desktop,)from backend.copilot.config import ChatConfig, CopilotLlmAuthProvider, CopilotLLMModel+from backend.copilot.credential_selection import remember_selectionfrom backend.copilot.db import (chat_message_has_assistant_reply,get_chat_messages_paginated,@@ -156,6 +157,8 @@ from backend.data.redis_client import get_redis_asyncfrom backend.data.understanding import get_business_understandingfrom backend.data.workspace import build_files_blockfrom backend.integrations.codex.access import enforce_codex_access_http+from backend.integrations.credentials_store import provider_matches+from backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.util.background import spawn_background_taskfrom backend.util.exceptions import InsufficientBalanceError, NotFoundErrorfrom backend.util.settings import Settings@@ -999,6 +1002,59 @@ async def disconnect_session_stream(return Response(status_code=204)+class CredentialSelectionRequest(BaseModel):+ """The credential the user picked for each provider on a connect card."""++ selections: dict[str, str] = Field(+ description="Provider slug to credential id.", max_length=20+ )+++ "/sessions/{session_id}/credential-selection",+ summary="Record credential picks for this chat",+ dependencies=[Security(auth.requires_user)],+ status_code=200,+ responses={404: {"description": "Session or credential not found"}},+)+async def select_session_credentials_route(+ session_id: str,+ request: CredentialSelectionRequest,+ user_id: Annotated[str, Security(auth.get_user_id)],+) -> dict:+ """Keep the account the user chose on a connect card for the rest of the chat.++ The card shows one account and the tools used to re-match on their own, so+ with two accounts for a provider a run could land on the other one. The+ tools now use exactly what is recorded here, and ask when several+ credentials qualify and nothing was picked.++ Every id is checked against the caller's own credentials and the provider+ it is filed under; one bad entry rejects the request and records nothing.+ """+ if await get_chat_session_metadata(session_id, user_id) is None:+ raise HTTPException(+ status_code=404,+ detail=f"Session {session_id} not found or access denied",+ )++ store = IntegrationCredentialsManager().store+ selections: dict[str, str] = {}+ for provider, credential_id in request.selections.items():+ provider = provider.strip().lower()+ if provider in selections:+ # " GitHub " and "github" name the same provider; keeping only the+ # later one would silently drop a credential the caller validated.+ raise HTTPException(status_code=422, detail="duplicate_provider")+ credential = await store.get_creds_by_id(user_id, credential_id)+ if credential is None or not provider_matches(credential.provider, provider):+ raise HTTPException(status_code=404, detail="credential_not_found")+ selections[provider] = credential_id++ await remember_selection(session_id, selections)+ return {"status": "ok"}++class ChangeSessionConnectionRequest(BaseModel):"""The connection the rest of this chat should run on."""diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 2ad4b102e8..cad4a2625e 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -4431,3 +4431,32 @@ def test_start_session_desktop_is_refused_for_an_archived_experts_chat(owns_active.assert_awaited_once()assert owns_active.await_args.args[1] == "exp-archived"open_desktop.assert_not_awaited()+++def test_credential_selection_rejects_a_provider_named_twice(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """ " GitHub " and "github" normalise to the same provider. Keeping only the+ later one would silently drop a credential the request had validated."""+ mocker.patch(+ "backend.api.features.chat.routes.get_chat_session_metadata",+ new=AsyncMock(return_value=MagicMock()),+ )+ store = MagicMock()+ store.get_creds_by_id = AsyncMock(return_value=MagicMock(provider="github"))+ mocker.patch(+ "backend.api.features.chat.routes.IntegrationCredentialsManager",+ return_value=MagicMock(store=store),+ )+ remember = mocker.patch(+ "backend.api.features.chat.routes.remember_selection", new=AsyncMock()+ )++ response = client.put(+ "/sessions/sess-1/credential-selection",+ json={"selections": {" GitHub ": "cred-a", "github": "cred-b"}},+ )++ assert response.status_code == 422+ assert response.json()["detail"] == "duplicate_provider"+ remember.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/copilot/credential_selection.py b/autogpt_platform/backend/backend/copilot/credential_selection.pynew file mode 100644index 0000000000..ed2fe2dd11--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/credential_selection.py@@ -0,0 +1,66 @@+"""The credential a user picked for each provider, for the rest of a chat.++The connect card and the backend used to choose credentials separately: the+card showed the account the user picked, and the backend re-matched on its own+and took whichever qualifying credential was stored first. With two accounts+for one provider the run could land on the wrong one.++So the card now reports the pick, and it is kept here for the session. A chat+tool uses exactly that credential, and when several credentials qualify and+none was picked it asks instead of choosing (see+``copilot.tools.utils.find_matching_credential``).++Kept in Redis rather than on the session row because it is advisory state with+a safe failure: losing it means the user is asked again, never that a run uses+an account they did not choose.+"""++import logging++from backend.data.redis_client import get_redis_async++logger = logging.getLogger(__name__)++SELECTION_TTL = 30 * 86400 # 30 days, far longer than a chat stays active+++def _key(session_id: str) -> str:+ return f"copilot:credential-selection:{session_id}"+++async def remember_selection(session_id: str, selections: dict[str, str]) -> None:+ """Record ``{provider: credential_id}`` picks, replacing earlier picks for+ the same providers. Raises if Redis is unreachable: the caller is an API+ request and should report that the pick did not take."""+ if not selections:+ return+ redis = await get_redis_async()+ # One transaction: a failure part way through must not leave half a pick,+ # which later matching would apply as if it were the whole of it.+ async with redis.pipeline(transaction=True) as pipe:+ for provider, credential_id in selections.items():+ pipe.hset(_key(session_id), provider, credential_id)+ pipe.expire(_key(session_id), SELECTION_TTL)+ await pipe.execute()+++async def selected_credentials(session_id: str | None) -> dict[str, str]:+ """``{provider: credential_id}`` picked in this session; empty when none.++ Never raises. An unreadable selection degrades to "nothing picked", which+ makes the tools ask rather than guess.+ """+ if not session_id:+ return {}+ try:+ redis = await get_redis_async()+ raw = await redis.hgetall(_key(session_id))+ except Exception:+ logger.warning("Could not read credential selection for session %s", session_id)+ return {}+ return {+ (k.decode() if isinstance(k, bytes) else k): (+ v.decode() if isinstance(v, bytes) else v+ )+ for k, v in raw.items()+ }diff --git a/autogpt_platform/backend/backend/copilot/credential_selection_test.py b/autogpt_platform/backend/backend/copilot/credential_selection_test.pynew file mode 100644index 0000000000..9f44ed46a6--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/credential_selection_test.py@@ -0,0 +1,88 @@+from unittest.mock import AsyncMock, patch++import pytest++from backend.copilot.credential_selection import (+ remember_selection,+ selected_credentials,+)+++class _FakeRedis:+ """Enough of redis.asyncio for the store: a transactional pipeline that+ applies its queued commands only on execute."""++ def __init__(self):+ self.hashes: dict[str, dict[str, str]] = {}+ self.expiries: dict[str, int] = {}++ def pipeline(self, transaction: bool = True):+ assert transaction, "picks must be written atomically"+ return _FakePipeline(self)++ async def hgetall(self, key):+ # Redis hands back bytes unless decoding is configured.+ return {k.encode(): v.encode() for k, v in self.hashes.get(key, {}).items()}+++class _FakePipeline:+ def __init__(self, redis: _FakeRedis):+ self.redis = redis+ self.queued: list = []++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ def hset(self, key, field, value):+ self.queued.append(("hset", key, field, value))++ def expire(self, key, ttl):+ self.queued.append(("expire", key, ttl))++ async def execute(self):+ for command in self.queued:+ if command[0] == "hset":+ _, key, field, value = command+ self.redis.hashes.setdefault(key, {})[field] = value+ else:+ _, key, ttl = command+ self.redis.expiries[key] = ttl+ self.queued = []+++def redis():+ fake = _FakeRedis()+ with patch(+ "backend.copilot.credential_selection.get_redis_async",+ new=AsyncMock(return_value=fake),+ ):+ yield fake+++async def test_a_pick_is_kept_for_the_session(redis):+ await remember_selection("s-1", {"github": "cred-a"})+ assert await selected_credentials("s-1") == {"github": "cred-a"}+ assert await selected_credentials("s-2") == {}+ assert redis.expiries # a session's picks do not live forever+++async def test_a_later_pick_replaces_the_earlier_one_for_that_provider(redis):+ await remember_selection("s-1", {"github": "cred-a", "linear": "cred-l"})+ await remember_selection("s-1", {"github": "cred-b"})+ assert await selected_credentials("s-1") == {"github": "cred-b", "linear": "cred-l"}+++async def test_an_unreadable_selection_means_nothing_was_picked():+ with patch(+ "backend.copilot.credential_selection.get_redis_async",+ new=AsyncMock(side_effect=ConnectionError("redis down")),+ ):+ assert await selected_credentials("s-1") == {}+ assert await selected_credentials(None) == {}diff --git a/autogpt_platform/backend/backend/copilot/integration_creds.py b/autogpt_platform/backend/backend/copilot/integration_creds.pyindex 9b747f9aba..fcd7637aa9 100644--- a/autogpt_platform/backend/backend/copilot/integration_creds.py+++ b/autogpt_platform/backend/backend/copilot/integration_creds.py@@ -101,7 +101,7 @@ class _LockedTTLCache(TTLCache):# (user_id, provider) → token string, or (user_id, provider, required_scopes)# when the caller asked for specific scopes. TTLCache handles expiry + eviction.-_CacheKey = tuple[str, str] | tuple[str, str, frozenset[str]]+_CacheKey = tuple[str, str] | tuple[str, str, frozenset[str], str | None]_token_cache: _LockedTTLCache = _LockedTTLCache(maxsize=_CACHE_MAX_SIZE, ttl=_TOKEN_CACHE_TTL)@@ -110,13 +110,16 @@ _null_cache: _LockedTTLCache = _LockedTTLCache(maxsize=_CACHE_MAX_SIZE, ttl=_NULL_CACHE_TTL)-# GitHub user identity caches (keyed by user_id only, not provider tuple).+# GitHub user identity caches, keyed (user_id, credential_id): a user with two+# GitHub accounts has two identities, and a chat that picked one must not be+# served the other's. credential_id is None when no account was picked.# Declared here so invalidate_user_provider_cache() can reference them._GH_IDENTITY_CACHE_TTL = 600.0 # 10 min — profile data rarely changes-_gh_identity_cache: TTLCache[str, dict[str, str]] = _LockedTTLCache(+_IdentityKey = tuple[str, str | None]+_gh_identity_cache: _LockedTTLCache = _LockedTTLCache(maxsize=_CACHE_MAX_SIZE, ttl=_GH_IDENTITY_CACHE_TTL)-_gh_identity_null_cache: TTLCache[str, bool] = _LockedTTLCache(+_gh_identity_null_cache: _LockedTTLCache = _LockedTTLCache(maxsize=_CACHE_MAX_SIZE, ttl=_NULL_CACHE_TTL)@@ -153,8 +156,8 @@ def invalidate_user_provider_cache(user_id: str, provider: str) -> None:_null_cache.pop_prefix((user_id, provider))if provider == "github":- _gh_identity_cache.pop(user_id, None)- _gh_identity_null_cache.pop(user_id, None)+ _gh_identity_cache.pop_prefix((user_id,))+ _gh_identity_null_cache.pop_prefix((user_id,))# Same-process writes (a token refresh performed by this process) invalidate@@ -171,12 +174,19 @@ except RuntimeError:_manager = IntegrationCredentialsManager()-def _cache_key(user_id: str, provider: str, required: frozenset[str]) -> _CacheKey:- return (user_id, provider, required) if required else (user_id, provider)+def _cache_key(+ user_id: str, provider: str, required: frozenset[str], credential_id: str | None+) -> _CacheKey:+ if required or credential_id:+ return (user_id, provider, required, credential_id)+ return (user_id, provider)async def get_provider_token(- user_id: str, provider: str, required_scopes: frozenset[str] = frozenset()+ user_id: str,+ provider: str,+ required_scopes: frozenset[str] = frozenset(),+ credential_id: str | None = None,) -> str | None:"""Return the user's access token for *provider*, or ``None`` if not connected.@@ -185,11 +195,13 @@ async def get_provider_token(*required_scopes* wins: that is the credential the connect card shows asconnected, so injecting any other would send the model back to a card thatalready says "Connected".+ *credential_id* is the credential the user picked for this provider in the+ chat; when it is still stored, it is the only candidate.Both found tokens and "not connected" results are cached for 60 s, and acredential write in any process evicts the entry before that lapses."""_ensure_cache_invalidation_listener()- cache_key = _cache_key(user_id, provider, required_scopes)+ cache_key = _cache_key(user_id, provider, required_scopes, credential_id)if cache_key in _null_cache:return None@@ -208,6 +220,11 @@ async def get_provider_token()return None+ if credential_id is not None:+ # The user picked this one. If it is gone, that is "not connected",+ # never a reason to hand the sandbox another account's token.+ creds_list = [c for c in creds_list if c.id == credential_id]+# Pass 1: prefer OAuth2 (carry scope info, refreshable via token endpoint).# Credentials covering the requested scopes come first, then ones with# "repo" (full git access, where a public-data-only token lacks push/pull).@@ -295,19 +312,24 @@ _listener_thread: threading.Thread | None = Noneasync def get_integration_env_vars(- user_id: str, required_scopes: Mapping[str, frozenset[str]] | None = None+ user_id: str,+ required_scopes: Mapping[str, frozenset[str]] | None = None,+ selected: Mapping[str, str] | None = None,) -> dict[str, str]:"""Return env vars for all providers the user has connected.Iterates :data:`PROVIDER_ENV_VARS`, fetches each token, and builds a flat``{env_var: token}`` dict ready to pass to a subprocess or E2B sandbox.Only providers with a stored credential contribute entries.- *required_scopes* maps a provider to the scopes its token should carry.+ *required_scopes* maps a provider to the scopes its token should carry, and+ *selected* to the credential the user picked for it in this chat."""env: dict[str, str] = {}for provider, var_names in PROVIDER_ENV_VARS.items():scopes = (required_scopes or {}).get(provider, frozenset())- token = await get_provider_token(user_id, provider, scopes)+ token = await get_provider_token(+ user_id, provider, scopes, (selected or {}).get(provider)+ )if token:for var in var_names:env[var] = token@@ -319,7 +341,9 @@ async def get_integration_env_vars(# ----------------------------------------------------------------------------async def get_github_user_git_identity(user_id: str) -> dict[str, str] | None:+async def get_github_user_git_identity(+ user_id: str, credential_id: str | None = None+) -> dict[str, str] | None:"""Fetch the GitHub user's name and email for git committer env vars.Uses the ``/user`` GitHub API endpoint with the user's stored token.@@ -327,17 +351,21 @@ async def get_github_user_git_identity(user_id: str) -> dict[str, str] | None:``GIT_COMMITTER_NAME``, and ``GIT_COMMITTER_EMAIL`` if the user has aconnected GitHub account. Returns ``None`` otherwise.+ *credential_id* is the GitHub account the user picked in this chat, so the+ identity matches the token the sandbox was given for the same account.+Results are cached for 10 minutes; "not connected" results are cached for60 s (same as null-token cache)."""- if user_id in _gh_identity_null_cache:+ key: _IdentityKey = (user_id, credential_id)+ if key in _gh_identity_null_cache:return None- if cached := _gh_identity_cache.get(user_id):+ if cached := _gh_identity_cache.get(key):return cached- token = await get_provider_token(user_id, "github")+ token = await get_provider_token(user_id, "github", frozenset(), credential_id)if not token:- _gh_identity_null_cache[user_id] = True+ _gh_identity_null_cache[key] = Truereturn Noneimport aiohttp@@ -383,5 +411,5 @@ async def get_github_user_git_identity(user_id: str) -> dict[str, str] | None:"GIT_COMMITTER_NAME": name,"GIT_COMMITTER_EMAIL": email,}- _gh_identity_cache[user_id] = identity+ _gh_identity_cache[key] = identityreturn identitydiff --git a/autogpt_platform/backend/backend/copilot/integration_creds_test.py b/autogpt_platform/backend/backend/copilot/integration_creds_test.pyindex 00bb47c567..0284207a3c 100644--- a/autogpt_platform/backend/backend/copilot/integration_creds_test.py+++ b/autogpt_platform/backend/backend/copilot/integration_creds_test.py@@ -16,6 +16,7 @@ from backend.copilot.integration_creds import (_gh_identity_null_cache,_null_cache,_token_cache,+ get_github_user_git_identity,get_integration_env_vars,get_provider_token,invalidate_user_provider_cache,@@ -101,31 +102,64 @@ class TestInvalidateUserProviderCache:def test_clears_gh_identity_cache_for_github_provider(self):"""When provider is 'github', identity caches must also be cleared."""- _gh_identity_cache[_USER] = {+ _gh_identity_cache[(_USER, None)] = {"GIT_AUTHOR_NAME": "Old Name","GIT_AUTHOR_EMAIL": "[email protected]","GIT_COMMITTER_NAME": "Old Name","GIT_COMMITTER_EMAIL": "[email protected]",}invalidate_user_provider_cache(_USER, "github")- assert _USER not in _gh_identity_cache+ assert (_USER, None) not in _gh_identity_cachedef test_clears_gh_identity_null_cache_for_github_provider(self):"""When provider is 'github', the identity null-cache must also be cleared."""- _gh_identity_null_cache[_USER] = True+ _gh_identity_null_cache[(_USER, None)] = Trueinvalidate_user_provider_cache(_USER, "github")- assert _USER not in _gh_identity_null_cache+ assert (_USER, None) not in _gh_identity_null_cache++ def test_clears_the_identity_of_every_github_account_the_user_has(self):+ """A picked account's identity is cached under its own key; a change+ to the user's GitHub credentials must drop all of them, not just the+ unpicked one."""+ _gh_identity_cache[(_USER, None)] = {"GIT_AUTHOR_NAME": "a"}+ _gh_identity_cache[(_USER, "cred-b")] = {"GIT_AUTHOR_NAME": "b"}+ _gh_identity_cache[("other-user", "cred-b")] = {"GIT_AUTHOR_NAME": "o"}+ invalidate_user_provider_cache(_USER, "github")+ assert (_USER, None) not in _gh_identity_cache+ assert (_USER, "cred-b") not in _gh_identity_cache+ assert ("other-user", "cred-b") in _gh_identity_cachedef test_does_not_clear_gh_identity_cache_for_other_providers(self):"""When provider is NOT 'github', identity caches must be left alone."""- _gh_identity_cache[_USER] = {+ _gh_identity_cache[(_USER, None)] = {"GIT_AUTHOR_NAME": "Some Name","GIT_AUTHOR_EMAIL": "[email protected]","GIT_COMMITTER_NAME": "Some Name","GIT_COMMITTER_EMAIL": "[email protected]",}invalidate_user_provider_cache(_USER, "some-other-provider")- assert _USER in _gh_identity_cache+ assert (_USER, None) in _gh_identity_cache+++class TestGitHubIdentityFollowsThePick:+ @pytest.mark.asyncio(loop_scope="session")+ async def test_the_picked_account_is_the_one_looked_up(self):+ lookup = AsyncMock(return_value=None)+ with patch("backend.copilot.integration_creds.get_provider_token", lookup):+ assert await get_github_user_git_identity(_USER, "cred-b") is None+ lookup.assert_awaited_once_with(_USER, "github", frozenset(), "cred-b")++ @pytest.mark.asyncio(loop_scope="session")+ async def test_one_accounts_cached_result_is_not_served_for_another(self):+ """Keyed by user alone, the first account looked up would answer for+ every other account the user picks for the next ten minutes."""+ lookup = AsyncMock(return_value=None)+ with patch("backend.copilot.integration_creds.get_provider_token", lookup):+ await get_github_user_git_identity(_USER, "cred-a")+ await get_github_user_git_identity(_USER, "cred-b")+ assert [c.args[3] for c in lookup.await_args_list] == ["cred-a", "cred-b"]+ assert (_USER, "cred-a") in _gh_identity_null_cache+ assert (_USER, "cred-b") in _gh_identity_null_cacheclass TestGetProviderToken:@@ -305,11 +339,34 @@ class TestRequiredScopes:scoped = (_USER, _PROVIDER, frozenset({"repo"}))_token_cache[(_USER, _PROVIDER)] = "tok"_token_cache[scoped] = "tok"- _gh_identity_cache[_USER] = {"GIT_AUTHOR_NAME": "x"}+ _gh_identity_cache[(_USER, None)] = {"GIT_AUTHOR_NAME": "x"}invalidate_user_provider_cache(_USER, "ProviderName.GITHUB")assert (_USER, _PROVIDER) not in _token_cacheassert scoped not in _token_cache- assert _USER not in _gh_identity_cache+ assert (_USER, None) not in _gh_identity_cache++ @pytest.mark.asyncio(loop_scope="session")+ async def test_the_credential_picked_in_the_chat_is_the_only_candidate(self):+ # Without scopes asked for, stored order would hand over the older one.+ manager = self._manager([self.older, self.newer])+ with patch("backend.copilot.integration_creds._manager", manager):+ token = await get_provider_token(+ _USER, _PROVIDER, credential_id=self.newer.id+ )+ env = await get_integration_env_vars(+ _USER, selected={"github": self.newer.id}+ )+ assert token == "tok-newer"+ assert env["GH_TOKEN"] == "tok-newer"++ @pytest.mark.asyncio(loop_scope="session")+ async def test_a_deleted_pick_yields_no_token_rather_than_another_account(self):+ manager = self._manager([self.older, self.newer])+ with patch("backend.copilot.integration_creds._manager", manager):+ token = await get_provider_token(+ _USER, _PROVIDER, credential_id="deleted-id"+ )+ assert token is Nonedef test_invalidation_drops_scoped_entries_too(self):scoped = (_USER, _PROVIDER, frozenset({"repo", "read:org"}))diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec.pyindex bb8b99400f..9e606402ae 100644--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py@@ -27,6 +27,7 @@ from backend.copilot.context import (looks_like_sdk_tool_result_path,sdk_tool_result_redirect_hint,)+from backend.copilot.credential_selection import selected_credentialsfrom backend.copilot.integration_creds import (get_github_user_git_identity,get_integration_env_vars,@@ -206,13 +207,18 @@ class BashExecTool(BaseTool):# Collect injected secret values so we can scrub them from output.secret_values: list[str] = []if user_id is not None:- integration_env = await get_integration_env_vars(user_id, required_scopes)+ selected = await selected_credentials(session_id)+ integration_env = await get_integration_env_vars(+ user_id, required_scopes, selected+ )secret_values = [v for v in integration_env.values() if v]envs.update(integration_env)# Set git author/committer identity from the user's GitHub profile# so commits made in the sandbox are attributed correctly.- git_identity = await get_github_user_git_identity(user_id)+ git_identity = await get_github_user_git_identity(+ user_id, selected.get("github")+ )if git_identity:envs.update(git_identity)diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.pyindex 51412890a2..00e51b266f 100644--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py@@ -10,6 +10,17 @@ from .bash_exec import BashExecToolfrom .models import BashExecResponse, ErrorResponse_USER = "user-bash-exec-test"+_PICKED = {"github": "cred-picked"}++[email protected](autouse=True)+def picked_credentials():+ """The chat's credential picks, which live in Redis outside these tests."""+ with patch(+ "backend.copilot.tools.bash_exec.selected_credentials",+ new=AsyncMock(return_value=_PICKED),+ ):+ yielddef _make_tool() -> BashExecTool:@@ -44,7 +55,7 @@ class TestBashExecE2BTokenInjection:patch("backend.copilot.tools.bash_exec.get_github_user_git_identity",new=AsyncMock(return_value=None),- ),+ ) as mock_identity,):result = await tool._execute_on_e2b(sandbox=sandbox,@@ -54,7 +65,11 @@ class TestBashExecE2BTokenInjection:user_id=_USER,)- mock_get_env.assert_awaited_once_with(_USER, None)+ # The session's picks reach the token lookup, not just its scopes.+ mock_get_env.assert_awaited_once_with(_USER, None, _PICKED)+ # And the commit identity comes from that same GitHub account, so a+ # commit made with one account's token is not signed as another's.+ mock_identity.assert_awaited_once_with(_USER, "cred-picked")call_kwargs = sandbox.commands.run.call_args[1]assert call_kwargs["envs"]["GH_TOKEN"] == "gh-secret"assert call_kwargs["envs"]["GITHUB_TOKEN"] == "gh-secret"diff --git a/autogpt_platform/backend/backend/copilot/tools/block_display_test.py b/autogpt_platform/backend/backend/copilot/tools/block_display_test.pyindex 143e4b8842..8dce2b7831 100644--- a/autogpt_platform/backend/backend/copilot/tools/block_display_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/block_display_test.py@@ -38,7 +38,7 @@ async def test_run_block_emits_name_before_execution_or_setup(if scenario == "invalid_schema":block.input_schema.jsonschema.side_effect = ValueError("Invalid schema")- async def resolve_credentials(*args):+ async def resolve_credentials(*args, **kwargs):assert published == [_BLOCK_NAME]return {}, [MagicMock()] if scenario == "credentials" else []@@ -115,7 +115,7 @@ async def test_approved_continuation_emits_name_before_credentials(database = _review_database(session, review_id)published: list[str] = []- async def resolve_credentials(*args):+ async def resolve_credentials(*args, **kwargs):assert published == [_BLOCK_NAME]return {}, [MagicMock()] if missing_credentials else []diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.pyindex a054c0ffec..fefa125a4c 100644--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py@@ -132,7 +132,7 @@ class ContinueRunBlockTool(BaseTool):)matched_creds, missing_creds = await resolve_block_credentials(- user_id, block, input_data, session.expert_id+ user_id, block, input_data, session.expert_id, session_id=session_id)if missing_creds:return ErrorResponse(diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 397dd0176b..cc828621ba 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -730,11 +730,14 @@ async def resolve_block_credentials(block: AnyBlockSchema,input_data: dict[str, Any] | None = None,expert_id: str | None = None,+ session_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], list[CredentialsMetaInput]]:"""Resolve credentials for a block by matching user's available credentials.Handles discriminated credentials (e.g. provider selection based on model).``expert_id`` narrows the pool to that expert's granted credentials.+ ``session_id`` is the chat the block runs in: its picked credentials win,+ and a choice between several is handed back to the user.Returns:(matched_credentials, missing_credentials)@@ -745,7 +748,9 @@ async def resolve_block_credentials(if not requirements:return {}, []- return await match_credentials_to_requirements(user_id, requirements, expert_id)+ return await match_credentials_to_requirements(+ user_id, requirements, expert_id, session_id+ )@dataclass@@ -855,7 +860,7 @@ async def prepare_block_for_execution(input_data.pop(field_name)matched_credentials, missing_credentials = await resolve_block_credentials(- user_id, block, input_data, session.expert_id+ user_id, block, input_data, session.expert_id, session_id=session_id)try:diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.pyindex a4b79da005..4e243c7556 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py@@ -1225,7 +1225,7 @@ async def test_prepare_block_null_non_credential_field_not_stripped() -> None:excl_ids, excl_types = _patch_excluded()captured: list[dict] = []- async def _capture_resolve(user_id, block, input_data, expert_id=None):+ async def _capture_resolve(user_id, block, input_data, expert_id=None, **_):captured.append(dict(input_data))return {}, []diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex e8631b2b1d..2576204c03 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -670,7 +670,7 @@ class RunAgentTool(BaseTool):(graph_credentials, error_response) — error_response is None when ready."""graph_credentials, missing_creds = await match_user_credentials_to_graph(- user_id, graph, expert_id+ user_id, graph, expert_id, session_id=session_id)# --- Reject unknown input fields (always, even for dry runs) ---diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.pyindex 923389345d..63b1961e79 100644--- a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py@@ -359,7 +359,9 @@ class SetupAgentWebhookTriggerTool(BaseTool):Returns ``(agent_credentials, None)`` when ready to proceed, or``({}, SetupRequirementsResponse)`` when the user must act first."""- matched, _ = await match_user_credentials_to_graph(user_id, graph, expert_id)+ matched, _ = await match_user_credentials_to_graph(+ user_id, graph, expert_id, session_id=session_id+ )trigger_cred_key = self._trigger_cred_key(graph, trigger_node)effective = dict(matched)diff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.pyindex 2440d5321d..7f588b570c 100644--- a/autogpt_platform/backend/backend/copilot/tools/utils.py+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py@@ -2,9 +2,11 @@import loggingimport re+from collections.abc import Mappingfrom typing import Anyfrom backend.api.features.library import model as library_model+from backend.copilot.credential_selection import selected_credentialsfrom backend.data.db_accessors import library_db, store_dbfrom backend.data.graph import GraphModelfrom backend.data.model import (@@ -14,6 +16,7 @@ from backend.data.model import (HostScopedCredentials,OAuth2Credentials,)+from backend.integrations.credentials_store import is_system_credentialfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.integrations.providers import ProviderNamefrom backend.util.exceptions import NotFoundError@@ -264,11 +267,14 @@ async def match_credentials_to_requirements(user_id: str,requirements: dict[str, CredentialsFieldInfo],expert_id: str | None = None,+ session_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], list[CredentialsMetaInput]]:"""Match user's credentials against a dictionary of credential requirements.This is the core matching logic shared by both graph and block credential matching.+ With a ``session_id`` the match is a chat tool's: the credential the user+ picked in that chat is used, and a choice between several is left to them."""matched: dict[str, CredentialsMetaInput] = {}missing: list[CredentialsMetaInput] = []@@ -277,9 +283,12 @@ async def match_credentials_to_requirements(return matched, missingavailable_creds = await get_user_credentials(user_id, expert_id)+ selected = await selected_credentials(session_id)for field_name, field_info in requirements.items():- matching_cred = find_matching_credential(available_creds, field_info)+ matching_cred = find_matching_credential(+ available_creds, field_info, selected, ask_when_ambiguous=bool(session_id)+ )if matching_cred:try:@@ -350,26 +359,51 @@ async def scope_credentials_to_expert(def find_matching_credential(available_creds: list[Credentials],field_info: CredentialsFieldInfo,+ selected: Mapping[str, str] | None = None,+ *,+ ask_when_ambiguous: bool = False,) -> Credentials | None:"""Find a credential that matches the required provider, type, scopes, host,- and — for MCP OAuth credentials — the server URL."""- for cred in available_creds:- if cred.provider not in field_info.provider:- continue- if cred.type not in field_info.supported_types:- continue- if cred.type == "oauth2" and not _credential_has_required_scopes(- cred, field_info- ):- continue- if cred.type == "host_scoped" and not _credential_is_for_host(cred, field_info):- continue- if cred.provider == ProviderName.MCP and not _credential_is_for_mcp_server(- cred, field_info- ):- continue- return cred- return None+ and — for MCP OAuth credentials — the server URL.++ ``selected`` maps a provider to the credential the user picked for it; a+ pick that fits always wins. ``ask_when_ambiguous`` is for a caller that can+ ask: when several of the user's own credentials fit and none was picked, it+ gets ``None``, which surfaces as a setup card where the user chooses. Taking+ the first fit there would run on whichever account was stored first.+ """+ fits = [c for c in available_creds if _credential_fits(c, field_info)]+ if selected:+ for cred in fits:+ if selected.get(_provider_slug(cred)) == cred.id:+ return cred+ if not ask_when_ambiguous:+ return fits[0] if fits else None+ own = [c for c in fits if not is_system_credential(c.id)]+ if len(own) > 1:+ return None+ return own[0] if own else (fits[0] if fits else None)+++def _provider_slug(cred: Credentials) -> str:+ # ProviderName is a str-Enum: str() would render "ProviderName.X".+ return str(getattr(cred.provider, "value", cred.provider))+++def _credential_fits(cred: Credentials, field_info: CredentialsFieldInfo) -> bool:+ if cred.provider not in field_info.provider:+ return False+ if cred.type not in field_info.supported_types:+ return False+ if cred.type == "oauth2" and not _credential_has_required_scopes(cred, field_info):+ return False+ if cred.type == "host_scoped" and not _credential_is_for_host(cred, field_info):+ return False+ if cred.provider == ProviderName.MCP and not _credential_is_for_mcp_server(+ cred, field_info+ ):+ return False+ return Truedef create_credential_meta_from_match(@@ -388,6 +422,7 @@ async def match_user_credentials_to_graph(user_id: str,graph: GraphModel,expert_id: str | None = None,+ session_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], list[str]]:"""Match user's available credentials against graph's required credentials.@@ -419,6 +454,7 @@ async def match_user_credentials_to_graph(available_creds = await scope_credentials_to_expert(user_id, expert_id, await creds_manager.store.get_all_creds(user_id))+ selected = await selected_credentials(session_id)# For each required credential field, find a matching user credential# field_info.provider is a frozenset because aggregate_credentials_inputs()@@ -430,7 +466,10 @@ async def match_user_credentials_to_graph(_,) in aggregated_creds.items():matching_cred = find_matching_credential(- available_creds, credential_requirements+ available_creds,+ credential_requirements,+ selected,+ ask_when_ambiguous=bool(session_id),)if matching_cred:diff --git a/autogpt_platform/backend/backend/copilot/tools/utils_test.py b/autogpt_platform/backend/backend/copilot/tools/utils_test.pyindex 841eac85d8..3f9eddf22d 100644--- a/autogpt_platform/backend/backend/copilot/tools/utils_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/utils_test.py@@ -229,3 +229,60 @@ async def _resolve_for(expert_id: str | None, allowed: list[str]):{"url": "https://api.example.com/v1/data"},expert_id,)+++def _key_cred(cred_id: str, provider: str = "github"):+ from backend.data.model import APIKeyCredentials++ return APIKeyCredentials(+ id=cred_id, provider=provider, title=cred_id, api_key=SecretStr("k")+ )+++def _find(creds, selected=None, *, ask=False, field=None):+ from backend.copilot.tools.utils import find_matching_credential++ return find_matching_credential(+ creds, field or _make_regular_field(), selected, ask_when_ambiguous=ask+ )+++def test_the_credential_the_user_picked_wins():+ creds = [_key_cred("work"), _key_cred("personal")]+ picked = _find(creds, {"github": "personal"}, ask=True)+ assert picked is not None and picked.id == "personal"+++def test_a_chat_tool_asks_rather_than_choosing_between_two_accounts():+ # None surfaces as a missing credential, which is the card with a picker.+ assert _find([_key_cred("work"), _key_cred("personal")], ask=True) is None+++def test_a_single_credential_needs_no_pick():+ picked = _find([_key_cred("only")], ask=True)+ assert picked is not None and picked.id == "only"+++def test_a_pick_that_no_longer_fits_is_ignored_not_trusted():+ # Deleted, or for another provider: fall back to asking, never to a guess.+ creds = [_key_cred("work"), _key_cred("personal")]+ assert _find(creds, {"github": "deleted-id"}, ask=True) is None+ assert _find(creds, {"slack": "work"}, ask=True) is None+++def test_callers_that_cannot_ask_keep_the_first_fit():+ # Schedules and expert setup have nobody to ask; their behaviour is unchanged.+ picked = _find([_key_cred("work"), _key_cred("personal")])+ assert picked is not None and picked.id == "work"+++def test_a_system_credential_is_used_when_the_user_has_none_of_their_own():+ from backend.integrations.credentials_store import openai_credentials++ field = CredentialsFieldInfo.model_validate(+ {"credentials_provider": ["openai"], "credentials_types": ["api_key"]},+ by_alias=True,+ )+ assert _find([openai_credentials], ask=True, field=field) is openai_credentials+ own = _key_cred("own-openai", provider="openai")+ assert _find([own, openai_credentials], ask=True, field=field) is owndiff --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 58334e2f42..1ac5c988ab 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@@ -123,7 +123,7 @@ export function ConnectorRow({ row }: Props) {// 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) {+ if (allProviders && row.selected && !selectedStillFits) {row.select(undefined);return;}@@ -143,6 +143,31 @@ export function ConnectorRow({ row }: Props) {expertGrant?.expertId,]);+ // Several saved accounts can satisfy one row. Nothing picks between them for+ // the user: the row offers them, and the backend runs on exactly that one.+ const pickable = expertGrant+ ? []+ : filterSystemCredentials(+ allProviders?.[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;++ async function pick(credential: Grantable): Promise<boolean> {+ row.select({+ id: credential.id,+ provider: row.provider,+ type: credential.type as CredentialsMetaInput["type"],+ title: credential.title,+ });+ row.onConnected();+ return true;+ }+const grantableOptions = [...(connected ? [connected] : []),...(expertGrant?.credentials ?? []).filter((c) => c.id !== connected?.id),@@ -212,7 +237,11 @@ export function ConnectorRow({ row }: Props) {}onClick={openDialog}>- {grantableOptions.length > 0 ? "Grant access" : "Connect"}+ {grantableOptions.length > 0+ ? "Grant access"+ : hasChoice+ ? "Choose account"+ : "Connect"}</Button>)}@@ -229,7 +258,15 @@ export function ConnectorRow({ row }: Props) {isPending: isGranting,error: grantError,}- : undefined+ : hasChoice+ ? {+ credentials: pickable,+ onUse: pick,+ isPending: false,+ error: null,+ purpose: "choose",+ }+ : undefined}open={isDialogOpen}onClose={() => setDialogOpen(false)}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.tsxnew file mode 100644index 0000000000..426edf18d8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.choice.test.tsx@@ -0,0 +1,159 @@+import type { ExistingCredentialsOffer } from "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/helpers";+import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { useState, type ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { ConnectorRow } from "../ConnectorRow";+import type { ConnectorRow as Row } from "../helpers";++vi.mock("@/app/api/__generated__/endpoints/experts/experts", () => ({+ useListExpertCredentials: () => ({+ data: undefined,+ isPending: false,+ isError: false,+ isFetching: false,+ refetch: vi.fn(),+ }),+ useGrantExpertCredentials: () => ({ mutateAsync: vi.fn(), isPending: false }),+ getListExpertCredentialsQueryKey: (expertId?: string) => [+ `/api/experts/${expertId}/credentials`,+ ],+}));++vi.mock(+ "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog",+ () => ({+ ConnectCredentialDialog: ({+ open,+ existing,+ }: {+ open: boolean;+ existing?: ExistingCredentialsOffer;+ }) =>+ open ? (+ <div data-testid="connect-dialog">+ {existing?.credentials.map((credential) => (+ <button+ key={credential.id}+ onClick={() => void existing.onUse(credential)}+ >+ {`use-${credential.title}`}+ </button>+ ))}+ </div>+ ) : null,+ }),+);++const work = {+ id: "cred-work",+ provider: "github",+ type: "api_key",+ title: "work",+};+const personal = { ...work, id: "cred-personal", title: "personal" };++function providers(saved: (typeof work)[]) {+ return {+ github: {+ provider: "github",+ providerName: "github",+ savedCredentials: saved,+ oAuthCallback: vi.fn(),+ createAPIKeyCredentials: vi.fn(),+ createUserPasswordCredentials: vi.fn(),+ createHostScopedCredentials: vi.fn(),+ deleteCredentials: vi.fn(),+ },+ } as unknown as React.ContextType<typeof CredentialsProvidersContext>;+}++function row(overrides: Partial<Row> = {}): Row {+ return {+ provider: "github",+ displayName: "GitHub",+ description: "Issues, pull requests, repositories",+ schema: {+ credentials_provider: ["github"],+ credentials_types: ["api_key"],+ },+ selected: undefined,+ hasUnansweredTarget: false,+ select: vi.fn(),+ onConnected: vi.fn(),+ ...overrides,+ };+}++function StatefulRow({ current }: { current: Row }) {+ const [selected, setSelected] = useState(current.selected);+ return (+ <ConnectorRow+ row={{+ ...current,+ selected,+ select: (value) => {+ current.select(value);+ setSelected(value);+ },+ }}+ />+ );+}++function renderRow(current: Row, saved: (typeof work)[]) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>+ <CredentialsProvidersContext.Provider value={providers(saved)}>+ {children}+ </CredentialsProvidersContext.Provider>+ </QueryClientProvider>+ );+ }+ return render(<StatefulRow current={current} />, { wrapper: Wrapper });+}++afterEach(cleanup);++describe("ConnectorRow with several saved accounts for one provider", () => {+ it("offers the accounts instead of picking one or asking for a new sign-in", () => {+ const current = row();+ renderRow(current, [work, personal]);++ expect(current.select).not.toHaveBeenCalled();+ fireEvent.click(screen.getByText("Choose account"));++ expect(screen.getByText("use-work")).toBeDefined();+ expect(screen.getByText("use-personal")).toBeDefined();+ });++ it("selects the account the user chose and keeps it", () => {+ const current = row();+ renderRow(current, [work, personal]);++ fireEvent.click(screen.getByText("Choose account"));+ fireEvent.click(screen.getByText("use-personal"));++ expect(current.select).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: "cred-personal", provider: "github" }),+ );+ expect(current.onConnected).toHaveBeenCalled();+ // Two accounts still match, which used to clear the selection again.+ expect(screen.getByText("Connected")).toBeDefined();+ });++ it("still connects a single saved account on its own", () => {+ const current = row();+ renderRow(current, [work]);++ expect(current.select).toHaveBeenCalledWith(+ expect.objectContaining({ id: "cred-work" }),+ );+ expect(screen.queryByText("Choose account")).toBeNull();+ });+});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 ab78c52326..4cbd490b03 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@@ -23,8 +23,8 @@ import {buildExpectedInputsSchema,buildPreviewRunMessage,buildRunMessage,- buildTriggerSetupMessage,buildSiblingInputsFromCredentials,+ buildTriggerSetupMessage,checkAllCredentialsComplete,checkAllInputsComplete,checkCanRun,@@ -34,6 +34,7 @@ import {getRequestedProviders,isRejectedCredentialSelected,mergeInputValues,+ reportCredentialPicks,} from "./helpers";import { CredentialRejectionNotice } from "../CredentialRejectionNotice/CredentialRejectionNotice";@@ -218,6 +219,10 @@ export function SetupRequirementsCard({justConnected,credentialsReady: !needsCredentials || isAllCredsComplete,buildMessage: () => buildProceedMessage(),+ // A trigger's line carries the chosen credential ids, and an edit-mode+ // card's may carry run inputs; only a bare confirmation is shareable.+ credentialsOnly: needsCredentials && !needsInputs && !isTriggerMode,+ beforeSend: () => reportCredentialPicks(sessionID, inputCredentials),onSent: markSent,connectors: needsCredentials? {@@ -290,7 +295,9 @@ export function SetupRequirementsCard({function handleRun() {const message = buildProceedMessage();markSent();- onSend(message);+ void reportCredentialPicks(sessionID, inputCredentials).then(() =>+ onSend(message),+ );}return (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 998a221daf..fee3316cdd 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@@ -11,6 +11,13 @@ import { SetupRequirementsCard } from "../SetupRequirementsCard";import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";import { useConnectedProvidersStore } from "../../../connectedProvidersStore";+import { putV2RecordCredentialPicksForThisChat } from "@/app/api/__generated__/endpoints/chat/chat";++// Proceed records the picked accounts first, then sends; the reply is what+// re-runs the tool, so it must find the pick already in place.+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ putV2RecordCredentialPicksForThisChat: vi.fn().mockResolvedValue(undefined),+}));const mockOnSend = vi.fn();vi.mock("../../CopilotChatActionsProvider/useCopilotChatActions", () => ({@@ -25,7 +32,10 @@ vi.mock(onCredentialChange,}: {requiredCredentials: Set<string>;- onCredentialChange: (key: string, value?: { id: string }) => void;+ onCredentialChange: (+ key: string,+ value?: { id: string; provider: string },+ ) => void;}) => (<div data-testid="credentials-grouped-view">Credentials@@ -33,7 +43,11 @@ vi.mock(data-testid="select-credential"onClick={() =>[...requiredCredentials].forEach((key) =>- onCredentialChange(key, { id: `cred-${key}` }),+ // The real picker hands back the provider with the id.+ onCredentialChange(key, {+ id: `cred-${key}`,+ provider: key.replace(/_credentials$/, ""),+ }),)}>@@ -178,7 +192,7 @@ describe("SetupRequirementsCard (edit mode)", () => {expect(proceed.closest("button")?.disabled).toBe(false);});- it("calls onSend and shows Connected message when Proceed is clicked", () => {+ it("calls onSend and shows Connected message when Proceed is clicked", async () => {render(<SetupRequirementsCardoutput={makeOutput({@@ -195,7 +209,7 @@ describe("SetupRequirementsCard (edit mode)", () => {/>,);fireEvent.click(screen.getByText("Proceed"));- expect(mockOnSend).toHaveBeenCalledOnce();+ await waitFor(() => expect(mockOnSend).toHaveBeenCalledOnce());expect(screen.getByText(/Connected. Continuing/)).toBeDefined();});@@ -374,7 +388,7 @@ describe("SetupRequirementsCard (preview mode)", () => {expect(proceed!.closest("button")?.disabled).toBe(false);});- it("sends the legacy run_agent message on Proceed", () => {+ it("sends the legacy run_agent message on Proceed", async () => {render(<SetupRequirementsCardinputsMode="preview"@@ -386,8 +400,10 @@ describe("SetupRequirementsCard (preview mode)", () => {/>,);fireEvent.click(screen.getByText("Proceed"));- expect(mockOnSend).toHaveBeenCalledWith(- "Please proceed with running the agent.",+ await waitFor(() =>+ expect(mockOnSend).toHaveBeenCalledWith(+ "Please proceed with running the agent.",+ ),);});});@@ -627,7 +643,7 @@ describe("SetupRequirementsCard (session-scoped dismissal)", () => {});describe("SetupRequirementsCard (trigger mode)", () => {- it("carries the picked credential IDs back on Proceed", () => {+ it("carries the picked credential IDs back on Proceed", async () => {render(<SetupRequirementsCardinputsMode="trigger"@@ -650,6 +666,15 @@ describe("SetupRequirementsCard (trigger mode)", () => {expect(screen.getByText("Proceed").closest("button")?.disabled).toBe(false);fireEvent.click(screen.getByText("Proceed"));+ await waitFor(() => expect(mockOnSend).toHaveBeenCalledOnce());+ // The pick reaches the backend before the reply that re-runs the tool.+ const record = vi.mocked(putV2RecordCredentialPicksForThisChat);+ expect(record).toHaveBeenCalledWith(expect.any(String), {+ selections: { github: "cred-github_credentials" },+ });+ expect(record.mock.invocationCallOrder[0]).toBeLessThan(+ mockOnSend.mock.invocationCallOrder[0],+ );const sent = mockOnSend.mock.calls[0][0] as string;expect(sent).toContain("setup_agent_webhook_trigger");expect(sent).toContain(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/reportCredentialPicks.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/reportCredentialPicks.test.tsnew file mode 100644index 0000000000..d5e69cf5e0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/reportCredentialPicks.test.ts@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { putV2RecordCredentialPicksForThisChat } from "@/app/api/__generated__/endpoints/chat/chat";+import { buildCredentialSelections, reportCredentialPicks } from "../helpers";++vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ putV2RecordCredentialPicksForThisChat: vi.fn(),+}));++const record = vi.mocked(putV2RecordCredentialPicksForThisChat);++const picked = {+ credentials: { id: "cred-personal", provider: "github" },+ linear_credentials: { id: "cred-linear", provider: "linear" },+ unfilled: undefined,+ half_filled: { provider: "slack" },+};++describe("buildCredentialSelections", () => {+ it("maps each chosen credential to its provider and skips unfilled fields", () => {+ expect(buildCredentialSelections(picked)).toEqual({+ github: "cred-personal",+ linear: "cred-linear",+ });+ });+});++describe("reportCredentialPicks", () => {+ beforeEach(() => record.mockReset());++ it("tells the backend which accounts were chosen for this chat", async () => {+ await reportCredentialPicks("session-1", picked);++ expect(record).toHaveBeenCalledWith("session-1", {+ selections: { github: "cred-personal", linear: "cred-linear" },+ });+ });++ it("stays quiet when there is no session or nothing was chosen", async () => {+ await reportCredentialPicks(null, picked);+ await reportCredentialPicks("session-1", { unfilled: undefined });++ expect(record).not.toHaveBeenCalled();+ });++ it("does not block the reply when recording fails", async () => {+ // With nothing recorded the backend asks again instead of guessing.+ record.mockRejectedValueOnce(new Error("network"));++ await expect(+ reportCredentialPicks("session-1", picked),+ ).resolves.toBeUndefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.tsindex 1f93c738b4..1cfab1c02f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts@@ -1,4 +1,5 @@import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";+import { putV2RecordCredentialPicksForThisChat } from "@/app/api/__generated__/endpoints/chat/chat";import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";import type { RJSFSchema } from "@rjsf/utils";import { CREDENTIALS_TYPES } from "@/lib/autogpt-server-api/types";@@ -352,6 +353,46 @@ export function isRejectedCredentialSelected();}+/** `{provider: credentialId}` for every credential chosen on the card. */+export function buildCredentialSelections(+ inputCredentials: Record<+ string,+ { id?: string; provider?: string } | undefined+ >,+): Record<string, string> {+ const selections: Record<string, string> = {};+ for (const credential of Object.values(inputCredentials)) {+ if (credential?.id && credential.provider) {+ selections[credential.provider] = credential.id;+ }+ }+ return selections;+}++/**+ * Tell the backend which accounts were chosen, before the reply that re-runs+ * the tool. The tools use exactly these for the rest of the chat; without them+ * they would match on their own and could run on a different account.+ *+ * Failure is swallowed on purpose: with nothing recorded the backend asks+ * again rather than guessing, so the worst case is a second card.+ */+export async function reportCredentialPicks(+ sessionID: string | null,+ inputCredentials: Record<+ string,+ { id?: string; provider?: string } | undefined+ >,+): Promise<void> {+ const selections = buildCredentialSelections(inputCredentials);+ if (!sessionID || Object.keys(selections).length === 0) return;+ try {+ await putV2RecordCredentialPicksForThisChat(sessionID, { selections });+ } catch {+ // See above.+ }+}+export function checkCanRun(needsCredentials: boolean,isAllCredentialsComplete: boolean,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 d9caf8de18..b7d65d4c6c 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@@ -30,7 +30,11 @@ import { ChainActionCard } from "../ChainActionCard/ChainActionCard";import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";import type { MessagePart } from "../ChatMessagesContainer/helpers";import { ACCORDION_PANEL, accordionState, PANEL_REVEAL } from "./accordion";-import { ChainActionsContext, type ChainActionEntry } from "./chainActions";+import {+ buildChainReply,+ ChainActionsContext,+ type ChainActionEntry,+} from "./chainActions";import { useCredentialFailureCounters } from "./useCredentialFailureCounters";import { ChainRowView } from "./ChainRowView";import {@@ -64,6 +68,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {const { onSend } = useCopilotChatActions();// The ref latches against a double effect run; the state re-renders Proceed.const autoSentRef = useRef(false);+ const sendingRef = useRef(false);const [autoSent, setAutoSent] = useState(false);// Action cards (credential setup, clarifying questions) register here@@ -146,13 +151,9 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {if (!canAutoSend || autoSentRef.current) return;autoSentRef.current = true;setAutoSent(true);- const message = pendingActions- .map((entry) => entry.buildMessage())- .filter(Boolean)- .join("\n\n");+ const message = buildChainReply(pendingActions);if (!message) return;- pendingActions.forEach((entry) => entry.onSent?.());- sendReply(message);+ void sendAfter(pendingActions, message);},// eslint-disable-next-line react-hooks/exhaustive-deps -- pendingActions is rebuilt every render; the ref makes this once-per-chain[canAutoSend],@@ -234,13 +235,24 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {// unconnected MCP server) are left out instead of blocking the ready ones.function handleProceed() {const readyActions = pendingActions.filter((entry) => entry.ready);- const message = readyActions- .map((entry) => entry.buildMessage())- .filter(Boolean)- .join("\n\n");+ const message = buildChainReply(readyActions);if (!message) return;- readyActions.forEach((entry) => entry.onSent?.());- sendReply(message);+ void sendAfter(readyActions, message);+ }++ // Proceed stays clickable while beforeSend runs, and a second click would+ // send the same reply again. The ref is set before the first await, so the+ // second click sees it in time.+ async function sendAfter(entries: ChainActionEntry[], message: string) {+ if (sendingRef.current) return;+ sendingRef.current = true;+ try {+ await Promise.all(entries.map((entry) => entry.beforeSend?.()));+ entries.forEach((entry) => entry.onSent?.());+ sendReply(message);+ } finally {+ sendingRef.current = false;+ }}return (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/buildChainReply.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/buildChainReply.test.tsnew file mode 100644index 0000000000..59e8f1daf8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/buildChainReply.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";+import { buildChainReply, type ChainActionEntry } from "../chainActions";++function entry(+ message: string | null,+ overrides: Partial<ChainActionEntry> = {},+): ChainActionEntry {+ return {+ id: message ?? "none",+ ready: true,+ buildMessage: () => message,+ ...overrides,+ };+}++const RERUN =+ "I've configured the required credentials. Please re-run this step now.";+const CONTINUE =+ "I've configured the required credentials. I've connected my account. Please continue.";++describe("buildChainReply", () => {+ it("confirms credentials once when several cards ask for the same account", () => {+ const reply = buildChainReply([+ entry(RERUN, { credentialsOnly: true }),+ entry(CONTINUE, { credentialsOnly: true }),+ ]);++ expect(reply).toBe(RERUN);+ });++ it("keeps every line that carries more than a confirmation", () => {+ const reply = buildChainReply([+ entry(RERUN, { credentialsOnly: true }),+ entry('Run with these inputs: {"repo_url": "x"}'),+ entry("Here are my answers: blue"),+ entry(null),+ ]);++ expect(reply).toBe(+ [+ RERUN,+ 'Run with these inputs: {"repo_url": "x"}',+ "Here are my answers: blue",+ ].join("\n\n"),+ );+ });+});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 b547b2b2a1..66c544ce30 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@@ -16,6 +16,13 @@ export interface ChainActionEntry {id: string;ready: boolean;buildMessage: () => string | null;+ /** The message only confirms that credentials are in place. Several cards+ * in one chain often ask for the same account, and the model needs to be+ * told once. */+ credentialsOnly?: boolean;+ /** Awaited before the chain's reply goes out. The reply is what makes the+ * tool run again, so anything it must find in place is settled here. */+ beforeSend?: () => Promise<void>;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. */@@ -46,3 +53,21 @@ export interface ChainActions {}export const ChainActionsContext = createContext<ChainActions | null>(null);++/** The chain's single reply. Every card contributes its line, except that+ * cards which only confirm credentials share one confirmation: two cards+ * asking for the same account used to say so twice in one message. */+export function buildChainReply(entries: ChainActionEntry[]): string {+ let confirmed = false;+ const lines: string[] = [];+ for (const entry of entries) {+ const line = entry.buildMessage();+ if (!line) continue;+ if (entry.credentialsOnly) {+ if (confirmed) continue;+ confirmed = true;+ }+ lines.push(line);+ }+ return lines.join("\n\n");+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex fbf95dd16c..824572962a 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -4358,6 +4358,59 @@}}},+ "/api/chat/sessions/{session_id}/credential-selection": {+ "put": {+ "tags": ["v2", "chat", "chat"],+ "summary": "Record credential picks for this chat",+ "description": "Keep the account the user chose on a connect card for the rest of the chat.\n\nThe card shows one account and the tools used to re-match on their own, so\nwith two accounts for a provider a run could land on the other one. The\ntools now use exactly what is recorded here, and ask when several\ncredentials qualify and nothing was picked.\n\nEvery id is checked against the caller's own credentials and the provider\nit is filed under; one bad entry rejects the request and records nothing.",+ "operationId": "putV2Record credential picks for this chat",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Session Id" }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CredentialSelectionRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "additionalProperties": true,+ "title": "Response Putv2Record Credential Picks For This Chat"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Session or credential not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/chat/sessions/{session_id}/desktop": {"post": {"tags": ["v2", "chat", "chat"],@@ -20021,6 +20074,21 @@"title": "CredentialRejection","description": "A stored credential that the provider refused at use time."},+ "CredentialSelectionRequest": {+ "properties": {+ "selections": {+ "additionalProperties": { "type": "string" },+ "type": "object",+ "maxProperties": 20,+ "title": "Selections",+ "description": "Provider slug to credential id."+ }+ },+ "type": "object",+ "required": ["selections"],+ "title": "CredentialSelectionRequest",+ "description": "The credential the user picked for each provider on a connect card."+ },"CredentialsDeletionNeedsConfirmationResponse": {"properties": {"deleted": {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 7c77b21a64..3a78f1beec 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@@ -81,7 +81,12 @@ export function ConnectCredentialDialog({const offered = existing?.credentials ?? [];const showExisting = offered.length > 0 && !addingNew;- const chosen = offered.find((c) => c.id === chosenId) ?? offered[0];+ const isChoosing = existing?.purpose === "choose";+ // 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 =+ offered.find((c) => c.id === chosenId) ??+ (isChoosing ? undefined : offered[0]);function resetAll() {reset();@@ -142,13 +147,14 @@ export function ConnectCredentialDialog({><Dialog.Content><div className="flex flex-col gap-5 pb-2">- {showExisting && chosen ? (+ {showExisting ? (<ExistingCredentialsViewprovider={provider}displayName={displayName}credentials={offered}- selectedId={chosen.id}+ selectedId={chosen?.id ?? null}onSelect={setChosenId}+ purpose={existing?.purpose}/>) : (<ConnectMethodView@@ -184,9 +190,14 @@ export function ConnectCredentialDialog({variant="primary"size="small"loading={existing?.isPending}+ disabled={!chosen}onClick={handleUseExisting}>- {existing?.isPending ? "Granting…" : "Use existing"}+ {existing?.isPending+ ? "Granting…"+ : 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 dda506a795..6ae3433d22 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@@ -482,4 +482,35 @@ describe("ConnectCredentialDialog with existing accounts", () => {expect(screen.queryByTestId("connect-method-view")).toBeNull();expect(screen.getByText("Use existing")).toBeDefined();});++ it("pre-selects nothing when the user is choosing between their own accounts", async () => {+ const existing = { ...offer(), purpose: "choose" as const };+ renderDialog({ existing });++ expect(screen.getByText("Choose a GitHub account")).toBeDefined();+ expect(screen.queryByText(/this expert/i)).toBeNull();+ for (const radio of screen.getAllByRole("radio")) {+ expect(radio.getAttribute("aria-checked")).toBe("false");+ }+ // Nothing is picked for the user, so there is nothing to confirm yet.+ expect(+ screen.getByText("Use this account").closest("button")?.disabled,+ ).toBe(true);++ fireEvent.click(screen.getByText("Personal GitHub"));+ fireEvent.click(screen.getByText("Use this account"));++ await waitFor(() =>+ expect(existing.onUse).toHaveBeenCalledWith(accounts[1]),+ );+ });++ it("keeps the expert grant wording and its default selection", () => {+ renderDialog({ existing: offer() });++ expect(screen.getByText("Give this expert access to GitHub")).toBeDefined();+ expect(screen.getAllByRole("radio")[0].getAttribute("aria-checked")).toBe(+ "true",+ );+ });});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 330eae586f..16fd2fe142 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@@ -11,8 +11,9 @@ interface Props {provider: string;displayName: string;credentials: ExistingCredential[];- selectedId: string;+ selectedId: string | null;onSelect: (id: string) => void;+ purpose?: "grant" | "choose";}// The step before the connect methods when the account already has a@@ -24,6 +25,7 @@ export function ExistingCredentialsView({credentials,selectedId,onSelect,+ purpose = "grant",}: Props) {return (<div className="flex flex-col gap-5 pt-2">@@ -46,11 +48,14 @@ export function ExistingCredentialsView({<div className="flex flex-col gap-1.5 text-center"><Text variant="h3" className="!text-[1.25rem] text-zinc-900">- Give this expert access to {displayName}+ {purpose === "choose"+ ? `Choose a ${displayName} account`+ : `Give this expert access to ${displayName}`}</Text><Text variant="body" className="!text-zinc-500">- Your account is already connected, but this expert can't use it- yet. Pick an account to share, or add a new one.+ {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."}</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 67d6fc9dca..dcbc5c29d6 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@@ -13,4 +13,8 @@ export interface ExistingCredentialsOffer {onUse: (credential: ExistingCredential) => Promise<boolean>;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";}