Skip to content

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): grant access from the connect card in expert chats (#14417)

Abhimanyu Yadave45aa3360059
diff --git a/autogpt_platform/backend/backend/api/features/experts/credentials_test.py b/autogpt_platform/backend/backend/api/features/experts/credentials_test.py
index 44bc4d53c0..1eba3f75f6 100644
--- a/autogpt_platform/backend/backend/api/features/experts/credentials_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/credentials_test.py
@@ -204,6 +204,103 @@ async def test_a_run_with_no_credentials_skips_the_lookup_entirely(
accessor.assert_not_called()
+async def test_derivation_includes_picker_credentials_the_user_owns(
+ mocker: pytest_mock.MockFixture,
+):
+ """A ``_credentials_id`` embedded in a picker field is enforced at run time,
+ so the seed must offer it or every Drive-backed expert workflow fails."""
+ node = SimpleNamespace(
+ block=SimpleNamespace(
+ input_schema=SimpleNamespace(
+ get_auto_credentials_fields=lambda: {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ )
+ ),
+ input_default={
+ "spreadsheet": {"_credentials_id": "cred-drive", "name": "sheet"},
+ "other": {"_credentials_id": "cred-foreign", "name": "not mine"},
+ },
+ )
+ mocker.patch(
+ "backend.data.graph.get_graph",
+ return_value=SimpleNamespace(
+ nodes=[], sub_graphs=[SimpleNamespace(nodes=[node])]
+ ),
+ )
+ mocker.patch(
+ "backend.copilot.tools.utils.match_user_credentials_to_graph",
+ AsyncMock(return_value=({}, {})),
+ )
+ mocker.patch(
+ "backend.api.features.experts.credentials._user_credentials",
+ AsyncMock(return_value=[_api_key_credential("cred-drive", "google")]),
+ )
+ expert = SimpleNamespace(
+ id="expert-1",
+ Workflows=[
+ SimpleNamespace(
+ id="wf-1",
+ LibraryAgent=SimpleNamespace(agentGraphId="g1", agentGraphVersion=1),
+ )
+ ],
+ )
+
+ derived, is_complete = await _derive_from_workflows("user-1", expert) # type: ignore[arg-type]
+
+ assert derived == {"cred-drive": "google"}
+ assert is_complete is True
+
+
+async def test_a_failed_credential_read_leaves_the_seed_pending(
+ mocker: pytest_mock.MockFixture,
+):
+ node = SimpleNamespace(
+ block=SimpleNamespace(
+ input_schema=SimpleNamespace(
+ get_auto_credentials_fields=lambda: {
+ "credentials": {
+ "field_name": "sheet",
+ "config": {"provider": "google"},
+ }
+ }
+ )
+ ),
+ input_default={"sheet": {"_credentials_id": "cred-drive"}},
+ )
+ mocker.patch(
+ "backend.data.graph.get_graph",
+ return_value=SimpleNamespace(nodes=[node], sub_graphs=[]),
+ )
+ mocker.patch(
+ "backend.copilot.tools.utils.match_user_credentials_to_graph",
+ AsyncMock(return_value=({}, {})),
+ )
+ mocker.patch(
+ "backend.api.features.experts.credentials._user_credentials",
+ AsyncMock(side_effect=RuntimeError("redis is down")),
+ )
+ expert = SimpleNamespace(
+ id="expert-1",
+ Workflows=[
+ SimpleNamespace(
+ id="wf-1",
+ LibraryAgent=SimpleNamespace(agentGraphId="g1", agentGraphVersion=1),
+ )
+ ],
+ )
+
+ derived, is_complete = await _derive_from_workflows("user-1", expert) # type: ignore[arg-type]
+
+ assert derived == {}
+ assert is_complete is False
+
+
@pytest.mark.asyncio
async def test_settling_the_seed_stamps_even_when_derivation_was_incomplete(
mocker: pytest_mock.MockFixture,
diff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
index fab3cd927b..142c63840f 100644
--- a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
@@ -23,6 +23,7 @@ from backend.data.model import CredentialsFieldInfo, CredentialsType
from backend.integrations.providers import ProviderName
from .base import BaseTool
+from .expert_scope import annotate_expert_grants
class ConnectIntegrationTool(BaseTool):
@@ -157,8 +158,7 @@ class ConnectIntegrationTool(BaseTool):
if session.expert_id is not None:
message_parts.append(
"Note: a credential connected here belongs to the account and "
- "still needs to be granted to this expert before it can use it; "
- "the next run will name it if so."
+ "is granted to this expert automatically."
)
# Route the single-provider entry through the shared serializer
@@ -185,6 +185,10 @@ class ConnectIntegrationTool(BaseTool):
# generic serializer produces from `field_key`.
missing_credentials[field_key]["title"] = f"{display_name} Credentials"
missing_credentials[field_key]["provider_name"] = display_name
+ if user_id:
+ missing_credentials = await annotate_expert_grants(
+ user_id, session.expert_id, missing_credentials
+ )
return SetupRequirementsResponse(
type=ResponseType.SETUP_REQUIREMENTS,
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
index 022dee1c00..0c6c7f720d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
@@ -9,15 +9,18 @@ expert's resources.
import logging
from enum import Enum
+from typing import Any, cast
from pydantic import BaseModel, Field
from backend.copilot.model import ChatSession
from backend.data.db_accessors import experts_db
-from backend.data.model import Credentials
+from backend.data.model import Credentials, CredentialsFieldInfo, CredentialsType
from backend.integrations.credentials_store import is_system_credential
+from backend.integrations.providers import ProviderName
from .models import AgentSavedResponse, ErrorResponse, ToolResponseBase
+from .utils import find_matching_credential
logger = logging.getLogger(__name__)
@@ -211,6 +214,60 @@ async def _ungranted_credentials(
]
+async def annotate_expert_grants(
+ user_id: str, expert_id: str | None, missing: dict[str, Any]
+) -> dict[str, Any]:
+ """Tell the setup card which expert is asking and what it could be granted.
+
+ Each missing credential gains an ``expert_grant`` entry so the card can
+ offer "Grant access" for an account credential the expert lacks, and can
+ grant a freshly connected one to the expert instead of leaving it
+ account-only. Returns a new mapping; personal AutoPilot passes through.
+ """
+ if expert_id is None or not missing:
+ return missing
+ providers = {
+ provider_slug(entry.get("provider", "")) for entry in missing.values()
+ } - {""}
+ candidates = await _ungranted_credentials(user_id, expert_id, providers)
+ return {
+ key: {
+ **entry,
+ "expert_grant": {
+ "expert_id": expert_id,
+ "credentials": [
+ {
+ "id": c.id,
+ "title": c.title or str(c.provider),
+ "type": str(c.type),
+ }
+ for c in candidates
+ if _satisfies_requirement(c, entry)
+ ],
+ },
+ }
+ for key, entry in missing.items()
+ }
+
+
+def _satisfies_requirement(credential: Credentials, entry: dict[str, Any]) -> bool:
+ """The same provider/type/scope/host predicate a run applies when matching,
+ so an offered grant is one the next run will accept."""
+ provider = provider_slug(entry.get("provider", ""))
+ types = entry.get("types") or ([entry["type"]] if entry.get("type") else [])
+ if not provider or not types:
+ return False
+ scopes = entry.get("scopes") or None
+ field_info = CredentialsFieldInfo[ProviderName, CredentialsType](
+ credentials_provider=frozenset([cast(ProviderName, provider)]),
+ credentials_types=frozenset(cast(CredentialsType, t) for t in types),
+ credentials_scopes=frozenset(scopes) if scopes else None,
+ discriminator=entry.get("discriminator"),
+ discriminator_values=set(entry.get("discriminator_values") or []),
+ )
+ return find_matching_credential([credential], field_info) is not None
+
+
async def ungranted_credential_hint(
user_id: str, expert_id: str | None, providers: set[str]
) -> str:
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py
index c80f15ddb5..38a6d2ec36 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py
@@ -1,6 +1,7 @@
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from pydantic import SecretStr
from backend.copilot.model import ChatSession
from backend.copilot.tools.expert_scope import (
@@ -182,6 +183,79 @@ async def test_hint_lists_owned_but_ungranted_credentials(experts):
assert none == "" and personal == ""
+async def test_missing_credentials_are_annotated_with_expert_grants(experts):
+ from backend.copilot.tools.expert_scope import annotate_expert_grants
+
+ def cred(id: str, type: str, scopes: list[str]):
+ return MagicMock(id=id, provider="github", title=id, type=type, scopes=scopes)
+
+ store = MagicMock()
+ store.get_all_creds = AsyncMock(
+ return_value=[
+ cred("granted-cred", "oauth2", ["repo"]),
+ cred("spare-cred", "oauth2", ["repo"]),
+ cred("wrong-type", "api_key", []),
+ cred("narrow-scope", "oauth2", ["read:user"]),
+ ]
+ )
+ missing = {
+ "github_credentials": {
+ "provider": "github",
+ "types": ["oauth2"],
+ "scopes": ["repo"],
+ }
+ }
+ with patch(
+ "backend.integrations.creds_manager.IntegrationCredentialsManager",
+ return_value=MagicMock(store=store),
+ ):
+ annotated = await annotate_expert_grants("user-1", "expert-a", missing)
+ untouched = await annotate_expert_grants("user-1", None, missing)
+ grant = annotated["github_credentials"]["expert_grant"]
+ assert grant["expert_id"] == "expert-a"
+ assert [c["id"] for c in grant["credentials"]] == ["spare-cred"]
+ assert grant["credentials"][0]["type"] == "oauth2"
+ assert "expert_grant" not in missing["github_credentials"]
+ assert untouched is missing
+
+
+async def test_grant_candidates_must_match_the_requested_mcp_server(experts):
+ from backend.copilot.tools.expert_scope import annotate_expert_grants
+ from backend.data.model import OAuth2Credentials
+
+ def mcp_cred(id: str, server_url: str):
+ return OAuth2Credentials(
+ id=id,
+ provider="mcp",
+ title=id,
+ access_token=SecretStr("token"),
+ scopes=[],
+ metadata={"mcp_server_url": server_url},
+ )
+
+ store = MagicMock()
+ store.get_all_creds = AsyncMock(
+ return_value=[
+ mcp_cred("right-server", "https://mcp.example.com/sse"),
+ mcp_cred("other-server", "https://mcp.other.com/sse"),
+ ]
+ )
+ missing = {
+ "mcp_credentials": {
+ "provider": "mcp",
+ "types": ["oauth2"],
+ "discriminator_values": ["https://mcp.example.com/sse"],
+ }
+ }
+ with patch(
+ "backend.integrations.creds_manager.IntegrationCredentialsManager",
+ return_value=MagicMock(store=store),
+ ):
+ annotated = await annotate_expert_grants("user-1", "expert-a", missing)
+ grant = annotated["mcp_credentials"]["expert_grant"]
+ assert [c["id"] for c in grant["credentials"]] == ["right-server"]
+
+
async def test_agent_built_by_expert_settles_grants_before_install(experts):
order: list[str] = []
experts.settle_credential_seed.side_effect = lambda *_: order.append("settle")
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index fc643e88e3..b1f6f0f2b5 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -50,7 +50,11 @@ from backend.util.feature_flag import Flag, is_feature_enabled
from backend.util.timezone_utils import get_user_timezone_or_utc
from backend.util.type import coerce_inputs_to_schema
-from .expert_scope import provider_slug, ungranted_credential_hint
+from .expert_scope import (
+ annotate_expert_grants,
+ provider_slug,
+ ungranted_credential_hint,
+)
from .models import (
BlockOutputResponse,
CredentialRejection,
@@ -898,8 +902,12 @@ async def prepare_block_for_execution(
dry_run or validate_only
):
credentials_fields_info = _resolve_discriminated_credentials(block, input_data)
- missing_creds_dict = build_missing_credentials_from_field_info(
- credentials_fields_info, set(matched_credentials.keys())
+ missing_creds_dict = await annotate_expert_grants(
+ user_id,
+ session.expert_id,
+ build_missing_credentials_from_field_info(
+ credentials_fields_info, set(matched_credentials.keys())
+ ),
)
missing_creds_list = list(missing_creds_dict.values())
if missing_credentials:
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
index 1717883c28..e8631b2b1d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
@@ -44,6 +44,7 @@ from .execution_utils import (
wait_for_execution,
)
from .expert_scope import (
+ annotate_expert_grants,
provider_slug,
require_installed_workflow,
ungranted_credential_hint,
@@ -552,11 +553,13 @@ class RunAgentTool(BaseTool):
trigger_info=trigger_info,
)
- def _build_setup_requirements_from_validation_error(
+ async def _build_setup_requirements_from_validation_error(
self,
graph: GraphModel,
error: GraphValidationError,
session_id: str,
+ user_id: str,
+ expert_id: str | None,
inputs: dict[str, Any] | None = None,
) -> SetupRequirementsResponse | None:
"""Turn a credential-only ``GraphValidationError`` into the inline
@@ -577,7 +580,9 @@ class RunAgentTool(BaseTool):
# creds are now invalid, so narrowing to `error.node_errors` would
# leak the stale mapping. Passing ``None`` means no field is
# treated as "already connected".
- credentials_dict = build_missing_credentials_from_graph(graph, None)
+ credentials_dict = await annotate_expert_grants(
+ user_id, expert_id, build_missing_credentials_from_graph(graph, None)
+ )
return SetupRequirementsResponse(
message=(
f"Agent '{graph.name}' has credentials that are missing or "
@@ -605,13 +610,14 @@ class RunAgentTool(BaseTool):
graph_version=graph.version,
)
- def _handle_graph_validation_race(
+ async def _handle_graph_validation_race(
self,
error: GraphValidationError,
graph: GraphModel,
user_id: str,
session_id: str,
action_verb: str,
+ expert_id: str | None = None,
inputs: dict[str, Any] | None = None,
) -> ToolResponseBase:
"""Handle a ``GraphValidationError`` that slipped past the prereq check.
@@ -627,10 +633,12 @@ class RunAgentTool(BaseTool):
graph.id,
{node_id: list(fields) for node_id, fields in error.node_errors.items()},
)
- creds_setup = self._build_setup_requirements_from_validation_error(
+ creds_setup = await self._build_setup_requirements_from_validation_error(
graph=graph,
error=error,
session_id=session_id,
+ user_id=user_id,
+ expert_id=expert_id,
inputs=inputs,
)
if creds_setup is not None:
@@ -690,8 +698,10 @@ class RunAgentTool(BaseTool):
# --- Credential gate ---
if missing_creds:
requirements_creds_dict = build_missing_credentials_from_graph(graph, None)
- missing_credentials_dict = build_missing_credentials_from_graph(
- graph, graph_credentials
+ missing_credentials_dict = await annotate_expert_grants(
+ user_id,
+ expert_id,
+ build_missing_credentials_from_graph(graph, graph_credentials),
)
return graph_credentials, SetupRequirementsResponse(
message=self._build_inputs_message(graph, MSG_WHAT_VALUES_TO_USE)
@@ -966,12 +976,13 @@ class RunAgentTool(BaseTool):
trigger_ref=session_id,
)
except GraphValidationError as e:
- return self._handle_graph_validation_race(
+ return await self._handle_graph_validation_race(
error=e,
graph=graph,
user_id=user_id,
session_id=session_id,
action_verb="running",
+ expert_id=session.expert_id,
inputs=inputs,
)
@@ -1290,12 +1301,13 @@ class RunAgentTool(BaseTool):
expert_id=session.expert_id,
)
except GraphValidationError as e:
- return self._handle_graph_validation_race(
+ return await self._handle_graph_validation_race(
error=e,
graph=graph,
user_id=user_id,
session_id=session_id,
action_verb="scheduling",
+ expert_id=session.expert_id,
inputs=inputs,
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
index df55327ad8..11e3c06222 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
@@ -580,10 +580,12 @@ async def test_build_setup_requirements_from_credential_validation_error(
)
# Race path: all credential fields shown as missing.
- response = tool._build_setup_requirements_from_validation_error(
+ response = await tool._build_setup_requirements_from_validation_error(
graph=graph,
error=error,
session_id="test-session",
+ user_id="test-user",
+ expert_id=None,
)
assert isinstance(response, SetupRequirementsResponse)
@@ -620,10 +622,12 @@ async def test_build_setup_requirements_shows_all_creds_missing_in_race(
node_errors={"some-node-id": {"credentials": "These credentials are required"}},
)
- response = tool._build_setup_requirements_from_validation_error(
+ response = await tool._build_setup_requirements_from_validation_error(
graph=graph,
error=error,
session_id="test-session",
+ user_id="test-user",
+ expert_id=None,
)
assert isinstance(response, SetupRequirementsResponse)
@@ -649,10 +653,12 @@ async def test_build_setup_requirements_returns_none_for_empty_node_errors(
node_errors={},
)
- response = tool._build_setup_requirements_from_validation_error(
+ response = await tool._build_setup_requirements_from_validation_error(
graph=graph,
error=error,
session_id="test-session",
+ user_id="test-user",
+ expert_id=None,
)
assert response is None
@@ -672,10 +678,12 @@ async def test_build_setup_requirements_returns_none_for_non_credential_error(
node_errors={"some-node-id": {"url": "Input field 'url' is required"}},
)
- response = tool._build_setup_requirements_from_validation_error(
+ response = await tool._build_setup_requirements_from_validation_error(
graph=graph,
error=error,
session_id="test-session",
+ user_id="test-user",
+ expert_id=None,
)
assert response is None
@@ -698,10 +706,12 @@ async def test_build_setup_requirements_returns_none_for_mixed_errors(
},
)
- response = tool._build_setup_requirements_from_validation_error(
+ response = await tool._build_setup_requirements_from_validation_error(
graph=graph,
error=error,
session_id="test-session",
+ user_id="test-user",
+ expert_id=None,
)
assert response is None
@@ -1792,3 +1802,40 @@ async def test_run_preset_refuses_uninstalled_workflow_for_expert():
assert isinstance(result, ErrorResponse)
assert result.error == "workflow_not_installed"
add_exec.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_validation_error_card_carries_expert_grants(
+ setup_firecrawl_test_data,
+):
+ """The race-path card is an expert connect card like every other one, so
+ the row must not fall back to the account's credential."""
+ graph = setup_firecrawl_test_data["graph"]
+ tool = RunAgentTool()
+ error = GraphValidationError(
+ message="Graph is invalid",
+ node_errors={"some-node-id": {"credentials": "These credentials are required"}},
+ )
+
+ async def annotate(user_id, expert_id, missing):
+ return {
+ key: {**entry, "expert_grant": {"expert_id": expert_id, "credentials": []}}
+ for key, entry in missing.items()
+ }
+
+ with patch(
+ "backend.copilot.tools.run_agent.annotate_expert_grants", side_effect=annotate
+ ):
+ response = await tool._build_setup_requirements_from_validation_error(
+ graph=graph,
+ error=error,
+ session_id="test-session",
+ user_id="test-user",
+ expert_id="expert-a",
+ )
+
+ assert isinstance(response, SetupRequirementsResponse)
+ missing = response.setup_info.user_readiness.missing_credentials
+ assert all(
+ entry["expert_grant"]["expert_id"] == "expert-a" for entry in missing.values()
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
index feb4132c6d..4b7a4ce85e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -36,6 +36,7 @@ from backend.util.request import (
)
from .base import BaseTool
+from .expert_scope import annotate_expert_grants
from .models import (
CredentialRejection,
ErrorResponse,
@@ -241,16 +242,20 @@ class RunMCPToolTool(BaseTool):
if creds is None and allowed_ids is not None:
ungranted = await auto_lookup_mcp_credential(user_id, normalized_url)
if ungranted is not None:
- return ErrorResponse(
+ # The card rather than a bare error: the expert can ask for the
+ # credential from it, which is what this PR adds.
+ return await self._build_setup_requirements(
+ server_url,
+ session_id,
+ user_id=user_id,
+ expert_id=session.expert_id,
message=(
f"The account's credential for {server_host(server_url)} "
f"(credential_id={ungranted.id}) is not granted to this "
- "expert. Ask the user to grant it on the expert's "
- "Integrations page or from personal AutoPilot with "
+ "expert. Ask the user to grant it from the card, on the "
+ "expert's Integrations page, or from personal AutoPilot with "
"grant_expert_credential."
),
- error="credential_not_granted",
- session_id=session_id,
)
client = (
MCPClient(server_url, authorization=mcp_authorization_header(creds))
@@ -321,8 +326,13 @@ class RunMCPToolTool(BaseTool):
# ``close`` is best-effort and swallows its own
# errors.
await probe_client.close()
- return self._build_setup_requirements(
- server_url, session_id, connected=connected, rejection=rejection
+ return await self._build_setup_requirements(
+ server_url,
+ session_id,
+ connected=connected,
+ rejection=rejection,
+ user_id=user_id,
+ expert_id=session.expert_id,
)
if client is None:
@@ -364,11 +374,13 @@ class RunMCPToolTool(BaseTool):
# not a rejection, so it stores, returns 2xx and greens the
# pill — and the next call 403s again. Reporting it as
# connected breaks that loop.
- return self._build_setup_requirements(
+ return await self._build_setup_requirements(
server_url,
session_id,
connected=creds is not None and not credential_rejected,
rejection=rejected,
+ user_id=user_id,
+ expert_id=session.expert_id,
)
host = server_host(server_url)
logger.warning("MCP HTTP error for %s: status=%s", host, e.status_code)
@@ -576,12 +588,16 @@ class RunMCPToolTool(BaseTool):
None,
)
- def _build_setup_requirements(
+ async def _build_setup_requirements(
self,
server_url: str,
session_id: str,
connected: bool = False,
rejection: CredentialRejection | None = None,
+ *,
+ user_id: str | None = None,
+ expert_id: str | None = None,
+ message: str | None = None,
) -> SetupRequirementsResponse | ErrorResponse:
"""Build a SetupRequirementsResponse for an MCP server credential.
@@ -590,6 +606,10 @@ class RunMCPToolTool(BaseTool):
instead of the bare Connect button. Used by the
``surface_connect_card`` path so the user always gets visible
feedback even when stored creds are still valid.
+
+ In an expert session the missing credential carries ``expert_grant``
+ so the card can grant an existing account credential to the expert or
+ grant a freshly connected one, the same as every other connect card.
"""
mcp_block = MCPToolBlock()
credentials_fields_info = mcp_block.input_schema.get_credentials_fields_info()
@@ -598,7 +618,7 @@ class RunMCPToolTool(BaseTool):
# can match the credential to the correct OAuth provider/server.
for field_info in credentials_fields_info.values():
if field_info.discriminator == "server_url":
- field_info.discriminator_values.add(server_url)
+ field_info.discriminator_values.add(normalize_mcp_url(server_url))
missing_creds_dict = build_missing_credentials_from_field_info(
credentials_fields_info, matched_keys=set()
@@ -618,20 +638,29 @@ class RunMCPToolTool(BaseTool):
session_id=session_id,
)
+ if user_id is not None and not connected:
+ missing_creds_dict = await annotate_expert_grants(
+ user_id, expert_id, missing_creds_dict
+ )
missing_creds_list = list(missing_creds_dict.values())
host = server_host(server_url)
service = _service_name(host)
- if rejection:
- status = f" (HTTP {rejection.status_code})" if rejection.status_code else ""
- message = (
- f"{service} rejected the saved credential{status}. "
- "Sign in again to continue."
- )
- elif connected:
- message = f"You're connected to {service}. Use Reconnect to swap accounts."
- else:
- message = f"To continue, sign in to {service} and approve access."
+ if message is None:
+ if rejection:
+ status = (
+ f" (HTTP {rejection.status_code})" if rejection.status_code else ""
+ )
+ message = (
+ f"{service} rejected the saved credential{status}. "
+ "Sign in again to continue."
+ )
+ elif connected:
+ message = (
+ f"You're connected to {service}. Use Reconnect to swap accounts."
+ )
+ else:
+ message = f"To continue, sign in to {service} and approve access."
return SetupRequirementsResponse(
message=message,
session_id=session_id,
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.py
index ff928d7d96..923389345d 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
@@ -30,7 +30,7 @@ from backend.util.exceptions import (
)
from .base import BaseTool
-from .expert_scope import require_installed_workflow
+from .expert_scope import annotate_expert_grants, require_installed_workflow
from .models import (
ErrorResponse,
ResponseType,
@@ -374,7 +374,11 @@ class SetupAgentWebhookTriggerTool(BaseTool):
for key, cred in effective.items()
if not (key == trigger_cred_key and trigger_cred_key not in selection)
}
- card_missing = build_missing_credentials_from_graph(graph, matched_for_card)
+ card_missing = await annotate_expert_grants(
+ user_id,
+ expert_id,
+ build_missing_credentials_from_graph(graph, matched_for_card),
+ )
if card_missing:
return {}, self._build_card(graph, card_missing, session_id)
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
index dab5fa8f0a..ca2b412f4c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pydantic import SecretStr
-from backend.blocks.mcp.helpers import server_host
+from backend.blocks.mcp.helpers import normalize_mcp_url, server_host
from backend.copilot.sdk.file_ref import FileRefExpansionError
from backend.data.model import OAuth2Credentials
@@ -1212,13 +1212,18 @@ async def test_credential_lookup_normalizes_trailing_slash():
async def test_build_setup_requirements_returns_setup_response():
"""_build_setup_requirements should return a SetupRequirementsResponse."""
tool = RunMCPToolTool()
- result = tool._build_setup_requirements(
+ result = await tool._build_setup_requirements(
server_url=_SERVER_URL,
session_id="test-session",
)
assert isinstance(result, SetupRequirementsResponse)
assert result.setup_info.agent_id == _SERVER_URL
assert "sign in" in result.message.lower()
+ missing = result.setup_info.user_readiness.missing_credentials
+ assert all(
+ entry["discriminator_values"] == [normalize_mcp_url(_SERVER_URL)]
+ for entry in missing.values()
+ )
# ---------------------------------------------------------------------------
@@ -1474,9 +1479,13 @@ async def test_rejected_card_differs_from_never_connected_by_the_rejection():
@pytest.mark.asyncio(loop_scope="session")
async def test_an_ungranted_mcp_credential_is_refused_for_an_expert():
+ """Still refused, but with the card rather than a bare error: this PR lets
+ the user grant the credential from it, so an ErrorResponse would leave the
+ expert with nothing to act on. The refusal is the message, not the type."""
response = await _run_with_grants([])
- assert isinstance(response, ErrorResponse)
- assert response.error == "credential_not_granted"
+ assert isinstance(response, SetupRequirementsResponse)
+ assert "not granted to this expert" in response.message
+ assert not response.setup_info.user_readiness.ready_to_run
@pytest.mark.asyncio(loop_scope="session")
@@ -1525,3 +1534,111 @@ async def _run_with_grants(allowed: list[str]):
session=make_session(_USER_ID, expert_id="expert-a"),
server_url=_SERVER_URL,
)
+
+
+# ---------------------------------------------------------------------------
+# Expert grants
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_ungranted_stored_credential_returns_a_grantable_connect_card():
+ """An expert whose account already holds the server's credential gets the
+ connect card with ``expert_grant`` so the user can grant it, not a bare
+ error that leaves the expert stuck."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID, expert_id="expert-a")
+ stored = MagicMock()
+ stored.id = "mcp-cred"
+
+ experts = MagicMock()
+ experts.expert_allowed_credential_ids = AsyncMock(return_value=[])
+
+ # The lookup narrows by allowed_ids before ranking, so the granted-set call
+ # finds nothing and the unfiltered one still sees the account's credential.
+ async def lookup(_user_id, _url, allowed_ids=None):
+ return None if allowed_ids is not None else stored
+
+ async def annotate(user_id, expert_id, missing):
+ return {
+ key: {
+ **entry,
+ "expert_grant": {
+ "expert_id": expert_id,
+ "credentials": [
+ {"id": "mcp-cred", "title": "Fetch", "type": "oauth2"}
+ ],
+ },
+ }
+ for key, entry in missing.items()
+ }
+
+ with (
+ patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host",
+ new_callable=AsyncMock,
+ ),
+ patch("backend.copilot.tools.run_mcp_tool.experts_db", return_value=experts),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new=lookup,
+ ),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.annotate_expert_grants",
+ side_effect=annotate,
+ ) as mock_annotate,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID, session=session, server_url=_SERVER_URL
+ )
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert "not granted to this expert" in response.message
+ mock_annotate.assert_awaited_once()
+ assert mock_annotate.await_args_list[0].args[:2] == (_USER_ID, "expert-a")
+ missing = response.setup_info.user_readiness.missing_credentials
+ assert all(
+ entry["expert_grant"]["credentials"][0]["id"] == "mcp-cred"
+ for entry in missing.values()
+ )
+
+
[email protected](loop_scope="session")
+async def test_auth_required_card_is_annotated_for_the_expert():
+ """A 401 in an expert chat produces a card that grants the fresh sign-in
+ to the expert, the same as run_agent and connect_integration."""
+ from backend.util.request import HTTPClientError
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID, expert_id="expert-a")
+ mock_client = AsyncMock()
+ mock_client.initialize = AsyncMock(
+ side_effect=HTTPClientError("Unauthorized", status_code=401)
+ )
+ experts = MagicMock()
+ experts.expert_allowed_credential_ids = AsyncMock(return_value=[])
+
+ with (
+ patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host",
+ new_callable=AsyncMock,
+ ),
+ patch("backend.copilot.tools.run_mcp_tool.experts_db", return_value=experts),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
+ patch("backend.copilot.tools.run_mcp_tool.MCPClient", return_value=mock_client),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.annotate_expert_grants",
+ new_callable=AsyncMock,
+ side_effect=lambda user_id, expert_id, missing: missing,
+ ) as mock_annotate,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID, session=session, server_url=_SERVER_URL
+ )
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert mock_annotate.await_args_list[0].args[:2] == (_USER_ID, "expert-a")
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.py
index bbbc1f183e..45aac6223b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py
@@ -351,7 +351,8 @@ def find_matching_credential(
available_creds: list[Credentials],
field_info: CredentialsFieldInfo,
) -> Credentials | None:
- """Find a credential that matches the required provider, type, scopes, and host."""
+ """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
@@ -363,6 +364,10 @@ def find_matching_credential(
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
@@ -424,27 +429,8 @@ async def match_user_credentials_to_graph(
_,
_,
) in aggregated_creds.items():
- # Find first matching credential by provider, type, scopes, and host/URL
- matching_cred = next(
- (
- cred
- for cred in available_creds
- if cred.provider in credential_requirements.provider
- and cred.type in credential_requirements.supported_types
- and (
- cred.type != "oauth2"
- or _credential_has_required_scopes(cred, credential_requirements)
- )
- and (
- cred.type != "host_scoped"
- or _credential_is_for_host(cred, credential_requirements)
- )
- and (
- cred.provider != ProviderName.MCP
- or _credential_is_for_mcp_server(cred, credential_requirements)
- )
- ),
- None,
+ matching_cred = find_matching_credential(
+ available_creds, credential_requirements
)
if matching_cred:
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx
index 0dca7fc774..0b0e448eee 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
@@ -1,31 +1,56 @@
"use client";
+import { useGrantExpertCredentials } from "@/app/api/__generated__/endpoints/experts/experts";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
import { Button } from "@/components/atoms/Button/Button";
import { Icon } from "@/components/atoms/Icon/Icon";
import { ConnectCredentialDialog } from "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog";
import { findSavedUserCredentialByProviderAndType } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";
import { filterSystemCredentials } from "@/components/contextual/CredentialsInput/helpers";
import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
import {
CredentialsProvidersContext,
+ type CredentialsProviderData,
type CredentialsProvidersContextType,
} from "@/providers/agent-credentials/credentials-provider";
import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";
-import { useContext, useEffect, useState } from "react";
+import { useContext, useEffect, useRef, useState } from "react";
import type { ConnectorRow as Row } from "./helpers";
+import { useExpertCredentialSelection } from "./useExpertCredentialSelection";
+import type { ExpertGrant } from "../SetupRequirementsCard/helpers";
interface Props {
row: Row;
}
+type Grantable = ExpertGrant["credentials"][number];
+type SavedCredential = CredentialsProviderData["savedCredentials"][number];
+
+const UNUSABLE_ACCOUNT_ERROR =
+ "That account is missing the access this needs. Try connecting again.";
+const GRANT_FAILED_ERROR = "Couldn't grant access. Try again.";
+
export function ConnectorRow({ row }: Props) {
const [isDialogOpen, setDialogOpen] = useState(false);
+ const [awaitingGrant, setAwaitingGrant] = useState(false);
+ const [grantError, setGrantError] = useState<string | null>(null);
+ // A credential connected from this row while an expert is asking. It stays
+ // here until its grant succeeds, so a failed grant is retried from the
+ // dialog's existing accounts instead of forcing another sign-in.
+ const [connected, setConnected] = useState<Grantable | null>(null);
+ // Credential ids that existed when Connect was clicked, so the grant goes
+ // to the account the user just added rather than one they already had.
+ // `null` while the provider's accounts were still loading, where a diff
+ // would call every account the user already had new.
+ const knownIds = useRef<Set<string> | null>(null);
const allProviders = useContext(CredentialsProvidersContext);
+ const { mutateAsync: grantCredentials, isPending: isGranting } =
+ useGrantExpertCredentials();
+ const expertGrant = row.expertGrant;
+ const grantedCredentials = useExpertCredentialSelection(row, allProviders);
- // A credential the user already had — or one they just created in the
- // dialog — satisfies this row, so pick it up as soon as the providers
- // query refreshes rather than making them choose it again.
const savedCredential = findSavedUserCredentialByProviderAndType(
row.schema.credentials_provider ?? [],
row.schema.credentials_types ?? [],
@@ -34,7 +59,64 @@ export function ConnectorRow({ row }: Props) {
row.schema.discriminator_values,
);
+ async function grant(
+ credential: Grantable,
+ candidate?: SavedCredential,
+ ): Promise<boolean> {
+ if (!expertGrant) return false;
+ setGrantError(null);
+ // Resolve the account before the POST: validating afterwards tells the
+ // user the grant failed while the expert already holds it.
+ const account =
+ candidate ??
+ allProviders?.[row.provider]?.savedCredentials.find(
+ (saved) => saved.id === credential.id,
+ );
+ if (!account || !grantableAmong(row, [account])) {
+ setGrantError(UNUSABLE_ACCOUNT_ERROR);
+ return false;
+ }
+ let response: Awaited<ReturnType<typeof grantCredentials>>;
+ try {
+ response = await grantCredentials({
+ expertId: expertGrant.expertId,
+ data: { credential_ids: [credential.id] },
+ });
+ } catch (error) {
+ setGrantError(
+ error instanceof ApiError ? error.message : GRANT_FAILED_ERROR,
+ );
+ return false;
+ }
+ if (!grantedCredentials.confirmGrant(credential.id, response)) {
+ setGrantError(GRANT_FAILED_ERROR);
+ return false;
+ }
+ setConnected(null);
+ row.select({
+ id: credential.id,
+ provider: row.provider,
+ type: credential.type as CredentialsMetaInput["type"],
+ title: credential.title,
+ });
+ row.onConnected();
+ return true;
+ }
+
useEffect(() => {
+ if (expertGrant) {
+ if (!awaitingGrant || row.selected || !knownIds.current) return;
+ const fresh = newlyConnectedCredential(
+ row,
+ allProviders,
+ knownIds.current,
+ );
+ if (!fresh) return;
+ setAwaitingGrant(false);
+ setConnected(fresh.grantable);
+ void grant(fresh.grantable, fresh.account);
+ return;
+ }
// Cards stream in one commit at a time, so a row's schema can widen after
// it auto-selected: a selection that no longer satisfies it must go, or
// the row reads Connected while Proceed sends a credential missing the
@@ -53,11 +135,36 @@ export function ConnectorRow({ row }: Props) {
title: savedCredential.title ?? undefined,
});
// eslint-disable-next-line react-hooks/exhaustive-deps -- row.select is rebuilt each render by the card
- }, [savedCredential?.id, row.selected, allProviders]);
+ }, [
+ savedCredential?.id,
+ row.selected,
+ allProviders,
+ awaitingGrant,
+ expertGrant?.expertId,
+ ]);
+
+ const grantableOptions = [
+ ...(connected ? [connected] : []),
+ ...(expertGrant?.credentials ?? []).filter((c) => c.id !== connected?.id),
+ ];
+ const isSatisfied = expertGrant
+ ? grantedCredentials.isSelectionGranted
+ : Boolean(row.selected);
+
+ function openDialog() {
+ knownIds.current = allProviders
+ ? new Set(
+ allProviders[row.provider]?.savedCredentials.map((c) => c.id) ?? [],
+ )
+ : null;
+ setGrantError(null);
+ setAwaitingGrant(false);
+ setDialogOpen(true);
+ }
return (
- <div className="flex items-center gap-3 px-4 py-3">
- <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-zinc-100 bg-white p-1.5">
+ <div className="flex items-center gap-3 px-4 py-2.5">
+ <span className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-zinc-100 bg-white p-1.5">
<ProviderAvatar id={row.provider} name={row.displayName} />
</span>
@@ -65,26 +172,42 @@ export function ConnectorRow({ row }: Props) {
<span className="truncate text-sm font-medium text-zinc-900">
{row.displayName}
</span>
- {row.description && (
- <span className="truncate text-sm text-zinc-500">
- {row.description}
+ {grantError && !isDialogOpen ? (
+ <span className="truncate text-xs text-red-600">{grantError}</span>
+ ) : expertGrant && !isSatisfied ? (
+ <span className="truncate text-xs text-zinc-500">
+ {grantableOptions.length > 0
+ ? "Needs this expert's access"
+ : "This expert needs its own access"}
</span>
+ ) : (
+ row.description && (
+ <span className="truncate text-xs text-zinc-500">
+ {row.description}
+ </span>
+ )
)}
</div>
- {row.selected ? (
+ {isSatisfied ? (
<span className="flex shrink-0 items-center gap-1.5 text-sm font-medium text-zinc-500">
<Icon icon={CheckmarkCircle02Icon} size={16} />
- Connected
+ {expertGrant ? "Granted" : "Connected"}
</span>
) : (
<Button
variant="primary"
size="small"
className="shrink-0"
- onClick={() => setDialogOpen(true)}
+ disabled={
+ isGranting ||
+ Boolean(
+ expertGrant && (grantedCredentials.isPending || !allProviders),
+ )
+ }
+ onClick={openDialog}
>
- Connect
+ {grantableOptions.length > 0 ? "Grant access" : "Connect"}
</Button>
)}
@@ -93,14 +216,102 @@ export function ConnectorRow({ row }: Props) {
provider={row.provider}
displayName={row.displayName}
credentialID={upgradableCredentialID(row.provider, allProviders)}
+ existing={
+ expertGrant
+ ? {
+ credentials: grantableOptions,
+ onUse: grant,
+ isPending: isGranting,
+ error: grantError,
+ }
+ : undefined
+ }
open={isDialogOpen}
onClose={() => setDialogOpen(false)}
- onConnected={row.onConnected}
+ onConnected={(credential) => {
+ if (!expertGrant) {
+ row.onConnected();
+ return;
+ }
+ // A flow that does not report its credential leaves the refresh to
+ // find the new account.
+ if (!credential) {
+ setAwaitingGrant(true);
+ return;
+ }
+ // Grant the reported credential directly: a re-auth that upgraded
+ // an existing account keeps its id, which a refresh diff would
+ // never surface. One that cannot satisfy the row is an error, not
+ // a wait.
+ const account = toSavedCredential(credential);
+ const usable = grantableAmong(row, [account]);
+ if (!usable) {
+ setGrantError(UNUSABLE_ACCOUNT_ERROR);
+ return;
+ }
+ setConnected(usable);
+ void grant(usable, account);
+ }}
/>
</div>
);
}
+/** The credential among `candidates` that satisfies `row`, shaped for a
+ * grant. Matching reads nothing but the candidates, so a row whose provider
+ * has not loaded yet is still answerable. */
+function grantableAmong(
+ row: Row,
+ candidates: SavedCredential[],
+): Grantable | null {
+ if (candidates.length === 0) return null;
+ const match = findSavedUserCredentialByProviderAndType(
+ row.schema.credentials_provider ?? [],
+ row.schema.credentials_types ?? [],
+ row.schema.credentials_scopes,
+ {
+ [row.provider]: {
+ savedCredentials: candidates,
+ } as CredentialsProviderData,
+ },
+ row.schema.discriminator_values,
+ );
+ return match
+ ? { id: match.id, title: match.title ?? row.displayName, type: match.type }
+ : null;
+}
+
+/** The API reports absent fields as null; the provider list omits them. */
+function toSavedCredential(
+ credential: CredentialsMetaResponse,
+): SavedCredential {
+ return {
+ ...credential,
+ title: credential.title ?? undefined,
+ username: credential.username ?? undefined,
+ scopes: credential.scopes ?? undefined,
+ host: credential.host ?? undefined,
+ };
+}
+
+/** The credential that satisfies `row` and did not exist before Connect was
+ * clicked, i.e. the account the user just signed in with, paired with the
+ * saved account it came from so granting it needs no second lookup — the
+ * provider list can have moved on again by then. */
+function newlyConnectedCredential(
+ row: Row,
+ allProviders: CredentialsProvidersContextType | null,
+ knownIds: Set<string>,
+): { grantable: Grantable; account: SavedCredential } | null {
+ const provider = allProviders?.[row.provider];
+ if (!provider) return null;
+ const added = provider.savedCredentials.filter((c) => !knownIds.has(c.id));
+ const grantable = grantableAmong(row, added);
+ if (!grantable) return null;
+ const account = added.find((c) => c.id === grantable.id);
+ return account ? { grantable, account } : null;
+}
+
/** The account a re-auth should upgrade in place. Signing in without it can
* grant narrower scopes than the user already had and leave a second row for
* the same provider, which no ConnectorRow can ever resolve. Only safe when
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx
index a20a8bf83f..2dd4ca5c29 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx
@@ -2,13 +2,15 @@ import {
CredentialsProvidersContext,
type CredentialsProvidersContextType,
} from "@/providers/agent-credentials/credentials-provider";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
cleanup,
fireEvent,
- render,
+ render as renderBare,
screen,
waitFor,
} from "@testing-library/react";
+import type { ReactElement, ReactNode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChainActionCard } from "../ChainActionCard";
import type {
@@ -29,6 +31,32 @@ vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
}),
}));
+vi.mock("@/app/api/__generated__/endpoints/experts/experts", () => ({
+ useListExpertCredentials: () => ({ data: [], refetch: vi.fn() }),
+ useGrantExpertCredentials: () => ({
+ mutateAsync: vi.fn(),
+ isPending: false,
+ }),
+ getListExpertCredentialsQueryKey: (expertId?: string) => [
+ `/api/experts/${expertId}/credentials`,
+ ],
+}));
+
+// ConnectorRow's expert-grant hook writes the granted list into the cache.
+const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+});
+
+function QueryWrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+function render(ui: ReactElement) {
+ return renderBare(ui, { wrapper: QueryWrapper });
+}
+
vi.mock(
"@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog",
() => ({
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsx
new file mode 100644
index 0000000000..1aae7b2564
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.expert.test.tsx
@@ -0,0 +1,844 @@
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
+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 as renderBare,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { useState, type ReactElement, type ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ConnectorRow } from "../ConnectorRow";
+import type { ConnectorRow as Row } from "../helpers";
+
+const mockGrant = vi.fn();
+// What the mocked dialog reports as the credential a sign-in produced.
+const mockReported: { current?: CredentialsMetaResponse } = {};
+const mockGrants = vi.fn((_expertId?: string, _options?: unknown) =>
+ grantsResult(),
+);
+vi.mock("@/app/api/__generated__/endpoints/experts/experts", () => ({
+ useListExpertCredentials: (expertId: string, options?: unknown) =>
+ mockGrants(expertId, options),
+ useGrantExpertCredentials: () => ({
+ mutateAsync: mockGrant,
+ isPending: false,
+ }),
+ getListExpertCredentialsQueryKey: (expertId?: string) => [
+ `/api/experts/${expertId}/credentials`,
+ ],
+}));
+
+// The selection hook writes the grant list it got back into the query cache,
+// so the rows need a client even though the list hook itself is mocked.
+const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+});
+
+function QueryWrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+function render(ui: ReactElement) {
+ return renderBare(ui, { wrapper: QueryWrapper });
+}
+
+vi.mock(
+ "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog",
+ () => ({
+ ConnectCredentialDialog: ({
+ open,
+ existing,
+ onClose,
+ onConnected,
+ }: {
+ open: boolean;
+ existing?: ExistingCredentialsOffer;
+ onClose: () => void;
+ onConnected?: (credential?: CredentialsMetaResponse) => void;
+ }) =>
+ open ? (
+ <div data-testid="connect-dialog">
+ {existing?.credentials.map((credential) => (
+ <button
+ key={credential.id}
+ onClick={() => void existing.onUse(credential)}
+ >
+ {`use-${credential.title}`}
+ </button>
+ ))}
+ {existing?.error && <span>{existing.error}</span>}
+ <button
+ onClick={() => {
+ onConnected?.(mockReported.current);
+ onClose();
+ }}
+ >
+ finish sign-in
+ </button>
+ </div>
+ ) : null,
+ }),
+);
+
+interface GrantsResult {
+ data?: { credential_id: string }[];
+ isPending: boolean;
+ isError: boolean;
+ isFetching: boolean;
+ refetch: () => Promise<{ data?: { credential_id: string }[] }>;
+}
+
+/** Credential ids the expert currently holds. A successful grant adds to it,
+ * the way the list the POST returns does once it lands in the cache. */
+let serverGrants: string[] = [];
+
+/** React Query cancels a refetch when a sibling row starts its own, so a row
+ * that trusted one would read pre-POST data. Always stale here. */
+function staleRefetch() {
+ return Promise.resolve({ data: [] as { credential_id: string }[] });
+}
+
+function grantsResult(overrides: Partial<GrantsResult> = {}): GrantsResult {
+ return {
+ data: serverGrants.map((id) => ({ credential_id: id })),
+ isPending: false,
+ isError: false,
+ isFetching: false,
+ refetch: staleRefetch,
+ ...overrides,
+ };
+}
+
+/** The backend answers a grant with the expert's whole grant list. */
+function grantResponse(ids: string[]) {
+ return {
+ status: 200 as const,
+ data: ids.map((id) => ({
+ credential_id: id,
+ provider: "github",
+ title: id,
+ type: "oauth2",
+ })),
+ headers: new Headers(),
+ };
+}
+
+function grantAll({ data }: { data: { credential_ids: string[] } }) {
+ serverGrants = [...new Set([...serverGrants, ...data.credential_ids])];
+ return Promise.resolve(grantResponse(serverGrants));
+}
+
+beforeEach(() => {
+ serverGrants = [];
+ mockGrant.mockReset();
+ mockGrant.mockImplementation(grantAll);
+ mockReported.current = undefined;
+ mockGrants.mockImplementation(() => grantsResult());
+});
+
+afterEach(() => {
+ cleanup();
+ queryClient.clear();
+});
+
+const savedGithub = {
+ id: "spare-cred",
+ provider: "github",
+ type: "oauth2",
+ title: "GH spare",
+ scopes: [],
+};
+
+const savedNotion = {
+ id: "notion-cred",
+ provider: "notion",
+ type: "oauth2",
+ title: "Notion",
+ scopes: [],
+};
+
+function providersFor(entries: Record<string, (typeof savedGithub)[]>) {
+ return Object.fromEntries(
+ Object.entries(entries).map(([provider, savedCredentials]) => [
+ provider,
+ {
+ provider,
+ providerName: provider,
+ savedCredentials,
+ oAuthCallback: vi.fn(),
+ createAPIKeyCredentials: vi.fn(),
+ createUserPasswordCredentials: vi.fn(),
+ createHostScopedCredentials: vi.fn(),
+ deleteCredentials: vi.fn(),
+ },
+ ]),
+ ) as unknown as React.ContextType<typeof CredentialsProvidersContext>;
+}
+
+function providersWithGithub(saved: (typeof savedGithub)[] = [savedGithub]) {
+ return providersFor({ github: saved });
+}
+
+function row(overrides: Partial<Row> = {}): Row {
+ return {
+ provider: "github",
+ displayName: "GitHub",
+ description: "Connect your GitHub account",
+ schema: { credentials_provider: ["github"], credentials_types: ["oauth2"] },
+ selected: undefined,
+ select: vi.fn(),
+ onConnected: vi.fn(),
+ ...overrides,
+ };
+}
+
+/** The card rebuilds the row from its own state on every render, so a row
+ * that only hydrates once needs its selection fed back in. */
+function StatefulRow({ current }: { current: Row }) {
+ const [selected, setSelected] = useState(current.selected);
+ return (
+ <ConnectorRow
+ row={{
+ ...current,
+ selected,
+ select: (value) => {
+ current.select(value);
+ setSelected(value);
+ },
+ }}
+ />
+ );
+}
+
+describe("ConnectorRow in an expert chat", () => {
+ it("restores a persisted expert grant without triggering another run", async () => {
+ serverGrants = ["spare-cred"];
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ await waitFor(() =>
+ expect(current.select).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "spare-cred" }),
+ ),
+ );
+ expect(mockGrant).not.toHaveBeenCalled();
+ expect(current.onConnected).not.toHaveBeenCalled();
+ });
+
+ it("shows Granted once the expert holds the selected credential", async () => {
+ serverGrants = ["spare-cred"];
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <StatefulRow current={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(await screen.findByText("Granted")).toBeDefined();
+ });
+
+ it("hydrates the first granted account when several of them match", async () => {
+ serverGrants = ["other-cred", "spare-cred"];
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([
+ savedGithub,
+ { ...savedGithub, id: "other-cred" },
+ ])}
+ >
+ <StatefulRow current={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(await screen.findByText("Granted")).toBeDefined();
+ expect(current.select).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "other-cred" }),
+ );
+ });
+
+ it("does not show Granted while the grant list is unavailable", () => {
+ mockGrants.mockImplementation(() =>
+ grantsResult({ data: undefined, isError: true }),
+ );
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ selected: { id: "spare-cred", provider: "github", type: "oauth2" },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(screen.queryByText("Granted")).toBeNull();
+ expect(screen.getByRole("button", { name: "Connect" })).toBeDefined();
+ expect(current.onConnected).not.toHaveBeenCalled();
+ });
+
+ it("drops a personal-mode selection when a later card makes the row an expert's", async () => {
+ const current = row();
+ const { rerender } = render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <StatefulRow current={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(await screen.findByText("Connected")).toBeDefined();
+ rerender(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <StatefulRow
+ current={{
+ ...current,
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ }}
+ />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(
+ await screen.findByRole("button", { name: "Connect" }),
+ ).toBeDefined();
+ expect(screen.queryByText("Connected")).toBeNull();
+ expect(screen.queryByText("Granted")).toBeNull();
+ });
+
+ it("clears a selected credential after the grant is revoked", async () => {
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ selected: { id: "spare-cred", provider: "github", type: "oauth2" },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ await waitFor(() => expect(current.select).toHaveBeenCalledWith(undefined));
+ });
+
+ it("preserves the chosen account when multiple matching accounts are granted", () => {
+ serverGrants = ["spare-cred", "other-cred"];
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ selected: { id: "other-cred", provider: "github", type: "oauth2" },
+ });
+ render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([
+ savedGithub,
+ { ...savedGithub, id: "other-cred" },
+ ])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(current.select).not.toHaveBeenCalled();
+ });
+
+ it("does not hydrate a granted credential lacking the required scopes", () => {
+ serverGrants = ["spare-cred"];
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ schema: {
+ credentials_provider: ["github"],
+ credentials_types: ["oauth2"],
+ credentials_scopes: ["repo"],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(current.select).not.toHaveBeenCalled();
+ });
+
+ it("does not treat the account's credential as connected", () => {
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(current.select).not.toHaveBeenCalled();
+ expect(screen.queryByText("Connected")).toBeNull();
+ expect(screen.getByText("This expert needs its own access")).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ expect(screen.queryByRole("button", { name: /^use-/ })).toBeNull();
+ });
+
+ it("offers the account's credential in the dialog and grants it", async () => {
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "spare-cred", title: "GH spare", type: "oauth2" }],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(screen.getByText("Needs this expert's access")).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-GH spare" }));
+ await waitFor(() =>
+ expect(mockGrant).toHaveBeenCalledWith({
+ expertId: "expert-a",
+ data: { credential_ids: ["spare-cred"] },
+ }),
+ );
+ expect(current.select).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "spare-cred", provider: "github" }),
+ );
+ expect(current.onConnected).toHaveBeenCalled();
+ });
+
+ it("grants before telling the chain the row connected", async () => {
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "spare-cred", title: "GH spare", type: "oauth2" }],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-GH spare" }));
+ await waitFor(() => expect(current.onConnected).toHaveBeenCalled());
+ expect(mockGrant.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(current.onConnected).mock.invocationCallOrder[0],
+ );
+ });
+
+ it("does not connect the row when the returned list omits the credential", async () => {
+ mockGrant.mockResolvedValue(grantResponse([]));
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "spare-cred", title: "GH spare", type: "oauth2" }],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-GH spare" }));
+ expect(
+ await screen.findByText("Couldn't grant access. Try again."),
+ ).toBeDefined();
+ expect(current.select).not.toHaveBeenCalled();
+ expect(current.onConnected).not.toHaveBeenCalled();
+ });
+
+ it("lists every grantable account and still lets the user connect a new one", () => {
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [
+ { id: "cred-1", title: "Work GitHub", type: "oauth2" },
+ { id: "cred-2", title: "Personal GitHub", type: "oauth2" },
+ ],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ expect(
+ screen.getByRole("button", { name: "use-Work GitHub" }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "use-Personal GitHub" }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "finish sign-in" }),
+ ).toBeDefined();
+ });
+
+ it("shows a retryable error when the grant fails", async () => {
+ mockGrant.mockRejectedValue(new Error("nope"));
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "spare-cred", title: "GH spare", type: "oauth2" }],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-GH spare" }));
+ expect(
+ await screen.findByText("Couldn't grant access. Try again."),
+ ).toBeDefined();
+ expect(screen.getByTestId("connect-dialog")).toBeDefined();
+ expect(current.onConnected).not.toHaveBeenCalled();
+ });
+
+ it("surfaces the reason the backend refused the grant", async () => {
+ const { ApiError } = await import("@/lib/autogpt-server-api/helpers");
+ mockGrant.mockRejectedValue(
+ new ApiError("Expert is out of credentials seats", 403, {}),
+ );
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "spare-cred", title: "GH spare", type: "oauth2" }],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-GH spare" }));
+ expect(
+ await screen.findByText("Expert is out of credentials seats"),
+ ).toBeDefined();
+ });
+
+ it("fails a grant it cannot resolve to an account without calling the API", async () => {
+ const current = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [
+ { id: "ghost-cred", title: "Ghost GitHub", type: "oauth2" },
+ ],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-Ghost GitHub" }));
+ expect(
+ await screen.findByText(
+ "That account is missing the access this needs. Try connecting again.",
+ ),
+ ).toBeDefined();
+ expect(mockGrant).not.toHaveBeenCalled();
+ expect(current.select).not.toHaveBeenCalled();
+ expect(current.onConnected).not.toHaveBeenCalled();
+ });
+
+ it("grants two rows back to back without failing the first", async () => {
+ const github = row({
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "spare-cred", title: "GH spare", type: "oauth2" }],
+ },
+ });
+ const notion = row({
+ provider: "notion",
+ displayName: "Notion",
+ schema: {
+ credentials_provider: ["notion"],
+ credentials_types: ["oauth2"],
+ },
+ expertGrant: {
+ expertId: "expert-a",
+ credentials: [{ id: "notion-cred", title: "Notion", type: "oauth2" }],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider
+ value={providersFor({ github: [savedGithub], notion: [savedNotion] })}
+ >
+ <StatefulRow current={github} />
+ <StatefulRow current={notion} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ screen
+ .getAllByRole("button", { name: "Grant access" })
+ .forEach((button) => fireEvent.click(button));
+ fireEvent.click(screen.getByRole("button", { name: "use-GH spare" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-Notion" }));
+ await waitFor(() => expect(screen.getAllByText("Granted")).toHaveLength(2));
+ expect(screen.queryByText("Couldn't grant access. Try again.")).toBeNull();
+ expect(github.onConnected).toHaveBeenCalledTimes(1);
+ expect(notion.onConnected).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("ConnectorRow after a sign-in in an expert chat", () => {
+ const existing = { ...savedGithub, id: "old-cred", title: "Old GitHub" };
+ const added = { ...savedGithub, id: "new-cred", title: "New GitHub" };
+
+ function reported(credential: typeof savedGithub) {
+ return { ...credential, username: null } as CredentialsMetaResponse;
+ }
+
+ it("grants the credential the sign-in reports without waiting for a refresh", async () => {
+ mockReported.current = reported(added);
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ await waitFor(() =>
+ expect(mockGrant).toHaveBeenCalledWith({
+ expertId: "expert-a",
+ data: { credential_ids: ["new-cred"] },
+ }),
+ );
+ expect(mockGrant).toHaveBeenCalledTimes(1);
+ expect(current.onConnected).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the just-granted account while the provider list catches up", async () => {
+ mockReported.current = reported(added);
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ const { rerender } = render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <StatefulRow current={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ expect(await screen.findByText("Granted")).toBeDefined();
+
+ // Another row granted an account this one also matches, while the
+ // provider list still predates the sign-in.
+ serverGrants = ["old-cred", "new-cred"];
+ rerender(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <StatefulRow current={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ await waitFor(() => expect(screen.getByText("Granted")).toBeDefined());
+ expect(current.select).toHaveBeenCalledTimes(1);
+ expect(current.select).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "new-cred" }),
+ );
+ });
+
+ it("grants a reported credential when the provider has no accounts yet", async () => {
+ mockReported.current = reported(added);
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider value={{}}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ await waitFor(() =>
+ expect(mockGrant).toHaveBeenCalledWith({
+ expertId: "expert-a",
+ data: { credential_ids: ["new-cred"] },
+ }),
+ );
+ expect(current.onConnected).toHaveBeenCalledTimes(1);
+ });
+
+ it("grants a re-authenticated account that kept its id", async () => {
+ mockReported.current = reported(existing);
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ await waitFor(() =>
+ expect(mockGrant).toHaveBeenCalledWith({
+ expertId: "expert-a",
+ data: { credential_ids: ["old-cred"] },
+ }),
+ );
+ });
+
+ it("reports an account that lacks the required scopes instead of granting it", async () => {
+ mockReported.current = reported(added);
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ schema: {
+ credentials_provider: ["github"],
+ credentials_types: ["oauth2"],
+ credentials_scopes: ["repo"],
+ },
+ });
+ render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ expect(
+ await screen.findByText(
+ "That account is missing the access this needs. Try connecting again.",
+ ),
+ ).toBeDefined();
+ expect(mockGrant).not.toHaveBeenCalled();
+ expect(current.select).not.toHaveBeenCalled();
+ });
+
+ it("grants the account that appeared after Connect, not a pre-existing one", async () => {
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ const { rerender } = render(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ rerender(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing, added])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ await waitFor(() =>
+ expect(mockGrant).toHaveBeenCalledWith({
+ expertId: "expert-a",
+ data: { credential_ids: ["new-cred"] },
+ }),
+ );
+ expect(mockGrant).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps Connect disabled until the accounts have loaded", async () => {
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ const { rerender } = render(
+ <CredentialsProvidersContext.Provider value={null}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ const connect = screen.getByRole("button", { name: "Connect" });
+ expect(connect.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(connect);
+ expect(screen.queryByRole("button", { name: "finish sign-in" })).toBeNull();
+ rerender(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([existing])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole("button", { name: "Connect" })
+ .hasAttribute("disabled"),
+ ).toBe(false),
+ );
+ expect(mockGrant).not.toHaveBeenCalled();
+ expect(current.select).not.toHaveBeenCalled();
+ });
+
+ it("keeps the new account available for a retry when the grant fails", async () => {
+ mockGrant.mockRejectedValueOnce(new Error("nope"));
+ const current = row({
+ expertGrant: { expertId: "expert-a", credentials: [] },
+ });
+ const { rerender } = render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub([])}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "finish sign-in" }));
+ rerender(
+ <CredentialsProvidersContext.Provider
+ value={providersWithGithub([added])}
+ >
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(
+ await screen.findByText("Couldn't grant access. Try again."),
+ ).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ fireEvent.click(screen.getByRole("button", { name: "use-New GitHub" }));
+ await waitFor(() => expect(mockGrant).toHaveBeenCalledTimes(2));
+ expect(current.onConnected).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("ConnectorRow in a personal chat", () => {
+ it("still auto-selects the account's credential", async () => {
+ const current = row();
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <ConnectorRow row={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ await waitFor(() =>
+ expect(current.select).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "spare-cred" }),
+ ),
+ );
+ });
+
+ it("asks for no grants at all", async () => {
+ const current = row();
+ render(
+ <CredentialsProvidersContext.Provider value={providersWithGithub()}>
+ <StatefulRow current={current} />
+ </CredentialsProvidersContext.Provider>,
+ );
+ expect(await screen.findByText("Connected")).toBeDefined();
+ expect(mockGrant).not.toHaveBeenCalled();
+ expect(mockGrants).toHaveBeenCalledWith(
+ "",
+ expect.objectContaining({
+ query: expect.objectContaining({ enabled: false }),
+ }),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.expertGrant.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.expertGrant.test.ts
new file mode 100644
index 0000000000..cac3e33061
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/helpers.expertGrant.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ intersectGrants,
+ toConnectorRows,
+ type ConnectorRequest,
+} from "../helpers";
+
+function request(
+ id: string,
+ credentials: { id: string; title: string; type: string }[],
+): ConnectorRequest {
+ return {
+ id,
+ fields: [
+ [
+ "credentials",
+ {
+ credentials_provider: ["github"],
+ credentials_types: ["oauth2"],
+ expert_grant: { expertId: "expert-a", credentials },
+ },
+ ],
+ ],
+ selected: {},
+ onChange: vi.fn(),
+ onConnected: vi.fn(),
+ };
+}
+
+describe("expert grant candidates on merged connector rows", () => {
+ it("offers only accounts eligible for every merged requirement", () => {
+ const shared = { id: "both", title: "Both", type: "oauth2" };
+ const rows = toConnectorRows(
+ [
+ request("a", [shared, { id: "only-a", title: "A", type: "oauth2" }]),
+ request("b", [shared, { id: "only-b", title: "B", type: "oauth2" }]),
+ ],
+ [],
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].expertGrant?.credentials.map((c) => c.id)).toEqual(["both"]);
+ });
+
+ it("offers nothing when only one requirement carries grant info", () => {
+ const grant = {
+ expertId: "e",
+ credentials: [{ id: "x", title: "X", type: "oauth2" }],
+ };
+ const closed = { expertId: "e", credentials: [] };
+ expect(intersectGrants(undefined, grant)).toEqual(closed);
+ expect(intersectGrants(grant, undefined)).toEqual(closed);
+ });
+
+ it("offers nothing when the merged requirements name different experts", () => {
+ const kept = {
+ expertId: "expert-a",
+ credentials: [{ id: "x", title: "X", type: "oauth2" }],
+ };
+ const incoming = {
+ expertId: "expert-b",
+ credentials: [{ id: "x", title: "X", type: "oauth2" }],
+ };
+ expect(intersectGrants(kept, incoming)).toEqual({
+ expertId: "expert-a",
+ credentials: [],
+ });
+ });
+
+ it("leaves a row without any grant info in personal mode", () => {
+ expect(intersectGrants(undefined, undefined)).toBeUndefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts
index 52109f5530..eba937f860 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts
@@ -3,6 +3,7 @@ import type { CredentialField } from "@/components/contextual/CredentialsInput/c
import { formatProviderName } from "@/components/contextual/IntegrationsPanel/helpers";
import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
import type { RJSFSchema } from "@rjsf/utils";
+import type { ExpertGrant } from "../SetupRequirementsCard/helpers";
import type { ClarifyingQuestion } from "../../tools/clarifying-questions";
/** One question card's ask. The card owns the inputs; the asking component
@@ -76,6 +77,10 @@ export interface ConnectorRow {
selected?: CredentialsMetaInput;
select: (value?: CredentialsMetaInput) => void;
onConnected: () => void;
+ /** Set when an expert asked: an account credential only counts once the
+ * expert has been granted it, so the connect dialog offers the account's
+ * existing credentials first and a freshly connected one is granted. */
+ expertGrant?: ExpertGrant;
}
/** Flattens every request into one row per provider: two tools asking for
@@ -92,6 +97,7 @@ export function toConnectorRows(
schema: CredentialField[1];
selected?: CredentialsMetaInput;
targets: { request: ConnectorRequest; key: string }[];
+ expertGrant?: ExpertGrant;
}
>();
@@ -105,9 +111,16 @@ export function toConnectorRows(
schema,
targets: [{ request, key }],
selected: request.selected[key],
+ expertGrant: schema.expert_grant as ExpertGrant | undefined,
});
continue;
}
+ // A granted credential answers every merged requirement at once, so
+ // only accounts eligible for all of them may be offered.
+ row.expertGrant = intersectGrants(
+ row.expertGrant,
+ schema.expert_grant as ExpertGrant | undefined,
+ );
// One row answers every card that asked for this provider, so it must
// request the union of their scopes — keeping only the first card's
// leaves the others permanently unsatisfiable. Scopes only: merging
@@ -126,6 +139,7 @@ export function toConnectorRows(
byName.get(provider)?.description ?? row.schema.description ?? null,
schema: row.schema,
selected: row.selected,
+ expertGrant: row.expertGrant,
select: (value?: CredentialsMetaInput) =>
row.targets.forEach(({ request, key }) => request.onChange(key, value)),
onConnected: () =>
@@ -133,6 +147,27 @@ export function toConnectorRows(
}));
}
+/** Grant candidates eligible for both requirements. A requirement the server
+ * sent no candidates for — or one belonging to another expert — narrows the
+ * row to nothing rather than letting the other side's candidates through:
+ * offering an account for a requirement it was never cleared for would grant
+ * access the expert was not meant to have. */
+export function intersectGrants(
+ kept: ExpertGrant | undefined,
+ incoming: ExpertGrant | undefined,
+): ExpertGrant | undefined {
+ const defined = kept ?? incoming;
+ if (!defined) return undefined;
+ if (!kept || !incoming || kept.expertId !== incoming.expertId) {
+ return { expertId: defined.expertId, credentials: [] };
+ }
+ const eligible = new Set(incoming.credentials.map((c) => c.id));
+ return {
+ expertId: kept.expertId,
+ credentials: kept.credentials.filter((c) => eligible.has(c.id)),
+ };
+}
+
/** Merges `incoming`'s scopes into `kept`, leaving every other schema field
* as the first card set it. */
function withUnionedScopes(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/useExpertCredentialSelection.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/useExpertCredentialSelection.ts
new file mode 100644
index 0000000000..28c17540fc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/useExpertCredentialSelection.ts
@@ -0,0 +1,131 @@
+import {
+ getListExpertCredentialsQueryKey,
+ useListExpertCredentials,
+ type grantExpertCredentialsResponse,
+ type listExpertCredentialsResponseSuccess,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { okData } from "@/app/api/helpers";
+import { findSavedUserCredentialByProviderAndType } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";
+import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
+import type { CredentialsProvidersContextType } from "@/providers/agent-credentials/credentials-provider";
+import { useQueryClient } from "@tanstack/react-query";
+import { useEffect } from "react";
+import type { ConnectorRow } from "./helpers";
+
+export function useExpertCredentialSelection(
+ row: ConnectorRow,
+ providers: CredentialsProvidersContextType | null,
+) {
+ const queryClient = useQueryClient();
+ const expertId = row.expertGrant?.expertId;
+ const grants = useListExpertCredentials(expertId ?? "", {
+ query: {
+ enabled: Boolean(row.expertGrant),
+ select: (response) => okData(response),
+ },
+ });
+ const provider = providers?.[row.provider];
+ const grantedIDs = new Set(grants.data?.map((grant) => grant.credential_id));
+ const saved = provider?.savedCredentials.filter((credential) =>
+ grantedIDs.has(credential.id),
+ );
+ function findCredential(id?: string) {
+ if (!provider || !saved) return undefined;
+ return findSavedUserCredentialByProviderAndType(
+ row.schema.credentials_provider ?? [],
+ row.schema.credentials_types ?? [],
+ row.schema.credentials_scopes,
+ {
+ [row.provider]: {
+ ...provider,
+ savedCredentials: id
+ ? saved.filter((credential) => credential.id === id)
+ : saved,
+ },
+ },
+ row.schema.discriminator_values,
+ );
+ }
+ // The matcher abstains when several accounts qualify, which would leave the
+ // row on Connect with an empty offer — the backend omits already-granted
+ // accounts — and no way forward. Grant order breaks the tie.
+ function firstGrantedMatch() {
+ for (const grant of grants.data ?? []) {
+ const match = findCredential(grant.credential_id);
+ if (match) return match;
+ }
+ return undefined;
+ }
+
+ const selectedID = row.selected?.id;
+ const isSelectedGranted = Boolean(selectedID && grantedIDs.has(selectedID));
+ // The provider list reloads asynchronously after a connect, so an account
+ // it has not caught up with is merely absent, not unusable.
+ const isSelectedLoaded = Boolean(
+ selectedID &&
+ provider?.savedCredentials.some(
+ (credential) => credential.id === selectedID,
+ ),
+ );
+ // A granted selection stays put: swapping it for a different granted
+ // account would undo the choice just made, and clearing it would flip the
+ // row from Granted back to Connect until the provider list catches up. Only
+ // a revoked grant, or a loaded account that fails the row, drops it.
+ const keepsSelection =
+ isSelectedGranted &&
+ (!isSelectedLoaded || Boolean(findCredential(selectedID)));
+ const hydrated = keepsSelection ? undefined : firstGrantedMatch();
+ const hasGrant = Boolean(row.expertGrant);
+ const isSelectionGranted = Boolean(
+ hasGrant && !grants.isError && grants.data && keepsSelection,
+ );
+
+ useEffect(() => {
+ if (!hasGrant || !grants.data || !providers || grants.isFetching) return;
+ if (keepsSelection || selectedID === hydrated?.id) return;
+ row.select(
+ hydrated
+ ? {
+ id: hydrated.id,
+ provider: row.provider,
+ type: hydrated.type as CredentialsMetaInput["type"],
+ title: hydrated.title ?? undefined,
+ }
+ : undefined,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- row is rebuilt each render by the card; track the fields it reads
+ }, [
+ hasGrant,
+ selectedID,
+ hydrated?.id,
+ keepsSelection,
+ grants.data,
+ grants.isFetching,
+ providers,
+ ]);
+
+ return {
+ isPending: grants.isPending,
+ isError: grants.isError,
+ isSelectionGranted,
+ /** Records the list the POST returned as the expert's grants and reports
+ * whether it holds `id`. That response is the only proof available: the
+ * list query is shared by every row of this expert, so a refetch started
+ * here is cancelled by a sibling row's and resolves against pre-POST
+ * data — a grant that landed would read back as a failure. */
+ confirmGrant(id: string, response: grantExpertCredentialsResponse) {
+ const granted = okData(response);
+ if (!granted || !expertId) return false;
+ const refreshed: listExpertCredentialsResponseSuccess = {
+ status: 200,
+ data: granted,
+ headers: response.headers,
+ };
+ queryClient.setQueryData(
+ getListExpertCredentialsQueryKey(expertId),
+ refreshed,
+ );
+ return granted.some((grant) => grant.credential_id === id);
+ },
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts
index b10ec93c1a..8564b10f8a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts
@@ -3,6 +3,7 @@ import { deriveAuthMethods } from "@/hooks/useCredentials";
import type { CredentialsType } from "@/lib/autogpt-server-api/types";
import {
coerceCredentialFields,
+ coerceExpertGrant,
buildSiblingInputsFromCredentials,
coerceExpectedInputs,
buildExpectedInputsSchema,
@@ -858,3 +859,95 @@ describe("buildRunMessage", () => {
expect(msg).toContain("Run with these inputs:");
});
});
+
+describe("coerceExpertGrant", () => {
+ it("maps the wire shape onto the card's grant", () => {
+ const grant = coerceExpertGrant({
+ expert_id: "expert-a",
+ credentials: [{ id: "cred-1", title: "Work GitHub", type: "oauth2" }],
+ });
+ expect(grant).toEqual({
+ expertId: "expert-a",
+ credentials: [{ id: "cred-1", title: "Work GitHub", type: "oauth2" }],
+ });
+ });
+
+ it("returns undefined for a non-object", () => {
+ expect(coerceExpertGrant(null)).toBeUndefined();
+ expect(coerceExpertGrant("expert-a")).toBeUndefined();
+ expect(coerceExpertGrant(undefined)).toBeUndefined();
+ });
+
+ it("returns undefined without an expert id", () => {
+ expect(coerceExpertGrant({ credentials: [] })).toBeUndefined();
+ expect(
+ coerceExpertGrant({ expert_id: "", credentials: [] }),
+ ).toBeUndefined();
+ expect(
+ coerceExpertGrant({ expert_id: 42, credentials: [] }),
+ ).toBeUndefined();
+ });
+
+ it("keeps the expert with an empty offer when credentials are not a list", () => {
+ expect(coerceExpertGrant({ expert_id: "expert-a" })).toEqual({
+ expertId: "expert-a",
+ credentials: [],
+ });
+ expect(
+ coerceExpertGrant({ expert_id: "expert-a", credentials: "cred-1" }),
+ ).toEqual({ expertId: "expert-a", credentials: [] });
+ });
+
+ it("drops candidates without a usable id", () => {
+ const grant = coerceExpertGrant({
+ expert_id: "expert-a",
+ credentials: [
+ null,
+ "cred-1",
+ { title: "No id" },
+ { id: "" },
+ { id: 7 },
+ { id: "cred-2", title: "Kept", type: "oauth2" },
+ ],
+ });
+ expect(grant?.credentials).toEqual([
+ { id: "cred-2", title: "Kept", type: "oauth2" },
+ ]);
+ });
+
+ it("falls back to the id as title and api_key as type", () => {
+ const grant = coerceExpertGrant({
+ expert_id: "expert-a",
+ credentials: [{ id: "cred-1" }, { id: "cred-2", title: 9, type: 9 }],
+ });
+ expect(grant?.credentials).toEqual([
+ { id: "cred-1", title: "cred-1", type: "api_key" },
+ { id: "cred-2", title: "cred-2", type: "api_key" },
+ ]);
+ });
+
+ it("passes an unrecognised type through rather than dropping the candidate", () => {
+ const grant = coerceExpertGrant({
+ expert_id: "expert-a",
+ credentials: [{ id: "cred-1", title: "Odd", type: "smoke_signal" }],
+ });
+ expect(grant?.credentials[0].type).toBe("smoke_signal");
+ });
+
+ it("reaches the card through coerceCredentialFields", () => {
+ const { credentialFields } = coerceCredentialFields({
+ cred1: {
+ provider: "github",
+ types: ["oauth2"],
+ expert_grant: {
+ expert_id: "expert-a",
+ credentials: [{ id: "cred-1", title: "Work", type: "oauth2" }],
+ },
+ },
+ });
+ expect(credentialFields[0][1].expert_grant).toEqual({
+ expertId: "expert-a",
+ credentials: [{ id: "cred-1", title: "Work", type: "oauth2" }],
+ });
+ });
+});
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.ts
index 161e6761e6..1f93c738b4 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
@@ -63,6 +63,10 @@ export function coerceCredentialFields(rawMissingCredentials: unknown): {
if (discriminatorValues && discriminatorValues.length > 0) {
schema.discriminator_values = discriminatorValues;
}
+ const expertGrant = coerceExpertGrant(cred.expert_grant);
+ if (expertGrant) {
+ schema.expert_grant = expertGrant;
+ }
credentialFields.push([key, schema]);
requiredCredentials.add(key);
@@ -71,6 +75,37 @@ export function coerceCredentialFields(rawMissingCredentials: unknown): {
return { credentialFields, requiredCredentials };
}
+/** Which expert a missing credential is for, and which of the account's
+ * credentials could be granted to it instead of connecting a new one. Only
+ * present on cards raised from an expert chat. */
+export interface ExpertGrant {
+ expertId: string;
+ credentials: { id: string; title: string; type: string }[];
+}
+
+/** Reads the wire `expert_grant` block. A candidate needs an id; an untitled
+ * one is labelled by its id, and a missing type falls back to `api_key`. */
+export function coerceExpertGrant(raw: unknown): ExpertGrant | undefined {
+ if (!raw || typeof raw !== "object") return undefined;
+ const grant = raw as Record<string, unknown>;
+ if (typeof grant.expert_id !== "string" || !grant.expert_id) return undefined;
+ const credentials = Array.isArray(grant.credentials)
+ ? grant.credentials.flatMap((entry) => {
+ if (!entry || typeof entry !== "object") return [];
+ const cred = entry as Record<string, unknown>;
+ if (typeof cred.id !== "string" || !cred.id) return [];
+ return [
+ {
+ id: cred.id,
+ title: typeof cred.title === "string" ? cred.title : cred.id,
+ type: typeof cred.type === "string" ? cred.type : "api_key",
+ },
+ ];
+ })
+ : [];
+ return { expertId: grant.expert_id, credentials };
+}
+
/**
* Extract the unique provider slugs the card is asking the user to connect.
*
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.tsx
index ecf2460079..3841128177 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
@@ -1,5 +1,6 @@
"use client";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
import { Button } from "@/components/atoms/Button/Button";
import { ConnectMethodView } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView";
import {
@@ -10,6 +11,9 @@ import {
import { getConnectableCredentialTypes } from "@/hooks/useCredentials";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api/types";
+import { useState } from "react";
+import { ExistingCredentialsView } from "./components/ExistingCredentialsView/ExistingCredentialsView";
+import type { ExistingCredentialsOffer } from "./helpers";
import { useConnectCredentialDialog } from "./useConnectCredentialDialog";
const KNOWN_AUTH_METHODS: ReadonlySet<AuthMethod> = new Set(
@@ -22,10 +26,15 @@ interface Props {
displayName: string;
/** Existing account to upgrade in place rather than signing in afresh. */
credentialID?: string;
+ /** Accounts to offer before the connect methods. With none, or once the
+ * user picks Add new, the dialog is the plain connect flow. */
+ existing?: ExistingCredentialsOffer;
open: boolean;
onClose: () => void;
- /** Fires only on a completed sign-in, unlike onClose. */
- onConnected?: () => void;
+ /** Fires only on a completed sign-in, unlike onClose, with the credential
+ * the flow produced when it reports one. Using an existing account goes
+ * through `existing.onUse` instead. */
+ onConnected?: (credential?: CredentialsMetaResponse) => void;
}
/** The onboarding connect flow (logo pair, "Connect AutoGPT to X",
@@ -37,10 +46,13 @@ export function ConnectCredentialDialog({
provider,
displayName,
credentialID,
+ existing,
open,
onClose,
onConnected,
}: Props) {
+ const [addingNew, setAddingNew] = useState(false);
+ const [chosenId, setChosenId] = useState<string | null>(null);
const {
selectedMethod,
setSelectedMethod,
@@ -55,25 +67,45 @@ export function ConnectCredentialDialog({
provider,
onConnected: handleConnected,
scopes: schema.credentials_scopes,
- credentialID,
+ // Add new asks for a second account, not a re-auth: keeping the upgrade
+ // target would sign the user back into the very account they are trying
+ // to add another alongside.
+ credentialID: addingNew ? undefined : credentialID,
});
- function handleClose() {
+ const offered = existing?.credentials ?? [];
+ const showExisting = offered.length > 0 && !addingNew;
+ const chosen = offered.find((c) => c.id === chosenId) ?? offered[0];
+
+ function resetAll() {
reset();
+ setAddingNew(false);
+ setChosenId(null);
+ }
+
+ function handleClose() {
+ resetAll();
onClose();
}
// The hook has already reset by the time it calls this.
- function handleConnected() {
- onConnected?.();
+ function handleConnected(credential?: CredentialsMetaResponse) {
+ setAddingNew(false);
+ setChosenId(null);
+ onConnected?.(credential);
onClose();
}
// Device auth completes inside ConnectMethodView, bypassing the hook, so
// this is the only place its reset can happen.
- function handleDeviceAuthSuccess() {
+ function handleDeviceAuthSuccess(credential?: CredentialsMetaResponse) {
reset();
- handleConnected();
+ handleConnected(credential);
+ }
+
+ async function handleUseExisting() {
+ if (!existing || !chosen) return;
+ if (await existing.onUse(chosen)) handleClose();
}
const connectable: ConnectableProvider = {
@@ -97,28 +129,64 @@ export function ConnectCredentialDialog({
>
<Dialog.Content>
<div className="flex flex-col gap-5 pb-2">
- <ConnectMethodView
- provider={connectable}
- selectedMethod={selectedMethod}
- onSelectMethod={setSelectedMethod}
- apiKeyForm={apiKeyForm}
- onApiKeySubmit={handleApiKeySubmit}
- onDeviceAuthSuccess={handleDeviceAuthSuccess}
- />
+ {showExisting && chosen ? (
+ <ExistingCredentialsView
+ provider={provider}
+ displayName={displayName}
+ credentials={offered}
+ selectedId={chosen.id}
+ onSelect={setChosenId}
+ />
+ ) : (
+ <ConnectMethodView
+ provider={connectable}
+ selectedMethod={selectedMethod}
+ onSelectMethod={setSelectedMethod}
+ apiKeyForm={apiKeyForm}
+ onApiKeySubmit={handleApiKeySubmit}
+ onDeviceAuthSuccess={handleDeviceAuthSuccess}
+ />
+ )}
+ {showExisting && existing?.error && (
+ <span role="alert" className="text-center text-xs text-red-600">
+ {existing.error}
+ </span>
+ )}
<div className="flex items-center justify-end gap-3">
<Button variant="secondary" size="small" onClick={handleClose}>
Cancel
</Button>
- {showContinue && (
- <Button
- variant="primary"
- size="small"
- disabled={isContinueDisabled}
- loading={isConnecting}
- onClick={handleContinue}
- >
- {isConnecting ? "Connecting…" : "Continue"}
- </Button>
+ {showExisting ? (
+ <>
+ <Button
+ variant="outline"
+ size="small"
+ disabled={existing?.isPending}
+ onClick={() => setAddingNew(true)}
+ >
+ Add new
+ </Button>
+ <Button
+ variant="primary"
+ size="small"
+ loading={existing?.isPending}
+ onClick={handleUseExisting}
+ >
+ {existing?.isPending ? "Granting…" : "Use existing"}
+ </Button>
+ </>
+ ) : (
+ showContinue && (
+ <Button
+ variant="primary"
+ size="small"
+ disabled={isContinueDisabled}
+ loading={isConnecting}
+ onClick={handleContinue}
+ >
+ {isConnecting ? "Connecting…" : "Continue"}
+ </Button>
+ )
)}
</div>
</div>
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.tsx
index c6ef2fc98d..e66714da48 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
@@ -5,6 +5,7 @@ import {
fireEvent,
render,
screen,
+ waitFor,
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ConnectCredentialDialog } from "../ConnectCredentialDialog";
@@ -287,4 +288,146 @@ describe("ConnectCredentialDialog", () => {
expect(onClose).toHaveBeenCalledOnce();
expect(apiKey.form.reset).toHaveBeenCalledOnce();
});
+
+ it("hands the produced credential to onConnected", () => {
+ const onConnected = vi.fn();
+ renderDialog({ onConnected });
+ const produced = { id: "new-cred", provider: "github", type: "oauth2" };
+
+ const { onSuccess } = mockUseOAuthConnect.mock.calls[0][0] as {
+ onSuccess: (credential?: unknown) => void;
+ };
+ act(() => onSuccess(produced));
+
+ expect(onConnected).toHaveBeenCalledWith(produced);
+ });
+});
+
+describe("ConnectCredentialDialog with existing accounts", () => {
+ const accounts = [
+ { id: "cred-1", title: "Work GitHub", type: "oauth2" },
+ { id: "cred-2", title: "Personal GitHub", type: "api_key" },
+ ];
+
+ function offer(
+ overrides: Partial<{
+ onUse: (credential: (typeof accounts)[number]) => Promise<boolean>;
+ isPending: boolean;
+ error: string | null;
+ }> = {},
+ ) {
+ return {
+ credentials: accounts,
+ onUse: vi.fn().mockResolvedValue(true),
+ isPending: false,
+ error: null,
+ ...overrides,
+ };
+ }
+
+ it("offers the accounts before the connect methods", () => {
+ renderDialog({ existing: offer() });
+
+ expect(screen.getByText("Give this expert access to GitHub")).toBeDefined();
+ expect(screen.queryByTestId("connect-method-view")).toBeNull();
+ expect(
+ screen
+ .getByRole("radio", { name: /Work GitHub/ })
+ .getAttribute("aria-checked"),
+ ).toBe("true");
+ expect(screen.getByText("Use existing")).toBeDefined();
+ expect(screen.queryByText("Continue")).toBeNull();
+ });
+
+ it("falls through to the connect methods when there is nothing to offer", () => {
+ renderDialog({ existing: { ...offer(), credentials: [] } });
+
+ expect(screen.getByTestId("connect-method-view")).toBeDefined();
+ expect(screen.queryByText("Use existing")).toBeNull();
+ });
+
+ it("uses the picked account and closes once it is granted", async () => {
+ const existing = offer();
+ const { onClose } = renderDialog({ existing });
+
+ fireEvent.click(screen.getByRole("radio", { name: /Personal GitHub/ }));
+ fireEvent.click(screen.getByText("Use existing"));
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(existing.onUse).toHaveBeenCalledWith(accounts[1]);
+ });
+
+ it("stays open with the error when the account cannot be used", async () => {
+ const existing = offer({
+ onUse: vi.fn().mockResolvedValue(false),
+ error: "Couldn't grant access. Try again.",
+ });
+ const { onClose } = renderDialog({ existing });
+
+ fireEvent.click(screen.getByText("Use existing"));
+
+ await waitFor(() => expect(existing.onUse).toHaveBeenCalledOnce());
+ expect(screen.getByRole("alert").textContent).toBe(
+ "Couldn't grant access. Try again.",
+ );
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("switches to the connect methods on Add new", () => {
+ renderDialog({ existing: offer() });
+
+ fireEvent.click(screen.getByText("Add new"));
+
+ expect(screen.getByTestId("connect-method-view")).toBeDefined();
+ expect(screen.getByText("Continue")).toBeDefined();
+ expect(screen.queryByText("Use existing")).toBeNull();
+ });
+
+ it("signs into a fresh account on Add new instead of upgrading the offered one", () => {
+ renderDialog({ existing: offer(), credentialID: "cred-1" });
+
+ const beforeAddNew = mockUseOAuthConnect.mock.calls.at(-1)?.[0] as {
+ credentialID?: string;
+ };
+ expect(beforeAddNew.credentialID).toBe("cred-1");
+
+ fireEvent.click(screen.getByText("Add new"));
+
+ // buildLoginParams omits credential_id for an undefined target, so the
+ // login asks for a brand-new account rather than re-authing cred-1.
+ const afterAddNew = mockUseOAuthConnect.mock.calls.at(-1)?.[0] as {
+ credentialID?: string;
+ };
+ expect(afterAddNew.credentialID).toBeUndefined();
+ });
+
+ it("keeps the upgrade target for the plain connect flow", () => {
+ renderDialog({ credentialID: "cred-1" });
+
+ const args = mockUseOAuthConnect.mock.calls.at(-1)?.[0] as {
+ credentialID?: string;
+ };
+ expect(args.credentialID).toBe("cred-1");
+ });
+
+ it("returns to the accounts after Add new is cancelled", () => {
+ const { onClose, rerender } = renderDialog({ existing: offer() });
+
+ fireEvent.click(screen.getByText("Add new"));
+ fireEvent.click(screen.getByText("Cancel"));
+ expect(onClose).toHaveBeenCalledOnce();
+
+ rerender(
+ <ConnectCredentialDialog
+ schema={baseSchema}
+ provider="github"
+ displayName="GitHub"
+ open
+ onClose={onClose}
+ existing={offer()}
+ />,
+ );
+ expect(screen.queryByTestId("connect-method-view")).toBeNull();
+ expect(screen.getByText("Use existing")).toBeDefined();
+ });
});
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.tsx
new file mode 100644
index 0000000000..330eae586f
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/components/ExistingCredentialsView/ExistingCredentialsView.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";
+import { Key01Icon, SecurityCheckIcon } from "@hugeicons/core-free-icons";
+import type { ExistingCredential } from "../../helpers";
+
+interface Props {
+ provider: string;
+ displayName: string;
+ credentials: ExistingCredential[];
+ selectedId: string;
+ onSelect: (id: string) => void;
+}
+
+// The step before the connect methods when the account already has a
+// credential the expert lacks: pick which one to hand over. Mirrors the
+// method radio cards so switching to Add new feels like the same dialog.
+export function ExistingCredentialsView({
+ provider,
+ displayName,
+ credentials,
+ selectedId,
+ onSelect,
+}: Props) {
+ return (
+ <div className="flex flex-col gap-5 pt-2">
+ <div className="flex items-center justify-center gap-6">
+ <span className="relative flex h-20 w-20 items-center justify-center rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-zinc-100">
+ <AutoGPTLogo
+ hideText
+ className="absolute left-1/2 top-1/2 h-8 w-[4.4rem] -translate-x-[77%] -translate-y-1/2"
+ />
+ </span>
+ <span aria-hidden className="grid grid-cols-3 gap-1.5">
+ {Array.from({ length: 9 }, (_, dot) => (
+ <span key={dot} className="h-1 w-1 rounded-full bg-[#5b21b6]/30" />
+ ))}
+ </span>
+ <span className="flex h-20 w-20 items-center justify-center rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.08)] ring-1 ring-zinc-100">
+ <ProviderAvatar id={provider} name={displayName} />
+ </span>
+ </div>
+
+ <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}
+ </Text>
+ <Text variant="body" className="!text-zinc-500">
+ Your account is already connected, but this expert can&apos;t use it
+ yet. Pick an account to share, or add a new one.
+ </Text>
+ </div>
+
+ <div
+ role="radiogroup"
+ aria-label="Account"
+ className="flex flex-col gap-1 rounded-2xl bg-neutral-100 p-1.5"
+ >
+ {credentials.map((credential) => {
+ const isSelected = credential.id === selectedId;
+ return (
+ <button
+ key={credential.id}
+ type="button"
+ role="radio"
+ aria-checked={isSelected}
+ onClick={() => onSelect(credential.id)}
+ className={
+ isSelected
+ ? "flex w-full items-center gap-3 rounded-xl bg-white p-3 text-left shadow-sm"
+ : "flex w-full items-center gap-3 rounded-xl p-3 text-left transition-colors hover:bg-white/60"
+ }
+ >
+ <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-white shadow-sm">
+ <Icon
+ icon={
+ credential.type === "oauth2" ? SecurityCheckIcon : Key01Icon
+ }
+ size={22}
+ className="text-zinc-700"
+ />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-sm font-semibold text-zinc-900">
+ {credential.title}
+ </span>
+ <span className="text-xs text-zinc-500">
+ {credential.type === "oauth2" ? "OAuth" : "API key"}
+ </span>
+ </span>
+ <span
+ aria-hidden
+ className={
+ isSelected
+ ? "flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 border-violet-600"
+ : "h-5 w-5 shrink-0 rounded-full border-2 border-zinc-200"
+ }
+ >
+ {isSelected && (
+ <span className="h-2.5 w-2.5 rounded-full bg-violet-600" />
+ )}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </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.ts
new file mode 100644
index 0000000000..67d6fc9dca
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/helpers.ts
@@ -0,0 +1,16 @@
+export interface ExistingCredential {
+ id: string;
+ title: string;
+ type: string;
+}
+
+/** Accounts the user already has that could satisfy the request without a
+ * new sign-in — an expert chat offers these before the connect methods. */
+export interface ExistingCredentialsOffer {
+ credentials: ExistingCredential[];
+ /** Resolves true once the credential is usable; false keeps the dialog
+ * open so the user can retry or add a new one instead. */
+ onUse: (credential: ExistingCredential) => Promise<boolean>;
+ isPending: boolean;
+ error: string | null;
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts
index 131ccb9367..fe9c0f9096 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/useConnectCredentialDialog.ts
@@ -6,11 +6,12 @@ import {
AuthType,
type AuthMethod,
} from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/helpers";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
import { useState } from "react";
interface Args {
provider: string;
- onConnected: () => void;
+ onConnected: (credential?: CredentialsMetaResponse) => void;
scopes?: string[];
credentialID?: string;
}
@@ -38,9 +39,9 @@ export function useConnectCredentialDialog({
apiKey.form.reset();
}
- function handleConnected() {
+ function handleConnected(credential?: CredentialsMetaResponse) {
reset();
- onConnected();
+ onConnected(credential);
}
function handleContinue() {