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): scope integrations per expert and surface them in the UI (#14215)
Ubbe006ef7b0dba3
diff --git a/autogpt_platform/backend/backend/api/features/experts/credentials.py b/autogpt_platform/backend/backend/api/features/experts/credentials.pynew file mode 100644index 0000000000..a8eb66ef72--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/credentials.py@@ -0,0 +1,258 @@+"""Per-expert credential grants — which of the owner's integrations an expert may use.++Deny-by-default: an expert reaches only the credentials granted to it here.+That rule cannot apply retroactively, so an expert whose ``credentialsSeededAt``+is still null gets its allow-list seeded on first read from the credentials its+installed workflows actually resolve to. Once stamped, the list is the user's+to curate — a revoked credential stays revoked, and installing a workflow grants+what that workflow needs so adding one never produces a silently broken expert.++System credentials (the platform's own LLM keys, built from settings rather than+stored per user) are never granted and never filtered: every expert may use them,+or no expert could run a single LLM block.+"""++import logging+from datetime import datetime, timezone++import prisma.models++from backend.api.features.experts.models import ExpertCredentialRef+from backend.data.model import Credentials+from backend.integrations.credentials_store import is_system_credential+from backend.util.exceptions import ExpertNotFoundError++logger = logging.getLogger(__name__)++_WORKFLOW_INCLUDE = {"Workflows": {"include": {"LibraryAgent": True}}}+++async def _owned_expert(user_id: str, expert_id: str) -> prisma.models.Expert:+ row = await prisma.models.Expert.prisma().find_first(+ where={+ "id": expert_id,+ "ownerUserId": user_id,+ "isTemplate": False,+ "isArchived": False,+ },+ include=_WORKFLOW_INCLUDE, # type: ignore[arg-type]+ )+ if row is None:+ raise ExpertNotFoundError(f"Expert #{expert_id} not found")+ return row+++async def _user_credentials(user_id: str) -> list[Credentials]:+ from backend.integrations.creds_manager import IntegrationCredentialsManager++ return await IntegrationCredentialsManager().store.get_all_creds(user_id)+++async def _derive_from_workflows(+ user_id: str, expert: prisma.models.Expert+) -> tuple[dict[str, str], bool]:+ """Credential id → provider for everything this expert's workflows resolve to.++ Returns ``(derived, is_complete)``. ``is_complete`` is False when any+ workflow failed to resolve, which keeps the seed pending: a transient+ graph-load failure must not be frozen in as "this expert reaches nothing",+ because enforcement would then block every run it has until the user+ noticed and re-granted by hand.+ """+ from backend.copilot.tools.utils import match_user_credentials_to_graph+ from backend.data.graph import get_graph++ derived: dict[str, str] = {}+ is_complete = True+ for workflow in expert.Workflows or []:+ library_agent = workflow.LibraryAgent+ if library_agent is None:+ continue+ try:+ graph = await get_graph(+ library_agent.agentGraphId,+ library_agent.agentGraphVersion,+ user_id,+ include_subgraphs=True,+ )+ # A workflow whose graph is gone resolves to nothing and always+ # will; that is a complete answer, not a failure to retry.+ if graph is None:+ continue+ matched, _ = await match_user_credentials_to_graph(user_id, graph)+ except Exception:+ logger.warning(+ f"Could not derive credentials for workflow #{workflow.id} on "+ f"expert #{expert.id}; leaving the seed pending",+ exc_info=True,+ )+ is_complete = False+ continue+ for meta in matched.values():+ if not is_system_credential(meta.id):+ derived[meta.id] = str(meta.provider)+ return derived, is_complete+++async def _seed_if_needed(user_id: str, expert: prisma.models.Expert) -> None:+ """Seed the allow-list from the expert's workflows, once.++ An incomplete derivation writes what it found but leaves the expert+ unstamped, so the next read retries the workflows that failed. Re-deriving+ is safe because it only ever adds grants — see ``_stamp_seeded`` for the one+ case where that is not good enough.+ """+ if expert.credentialsSeededAt is not None:+ return+ derived, is_complete = await _derive_from_workflows(user_id, expert)+ if derived:+ await prisma.models.ExpertCredential.prisma().create_many(+ data=[+ {+ "expertId": expert.id,+ "credentialId": credential_id,+ "provider": provider,+ }+ for credential_id, provider in derived.items()+ ],+ skip_duplicates=True,+ )+ if not is_complete:+ return+ # Stamped even when nothing was derived: an expert with no workflows has+ # legitimately been offered nothing, and re-deriving on every read would+ # pay for a graph load per workflow on every header render.+ await _stamp_seeded(expert.id)+++async def _stamp_seeded(expert_id: str) -> None:+ """Mark the allow-list as curated, so seeding never runs again.++ Re-seeding is additive, so a pending seed can never undo a *grant* — but it+ can undo a *revoke* by re-deriving the credential the user just removed.+ Revoking therefore finalizes the seed even if derivation never completed:+ an expert missing a grant is a visible, fixable problem, while one that+ silently regains access the user revoked is a broken promise.+ """+ await prisma.models.Expert.prisma().update_many(+ where={"id": expert_id, "credentialsSeededAt": None},+ data={"credentialsSeededAt": datetime.now(timezone.utc)},+ )+++async def _grants(expert_id: str) -> list[prisma.models.ExpertCredential]:+ return await prisma.models.ExpertCredential.prisma().find_many(+ where={"expertId": expert_id}, order={"createdAt": "asc"}+ )+++def _to_refs(+ grants: list[prisma.models.ExpertCredential],+ credentials: list[Credentials],+) -> list[ExpertCredentialRef]:+ """Grants joined against the owner's live credentials.++ A grant whose credential no longer exists is dropped rather than rendered:+ the row is inert (enforcement matches on id, and the id resolves to+ nothing), and showing a logo for a deleted credential would claim access+ the expert does not have.+ """+ by_id = {c.id: c for c in credentials}+ refs: list[ExpertCredentialRef] = []+ for grant in grants:+ credential = by_id.get(grant.credentialId)+ if credential is None:+ continue+ refs.append(+ ExpertCredentialRef(+ credential_id=credential.id,+ provider=str(credential.provider),+ title=credential.title or str(credential.provider),+ type=str(credential.type),+ )+ )+ return refs+++async def list_expert_credentials(+ user_id: str, expert_id: str+) -> list[ExpertCredentialRef]:+ expert = await _owned_expert(user_id, expert_id)+ await _seed_if_needed(user_id, expert)+ grants, credentials = await _grants(expert_id), await _user_credentials(user_id)+ return _to_refs(grants, credentials)+++async def grant_expert_credentials(+ user_id: str, expert_id: str, credential_ids: list[str]+) -> list[ExpertCredentialRef]:+ """Grant credentials to an expert. Unknown or system ids are rejected.++ Rejecting rather than ignoring: a silently dropped id would leave the user+ looking at a management list that disagrees with what they just added.+ """+ expert = await _owned_expert(user_id, expert_id)+ credentials = await _user_credentials(user_id)+ by_id = {c.id: c for c in credentials}++ unknown = [+ credential_id+ for credential_id in credential_ids+ if credential_id not in by_id or is_system_credential(credential_id)+ ]+ if unknown:+ raise ValueError(f"Not your credentials: {', '.join(sorted(unknown))}")++ # Seed before granting so the seed cannot later overwrite an explicit add.+ await _seed_if_needed(user_id, expert)+ if credential_ids:+ await prisma.models.ExpertCredential.prisma().create_many(+ data=[+ {+ "expertId": expert_id,+ "credentialId": credential_id,+ "provider": str(by_id[credential_id].provider),+ }+ for credential_id in credential_ids+ ],+ skip_duplicates=True,+ )+ return _to_refs(await _grants(expert_id), credentials)+++async def revoke_expert_credential(+ user_id: str, expert_id: str, credential_id: str+) -> list[ExpertCredentialRef]:+ expert = await _owned_expert(user_id, expert_id)+ # Seed first: revoking from a never-seeded expert must remove that one+ # credential, not leave an empty list that the next read seeds straight back.+ await _seed_if_needed(user_id, expert)+ await prisma.models.ExpertCredential.prisma().delete_many(+ where={"expertId": expert_id, "credentialId": credential_id}+ )+ # Finalize even if the seed was left pending by a failed derivation, or the+ # next read would re-derive exactly the credential just revoked.+ await _stamp_seeded(expert_id)+ return _to_refs(await _grants(expert_id), await _user_credentials(user_id))+++async def expert_allowed_credential_ids(user_id: str, expert_id: str) -> list[str]:+ """The credential ids *expert_id* may use. Enforcement's source of truth.++ Raises ``ExpertNotFoundError`` for an expert the user does not own, so a+ bad scope fails the run rather than falling through to unrestricted access.+ """+ expert = await _owned_expert(user_id, expert_id)+ await _seed_if_needed(user_id, expert)+ return [grant.credentialId for grant in await _grants(expert_id)]+++def filter_credentials_for_expert(+ credentials: list[Credentials], allowed_ids: set[str]+) -> list[Credentials]:+ """Drop credentials an expert has not been granted, keeping system ones."""+ return [+ credential+ for credential in credentials+ if is_system_credential(credential.id) or credential.id in allowed_ids+ ]diff --git a/autogpt_platform/backend/backend/api/features/experts/credentials_test.py b/autogpt_platform/backend/backend/api/features/experts/credentials_test.pynew file mode 100644index 0000000000..ef9324c8dd--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/credentials_test.py@@ -0,0 +1,203 @@+"""Tests for per-expert credential grants and the enforcement they drive."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+import pytest_mock+from pydantic import SecretStr++from backend.api.features.experts.credentials import (+ _derive_from_workflows,+ _to_refs,+ filter_credentials_for_expert,+)+from backend.data.model import APIKeyCredentials, CredentialsMetaInput+from backend.executor.utils import _enforce_expert_credential_scope+++def _api_key_credential(credential_id: str, provider: str) -> APIKeyCredentials:+ return APIKeyCredentials(+ id=credential_id,+ provider=provider,+ api_key=SecretStr("key"),+ title=f"{provider} key",+ )+++class _Grant:+ def __init__(self, credential_id: str, provider: str) -> None:+ self.credentialId = credential_id+ self.provider = provider+++def test_refs_drop_grants_whose_credential_was_deleted():+ """A grant pointing at a deleted credential is inert, not renderable.++ Rendering it would claim the expert has access it does not have — the id+ resolves to nothing at enforcement time.+ """+ linkedin = _api_key_credential("cred-linkedin", "linkedin")+ grants = [_Grant("cred-linkedin", "linkedin"), _Grant("cred-gone", "notion")]++ refs = _to_refs(grants, [linkedin]) # type: ignore[arg-type]++ assert [ref.credential_id for ref in refs] == ["cred-linkedin"]+ assert refs[0].provider == "linkedin"+++def test_refs_read_title_from_the_live_credential():+ """Titles come from the credential, not the grant, so renames propagate."""+ credential = _api_key_credential("cred-1", "notion")+ credential.title = "Work Notion"++ refs = _to_refs([_Grant("cred-1", "notion")], [credential]) # type: ignore[arg-type]++ assert refs[0].title == "Work Notion"+++def test_filter_drops_ungranted_credentials():+ granted = _api_key_credential("cred-granted", "linkedin")+ ungranted = _api_key_credential("cred-ungranted", "notion")++ kept = filter_credentials_for_expert([granted, ungranted], {"cred-granted"})++ assert [c.id for c in kept] == ["cred-granted"]+++def test_filter_always_keeps_system_credentials(mocker: pytest_mock.MockFixture):+ """Platform LLM keys carry no grant; filtering them would stop every expert+ from running a single LLM block."""+ mocker.patch(+ "backend.api.features.experts.credentials.is_system_credential",+ side_effect=lambda credential_id: credential_id == "cred-system",+ )+ system = _api_key_credential("cred-system", "openai")+ ungranted = _api_key_credential("cred-ungranted", "notion")++ kept = filter_credentials_for_expert([system, ungranted], set())++ assert [c.id for c in kept] == ["cred-system"]+++def test_filter_with_no_grants_keeps_nothing_user_owned():+ """Deny-by-default: an expert with an empty allow-list reaches nothing."""+ credential = _api_key_credential("cred-1", "linkedin")++ assert filter_credentials_for_expert([credential], set()) == []+++async def test_derivation_reports_incomplete_when_a_workflow_fails(+ mocker: pytest_mock.MockFixture,+):+ """A transient graph-load failure must leave the seed pending.++ Stamping here would freeze an under-seeded allow-list in place, and+ enforcement reads that as "reaches nothing" — blocking every run the+ expert has until someone re-granted by hand.+ """+ mocker.patch("backend.data.graph.get_graph", side_effect=RuntimeError("db 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+++async def test_a_workflow_whose_graph_is_gone_still_counts_as_complete(+ mocker: pytest_mock.MockFixture,+):+ """A missing graph resolves to nothing and always will — retrying it every+ read would cost a graph load per header render forever."""+ mocker.patch("backend.data.graph.get_graph", return_value=None)+ 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 True+++async def test_an_expert_with_no_workflows_seeds_completely():+ expert = SimpleNamespace(id="expert-1", Workflows=[])++ derived, is_complete = await _derive_from_workflows("user-1", expert) # type: ignore[arg-type]++ assert derived == {}+ assert is_complete is True+++async def test_execution_is_rejected_when_a_credential_was_not_granted(+ mocker: pytest_mock.MockFixture,+):+ mocker.patch(+ "backend.executor.utils.get_experts_db",+ return_value=AsyncMock(+ expert_allowed_credential_ids=AsyncMock(return_value=["cred-granted"])+ ),+ )++ with pytest.raises(ValueError, match="cred-ungranted"):+ await _enforce_expert_credential_scope(+ "user-1",+ "expert-1",+ {+ "field": CredentialsMetaInput(+ id="cred-ungranted", provider="notion", type="api_key"+ )+ },+ )+++async def test_execution_is_allowed_when_every_credential_was_granted(+ mocker: pytest_mock.MockFixture,+):+ mocker.patch(+ "backend.executor.utils.get_experts_db",+ return_value=AsyncMock(+ expert_allowed_credential_ids=AsyncMock(return_value=["cred-granted"])+ ),+ )++ await _enforce_expert_credential_scope(+ "user-1",+ "expert-1",+ {+ "field": CredentialsMetaInput(+ id="cred-granted", provider="linkedin", type="api_key"+ )+ },+ )+++async def test_a_run_with_no_credentials_skips_the_lookup_entirely(+ mocker: pytest_mock.MockFixture,+):+ accessor = mocker.patch("backend.executor.utils.get_experts_db")++ await _enforce_expert_credential_scope("user-1", "expert-1", None)++ accessor.assert_not_called()diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pyindex 524c170d1f..b0670bfde7 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -11,6 +11,12 @@ from prisma.enums import ResourceVisibilityfrom pydantic import JsonValue, ValidationErrorfrom backend.api.features.experts import raise_attachments, scheduling++# Re-exported so `db_accessors.experts_db()` resolves the same attribute name+# on both branches: the module here, and the RPC client stub in db_manager.+from backend.api.features.experts.credentials import (+ expert_allowed_credential_ids as expert_allowed_credential_ids,+)from backend.api.features.experts.errors import (ACTIVE_EXPERT_LIMIT,LIFETIME_RAISED_EXPERT_LIMIT,diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.pyindex a61c8c811d..7cfa2300d6 100644--- a/autogpt_platform/backend/backend/api/features/experts/models.py+++ b/autogpt_platform/backend/backend/api/features/experts/models.py@@ -106,6 +106,19 @@ class ExpertIdentity(BaseModel):is_archived: bool+class ExpertCredentialRef(BaseModel):+ """One integration credential an expert is allowed to use.++ ``title``/``type`` are read from the owner's live credential rather than+ stored on the grant, so a renamed credential renames everywhere at once.+ """++ credential_id: str+ provider: str+ title: str+ type: str++class Expert(BaseModel):id: strname: strdiff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.pyindex 52f571f9f6..31626a2d54 100644--- a/autogpt_platform/backend/backend/api/features/experts/routes.py+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py@@ -3,6 +3,7 @@ import fastapifrom fastapi import APIRouter, Securityfrom pydantic import BaseModel, Field, field_validator+from backend.api.features.experts import credentials as expert_credentialsfrom backend.api.features.experts import experts_db, schedulingfrom backend.api.features.experts.models import (EXPERT_AVATAR_URL_MAX_LENGTH,@@ -11,6 +12,7 @@ from backend.api.features.experts.models import (MAX_RAISE_ATTACHMENTS,WEEKLY_BUDGET_MAX_CREDITS,Expert,+ ExpertCredentialRef,ExpertDetachPreview,ExpertIdentity,ExpertPod,@@ -284,6 +286,67 @@ async def list_expert_runs(raise fastapi.HTTPException(status_code=404, detail=str(e))+class GrantCredentialsRequest(BaseModel):+ credential_ids: list[str] = Field(min_length=1, max_length=50)+++ "/{expert_id}/credentials",+ operation_id="list_expert_credentials",+ responses={404: {"description": "Expert not found"}},+)+async def list_expert_credentials(+ expert_id: str,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> list[ExpertCredentialRef]:+ """The integrations this expert is allowed to use."""+ try:+ return await expert_credentials.list_expert_credentials(user_id, expert_id)+ except experts_db.ExpertNotFoundError as e:+ raise fastapi.HTTPException(status_code=404, detail=str(e))+++ "/{expert_id}/credentials",+ operation_id="grant_expert_credentials",+ responses={+ 404: {"description": "Expert not found"},+ 400: {"description": "Unknown credential"},+ },+)+async def grant_expert_credentials(+ expert_id: str,+ request: GrantCredentialsRequest,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> list[ExpertCredentialRef]:+ try:+ return await expert_credentials.grant_expert_credentials(+ user_id, expert_id, request.credential_ids+ )+ except experts_db.ExpertNotFoundError as e:+ raise fastapi.HTTPException(status_code=404, detail=str(e))+ except ValueError as e:+ raise fastapi.HTTPException(status_code=400, detail=str(e))+++ "/{expert_id}/credentials/{credential_id}",+ operation_id="revoke_expert_credential",+ responses={404: {"description": "Expert not found"}},+)+async def revoke_expert_credential(+ expert_id: str,+ credential_id: str,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> list[ExpertCredentialRef]:+ try:+ return await expert_credentials.revoke_expert_credential(+ user_id, expert_id, credential_id+ )+ except experts_db.ExpertNotFoundError as e:+ raise fastapi.HTTPException(status_code=404, detail=str(e))++@router.patch("/{expert_id}/soul",operation_id="update_expert_soul",diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex f382cdbf3c..56dd410be3 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -387,6 +387,7 @@ class RunAgentTool(BaseTool):user_id=user_id,params=params,session_id=session_id,+ expert_id=session.expert_id,)if prereq_error:return prereq_error@@ -614,6 +615,7 @@ class RunAgentTool(BaseTool):user_id: str,params: "RunAgentInput",session_id: str,+ expert_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], ToolResponseBase | None]:"""Validate credentials and inputs before execution.@@ -625,7 +627,7 @@ class RunAgentTool(BaseTool):(graph_credentials, error_response) — error_response is None when ready."""graph_credentials, missing_creds = await match_user_credentials_to_graph(- user_id, graph+ user_id, graph, expert_id)# --- Reject unknown input fields (always, even for dry runs) ---diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.pyindex 6c17760234..0a8199d199 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@@ -205,7 +205,12 @@ class SetupAgentWebhookTriggerTool(BaseTool):return config_requiredagent_credentials, card = await self._resolve_credentials(- user_id, graph, trigger_node, kwargs.get("credentials") or {}, session_id+ user_id,+ graph,+ trigger_node,+ kwargs.get("credentials") or {},+ session_id,+ session.expert_id,)if card:return card@@ -332,6 +337,7 @@ class SetupAgentWebhookTriggerTool(BaseTool):trigger_node: Node,selection: dict[str, str],session_id: str | None,+ expert_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], SetupRequirementsResponse | None]:"""Resolve the agent's credentials, or return a setup card to fill them.@@ -343,12 +349,12 @@ class SetupAgentWebhookTriggerTool(BaseTool):Returns ``(agent_credentials, None)`` when ready to proceed, or``({}, SetupRequirementsResponse)`` when the user must act first."""- matched, _ = await match_user_credentials_to_graph(user_id, graph)+ matched, _ = await match_user_credentials_to_graph(user_id, graph, expert_id)trigger_cred_key = self._trigger_cred_key(graph, trigger_node)effective = dict(matched)if selection:- available = await get_user_credentials(user_id)+ available = await get_user_credentials(user_id, expert_id)effective.update(self._resolve_selection(graph, selection, available))# Force the trigger credential into the card until it's explicitlydiff --git a/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py b/autogpt_platform/backend/backend/copilot/tools/test_dry_run.pyindex 25c5007b9a..6b5af569a6 100644--- a/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py+++ b/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py@@ -754,7 +754,7 @@ async def test_run_agent_session_dry_run_overrides_kwargs():captured_params = {}- async def capture_prerequisites(graph, user_id, params, session_id):+ async def capture_prerequisites(graph, user_id, params, session_id, expert_id=None):captured_params["dry_run"] = params.dry_runreturn {}, None@@ -796,7 +796,7 @@ async def test_run_agent_session_dry_run_false_allows_scheduling():captured_params = {}- async def capture_prerequisites(graph, user_id, params, session_id):+ async def capture_prerequisites(graph, user_id, params, session_id, expert_id=None):captured_params["dry_run"] = params.dry_runreturn {}, None@@ -840,7 +840,7 @@ async def test_run_agent_session_dry_run_false_allows_llm_dry_run_true():captured_params = {}- async def capture_prerequisites(graph, user_id, params, session_id):+ async def capture_prerequisites(graph, user_id, params, session_id, expert_id=None):captured_params["dry_run"] = params.dry_runreturn {}, Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.pyindex 5e494c4788..6021ced003 100644--- a/autogpt_platform/backend/backend/copilot/tools/utils.py+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py@@ -262,6 +262,7 @@ async def get_or_create_library_agent(async def match_credentials_to_requirements(user_id: str,requirements: dict[str, CredentialsFieldInfo],+ expert_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], list[CredentialsMetaInput]]:"""Match user's credentials against a dictionary of credential requirements.@@ -274,7 +275,7 @@ async def match_credentials_to_requirements(if not requirements:return matched, missing- available_creds = await get_user_credentials(user_id)+ available_creds = await get_user_credentials(user_id, expert_id)for field_name, field_info in requirements.items():matching_cred = find_matching_credential(available_creds, field_info)@@ -314,10 +315,35 @@ async def match_credentials_to_requirements(return matched, missing-async def get_user_credentials(user_id: str) -> list[Credentials]:- """Get all available credentials for a user."""+async def get_user_credentials(+ user_id: str, expert_id: str | None = None+) -> list[Credentials]:+ """Get the credentials available for a user, scoped to an expert if given."""creds_manager = IntegrationCredentialsManager()- return await creds_manager.store.get_all_creds(user_id)+ credentials = await creds_manager.store.get_all_creds(user_id)+ return await scope_credentials_to_expert(user_id, expert_id, credentials)+++async def scope_credentials_to_expert(+ user_id: str,+ expert_id: str | None,+ credentials: list[Credentials],+) -> list[Credentials]:+ """Narrow *credentials* to what *expert_id* has been granted.++ A plain (non-expert) session passes ``expert_id=None`` and keeps everything.+ Filtering at selection time — rather than only at the executor's gate — is+ what makes an ungranted integration surface as "missing credentials", so the+ user is offered the connect/grant step instead of a run that fails later.+ """+ if expert_id is None:+ return credentials++ from backend.api.features.experts.credentials import filter_credentials_for_expert+ from backend.data.db_accessors import experts_db++ allowed = set(await experts_db().expert_allowed_credential_ids(user_id, expert_id))+ return filter_credentials_for_expert(credentials, allowed)def find_matching_credential(@@ -355,6 +381,7 @@ def create_credential_meta_from_match(async def match_user_credentials_to_graph(user_id: str,graph: GraphModel,+ expert_id: str | None = None,) -> tuple[dict[str, CredentialsMetaInput], list[str]]:"""Match user's available credentials against graph's required credentials.@@ -381,9 +408,11 @@ async def match_user_credentials_to_graph(if not aggregated_creds:return graph_credentials_inputs, missing_creds- # Get all available credentials for the user+ # Get the credentials available for the user, narrowed to the expert's grantscreds_manager = IntegrationCredentialsManager()- available_creds = await creds_manager.store.get_all_creds(user_id)+ available_creds = await scope_credentials_to_expert(+ user_id, expert_id, await creds_manager.store.get_all_creds(user_id)+ )# For each required credential field, find a matching user credential# field_info.provider is a frozenset because aggregate_credentials_inputs()@@ -502,6 +531,7 @@ def _credential_is_for_mcp_server(async def check_user_has_required_credentials(user_id: str,required_credentials: list[CredentialsMetaInput],+ expert_id: str | None = None,) -> list[CredentialsMetaInput]:"""Check which required credentials the user is missing.@@ -517,7 +547,9 @@ async def check_user_has_required_credentials(return []creds_manager = IntegrationCredentialsManager()- available_creds = await creds_manager.store.get_all_creds(user_id)+ available_creds = await scope_credentials_to_expert(+ user_id, expert_id, await creds_manager.store.get_all_creds(user_id)+ )missing: list[CredentialsMetaInput] = []for required in required_credentials:diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 40813dfade..4a980211d1 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -2,6 +2,7 @@ import loggingfrom contextlib import asynccontextmanagerfrom typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, TypeVar, cast+from backend.api.features.experts import credentials as expert_credentialsfrom backend.api.features.experts import experts_dbfrom backend.api.features.experts import scheduling as experts_schedulingfrom backend.api.features.library.db import (@@ -516,6 +517,7 @@ class DatabaseManager(AppService):list_experts = _(experts_db.list_experts)resolve_private_expert_tenancy = _(experts_db.resolve_private_expert_tenancy)enforce_expert_run_budget = _(experts_scheduling.enforce_expert_run_budget)+ expert_allowed_credential_ids = _(expert_credentials.expert_allowed_credential_ids)update_soul = _(experts_db.update_soul)update_soul_if_current = _(experts_db.update_soul_if_current)update_soul_fields = _(experts_db.update_soul_fields)@@ -889,6 +891,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):list_experts = d.list_expertsresolve_private_expert_tenancy = d.resolve_private_expert_tenancyenforce_expert_run_budget = d.enforce_expert_run_budget+ expert_allowed_credential_ids = d.expert_allowed_credential_idsupdate_soul = d.update_soulupdate_soul_if_current = d.update_soul_if_currentupdate_soul_fields = d.update_soul_fieldsdiff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex 3e81a5ffbf..19866a8556 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -44,6 +44,7 @@ from backend.data.model import (NodeExecutionStats,)from backend.data.rabbitmq import Exchange, ExchangeType, Queue, RabbitMQConfig+from backend.integrations.credentials_store import is_system_credentialfrom backend.util.clients import (get_async_execution_event_bus,get_async_execution_queue,@@ -1193,6 +1194,41 @@ async def _resolve_expert_execution_tenancy(return await get_experts_db().resolve_private_expert_tenancy(user_id, expert_id)+async def _enforce_expert_credential_scope(+ user_id: str,+ expert_id: str,+ graph_credentials_inputs: Optional[Mapping[str, CredentialsMetaInput]],+) -> None:+ """Reject a run that would use credentials this expert was not granted.++ The gate lives here rather than at each caller because every expert-attributed+ run funnels through ``add_graph_execution`` — schedules, webhook triggers and+ copilot tool runs alike. Enforcing at creation also means a revoke takes effect+ on the next run instead of only on newly created schedules.++ System credentials (platform LLM keys) carry no grant and are always allowed;+ filtering them would stop every expert from running an LLM block.+ """+ if not graph_credentials_inputs:+ return+ allowed = set(+ await get_experts_db().expert_allowed_credential_ids(user_id, expert_id)+ )+ denied = sorted(+ {+ meta.id+ for meta in graph_credentials_inputs.values()+ if not is_system_credential(meta.id) and meta.id not in allowed+ }+ )+ if denied:+ raise ValueError(+ f"Expert #{expert_id} has not been given access to credentials "+ f"{', '.join(denied)}. Grant them on the expert's page to let it "+ f"run this workflow."+ )++async def add_graph_execution(graph_id: str,user_id: str,@@ -1331,6 +1367,9 @@ async def add_graph_execution(user_id, expert_id)await _enforce_expert_run_budget(user_id, expert_id)+ await _enforce_expert_credential_scope(+ user_id, expert_id, graph_credentials_inputs+ )parent_exec_id = (execution_context.parent_execution_id if execution_context else Nonediff --git a/autogpt_platform/backend/migrations/20260828120000_add_expert_credentials/migration.sql b/autogpt_platform/backend/migrations/20260828120000_add_expert_credentials/migration.sqlnew file mode 100644index 0000000000..1eaf8b4216--- /dev/null+++ b/autogpt_platform/backend/migrations/20260828120000_add_expert_credentials/migration.sql@@ -0,0 +1,25 @@+-- CreateTable+CREATE TABLE "ExpertCredential" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "expertId" TEXT NOT NULL,+ "credentialId" TEXT NOT NULL,+ "provider" TEXT NOT NULL,++ CONSTRAINT "ExpertCredential_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "ExpertCredential_expertId_credentialId_key" ON "ExpertCredential"("expertId", "credentialId");++-- CreateIndex+CREATE INDEX "ExpertCredential_expertId_idx" ON "ExpertCredential"("expertId");++-- AddForeignKey+ALTER TABLE "ExpertCredential" ADD CONSTRAINT "ExpertCredential_expertId_fkey" FOREIGN KEY ("expertId") REFERENCES "Expert"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AlterTable+-- Left NULL for every existing expert on purpose: the first read of an+-- expert's integrations seeds the allow-list from its installed workflows,+-- so enforcement cannot lock out a roster that predates this table.+ALTER TABLE "Expert" ADD COLUMN "credentialsSeededAt" TIMESTAMP(3);diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 6ec7571457..1858f7187f 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -968,7 +968,14 @@ model Expert {// and triggers. Chat is never paused. Cleared by the resume endpoint.schedulesPausedAt DateTime?+ // Null until the credential allow-list has been seeded from the expert's+ // installed workflows. Distinguishes "never curated" from "deliberately+ // empty": without it, revoking an expert's last credential would look+ // identical to a fresh expert and re-seed the grant straight back.+ credentialsSeededAt DateTime?+Workflows ExpertWorkflow[]+ Credentials ExpertCredential[]ChatSessions ChatSession[]GraphExecutions AgentGraphExecution[]AgentPresets AgentPreset[]@@ -1024,6 +1031,31 @@ model ExpertWorkflow {@@index([expertId])}+// Which of the owner's integration credentials an expert may use.+// Deny-by-default: an expert with no rows here reaches nothing, so the+// seeding marker on Expert (credentialsSeededAt) is what keeps existing+// experts working across the migration.+model ExpertCredential {+ id String @id @default(uuid())+ createdAt DateTime @default(now())++ expertId String+ Expert Expert @relation(fields: [expertId], references: [id], onDelete: Cascade)++ // IntegrationCredential.id for USER-scoped rows. Deliberately NOT a foreign+ // key: system credentials (platform LLM keys built from settings) never have+ // a row at all, and reads intersect grants against the user's live+ // credentials anyway — so a deleted credential leaves an inert grant rather+ // than blocking the delete or cascading a revoke the user did not ask for.+ credentialId String+ // Denormalized so listing an expert's integrations never has to decrypt a+ // payload just to learn which logo to draw.+ provider String++ @@unique([expertId, credentialId])+ @@index([expertId])+}+// Audit log for expert schedule pauses (budget breach, archive). "All// pauses logged and reversible": resume stamps clearedAt on the open row.model ExpertPauseEvent {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-integrations.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-integrations.test.tsxnew file mode 100644index 0000000000..bf14662287--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-integrations.test.tsx@@ -0,0 +1,147 @@+import { getListExpertCredentialsMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";+import type { ExpertCredentialRef } from "@/app/api/__generated__/models/expertCredentialRef";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ within,+} from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { ThreadHeader } from "../components/ChatMessagesContainer/components/ThreadHeader";++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return { ...actual, useGetFlag: () => true };+});++const mariaIdentity = {+ id: "expert-maria",+ name: "Maria",+ avatarUrl: null,+ role: "Marketing Strategist",+ isArchived: false,+ readOnlyReason: null,+};++function credential(provider: string): ExpertCredentialRef {+ return {+ credential_id: `cred-${provider}`,+ provider,+ title: `${provider} account`,+ type: "oauth2",+ };+}++function renderHeader() {+ return render(+ <ThreadHeader+ expertIdentity={mariaIdentity}+ readOnly={false}+ areFilesOpen={false}+ />,+ );+}++describe("expert integrations in the thread header", () => {+ it("shows the first three logos and counts the rest", async () => {+ server.use(+ getListExpertCredentialsMockHandler([+ credential("linkedin"),+ credential("notion"),+ credential("github"),+ credential("slack"),+ credential("gmail"),+ ]),+ );++ renderHeader();++ const cluster = await screen.findByTestId("expert-integrations");+ expect(within(cluster).getAllByRole("img")).toHaveLength(3);+ expect(within(cluster).getByText("+2")).toBeDefined();+ });++ it("omits the counter when everything fits", async () => {+ server.use(+ getListExpertCredentialsMockHandler([+ credential("linkedin"),+ credential("notion"),+ ]),+ );++ renderHeader();++ const cluster = await screen.findByTestId("expert-integrations");+ expect(within(cluster).getAllByRole("img")).toHaveLength(2);+ expect(within(cluster).queryByText(/^\+/)).toBeNull();+ });++ it("lists every integration by name once opened", async () => {+ server.use(+ getListExpertCredentialsMockHandler([+ credential("linkedin"),+ credential("notion"),+ credential("github"),+ credential("slack"),+ ]),+ );++ renderHeader();+ await userEvent.click(await screen.findByTestId("expert-integrations"));++ expect(await screen.findByText("slack account")).toBeDefined();+ expect(screen.getByText("linkedin account")).toBeDefined();+ expect(+ screen.getByRole("link", { name: /Manage what Maria can access/ }),+ ).toBeDefined();+ });++ it("names an MCP integration after the service, not its URL", async () => {+ server.use(+ getListExpertCredentialsMockHandler([+ {+ credential_id: "cred-mcp",+ provider: "mcp",+ title: "MCP: mcp.sentry.dev",+ type: "host_scoped",+ },+ ]),+ );++ renderHeader();+ await userEvent.click(await screen.findByTestId("expert-integrations"));++ expect(await screen.findByText("Sentry")).toBeDefined();+ expect(screen.queryByText("MCP: mcp.sentry.dev")).toBeNull();+ });++ it("keeps the integration's name when its logo fails to load", async () => {+ server.use(getListExpertCredentialsMockHandler([credential("linkedin")]));++ renderHeader();++ const cluster = await screen.findByTestId("expert-integrations");+ const logo = within(cluster).getByRole("img", { name: "LinkedIn" });+ fireEvent.error(logo);++ // The PNG is missing for plenty of providers, so the fallback glyph must+ // still announce which integration it stands for.+ expect(+ within(cluster).getByRole("img", { name: "LinkedIn" }),+ ).toBeDefined();+ });++ it("renders nothing when the expert reaches no integrations", async () => {+ server.use(getListExpertCredentialsMockHandler([]));++ renderHeader();++ expect(await screen.findByTestId("expert-thread-header")).toBeDefined();+ expect(screen.queryByTestId("expert-integrations")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertIntegrations/ExpertIntegrations.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertIntegrations/ExpertIntegrations.tsxnew file mode 100644index 0000000000..9bec976368--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertIntegrations/ExpertIntegrations.tsx@@ -0,0 +1,80 @@+"use client";++import Link from "next/link";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/molecules/Popover/Popover";+import { IntegrationLogo } from "@/components/molecules/IntegrationLogo/IntegrationLogo";+import {+ formatCredentialName,+ formatProviderName,+} from "@/components/contextual/IntegrationsPanel/helpers";+import { useExpertIntegrations } from "./useExpertIntegrations";++interface Props {+ expertId: string;+ expertName: string;+}++const VISIBLE_LOGOS = 3;++/** The integrations this expert can reach, under its name in the thread header.+ *+ * Renders nothing when the expert has none: a header that says "Integrations"+ * above an empty row reads as a loading failure rather than an empty state.+ */+export function ExpertIntegrations({ expertId, expertName }: Props) {+ const { integrations } = useExpertIntegrations(expertId);++ if (integrations.length === 0) return null;++ const visible = integrations.slice(0, VISIBLE_LOGOS);+ const overflow = integrations.length - visible.length;++ return (+ <Popover>+ <PopoverTrigger+ className="ml-2 flex shrink-0 items-center gap-1 rounded-full px-1.5 py-1 hover:bg-zinc-100"+ aria-label={`${expertName}'s integrations`}+ data-testid="expert-integrations"+ >+ {visible.map((integration) => (+ <IntegrationLogo+ key={integration.credential_id}+ provider={integration.provider}+ alt={formatProviderName(integration.provider)}+ />+ ))}+ {overflow > 0 ? (+ <span className="ml-0.5 text-xs text-zinc-500">+{overflow}</span>+ ) : null}+ </PopoverTrigger>+ <PopoverContent align="start" className="w-64 p-3">+ <div className="mb-2 text-xs font-medium uppercase tracking-[0.14em] text-zinc-400">+ Integrations+ </div>+ <ul className="flex flex-col gap-2">+ {integrations.map((integration) => (+ <li+ key={integration.credential_id}+ className="flex items-center gap-2"+ >+ <IntegrationLogo provider={integration.provider} />+ <span className="truncate text-sm text-zinc-700">+ {formatCredentialName(integration.title, integration.provider)}+ </span>+ </li>+ ))}+ </ul>+ <Link+ href={`/team/${expertId}`}+ className="mt-3 block text-xs text-zinc-500 underline hover:text-zinc-800"+ >+ Manage what {expertName} can access+ </Link>+ </PopoverContent>+ </Popover>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertIntegrations/useExpertIntegrations.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertIntegrations/useExpertIntegrations.tsnew file mode 100644index 0000000000..3e9a0ecf4b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertIntegrations/useExpertIntegrations.ts@@ -0,0 +1,13 @@+import { useListExpertCredentials } from "@/app/api/__generated__/endpoints/experts/experts";+import { okData } from "@/app/api/helpers";++export function useExpertIntegrations(expertId: string | null) {+ const query = useListExpertCredentials(expertId ?? "", {+ query: {+ enabled: Boolean(expertId),+ select: (response) => okData(response) ?? [],+ },+ });++ return { integrations: query.data ?? [] };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsxindex 8e5b021c84..9764585a78 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsx@@ -1,6 +1,7 @@import { cn } from "@/lib/utils";import type { ExpertIdentity } from "../../../useExpertMap";import { ExpertAvatar } from "./ExpertAvatar/ExpertAvatar";+import { ExpertIntegrations } from "./ExpertIntegrations/ExpertIntegrations";import { ExpertSchedulesButton } from "./ExpertSchedulesButton/ExpertSchedulesButton";// Autopilot's product-facing title when a session carries no expert identity.@@ -52,6 +53,12 @@ export function ThreadHeader({{expertIdentity?.role ?? DEFAULT_EXPERT_ROLE}</span></div>+ {expertIdentity && !expertIdentity.isArchived && (+ <ExpertIntegrations+ expertId={expertIdentity.id}+ expertName={expertIdentity.name}+ />+ )}{expertIdentity && !readOnly && !expertIdentity.isArchived && (<ExpertSchedulesButtonexpertId={expertIdentity.id}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.tsindex 56d09d8edc..775c2d205e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/resultHelpers.ts@@ -1,3 +1,5 @@+export { integrationIconSrc } from "@/components/molecules/IntegrationLogo/helpers";+export function asObject(value: unknown): Record<string, unknown> | null {if (typeof value === "string") {try {@@ -22,15 +24,6 @@ export function safeHostname(url: string): string | null {}}-export function integrationIconSrc(provider: string): string | null {- const slug = provider- .trim()- .toLowerCase()- .replace(/[\s-]+/g, "_")- .replace(/[^a-z0-9_]/g, "");- return slug ? `/integrations/${slug}.png` : null;-}-// Every backend tool response carries these envelope fields; cards read the// domain payload, so shape detection runs on the stripped object.const BASE_RESPONSE_KEYS = new Set(["type", "message", "session_id"]);diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsxnew file mode 100644index 0000000000..c36ee31995--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsx@@ -0,0 +1,318 @@+import {+ getGetExpertMockHandler,+ getListExpertCredentialsMockHandler,+ getListExpertRunsMockHandler,+} from "@/app/api/__generated__/endpoints/experts/experts.msw";+import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { ExpertCredentialRef } from "@/app/api/__generated__/models/expertCredentialRef";+import { server } from "@/mocks/mock-server";+import {+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { beforeEach, describe, expect, it, vi } from "vitest";+import ExpertDetailPage from "../page";++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useFlagStatus: () => ({ enabled: true, ready: true }),+ };+});++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: vi.fn(),+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ usePathname: () => "/team/expert-maria",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({ expertId: "expert-maria" }),+ notFound: () => {+ throw new Error("NEXT_NOT_FOUND");+ },+}));++const maria = {+ id: "expert-maria",+ name: "Maria",+ avatar_url: null,+ color: "",+ role: "Marketing Strategist",+ tagline: null,+ bio: "Maria is a senior marketing strategist.",+ skills: [],+ identity: "You are Maria.",+ voice_preferences: "Direct.",+ voice_samples: [],+ boundaries: "",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: null,+ is_archived: false,+ workflows: [],+ weekly_budget: null,+ weekly_spend: 0,+ schedules_paused_at: null,+ pod_id: null,+} as unknown as Expert;++const linkedin: ExpertCredentialRef = {+ credential_id: "cred-linkedin",+ provider: "linkedin",+ title: "Work LinkedIn",+ type: "oauth2",+};++beforeEach(() => {+ server.use(+ getGetExpertMockHandler(maria),+ getGetV1ListExecutionSchedulesForAUserMockHandler([]),+ getListExpertRunsMockHandler([]),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json([+ {+ id: "cred-linkedin",+ provider: "linkedin",+ type: "oauth2",+ title: "Work LinkedIn",+ },+ {+ id: "cred-notion",+ provider: "notion",+ type: "api_key",+ title: "Team Notion",+ },+ ]),+ ),+ );+});++describe("managing an expert's integrations", () => {+ it("lists what the expert can reach", async () => {+ server.use(getListExpertCredentialsMockHandler([linkedin]));++ render(<ExpertDetailPage />);++ const section = await screen.findByTestId("expert-integrations-section");+ expect(await within(section).findByText("Work LinkedIn")).toBeDefined();+ expect(within(section).getByText("LinkedIn")).toBeDefined();+ });++ it("explains the empty state instead of showing a bare list", async () => {+ server.use(getListExpertCredentialsMockHandler([]));++ render(<ExpertDetailPage />);++ const section = await screen.findByTestId("expert-integrations-section");+ expect(+ await within(section).findByText(+ /Nothing connected yet\. Add a tool and Maria can use it/,+ ),+ ).toBeDefined();+ });++ it("revokes an integration through the API", async () => {+ let revoked: string | null = null;+ server.use(+ getListExpertCredentialsMockHandler([linkedin]),+ http.delete(+ "*/api/experts/expert-maria/credentials/:credentialId",+ ({ params }) => {+ revoked = params.credentialId as string;+ return HttpResponse.json([]);+ },+ ),+ );++ render(<ExpertDetailPage />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Remove Work LinkedIn" }),+ );++ await waitFor(() => expect(revoked).toBe("cred-linkedin"));+ });++ it("only offers credentials the expert does not already have", async () => {+ let granted: string[] = [];+ server.use(+ getListExpertCredentialsMockHandler([linkedin]),+ http.post(+ "*/api/experts/expert-maria/credentials",+ async ({ request }) => {+ const body = (await request.json()) as { credential_ids: string[] };+ granted = body.credential_ids;+ return HttpResponse.json([linkedin]);+ },+ ),+ );++ render(<ExpertDetailPage />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Add integration/ }),+ );++ expect(await screen.findByText("Team Notion")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Work LinkedIn" })).toBeNull();++ await userEvent.click(screen.getByText("Team Notion"));+ await waitFor(() => expect(granted).toEqual(["cred-notion"]));+ });++ it("offers connecting a new service when there is nothing left to grant", async () => {+ server.use(+ getListExpertCredentialsMockHandler([]),+ http.get("*/api/integrations/providers", () => HttpResponse.json([])),+ http.get("*/api/integrations/credentials", () => HttpResponse.json([])),+ );++ render(<ExpertDetailPage />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Add integration/ }),+ );+ expect(await screen.findByText("Nothing connected yet.")).toBeDefined();++ await userEvent.click(+ screen.getByRole("button", { name: /Connect a new service/ }),+ );++ expect(await screen.findByLabelText("Search services")).toBeDefined();+ expect(+ screen.getByText(+ "Pick a service to connect. Maria will be able to use it on your behalf.",+ ),+ ).toBeDefined();+ });++ it("grants only the credential the dialog created", async () => {+ const workLinkedin = {+ id: "cred-linkedin",+ provider: "linkedin",+ type: "oauth2",+ title: "Work LinkedIn",+ };+ const teamNotion = {+ id: "cred-notion",+ provider: "notion",+ type: "api_key",+ title: "Team Notion",+ };+ // Lands on the account while the dialog is open, e.g. from another tab.+ const teamSlack = {+ id: "cred-slack",+ provider: "slack",+ type: "oauth2",+ title: "Team Slack",+ };+ let connected = [workLinkedin];+ const granted: string[][] = [];++ server.use(+ getListExpertCredentialsMockHandler([linkedin]),+ http.get("*/api/integrations/providers", () =>+ HttpResponse.json([+ {+ name: "notion",+ description: "Docs and databases",+ supported_auth_types: ["api_key"],+ },+ ]),+ ),+ http.get("*/api/integrations/credentials", () =>+ HttpResponse.json(connected),+ ),+ http.post("*/api/integrations/notion/credentials", () => {+ connected = [workLinkedin, teamSlack, teamNotion];+ return HttpResponse.json(teamNotion, { status: 201 });+ }),+ http.post(+ "*/api/experts/expert-maria/credentials",+ async ({ request }) => {+ const body = (await request.json()) as { credential_ids: string[] };+ granted.push(body.credential_ids);+ return HttpResponse.json([linkedin]);+ },+ ),+ );++ render(<ExpertDetailPage />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Add integration/ }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: /Connect a new service/ }),+ );+ await userEvent.click(await screen.findByText("Notion"));++ await userEvent.type(+ await screen.findByPlaceholderText("My Notion key"),+ "Team Notion",+ );+ await userEvent.type(screen.getByPlaceholderText("sk-..."), "secret-value");+ await userEvent.click(screen.getByRole("button", { name: "Save API key" }));++ await waitFor(() => expect(granted).toEqual([["cred-notion"]]));+ });++ it("does not offer integrations when the expert's own list fails to load", async () => {+ let grantAttempts = 0;+ server.use(+ http.get("*/api/experts/expert-maria/credentials", () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ http.post("*/api/experts/expert-maria/credentials", () => {+ grantAttempts += 1;+ return HttpResponse.json([]);+ }),+ );++ render(<ExpertDetailPage />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Add integration/ }),+ );++ expect(+ await screen.findByText("Couldn't load what Maria already has."),+ ).toBeDefined();+ expect(screen.queryByText("Team Notion")).toBeNull();+ expect(grantAttempts).toBe(0);+ });++ it("names an MCP credential after the service behind it", async () => {+ server.use(+ getListExpertCredentialsMockHandler([+ {+ credential_id: "cred-mcp",+ provider: "mcp",+ title: "MCP: mcp.sentry.dev",+ type: "host_scoped",+ },+ ]),+ );++ render(<ExpertDetailPage />);++ const section = await screen.findByTestId("expert-integrations-section");+ expect(await within(section).findByText("Sentry")).toBeDefined();+ expect(within(section).getByText("MCP server")).toBeDefined();+ expect(within(section).getByText("Ready")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertIntegrationsSection/ExpertIntegrationsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertIntegrationsSection/ExpertIntegrationsSection.tsxnew file mode 100644index 0000000000..e0341ec703--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertIntegrationsSection/ExpertIntegrationsSection.tsx@@ -0,0 +1,216 @@+"use client";++import {+ Avatar,+ AvatarFallback,+ AvatarImage,+} from "@/components/atoms/Avatar/Avatar";+import { Badge } from "@/components/atoms/Badge/Badge";+import { Button } from "@/components/atoms/Button/Button";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { Icon } from "@/components/atoms/Icon/Icon";+import { ConnectServiceDialog } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/ConnectServiceDialog";+import {+ formatCredentialName,+ formatCredentialSource,+ formatProviderName,+} from "@/components/contextual/IntegrationsPanel/helpers";+import { IntegrationLogo } from "@/components/molecules/IntegrationLogo/IntegrationLogo";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/molecules/Popover/Popover";+import { Delete02Icon, PlusSignIcon } from "@hugeicons/core-free-icons";+import { useExpertIntegrationsSection } from "./useExpertIntegrationsSection";++interface Props {+ expertId: string;+ expertName: string;+ expertAvatarUrl: string | null;+}++export function ExpertIntegrationsSection({+ expertId,+ expertName,+ expertAvatarUrl,+}: Props) {+ const {+ granted,+ grantable,+ isAdding,+ openAdd,+ closeAdd,+ isConnecting,+ openConnect,+ closeConnect,+ connectCredential,+ addIntegration,+ removeIntegration,+ isGranting,+ isRevoking,+ isLoading,+ isError,+ isGrantableLoading,+ isGrantableError,+ refetch,+ } = useExpertIntegrationsSection(expertId);++ return (+ <section data-testid="expert-integrations-section">+ <div className="mb-2.5 flex items-center justify-between">+ <div className="text-xs font-medium uppercase tracking-[0.14em] text-zinc-400">+ Integrations+ </div>+ <Popover+ open={isAdding}+ onOpenChange={(open) => (open ? openAdd() : closeAdd())}+ >+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ size="small"+ leftIcon={<Icon icon={PlusSignIcon} size={16} />}+ >+ Add integration+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-72 p-2">+ {isGrantableLoading ? (+ <div className="flex flex-col gap-2 p-2">+ <Skeleton className="h-8 w-full" />+ <Skeleton className="h-8 w-full" />+ </div>+ ) : isGrantableError ? (+ <p className="px-2 py-3 text-sm text-zinc-500">+ Couldn't load your services.+ </p>+ ) : isError ? (+ <p className="px-2 py-3 text-sm text-zinc-500">+ Couldn't load what {expertName} already has.+ </p>+ ) : grantable.length === 0 ? (+ <p className="px-2 py-3 text-sm text-zinc-500">+ {granted.length === 0+ ? "Nothing connected yet."+ : `${expertName} can already use everything you've connected.`}+ </p>+ ) : (+ <ul className="max-h-72 overflow-y-auto">+ {grantable.map((credential) => (+ <li key={credential.id}>+ <button+ type="button"+ disabled={isGranting}+ className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left hover:bg-zinc-50 disabled:opacity-50"+ onClick={() => addIntegration(credential.id)}+ >+ <IntegrationLogo provider={credential.provider} />+ <span className="min-w-0 flex-1 truncate text-sm text-zinc-700">+ {credential.title+ ? formatCredentialName(+ credential.title,+ credential.provider,+ )+ : formatProviderName(credential.provider)}+ </span>+ </button>+ </li>+ ))}+ </ul>+ )}++ <div className="mt-1 border-t border-zinc-100 pt-1">+ <button+ type="button"+ disabled={isGranting}+ className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm text-zinc-700 hover:bg-zinc-50 disabled:opacity-50"+ onClick={openConnect}+ >+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-zinc-100 text-zinc-500">+ <Icon icon={PlusSignIcon} size={14} />+ </span>+ Connect a new service…+ </button>+ </div>+ </PopoverContent>+ </Popover>+ </div>++ {isLoading ? (+ <Skeleton className="h-24 w-full rounded-xl" />+ ) : isError ? (+ <ErrorCard+ context="this expert's integrations"+ hint="We could not load what this expert can reach."+ onRetry={refetch}+ />+ ) : granted.length === 0 ? (+ <p className="text-sm text-zinc-500">+ Nothing connected yet. Add a tool and {expertName} can use it on your+ behalf.+ </p>+ ) : (+ <div className="divide-y divide-zinc-100 rounded-xl border border-zinc-200/80 bg-white">+ {granted.map((integration) => {+ const name = formatCredentialName(+ integration.title,+ integration.provider,+ );+ return (+ <div+ key={integration.credential_id}+ className="flex items-center gap-3 px-4 py-3"+ data-testid="expert-integration-row"+ >+ <IntegrationLogo provider={integration.provider} size={18} />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[15px] font-medium text-zinc-800">+ {name}+ </div>+ <div className="text-[13px] text-zinc-500">+ {formatCredentialSource(integration.provider)}+ </div>+ </div>+ <Badge variant="success" size="small">+ Ready+ </Badge>+ <Button+ variant="ghost"+ size="small"+ disabled={isRevoking}+ aria-label={`Remove ${name}`}+ leftIcon={<Icon icon={Delete02Icon} size={16} />}+ onClick={() => removeIntegration(integration.credential_id)}+ >+ Remove+ </Button>+ </div>+ );+ })}+ </div>+ )}++ <ConnectServiceDialog+ open={isConnecting}+ onOpenChange={(open) => {+ if (!open) closeConnect();+ }}+ title={+ <span className="flex items-center gap-2.5">+ <Avatar className="size-7">+ {expertAvatarUrl ? (+ <AvatarImage src={expertAvatarUrl} alt="" />+ ) : null}+ <AvatarFallback>{expertName}</AvatarFallback>+ </Avatar>+ Connect a service for {expertName}+ </span>+ }+ description={`Pick a service to connect. ${expertName} will be able to use it on your behalf.`}+ onConnected={connectCredential}+ />+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertIntegrationsSection/useExpertIntegrationsSection.ts b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertIntegrationsSection/useExpertIntegrationsSection.tsnew file mode 100644index 0000000000..53990b21af--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertIntegrationsSection/useExpertIntegrationsSection.ts@@ -0,0 +1,134 @@+import {+ getListExpertCredentialsQueryKey,+ useGrantExpertCredentials,+ useListExpertCredentials,+ useRevokeExpertCredential,+} from "@/app/api/__generated__/endpoints/experts/experts";+import { useGetV1ListCredentials } from "@/app/api/__generated__/endpoints/integrations/integrations";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";+import { okData } from "@/app/api/helpers";+import { filterSystemCredentials } from "@/components/contextual/CredentialsInput/helpers";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { useQueryClient } from "@tanstack/react-query";+import { useRef, useState } from "react";++export function useExpertIntegrationsSection(expertId: string) {+ const queryClient = useQueryClient();+ const { toast } = useToast();+ const [isAdding, setIsAdding] = useState(false);+ const [isConnecting, setIsConnecting] = useState(false);+ // Whether the dialog we just closed actually created something. Closing+ // without a credential means the user backed out, and the picker they came+ // from should come back rather than the click going nowhere.+ const didConnect = useRef(false);++ const grantedQuery = useListExpertCredentials(expertId, {+ query: { select: (response) => okData(response) ?? [] },+ });+ // System credentials (platform LLM keys) are filtered out because they are+ // never granted and never revocable — offering them would suggest otherwise.+ const connectedQuery = useGetV1ListCredentials({+ query: {+ select: (response) =>+ response.status === 200 ? filterSystemCredentials(response.data) : [],+ },+ });++ const granted = grantedQuery.data ?? [];+ const grantedIds = new Set(granted.map((g) => g.credential_id));+ const grantable = (connectedQuery.data ?? []).filter(+ (credential) => !grantedIds.has(credential.id),+ );++ function invalidate() {+ queryClient.invalidateQueries({+ queryKey: getListExpertCredentialsQueryKey(expertId),+ });+ }++ const { mutate: grant, isPending: isGranting } = useGrantExpertCredentials({+ mutation: {+ onSuccess: () => {+ setIsAdding(false);+ invalidate();+ },+ onError: () =>+ toast({ title: "Could not add integration", variant: "destructive" }),+ },+ });++ const { mutate: revoke, isPending: isRevoking } = useRevokeExpertCredential({+ mutation: {+ onSuccess: invalidate,+ onError: () =>+ toast({+ title: "Could not remove integration",+ variant: "destructive",+ }),+ },+ });++ function openAdd() {+ setIsAdding(true);+ }++ function closeAdd() {+ setIsAdding(false);+ }++ function openConnect() {+ setIsAdding(false);+ didConnect.current = false;+ setIsConnecting(true);+ }++ // The dialog names the credential it created, so a credential the user+ // happens to add elsewhere while it is open is never swept in.+ function connectCredential(credential: CredentialsMetaResponse) {+ didConnect.current = true;+ grant({ expertId, data: { credential_ids: [credential.id] } });+ }++ function closeConnect() {+ setIsConnecting(false);+ if (!didConnect.current) setIsAdding(true);+ didConnect.current = false;+ }++ function addIntegration(credentialId: string) {+ grant({ expertId, data: { credential_ids: [credentialId] } });+ }++ function removeIntegration(credentialId: string) {+ revoke({ expertId, credentialId });+ }++ async function refetch() {+ await Promise.all([grantedQuery.refetch(), connectedQuery.refetch()]);+ }++ return {+ granted,+ grantable,+ // Both queries are reported separately: a failed connected-credentials read+ // must not claim the expert has no access, and a failed granted read must+ // not claim there is nothing left to add. Collapsing either into an empty+ // array would render a confident lie.+ isLoading: grantedQuery.isLoading,+ isError: grantedQuery.isError,+ isGrantableLoading: connectedQuery.isLoading,+ isGrantableError: connectedQuery.isError,+ refetch,+ isAdding,+ openAdd,+ closeAdd,+ isConnecting,+ openConnect,+ closeConnect,+ connectCredential,+ addIntegration,+ removeIntegration,+ isGranting,+ isRevoking,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsxindex 38a553772c..97af38ded5 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx@@ -21,6 +21,7 @@ import { getLastRunLabel } from "../helpers";import { FireExpertDialog } from "../components/FireExpertDialog/FireExpertDialog";import { FireExpertMenu } from "../components/FireExpertMenu/FireExpertMenu";import { ExpertAboutSection } from "./components/ExpertAboutSection";+import { ExpertIntegrationsSection } from "./components/ExpertIntegrationsSection/ExpertIntegrationsSection";import { ExpertSchedulesSection } from "./components/ExpertSchedulesSection";import { ExpertWorkSection } from "./components/ExpertWorkSection/ExpertWorkSection";import { ExpertWorkflowsSection } from "./components/ExpertWorkflowsSection";@@ -195,6 +196,12 @@ export default function ExpertDetailPage() {lastRunLabel={getLastRunLabel(expert)}/>+ <ExpertIntegrationsSection+ expertId={expert.id}+ expertName={expert.name}+ expertAvatarUrl={expert.avatar_url ?? null}+ />+<ExpertWorkflowsSectionexpert={expert}accentIconClass={accent.icon}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 6e00a2e477..b2da12afc0 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -6180,6 +6180,154 @@}}},+ "/api/experts/{expert_id}/credentials": {+ "get": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "List Expert Credentials",+ "description": "The integrations this expert is allowed to use.",+ "operationId": "list_expert_credentials",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "expert_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Expert Id" }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ExpertCredentialRef"+ },+ "title": "Response List Expert Credentials"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Expert not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Grant Expert Credentials",+ "operationId": "grant_expert_credentials",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "expert_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Expert Id" }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GrantCredentialsRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ExpertCredentialRef"+ },+ "title": "Response Grant Expert Credentials"+ }+ }+ }+ },+ "400": { "description": "Unknown credential" },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Expert not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },+ "/api/experts/{expert_id}/credentials/{credential_id}": {+ "delete": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Revoke Expert Credential",+ "operationId": "revoke_expert_credential",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "expert_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Expert Id" }+ },+ {+ "name": "credential_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Credential Id" }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ExpertCredentialRef"+ },+ "title": "Response Revoke Expert Credential"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Expert not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/experts/{expert_id}/detach-preview": {"get": {"tags": ["v2", "experts", "experts", "private"],@@ -19094,6 +19242,18 @@],"title": "Expert"},+ "ExpertCredentialRef": {+ "properties": {+ "credential_id": { "type": "string", "title": "Credential Id" },+ "provider": { "type": "string", "title": "Provider" },+ "title": { "type": "string", "title": "Title" },+ "type": { "type": "string", "title": "Type" }+ },+ "type": "object",+ "required": ["credential_id", "provider", "title", "type"],+ "title": "ExpertCredentialRef",+ "description": "One integration credential an expert is allowed to use.\n\n``title``/``type`` are read from the owner's live credential rather than\nstored on the grant, so a renamed credential renames everywhere at once."+ },"ExpertDetachPreview": {"properties": {"schedule_names": {@@ -19604,6 +19764,20 @@"title": "GlobalSearchResponse","description": "Top-N hits bucketed by item type.\n\nFor a non-empty query this contains hybrid-search results.\nFor an empty query this contains the most-recently-updated items\nper bucket (cached per-user with a short TTL)."},+ "GrantCredentialsRequest": {+ "properties": {+ "credential_ids": {+ "items": { "type": "string" },+ "type": "array",+ "maxItems": 50,+ "minItems": 1,+ "title": "Credential Ids"+ }+ },+ "type": "object",+ "required": ["credential_ids"],+ "title": "GrantCredentialsRequest"+ },"Graph": {"properties": {"id": { "type": "string", "title": "Id" },diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/ConnectServiceDialog.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/ConnectServiceDialog.tsxindex 1e09c7a77d..d077d9da9f 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/ConnectServiceDialog.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/ConnectServiceDialog.tsx@@ -7,6 +7,7 @@ import {useReducedMotion,} from "framer-motion";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { Dialog } from "@/components/molecules/Dialog/Dialog";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";@@ -18,8 +19,15 @@ import { useMeasuredHeight } from "./useMeasuredHeight";interface Props {open: boolean;onOpenChange: (open: boolean) => void;+ title?: React.ReactNode;+ description?: string;+ onConnected?: (credential: CredentialsMetaResponse) => void;}+const DEFAULT_TITLE = "Connect a service";+const DEFAULT_DESCRIPTION =+ "Pick a service to connect an API key or authorize with OAuth.";+const TRANSITION = { duration: 0.15, ease: [0, 0, 0.2, 1] as const };const HEIGHT_TRANSITION = {duration: 0.2,@@ -38,7 +46,13 @@ const reducedVariants = {exit: { opacity: 0 },};-export function ConnectServiceDialog({ open, onOpenChange }: Props) {+export function ConnectServiceDialog({+ open,+ onOpenChange,+ title = DEFAULT_TITLE,+ description = DEFAULT_DESCRIPTION,+ onConnected,+}: Props) {const {query,setQuery,@@ -53,7 +67,7 @@ export function ConnectServiceDialog({ open, onOpenChange }: Props) {handleSelect,handleBack,handleSuccess,- } = useConnectServiceDialog({ open, onOpenChange });+ } = useConnectServiceDialog({ open, onOpenChange, onConnected });const reduceMotion = useReducedMotion();const variants = reduceMotion ? reducedVariants : stepVariants;@@ -61,7 +75,7 @@ export function ConnectServiceDialog({ open, onOpenChange }: Props) {return (<Dialog- title="Connect a service"+ title={title}styling={{ maxWidth: "40rem" }}controlled={{isOpen: open,@@ -104,6 +118,7 @@ export function ConnectServiceDialog({ open, onOpenChange }: Props) {setQuery={setQuery}providers={providers}onSelect={handleSelect}+ description={description}/>)}</motion.div>diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ApiKeyConnectForm.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ApiKeyConnectForm.tsxindex 9242511864..8068440919 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ApiKeyConnectForm.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ApiKeyConnectForm.tsx@@ -10,12 +10,14 @@ import {FormMessage,} from "@/components/molecules/Form/Form";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";+import { useApiKeyConnectForm } from "./useApiKeyConnectForm";interface Props {provider: string;providerName: string;- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}export function ApiKeyConnectForm({diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsxindex 45b8bb86b4..d9ae92188f 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx@@ -1,6 +1,7 @@"use client";import { motion, useReducedMotion } from "framer-motion";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import {@@ -23,7 +24,7 @@ const MCP_PROVIDER_ID = "mcp";interface Props {provider: ConnectableProvider;onBack: () => void;- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}const TAB_PRIORITY: AuthMethod[] = [diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsxindex 1bfc30e86c..caa90de110 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx@@ -9,6 +9,7 @@ import {postV2StoreABearerTokenForAnMcpServer,} from "@/app/api/__generated__/endpoints/mcp/mcp";import { getGetV1ListCredentialsQueryKey } from "@/app/api/__generated__/endpoints/integrations/integrations";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import type { MCPOAuthLoginResponse } from "@/app/api/__generated__/models/mCPOAuthLoginResponse";import { Button } from "@/components/atoms/Button/Button";import { Input } from "@/components/atoms/Input/Input";@@ -16,7 +17,7 @@ import { Text } from "@/components/atoms/Text/Text";import { openOAuthPopup } from "@/lib/oauth-popup";interface Props {- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}type Phase = "form" | "manual-token";@@ -83,13 +84,13 @@ export function McpConnectPanel({ onSuccess }: Props) {const result = await promise;- await postV2ExchangeOauthCodeForMcpTokens({+ const exchanged = await postV2ExchangeOauthCodeForMcpTokens({code: result.code,state_token,});await invalidateCredentials();- onSuccess();+ onSuccess(exchanged.status === 200 ? exchanged.data : undefined);} catch (e: unknown) {const message = getErrorMessage(e);if (message === "OAuth flow timed out") {@@ -109,13 +110,13 @@ export function McpConnectPanel({ onSuccess }: Props) {setIsSubmitting(true);try {- await postV2StoreABearerTokenForAnMcpServer({+ const stored = await postV2StoreABearerTokenForAnMcpServer({server_url: trimmedUrl,token: trimmedToken,});await invalidateCredentials();- onSuccess();+ onSuccess(stored.status === 200 ? stored.data : undefined);} catch (e: unknown) {setError(getErrorMessage(e));} finally {diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsxindex 82fc634208..3109ec1183 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx@@ -1,5 +1,7 @@"use client";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";+import {AuthType,type AuthMethod,@@ -21,7 +23,7 @@ const TAB_LABEL: Record<AuthMethod, string> = {interface Props {method: AuthMethod;provider: ConnectableProvider;- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}export function MethodPanel({ method, provider, onSuccess }: Props) {diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsxindex f2639167a7..302080178e 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/OAuthConnectButton.tsx@@ -2,6 +2,8 @@import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";+import { useOAuthConnect } from "./useOAuthConnect";import { LinkSquare01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -10,7 +12,7 @@ interface Props {provider: string;providerName: string;buttonLabel?: string;- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}export function OAuthConnectButton({diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.tsindex 349c85d28e..ae57eda989 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts@@ -9,13 +9,14 @@ import {getGetV1ListCredentialsQueryKey,postV1CreateCredentials,} from "@/app/api/__generated__/endpoints/integrations/integrations";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { toast } from "@/components/molecules/Toast/use-toast";import { apiKeyConnectSchema, type ApiKeyConnectFormValues } from "./schema";interface Args {provider: string;- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}function toUnixSeconds(value: string | undefined): number | undefined {@@ -42,7 +43,7 @@ export function useApiKeyConnectForm({ provider, onSuccess }: Args) {// Trust HTTP semantics rather than pinning to a specific 2xx code —// proxies / future backend changes can swap 201 ↔ 200 without this// breaking and silently failing in production.- await postV1CreateCredentials(provider, {+ const created = await postV1CreateCredentials(provider, {provider,type: "api_key",title: values.title,@@ -54,7 +55,10 @@ export function useApiKeyConnectForm({ provider, onSuccess }: Args) {await queryClient.invalidateQueries({queryKey: getGetV1ListCredentialsQueryKey(),});- onSuccess();+ // Narrow by shape rather than by status code: the comment above keeps+ // this flow indifferent to a 201 ↔ 200 swap, and only the success+ // payload carries an id.+ onSuccess("id" in created.data ? created.data : undefined);} catch (error) {toast({title: "Couldn't save API key",diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.tsindex 4047d1be97..358b2b7aa1 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts@@ -8,6 +8,7 @@ import {getV1InitiateOauthFlow,postV1ExchangeOauthCodeForTokens,} from "@/app/api/__generated__/endpoints/integrations/integrations";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { toast } from "@/components/molecules/Toast/use-toast";import {OAUTH_ERROR_POPUP_BLOCKED,@@ -19,7 +20,7 @@ import { getOAuthErrorMessage } from "./helpers";interface Args {provider: string;- onSuccess: () => void;+ onSuccess: (credential?: CredentialsMetaResponse) => void;}export function useOAuthConnect({ provider, onSuccess }: Args) {@@ -108,7 +109,7 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {const { code, state } = await promise;abortRef.current = null;- await postV1ExchangeOauthCodeForTokens(provider, {+ const exchanged = await postV1ExchangeOauthCodeForTokens(provider, {code,state_token: state,});@@ -117,7 +118,9 @@ export function useOAuthConnect({ provider, onSuccess }: Args) {await queryClient.invalidateQueries({queryKey: getGetV1ListCredentialsQueryKey(),});- onSuccess();+ // customMutator rejects non-2xx, so a 200 is the only way to get here;+ // the check narrows the union rather than guarding a real branch.+ onSuccess(exchanged.status === 200 ? exchanged.data : undefined);} catch (error) {// Close the dangling about:blank window only while this flow still// owns it — i.e. the error occurred before openOAuthPopup adopted thediff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ListView.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ListView.tsxindex 4aa4ce442b..8e62b130bb 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ListView.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ListView.tsx@@ -13,13 +13,20 @@ interface Props {setQuery: (next: string) => void;providers: ConnectableProvider[];onSelect: (id: string) => void;+ description: string;}-export function ListView({ query, setQuery, providers, onSelect }: Props) {+export function ListView({+ query,+ setQuery,+ providers,+ onSelect,+ description,+}: Props) {return (<div className="flex flex-col gap-4"><Text variant="body" className="text-[#505057]">- Pick a service to connect an API key or authorize with OAuth.+ {description}</Text><div className="relative w-full">diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/useConnectServiceDialog.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/useConnectServiceDialog.tsindex f84c00dd60..c1a7687dd9 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/useConnectServiceDialog.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/useConnectServiceDialog.ts@@ -3,6 +3,7 @@import { useEffect, useState } from "react";import { useGetV1ListProviders } from "@/app/api/__generated__/endpoints/integrations/integrations";+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { useDebouncedValue } from "@/hooks/useDebouncedValue";import {@@ -14,9 +15,14 @@ import {interface Args {open: boolean;onOpenChange: (open: boolean) => void;+ onConnected?: (credential: CredentialsMetaResponse) => void;}-export function useConnectServiceDialog({ open, onOpenChange }: Args) {+export function useConnectServiceDialog({+ open,+ onOpenChange,+ onConnected,+}: Args) {const [query, setQuery] = useState("");const debouncedQuery = useDebouncedValue(query, 250);const [selectedId, setSelectedId] = useState<string | null>(null);@@ -56,7 +62,10 @@ export function useConnectServiceDialog({ open, onOpenChange }: Args) {setSelectedId(null);}- function handleSuccess() {+ // Report the credential this dialog created before closing, so callers act+ // on the one they asked for rather than on whatever else appeared meanwhile.+ function handleSuccess(credential?: CredentialsMetaResponse) {+ if (credential) onConnected?.(credential);onOpenChange(false);}diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.tsindex ca55d61bea..44b0fc2d14 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts@@ -44,6 +44,7 @@ const PROVIDER_DISPLAY_NAME_OVERRIDES: Record<string, string> = {d_id: "D-ID",ideogram: "Ideogram",jina: "Jina",+ linkedin: "LinkedIn",mcp: "MCP",twitter: "X",zerobounce: "ZeroBounce",@@ -70,7 +71,7 @@ export function formatMaskedValue(credential: CredentialView): string {return "Configured";}-function stripProviderPrefix(title: string, provider: string): string {+export function stripProviderPrefix(title: string, provider: string): string {// The row already lives under the provider group, so any leading// ``<ProviderName>: `` in the per-credential title doubles up. Strip// it generically (case-insensitive) so e.g. ``"MCP: mcp.sentry.dev"``@@ -83,6 +84,49 @@ function stripProviderPrefix(title: string, provider: string): string {: title;}+const MCP_PROVIDER = "mcp";++// Labels that route the request rather than name the service behind it.+const MCP_HOST_NOISE = new Set(["mcp", "api", "www", "server"]);++function toHostname(value: string): string | null {+ try {+ const url = new URL(value.includes("://") ? value : `https://${value}`);+ return url.hostname || null;+ } catch {+ return null;+ }+}++function mcpServiceName(value: string): string | null {+ const host = toHostname(value);+ if (!host) return null;+ // Drop the TLD, then the routing noise, so ``mcp.sentry.dev`` reads as the+ // service a person recognises rather than the URL we happen to call.+ const name = host+ .split(".")+ .filter(Boolean)+ .slice(0, -1)+ .find((label) => !MCP_HOST_NOISE.has(label));+ return name ? formatProviderName(name) : null;+}++// The credential's own name, said the way a person would. MCP credentials are+// titled after the server URL, which is the one case where the stored title is+// an address rather than a name.+export function formatCredentialName(title: string, provider: string): string {+ const stripped = stripProviderPrefix(title, provider);+ if (provider !== MCP_PROVIDER) return stripped;+ return mcpServiceName(stripped) ?? stripped;+}++// Where the credential comes from, for the line under its name.+export function formatCredentialSource(provider: string): string {+ return provider === MCP_PROVIDER+ ? "MCP server"+ : formatProviderName(provider);+}+function toCredentialView(cred: CredentialsMetaResponse): CredentialView {const rawTitle = cred.title ?? formatProviderName(cred.provider);return {diff --git a/autogpt_platform/frontend/src/components/molecules/IntegrationLogo/IntegrationLogo.tsx b/autogpt_platform/frontend/src/components/molecules/IntegrationLogo/IntegrationLogo.tsxnew file mode 100644index 0000000000..605561847d--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/IntegrationLogo/IntegrationLogo.tsx@@ -0,0 +1,57 @@+"use client";++import Image from "next/image";+import { useState } from "react";+import { PuzzleIcon } from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";+import { cn } from "@/lib/utils";+import { integrationIconSrc } from "./helpers";++interface Props {+ provider: string;+ /** Accessible label; defaults to the provider slug. */+ alt?: string;+ size?: number;+ className?: string;+}++/** A provider's logo, degrading to a neutral glyph.+ *+ * Providers are added faster than their PNGs are, so a missing file is normal+ * rather than exceptional — it falls back instead of rendering a broken image.+ */+export function IntegrationLogo({+ provider,+ alt,+ size = 16,+ className,+}: Props) {+ const [failed, setFailed] = useState(false);+ const src = integrationIconSrc(provider);++ // The fallback keeps the caller's label: a provider whose PNG is missing is+ // still a named integration, and dropping the label would make it invisible+ // to anyone reading the page with a screen reader.+ if (!src || failed) {+ return (+ <Icon+ icon={PuzzleIcon}+ size={size}+ role="img"+ aria-label={alt ?? provider}+ className={cn("text-zinc-400", className)}+ />+ );+ }++ return (+ <Image+ src={src}+ alt={alt ?? provider}+ width={size}+ height={size}+ className={cn("rounded-sm object-contain", className)}+ onError={() => setFailed(true)}+ />+ );+}diff --git a/autogpt_platform/frontend/src/components/molecules/IntegrationLogo/helpers.ts b/autogpt_platform/frontend/src/components/molecules/IntegrationLogo/helpers.tsnew file mode 100644index 0000000000..b526f15abe--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/IntegrationLogo/helpers.ts@@ -0,0 +1,15 @@+/** Map a provider slug to its logo in `public/integrations`.+ *+ * The slug is scrubbed rather than trusted: provider strings reach this from+ * tool payloads and credential rows, and an unscrubbed one would let `../../`+ * walk out of the integrations directory. A slug that scrubs to nothing has no+ * icon at all, which callers render as their fallback.+ */+export function integrationIconSrc(provider: string): string | null {+ const slug = provider+ .trim()+ .toLowerCase()+ .replace(/[\s-]+/g, "_")+ .replace(/[^a-z0-9_]/g, "");+ return slug ? `/integrations/${slug}.png` : null;+}