AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend/copilot): provision the managed Ayrshare profile when AutoPilot needs it (#15369)
Bentlyb92c8bdf2426
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex 50af82c12d..4c46a6b8d4 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -2,7 +2,7 @@ import asyncioimport loggingimport secretsfrom contextlib import suppress-from datetime import datetime, timedelta, timezone+from datetime import datetimefrom typing import TYPE_CHECKING, Annotated, Any, List, Literal, TypeGuard, get_argsfrom autogpt_libs.auth import get_optional_user_id, get_user_id@@ -33,7 +33,6 @@ from backend.data.integrations import (wait_for_webhook_event,)from backend.data.model import (- APIKeyCredentials,Credentials,CredentialsType,HostScopedCredentials,@@ -43,7 +42,6 @@ from backend.data.model import ()from backend.data.onboarding import OnboardingStep, complete_onboarding_stepfrom backend.executor.utils import add_graph_execution-from backend.integrations.ayrshare import AyrshareClient, SocialPlatformfrom backend.integrations.codex.access import (enforce_codex_access_http,has_codex_access_for_discovery,@@ -60,13 +58,13 @@ from backend.integrations.creds_manager import (IntegrationCredentialsManager,create_mcp_oauth_handler,)-from backend.integrations.managed_credentials import (- ensure_managed_credential,- ensure_managed_credentials,+from backend.integrations.managed_credentials import ensure_managed_credentials+from backend.integrations.managed_providers.ayrshare import (+ AyrshareNotConfiguredError,+ AyrshareProvisioningError,)-from backend.integrations.managed_providers.ayrshare import AyrshareManagedProviderfrom backend.integrations.managed_providers.ayrshare import (- settings_available as ayrshare_settings_available,+ get_sso_link as get_ayrshare_sso_link,)from backend.integrations.mcp_catalog import get_mcp_catalogfrom backend.integrations.oauth import (@@ -87,7 +85,6 @@ from backend.util.exceptions import (ExpertRunPausedError,GraphNotAccessibleError,GraphNotInLibraryError,- MissingConfigError,NeedConfirmation,NotFoundError,)@@ -1951,82 +1948,13 @@ async def get_ayrshare_sso_url(hosted social-linking page; all profile lifecycle logic lives with themanaged provider."""- if not ayrshare_settings_available():- raise HTTPException(- status_code=HTTP_500_INTERNAL_SERVER_ERROR,- detail="Ayrshare integration is not configured",- )-- try:- client = AyrshareClient()- except MissingConfigError:- raise HTTPException(- status_code=HTTP_500_INTERNAL_SERVER_ERROR,- detail="Ayrshare integration is not configured",- )-- # On-demand provisioning: AyrshareManagedProvider opts out of the- # credentials sweep (profile quota is per-user subscription-bound). This- # endpoint is the only trigger that provisions a profile — one Ayrshare- # profile per user who actually opens the connect flow, not one per- # every authenticated user.- provisioned = await ensure_managed_credential(- user_id, creds_manager.store, AyrshareManagedProvider()- )- if not provisioned:- raise HTTPException(- status_code=HTTP_502_BAD_GATEWAY,- detail="Failed to provision Ayrshare profile",- )-- ayrshare_creds = [- c- for c in await creds_manager.store.get_creds_by_provider(user_id, "ayrshare")- if c.is_managed and isinstance(c, APIKeyCredentials)- ]- if not ayrshare_creds:- logger.error(- "Ayrshare credential provisioning did not produce a credential for user %s",- user_id,- )- raise HTTPException(- status_code=HTTP_502_BAD_GATEWAY,- detail="Failed to provision Ayrshare profile",- )- profile_key_str = ayrshare_creds[0].api_key.get_secret_value()-- private_key = settings.secrets.ayrshare_jwt_key- # Ayrshare JWT max lifetime is 2880 minutes (48 h).- max_expiry_minutes = 2880try:- jwt_response = await client.generate_jwt(- private_key=private_key,- profile_key=profile_key_str,- # `allowed_social` is the set of networks the Ayrshare-hosted- # social-linking page will *offer* the user to connect. Blocks- # exist for more platforms than are listed here; the list is- # deliberately narrower so the rollout can verify each network- # end-to-end before widening the user-visible surface. Keep- # in sync with tested platforms — extend as each is verified- # against the block + Ayrshare's network-specific quirks.- allowed_social=[- SocialPlatform.TWITTER,- SocialPlatform.LINKEDIN,- SocialPlatform.INSTAGRAM,- SocialPlatform.YOUTUBE,- SocialPlatform.TIKTOK,- ],- expires_in=max_expiry_minutes,- verify=True,- )- except Exception as exc:- logger.error("Error generating Ayrshare JWT for user %s: %s", user_id, exc)- raise HTTPException(- status_code=HTTP_502_BAD_GATEWAY, detail="Failed to generate JWT"- )-- expires_at = datetime.now(timezone.utc) + timedelta(minutes=max_expiry_minutes)- return AyrshareSSOResponse(sso_url=jwt_response.url, expires_at=expires_at)+ link = await get_ayrshare_sso_link(user_id, creds_manager.store)+ except AyrshareNotConfiguredError as exc:+ raise HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc))+ except AyrshareProvisioningError as exc:+ raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, detail=str(exc))+ return AyrshareSSOResponse(sso_url=link.url, expires_at=link.expires_at)# === PROVIDER DISCOVERY ENDPOINTS ===diff --git a/autogpt_platform/backend/backend/api/features/integrations/router_test.py b/autogpt_platform/backend/backend/api/features/integrations/router_test.pyindex 5b501acc0c..1fe91fd01f 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router_test.py@@ -1,6 +1,7 @@"""Tests for credentials API security: no secret leakage, SDK defaults filtered."""from contextlib import asynccontextmanager+from datetime import datetime, timezonefrom unittest.mock import AsyncMock, MagicMock, patchimport fastapi@@ -16,6 +17,10 @@ from backend.data.model import (OAuth2Credentials,UserPasswordCredentials,)+from backend.integrations.managed_providers.ayrshare import (+ AyrshareNotConfiguredError,+ AyrshareProvisioningError,+)from backend.integrations.providers import ProviderNamefrom backend.util.exceptions import NotFoundError@@ -1519,3 +1524,38 @@ class TestDeviceAuthEndpoints:)# And never the "newest for this provider" shortcut.mock_mgr.store.get_creds_by_provider.assert_not_called()+++class TestAyrshareSSOURL:+ """The builder's connect button, now on the shared provisioning path."""++ def test_returns_the_link(self):+ link = MagicMock(url="https://sso", expires_at=datetime.now(timezone.utc))+ with patch(+ "backend.api.features.integrations.router.get_ayrshare_sso_link",+ AsyncMock(return_value=link),+ ) as get_link:+ response = client.get("/ayrshare/sso_url")++ assert response.status_code == 200+ assert response.json()["sso_url"] == "https://sso"+ assert get_link.await_args.args[0] == JWT_USER_ID++ def test_not_configured_is_500(self):+ with patch(+ "backend.api.features.integrations.router.get_ayrshare_sso_link",+ AsyncMock(side_effect=AyrshareNotConfiguredError("not configured")),+ ):+ response = client.get("/ayrshare/sso_url")++ assert response.status_code == 500++ def test_failed_provisioning_is_502(self):+ with patch(+ "backend.api.features.integrations.router.get_ayrshare_sso_link",+ AsyncMock(side_effect=AyrshareProvisioningError("Failed to generate JWT")),+ ):+ response = client.get("/ayrshare/sso_url")++ assert response.status_code == 502+ assert response.json()["detail"] == "Failed to generate JWT"diff --git a/autogpt_platform/backend/backend/copilot/tools/ayrshare_managed.py b/autogpt_platform/backend/backend/copilot/tools/ayrshare_managed.pynew file mode 100644index 0000000000..fec9221db8--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/ayrshare_managed.py@@ -0,0 +1,335 @@+"""AutoPilot's side of the managed Ayrshare profile (SECRT-2878).++Ayrshare blocks post with a per-user profile key that AutoGPT provisions+(:class:`~backend.integrations.managed_providers.ayrshare.AyrshareManagedProvider`).+It opts out of the credentials sweep, so a user who never opened the+builder's "Connect Social Media Accounts" button has no credential, and the+copilot used to answer every ``post_to_*`` call with a card asking for an+API key the user cannot have. Here the copilot provisions the profile on+demand through the same path as ``/ayrshare/sso_url`` and points the user at+the card's connect button, which fetches its own SSO link on click. No SSO+link goes into anything the copilot returns: tool output is stored with the+chat, sent to the model provider and served by a shared chat, and the link+signs the user into their Ayrshare page for two days.+"""++import logging+import re+from typing import Any++from backend.blocks._base import AnyBlockSchema+from backend.blocks.ayrshare._cost import AYRSHARE_POST_COSTS+from backend.copilot.context import is_unattended_turn+from backend.integrations.creds_manager import IntegrationCredentialsManager+from backend.integrations.managed_providers.ayrshare import (+ AyrshareNotConfiguredError,+ AyrshareProvisioningError,+ provision_profile,+)++from .expert_scope import annotate_expert_grants, provider_slug+from .models import (+ ErrorResponse,+ SetupInfo,+ SetupRequirementsResponse,+ ToolResponseBase,+ UserReadiness,+)+from .utils import build_missing_credentials_from_field_info, sanitize_provider_message++logger = logging.getLogger(__name__)++AYRSHARE = "ayrshare"++NO_API_KEY = (+ "AutoGPT holds the Ayrshare account, so never ask the user for an Ayrshare "+ "API key or subscription."+)++# The labels the user sees: the chat card's Ayrshare row (ConnectorRow) and the+# agent builder's button (AyrshareConnectButton).+CONNECT_BUTTON = "Connect"+BUILDER_CONNECT_BUTTON = "Connect Social Media Accounts"+++def _post_cost(*, is_video: bool) -> str:+ cost = next(+ c for c in AYRSHARE_POST_COSTS if c.cost_filter.get("is_video") is is_video+ )+ return f"${cost.cost_amount / 100:.2f}"+++POST_COST = (+ f"Each post costs {_post_cost(is_video=False)} "+ f"({_post_cost(is_video=True)} for video)."+)++NOT_AVAILABLE_MESSAGE = (+ "Posting to social networks through Ayrshare is not available on this "+ "AutoGPT deployment (it has not been set up here). Tell the user plainly "+ "that social posting is not available yet. " + NO_API_KEY+)++PROVISIONING_FAILED_MESSAGE = (+ "Could not set up the user's social posting profile just now. Try again "+ "in a moment. " + NO_API_KEY+)++# Ayrshare answers a post to a network the profile has not linked with a+# per-platform error such as "Twitter is not linked" or "... Please confirm+# the linkage on the Social Accounts page".+_NOT_LINKED_RE = re.compile(+ r"not\s+linked|linkage|no\s+(linked\s+)?social\s+accounts?", re.IGNORECASE+)+++def is_ayrshare(provider: object) -> bool:+ return provider_slug(provider).strip().lower() == AYRSHARE+++def is_not_linked_error(exc: BaseException) -> bool:+ """True when Ayrshare refused a post because the network is not linked."""+ seen: set[int] = set()+ current: BaseException | None = exc+ while current is not None and id(current) not in seen:+ seen.add(id(current))+ if _NOT_LINKED_RE.search(str(current)):+ return True+ current = current.__cause__ or current.__context__+ return False+++async def ensure_profile(user_id: str) -> ErrorResponse | None:+ """Provision the user's profile if needed, so the card's connect button+ has one to link to, or the error the copilot should relay instead."""+ try:+ await provision_profile(user_id, IntegrationCredentialsManager().store)+ except AyrshareNotConfiguredError:+ return ErrorResponse(+ message=NOT_AVAILABLE_MESSAGE, error="ayrshare_not_configured"+ )+ except AyrshareProvisioningError as exc:+ logger.warning("Ayrshare profile failed for user %s: %s", user_id, exc)+ return ErrorResponse(+ message=PROVISIONING_FAILED_MESSAGE, error="ayrshare_provisioning_failed"+ )+ return None+++GRANT_TO_EXPERT = (+ "This expert has not been granted the user's posting profile yet, so also "+ "ask them to grant it with the Grant button on the card."+)+++def link_message(lead: str, *, needs_grant: bool = False) -> str:+ grant = f"{GRANT_TO_EXPERT} " if needs_grant else ""+ return (+ f"{lead} Ask the user to link their social accounts with the "+ f"{CONNECT_BUTTON} button in the card, which opens Ayrshare's page. "+ f"{grant}Do not write a link to that page yourself. "+ "Once they say they have linked them, run the step again. "+ f"{POST_COST} " + NO_API_KEY+ )+++async def with_expert_grants(+ user_id: str, expert_id: str | None, entries: dict[str, dict[str, Any]]+) -> tuple[dict[str, dict[str, Any]], bool]:+ """The entries annotated with what the expert could be granted, and+ whether it lacks the managed credential.++ An expert only runs with credentials it was granted, and the managed one+ is no exception, so linking networks alone would leave it unable to post.+ Called after provisioning, so the profile is there to be granted.+ """+ annotated = await annotate_expert_grants(user_id, expert_id, entries)+ needs_grant = any(+ entry.get("expert_grant", {}).get("credentials") for entry in annotated.values()+ )+ return annotated, needs_grant+++def link_accounts_card(+ *,+ agent_id: str,+ agent_name: str,+ missing_credentials: dict[str, dict[str, Any]],+ message: str,+ session_id: str | None,+ execution_modes: tuple[str, ...] = ("immediate",),+) -> SetupRequirementsResponse:+ """The setup card for an Ayrshare field.++ Each entry keeps the usual shape (provider ``ayrshare``), which the chat+ card renders as the Ayrshare connect button rather than a key field.+ """+ entries = dict(missing_credentials)+ return SetupRequirementsResponse(+ message=message,+ session_id=session_id,+ setup_info=SetupInfo(+ agent_id=agent_id,+ agent_name=agent_name,+ user_readiness=UserReadiness(+ has_all_credentials=False,+ missing_credentials=entries,+ ready_to_run=False,+ ),+ requirements={+ "credentials": list(entries.values()),+ "inputs": [],+ "execution_modes": list(execution_modes),+ },+ ),+ )+++async def provision_for_block(+ user_id: str,+ block: AnyBlockSchema,+ block_id: str,+ session_id: str | None,+ expert_id: str | None = None,+) -> ToolResponseBase | None:+ """Answer for an Ayrshare block that found no credential to run with.++ Provisions the user's managed profile and returns the connect card, since a+ profile that was just created has no linked networks yet. ``None`` when+ the user already has the managed credential and something else kept it+ out of the match (an expert grant, a pinned account): the usual card+ handles those.+ """+ store = IntegrationCredentialsManager().store+ if await store.has_managed_credential(user_id, AYRSHARE):+ return None+ reason = "no social account is linked to the user's AutoGPT posting profile yet"+ return await _block_link_answer(+ user_id,+ block,+ block_id,+ session_id,+ expert_id,+ reason=reason,+ lead=(+ f"Block '{block.name}' posts through AutoGPT's managed Ayrshare "+ f"account, and {reason}."+ ),+ )+++async def connect_for_block(+ user_id: str,+ block: AnyBlockSchema,+ block_id: str,+ session_id: str | None,+ expert_id: str | None = None,+) -> ToolResponseBase:+ """Answer for an explicit connect on an Ayrshare block.++ Having the managed credential says nothing about which networks are+ linked, so connecting always means showing the connect card.+ """+ return await _block_link_answer(+ user_id,+ block,+ block_id,+ session_id,+ expert_id,+ reason="the user asked to connect their social accounts",+ lead=f"Block '{block.name}' posts through AutoGPT's managed Ayrshare account.",+ )+++async def not_linked_response(+ user_id: str,+ block: AnyBlockSchema,+ block_id: str,+ exc: BaseException,+ session_id: str | None,+ expert_id: str | None = None,+) -> ToolResponseBase:+ """Answer for a post Ayrshare refused because the network is not linked."""+ detail = sanitize_provider_message(str(exc))+ return await _block_link_answer(+ user_id,+ block,+ block_id,+ session_id,+ expert_id,+ reason=f"the network is not linked to the user's posting profile ({detail})",+ lead=f"Block '{block.name}' did not post: Ayrshare said \"{detail}\".",+ outside=(detail,),+ )+++async def _block_link_answer(+ user_id: str,+ block: AnyBlockSchema,+ block_id: str,+ session_id: str | None,+ expert_id: str | None,+ *,+ reason: str,+ lead: str,+ outside: tuple[str, ...] = (),+) -> ToolResponseBase:+ error = await ensure_profile(user_id)+ if error is not None:+ error.session_id = session_id+ return error.from_outside()+ entries, needs_grant = await with_expert_grants(+ user_id, expert_id, _block_entries(block)+ )+ if is_unattended_turn():+ return _unattended_link_error(+ f"Block '{block.name}'", reason, session_id, needs_grant=needs_grant+ ).from_outside(*outside)+ return link_accounts_card(+ agent_id=block_id,+ agent_name=block.name,+ missing_credentials=entries,+ message=link_message(lead, needs_grant=needs_grant),+ session_id=session_id,+ ).from_outside(*outside)+++def _unattended_link_error(+ subject: str, reason: str, session_id: str | None, *, needs_grant: bool+) -> ErrorResponse:+ logger.warning(+ "Unattended copilot turn in session %s: %s skipped, %s",+ session_id,+ subject,+ reason,+ )+ return ErrorResponse(+ message=(+ f"{subject} did not post: {reason}. Nobody is watching this turn "+ "(it was scheduled), so say plainly in your reply that the post "+ "was skipped and that the user can link their social accounts by "+ f"opening this chat and choosing {CONNECT_BUTTON} on the Ayrshare "+ f"card (or {BUILDER_CONNECT_BUTTON} in the agent builder)"+ + (+ ", then grant this expert access to it on the expert's "+ "Integrations page"+ if needs_grant+ else ""+ )+ + ". Do not write a link to Ayrshare's page yourself. "+ + NO_API_KEY+ ),+ error="ayrshare_accounts_not_linked",+ session_id=session_id,+ )+++def _block_entries(block: AnyBlockSchema) -> dict[str, dict[str, Any]]:+ return build_missing_credentials_from_field_info(+ {+ field: info+ for field, info in block.input_schema.get_credentials_fields_info().items()+ if any(is_ayrshare(p) for p in info.provider)+ },+ matched_keys=set(),+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/ayrshare_managed_test.py b/autogpt_platform/backend/backend/copilot/tools/ayrshare_managed_test.pynew file mode 100644index 0000000000..d0342f58fb--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/ayrshare_managed_test.py@@ -0,0 +1,521 @@+"""AutoPilot and the managed Ayrshare profile (SECRT-2878).++The repro tests patch only names that exist before the fix too (the org+secrets, the provisioning lock, the credential store and Ayrshare's JWT+call), so on the old code they fail on behaviour, not on a missing symbol.+"""++from contextlib import ExitStack, contextmanager+from typing import Iterator+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from pydantic import SecretStr++from backend.blocks.ayrshare.post_to_linkedin import PostToLinkedInBlock+from backend.blocks.ayrshare.post_to_x import PostToXBlock+from backend.copilot.context import _current_permissions, set_turn_unattended+from backend.copilot.permissions import CopilotPermissions+from backend.copilot.tools.ayrshare_managed import (+ BUILDER_CONNECT_BUTTON,+ GRANT_TO_EXPERT,+)+from backend.copilot.tools.connect_integration import ConnectIntegrationTool+from backend.copilot.tools.helpers import execute_block, prepare_block_for_execution+from backend.copilot.tools.models import (+ BlockOutputResponse,+ ErrorResponse,+ SetupRequirementsResponse,+ ToolResponseBase,+)+from backend.copilot.tools.run_block import RunBlockTool+from backend.data.model import APIKeyCredentials, CredentialsMetaInput+from backend.integrations.ayrshare import (+ AyrshareClient,+ JWTResponse,+ PostIds,+ PostResponse,+)+from backend.integrations.credentials_store import IntegrationCredentialsStore+from backend.integrations.providers import ProviderName+from backend.util.exceptions import BlockExecutionError++from ._test_data import make_session++USER = "user-ayrshare-copilot"+SSO_URL = "https://profile.ayrshare.com/social-accounts?domain=id-pojeg&jwt=tok"+MANAGED = APIKeyCredentials(+ id="managed-ayrshare",+ provider="ayrshare",+ title="Ayrshare (managed by AutoGPT)",+ api_key=SecretStr("profile-key"),+ expires_at=None,+ is_managed=True,+)+++@contextmanager+def ayrshare_backend(+ *, configured: bool = True, has_profile: bool = False+) -> Iterator[MagicMock]:+ """Ayrshare as the deployment sees it: org secrets, the user's profile+ and the JWT endpoint. Yields the provisioning mock."""+ secrets = MagicMock()+ secrets.secrets.ayrshare_api_key = "org-key" if configured else ""+ secrets.secrets.ayrshare_jwt_key = "jwt-key" if configured else ""+ provision = AsyncMock(return_value=True)+ with ExitStack() as stack:+ stack.enter_context(+ patch(+ "backend.integrations.managed_providers.ayrshare.Settings",+ return_value=secrets,+ )+ )+ stack.enter_context(patch("backend.integrations.ayrshare.settings", secrets))+ stack.enter_context(+ patch(+ "backend.integrations.managed_credentials._provision_under_lock",+ provision,+ )+ )+ stack.enter_context(+ patch.object(+ IntegrationCredentialsStore,+ "has_managed_credential",+ AsyncMock(return_value=has_profile),+ )+ )+ stack.enter_context(+ patch.object(+ IntegrationCredentialsStore,+ "get_creds_by_provider",+ AsyncMock(return_value=[MANAGED]),+ )+ )+ stack.enter_context(+ patch.object(+ AyrshareClient,+ "generate_jwt",+ AsyncMock(+ return_value=JWTResponse(+ status="success", title="t", token="tok", url=SSO_URL+ )+ ),+ )+ )+ stack.enter_context(+ patch(+ "backend.copilot.tools.utils.get_user_credentials",+ AsyncMock(return_value=[]),+ )+ )+ stack.enter_context(+ patch(+ "backend.copilot.tools.utils.selected_credentials",+ AsyncMock(return_value={}),+ )+ )+ yield provision+++async def _prepare(block_id: str, *, session=None):+ return await prepare_block_for_execution(+ block_id=block_id,+ input_data={"post": "Hello from AutoPilot"},+ user_id=USER,+ session=session or make_session(USER),+ session_id="s-ayrshare",+ dry_run=False,+ )+++def assert_no_sso_link(result: ToolResponseBase) -> None:+ # Tool output is stored with the chat, sent to the model provider and+ # served by a shared chat; the link signs into the user's Ayrshare page.+ dumped = result.model_dump_json()+ assert SSO_URL not in dumped+ assert "jwt=" not in dumped+ assert "connect_url" not in dumped++[email protected](loop_scope="session")+class TestBlockWithoutCredential:+ @pytest.mark.parametrize("block", [PostToLinkedInBlock(), PostToXBlock()])+ async def test_provisions_the_profile_and_returns_the_connect_card(self, block):+ # Repro of SECRT-2878: every prod session ended on "requires+ # credentials that are not configured".+ with ayrshare_backend() as provision:+ result = await _prepare(block.id)++ assert isinstance(result, SetupRequirementsResponse)+ assert "not configured" not in result.message+ # The chat card's Ayrshare row reads "Connect"; the builder's longer+ # label is not on the card, so the model must not point at it.+ assert "with the Connect button in the card" in result.message+ assert BUILDER_CONNECT_BUTTON not in result.message+ assert "Each post costs $0.02 ($0.05 for video)." in result.message+ provision.assert_awaited_once()+ (entry,) = result.setup_info.user_readiness.missing_credentials.values()+ assert entry["provider"] == "ayrshare"++ async def test_not_configured_says_it_is_unavailable(self):+ with ayrshare_backend(configured=False) as provision:+ result = await _prepare(PostToLinkedInBlock().id)++ assert isinstance(result, ErrorResponse)+ assert result.error == "ayrshare_not_configured"+ assert "not available" in result.message+ provision.assert_not_awaited()++ async def test_existing_profile_kept_out_of_the_match_is_not_reprovisioned(self):+ # An expert grant or a pinned account hid it: the usual card handles it.+ with ayrshare_backend(has_profile=True) as provision:+ result = await _prepare(PostToLinkedInBlock().id)++ assert isinstance(result, SetupRequirementsResponse)+ assert "not configured" in result.message+ provision.assert_not_awaited()++ @pytest.mark.parametrize("dry_run,validate_only", [(True, False), (False, True)])+ async def test_inspection_provisions_nothing(self, dry_run, validate_only):+ with ayrshare_backend() as provision:+ await prepare_block_for_execution(+ block_id=PostToLinkedInBlock().id,+ input_data={"post": "Hello from AutoPilot"},+ user_id=USER,+ session=make_session(USER),+ session_id="s-ayrshare",+ dry_run=dry_run,+ validate_only=validate_only,+ )++ provision.assert_not_awaited()++ async def test_unattended_turn_says_where_to_connect(self):+ session = make_session(USER)+ set_turn_unattended(session, scheduled=True)+ try:+ with ayrshare_backend():+ result = await _prepare(PostToLinkedInBlock().id)+ finally:+ set_turn_unattended(session, scheduled=False)++ assert isinstance(result, ErrorResponse)+ assert result.error == "ayrshare_accounts_not_linked"+ assert "choosing Connect on the Ayrshare card" in result.message+ assert f"or {BUILDER_CONNECT_BUTTON} in the agent builder" in result.message++ async def test_a_block_the_session_may_not_run_provisions_nothing(self):+ block_id = PostToLinkedInBlock().id+ token = _current_permissions.set(+ CopilotPermissions(blocks=[block_id], blocks_exclude=True)+ )+ try:+ with ayrshare_backend() as provision:+ result = await RunBlockTool()._execute(+ USER,+ make_session(USER),+ block_id=block_id,+ input_data={"post": "Hello from AutoPilot"},+ )+ finally:+ _current_permissions.reset(token)++ assert isinstance(result, ErrorResponse)+ assert "not permitted" in result.message+ assert SSO_URL not in result.message+ provision.assert_not_awaited()++[email protected](loop_scope="session")+class TestConnectIntegration:+ async def test_ayrshare_returns_the_managed_connect_card(self):+ with ayrshare_backend() as provision:+ result = await ConnectIntegrationTool()._execute(+ USER, make_session(USER), provider="ayrshare"+ )++ assert isinstance(result, SetupRequirementsResponse)+ assert "with the Connect button in the card" in result.message+ provision.assert_awaited_once()+ entry = result.setup_info.user_readiness.missing_credentials[+ "ayrshare_credentials"+ ]+ assert entry["provider"] == "ayrshare"++ async def test_ayrshare_not_configured(self):+ with ayrshare_backend(configured=False):+ result = await ConnectIntegrationTool()._execute(+ USER, make_session(USER), provider="ayrshare"+ )++ assert isinstance(result, ErrorResponse)+ assert result.error == "ayrshare_not_configured"++ async def test_a_dry_run_creates_nothing(self):+ session = make_session(USER)+ session.metadata.dry_run = True+ with ayrshare_backend() as provision:+ result = await ConnectIntegrationTool()._execute(+ USER, session, provider="ayrshare"+ )++ assert isinstance(result, ErrorResponse)+ assert result.error == "dry_run"+ assert "nothing was created" in result.message.lower()+ assert SSO_URL not in result.message+ provision.assert_not_awaited()+++def test_connect_integration_offers_ayrshare():+ tool = ConnectIntegrationTool()+ assert tool.parameters["properties"]["provider"]["enum"] == [+ "github",+ "ayrshare",+ ]+ assert "'ayrshare'" in tool.description+++def _patch_execution(spend: AsyncMock, *, post: AsyncMock | None = None):+ """The platform around a real block run: workspace, user, credit store,+ the stored managed credential and Ayrshare's post endpoint."""+ workspace = MagicMock()+ workspace.get_or_create_workspace = AsyncMock(return_value=MagicMock(id="ws-1"))+ users = MagicMock()+ users.get_user_by_id = AsyncMock(return_value=MagicMock(timezone="UTC"))+ credits = MagicMock(get_credits=AsyncMock(return_value=100), spend_credits=spend)+ creds = MagicMock(get=AsyncMock(return_value=MANAGED))+ secrets = MagicMock()+ secrets.secrets.ayrshare_api_key = "org-key"+ stack = ExitStack()+ for target, value in (+ ("backend.copilot.tools.helpers.workspace_db", workspace),+ ("backend.copilot.tools.helpers.user_db", users),+ ("backend.copilot.tools.helpers.credit_db", credits),+ ("backend.copilot.tools.helpers.IntegrationCredentialsManager", creds),+ ):+ stack.enter_context(patch(target, return_value=value))+ stack.enter_context(patch("backend.integrations.ayrshare.settings", secrets))+ if post is not None:+ stack.enter_context(patch.object(AyrshareClient, "create_post", post))+ return stack+++async def _run(block, post: AsyncMock, spend: AsyncMock, **inputs):+ meta = CredentialsMetaInput(+ id=MANAGED.id,+ provider=ProviderName("ayrshare"),+ type="api_key",+ )+ with _patch_execution(spend, post=post):+ return await execute_block(+ block=block,+ block_id=block.id,+ input_data={"post": "Hello", **inputs},+ user_id=USER,+ session_id="s-ayrshare",+ node_exec_id="n-ayrshare",+ matched_credentials={"credentials": meta},+ dry_run=False,+ )+++def _posted() -> AsyncMock:+ return AsyncMock(+ return_value=PostResponse(+ status="success",+ id="p-1",+ refId="r-1",+ profileTitle="User",+ post="Hello",+ postIds=[+ PostIds(+ status="success",+ id="li-1",+ postUrl="https://linkedin.com/p/1",+ platform="linkedin",+ )+ ],+ )+ )++[email protected](loop_scope="session")+class TestManagedPostBilling:+ @pytest.mark.parametrize("is_video,cost", [(False, 2), (True, 5)])+ async def test_a_managed_post_charges_the_block_credits(self, is_video, cost):+ spend = AsyncMock()+ post = _posted()+ result = await _run(PostToLinkedInBlock(), post, spend, is_video=is_video)++ assert isinstance(result, BlockOutputResponse)+ assert post.await_args.kwargs["profile_key"] == "profile-key"+ spend.assert_awaited_once()+ assert spend.await_args.kwargs["cost"] == cost++[email protected](loop_scope="session")+class TestPostToUnlinkedNetwork:+ async def test_returns_the_connect_card_and_charges_nothing(self):+ spend = AsyncMock()+ post = AsyncMock(+ side_effect=BlockExecutionError(+ "Ayrshare API request failed (400): Twitter is not linked",+ "PostToXBlock",+ "x",+ )+ )+ with ayrshare_backend(has_profile=True):+ result = await _run(PostToXBlock(), post, spend)++ assert isinstance(result, SetupRequirementsResponse)+ assert "with the Connect button in the card" in result.message+ assert "Twitter is not linked" in result.message+ spend.assert_not_awaited()++ async def test_other_ayrshare_errors_stay_errors(self):+ post = AsyncMock(+ side_effect=BlockExecutionError("Duplicate post", "PostToXBlock", "x")+ )+ result = await _run(PostToXBlock(), post, AsyncMock())++ assert isinstance(result, ErrorResponse)+ assert "Duplicate post" in result.message+++def _unlinked_post() -> AsyncMock:+ return AsyncMock(+ side_effect=BlockExecutionError(+ "Ayrshare API request failed (400): Twitter is not linked",+ "PostToXBlock",+ "x",+ )+ )+++async def _block_without_credential(session):+ return await _prepare(PostToLinkedInBlock().id, session=session)+++async def _connect(session):+ return await ConnectIntegrationTool()._execute(USER, session, provider="ayrshare")+++async def _post_to_unlinked_network(session):+ return await _run(PostToXBlock(), _unlinked_post(), AsyncMock())++[email protected](loop_scope="session")+class TestNoSSOLinkInChat:+ @pytest.mark.parametrize("unattended", [False, True])+ @pytest.mark.parametrize(+ "answer,has_profile",+ [+ (_block_without_credential, False),+ (_connect, False),+ (_connect, True),+ (_post_to_unlinked_network, True),+ ],+ )+ async def test_no_response_carries_the_sso_link(+ self, answer, has_profile, unattended+ ):+ session = make_session(USER)+ set_turn_unattended(session, scheduled=unattended)+ signed = JWTResponse(status="success", title="t", token="tok", url=SSO_URL)+ try:+ with (+ ayrshare_backend(has_profile=has_profile),+ patch.object(+ AyrshareClient, "generate_jwt", AsyncMock(return_value=signed)+ ) as sign,+ ):+ result = await answer(session)+ finally:+ set_turn_unattended(session, scheduled=False)++ if unattended and answer is not _connect:+ assert isinstance(result, ErrorResponse)+ assert result.error == "ayrshare_accounts_not_linked"+ else:+ assert isinstance(result, SetupRequirementsResponse)+ assert_no_sso_link(result)+ sign.assert_not_awaited()+++EXPERT = "expert-ayrshare"+++async def _expert_block_without_credential():+ return await _prepare(+ PostToLinkedInBlock().id, session=make_session(USER, expert_id=EXPERT)+ )+++async def _expert_connect():+ return await ConnectIntegrationTool()._execute(+ USER, make_session(USER, expert_id=EXPERT), provider="ayrshare"+ )+++@contextmanager+def expert_grants(allowed: list[str]) -> Iterator[None]:+ """An expert whose grant list is *allowed*, on an account whose only+ credential is the managed profile the copilot just provisioned."""+ experts = MagicMock()+ experts.expert_allowed_credential_ids = AsyncMock(return_value=allowed)+ with (+ patch("backend.copilot.tools.expert_scope.experts_db", return_value=experts),+ patch.object(+ IntegrationCredentialsStore,+ "get_all_creds",+ AsyncMock(return_value=[MANAGED]),+ ),+ ):+ yield++[email protected](loop_scope="session")+class TestExpertSession:+ # An expert runs only with credentials it was granted, the managed one+ # included, so the card must offer the grant or linking alone leaves the+ # expert unable to post.+ @pytest.mark.parametrize(+ "answer", [_expert_block_without_credential, _expert_connect]+ )+ async def test_the_card_offers_the_profile_to_the_expert(self, answer):+ with ayrshare_backend(), expert_grants([]):+ result = await answer()++ assert isinstance(result, SetupRequirementsResponse)+ (entry,) = result.setup_info.user_readiness.missing_credentials.values()+ assert entry["expert_grant"]["expert_id"] == EXPERT+ assert [c["id"] for c in entry["expert_grant"]["credentials"]] == [MANAGED.id]+ assert GRANT_TO_EXPERT in result.message+ assert_no_sso_link(result)++ @pytest.mark.parametrize(+ "answer", [_expert_block_without_credential, _expert_connect]+ )+ async def test_an_expert_already_granted_is_not_asked_again(self, answer):+ with ayrshare_backend(), expert_grants([MANAGED.id]):+ result = await answer()++ assert isinstance(result, SetupRequirementsResponse)+ (entry,) = result.setup_info.user_readiness.missing_credentials.values()+ assert entry["expert_grant"]["credentials"] == []+ assert GRANT_TO_EXPERT not in result.message++ async def test_unattended_says_to_grant_the_expert(self):+ session = make_session(USER, expert_id=EXPERT)+ set_turn_unattended(session, scheduled=True)+ try:+ with ayrshare_backend(), expert_grants([]):+ result = await _prepare(PostToLinkedInBlock().id, session=session)+ finally:+ set_turn_unattended(session, scheduled=False)++ assert isinstance(result, ErrorResponse)+ assert result.error == "ayrshare_accounts_not_linked"+ assert "grant this expert access" in result.message+ assert_no_sso_link(result)diff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration.pyindex 98a3a2968d..c9ea8af57d 100644--- a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py@@ -23,11 +23,27 @@ from backend.copilot.tools.utils import build_missing_credentials_from_field_inffrom backend.data.model import CredentialsFieldInfo, CredentialsTypefrom backend.integrations.providers import ProviderName+from .ayrshare_managed import (+ AYRSHARE,+ ensure_profile,+ link_accounts_card,+ link_message,+ with_expert_grants,+)from .base import BaseToolfrom .expert_scope import annotate_expert_grantsCONNECT_INTEGRATION_TOOL = "connect_integration"+# Providers whose account AutoGPT holds: connecting shows the user a button to+# link their own accounts to it, never a key or token field. Kept out of+# SUPPORTED_PROVIDERS, which also decides what is injected into the sandbox.+MANAGED_PROVIDERS: dict[str, str] = {AYRSHARE: "Ayrshare"}+++def _supported_providers() -> list[str]:+ return [*SUPPORTED_PROVIDERS, *MANAGED_PROVIDERS]+def _merged_scopes(provider: str, extra: list[str]) -> frozenset[str]:entry = SUPPORTED_PROVIDERS.get(provider)@@ -75,14 +91,18 @@ class ConnectIntegrationTool(BaseTool):@propertydef description(self) -> str:- supported = ", ".join(f"'{p}'" for p in SUPPORTED_PROVIDERS)+ supported = ", ".join(f"'{p}'" for p in _supported_providers())return (f"Prompt the user to connect a required integration. "f"Supported providers: {supported}. "+ "'ayrshare' (post_to_* blocks) returns the card where the user "+ "links their social accounts, whenever they want to link them; "+ "never ask for its API key. ""ONLY call this tool for one of the supported providers listed above — ""do NOT call it for Google, Gmail, Slack, or any other provider not in the list. "- "Call this ONLY when an external CLI or API call in the sandbox "- "fails because the user has not connected the relevant account. "+ "For the other providers, call this ONLY when an external CLI or API "+ "call in the sandbox fails because the user has not connected the "+ "relevant account. ""Do NOT call this for agent block credential issues — `run_agent` ""automatically detects and prompts for the correct provider based ""on the agent's graph metadata. Using this tool for agent blocks "@@ -110,7 +130,7 @@ class ConnectIntegrationTool(BaseTool):"Integration provider slug, e.g. 'github'. ""Must be one of the supported providers."),- "enum": list(SUPPORTED_PROVIDERS.keys()),+ "enum": _supported_providers(),},"reason": {"type": "string",@@ -167,9 +187,24 @@ class ConnectIntegrationTool(BaseTool):str(s).strip() for s in (scopes or []) if str(s).strip()]+ if provider in MANAGED_PROVIDERS and user_id:+ # Connecting creates the user's real profile; a dry run may not.+ if session.dry_run:+ return ErrorResponse(+ message=(+ f"This is a dry-run session, so connecting "+ f"{MANAGED_PROVIDERS[provider]} was skipped. Nothing was "+ "created."+ ),+ error="dry_run",+ session_id=session_id,+ )+ return await _connect_managed(+ user_id, provider, reason, session_id, session.expert_id+ )entry = SUPPORTED_PROVIDERS.get(provider)if not entry:- supported = ", ".join(f"'{p}'" for p in SUPPORTED_PROVIDERS)+ supported = ", ".join(f"'{p}'" for p in _supported_providers())return ErrorResponse(message=(f"Unknown provider '{provider}'. Supported providers: {supported}."@@ -249,3 +284,44 @@ class ConnectIntegrationTool(BaseTool):},),)+++async def _connect_managed(+ user_id: str,+ provider: str,+ reason: str,+ session_id: str | None,+ expert_id: str | None,+) -> ToolResponseBase:+ """The card for a provider AutoGPT holds the account for.++ Provisions the user's profile when it does not exist yet, through the+ same path as the builder's connect button, and hands back the card with+ that button.+ """+ error = await ensure_profile(user_id)+ if error is not None:+ error.session_id = session_id+ return error+ display_name = MANAGED_PROVIDERS[provider]+ field_key = f"{provider}_credentials"+ field_info = CredentialsFieldInfo[ProviderName, CredentialsType](+ credentials_provider=frozenset([ProviderName(provider)]),+ credentials_types=frozenset(["api_key"]),+ credentials_scopes=None,+ )+ missing = build_missing_credentials_from_field_info(+ credential_fields={field_key: field_info}, matched_keys=set()+ )+ missing[field_key]["title"] = f"{display_name} Credentials"+ missing[field_key]["provider_name"] = display_name+ missing, needs_grant = await with_expert_grants(user_id, expert_id, missing)+ lead = "To post to social networks, the user links their accounts once."+ return link_accounts_card(+ agent_id=f"connect_{provider}",+ agent_name=display_name,+ missing_credentials=missing,+ message=link_message(f"{lead} {reason}".strip(), needs_grant=needs_grant),+ session_id=session_id,+ execution_modes=(),+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.pyindex 3b07a1147e..e078196601 100644--- a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py@@ -218,10 +218,6 @@ async def test_an_approved_irreversible_block_asks_once(gate):"backend.copilot.tools.run_block.prepare_block_for_execution",AsyncMock(return_value=prep),),- patch(- "backend.copilot.tools.run_block.get_current_permissions",- return_value=None,- ),patch("backend.copilot.tools.run_block.check_spend_approval",AsyncMock(return_value=None),diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 83e55e57e5..ac551fee71 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -19,7 +19,7 @@ from backend.copilot.constants import (COPILOT_SESSION_PREFIX,MAX_TOOL_WAIT_SECONDS,)-from backend.copilot.context import is_unattended_turn+from backend.copilot.context import get_current_permissions, is_unattended_turnfrom backend.copilot.credential_selection import turn_credential_pinsfrom backend.copilot.model import ChatSessionfrom backend.copilot.sdk.env import config as chat_config@@ -54,6 +54,9 @@ from backend.util.request import HTTPClientErrorfrom backend.util.timezone_utils import get_user_timezone_or_utcfrom backend.util.type import coerce_inputs_to_schema+from .ayrshare_managed import is_ayrshare, is_not_linked_error+from .ayrshare_managed import not_linked_response as ayrshare_not_linked_response+from .ayrshare_managed import provision_for_block as provision_ayrshare_for_blockfrom .expert_scope import (annotate_expert_grants,provider_slug,@@ -607,6 +610,10 @@ async def execute_block()except BlockError as e:+ if is_ayrshare(get_block_provider(block)) and is_not_linked_error(e):+ return await ayrshare_not_linked_response(+ user_id, block, block_id, e, session_id, expert_id+ )status_code = credential_rejection_status(e)if status_code is not None and matched_credentials:logger.warning(@@ -1040,6 +1047,10 @@ async def prepare_block_for_execution(session_id=session_id,).from_outside()+ # Before credentials: resolving them can provision a managed profile.+ if denied := _permission_denied(block_id, block.name, session_id):+ return denied+emit_tool_display_name(block.name)# LLMs sometimes pass `"credentials": null` instead of omitting the field.@@ -1053,6 +1064,18 @@ async def prepare_block_for_execution(matched_credentials, missing_credentials = await resolve_block_credentials(user_id, block, input_data, session.expert_id, session_id=session_id)+ # Ayrshare's credential is a profile AutoGPT provisions, never one the+ # user brings: create it now and hand back the account-linking link.+ if (+ any(is_ayrshare(m.provider) for m in missing_credentials)+ and not (dry_run or validate_only)+ and (+ managed := await provision_ayrshare_for_block(+ user_id, block, block_id, session_id, session.expert_id+ )+ )+ ):+ return managedtry:input_schema: dict[str, Any] = block.input_schema.jsonschema()@@ -1190,6 +1213,32 @@ async def prepare_block_for_execution()+def _permission_denied(+ block_id: str, block_name: str, session_id: str+) -> ErrorResponse | None:+ """The refusal when the session's permissions do not allow this block."""+ perms = get_current_permissions()+ if perms is None or perms.is_block_allowed(block_id, block_name):+ return None+ available_hint = (+ f"Allowed identifiers: {perms.blocks!r}. "+ if not perms.blocks_exclude and perms.blocks+ else (+ f"Blocked identifiers: {perms.blocks!r}. "+ if perms.blocks_exclude and perms.blocks+ else ""+ )+ )+ return ErrorResponse(+ message=(+ f"Block '{block_name}' ({block_id}) is not permitted "+ f"by the current execution permissions. {available_hint}"+ "Use find_capability to discover blocks that are allowed."+ ),+ session_id=session_id,+ ).from_outside()++def required_input_keys(block: AnyBlockSchema) -> set[str]:"""Inputs a block needs from its caller; without them ``run_block`` answerswith the schema and runs nothing. Credentials resolve on their own."""diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.pyindex 4b5dd4ecaf..d2db6c7614 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py@@ -6,7 +6,6 @@ from typing import Anyfrom backend.blocks.llm import LLM_PROVIDER_NAMESfrom backend.copilot.constants import COPILOT_NODE_EXEC_ID_SEPARATOR-from backend.copilot.context import get_current_permissionsfrom backend.copilot.model import ChatSessionfrom backend.data.activity_event import ActivityEventDraft@@ -172,27 +171,6 @@ class RunBlockTool(BaseTool):return prep_or_errprep: BlockPreparation = prep_or_err- # Check block-level permissions before execution.- perms = get_current_permissions()- if perms is not None and not perms.is_block_allowed(block_id, prep.block.name):- available_hint = (- f"Allowed identifiers: {perms.blocks!r}. "- if not perms.blocks_exclude and perms.blocks- else (- f"Blocked identifiers: {perms.blocks!r}. "- if perms.blocks_exclude and perms.blocks- else ""- )- )- return ErrorResponse(- message=(- f"Block '{prep.block.name}' ({block_id}) is not permitted "- f"by the current execution permissions. {available_hint}"- "Use find_capability to discover blocks that are allowed."- ),- session_id=session_id,- ).from_outside()-# Dry-run fast-path: skip credential/HITL checks — simulation never calls# the real service so credentials and review gates are not needed.# Input field validation (unrecognized fields) is already handled bydiff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability.py b/autogpt_platform/backend/backend/copilot/tools/run_capability.pyindex f894b4eef6..47a639c2cc 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_capability.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability.py@@ -13,6 +13,7 @@ from typing import Anyfrom urllib.parse import urlsplitfrom backend.blocks import get_block+from backend.copilot.capabilities.block_meta import get_block_providerfrom backend.copilot.capabilities.mcp_review import (MCPReviewPayload,needs_review,@@ -31,6 +32,8 @@ from backend.copilot.permissions import BLOCK_GATE, MCP_GATEfrom backend.copilot.tool_display import emit_tool_display_namefrom backend.data.activity_event import ActivityEventDraft+from .ayrshare_managed import connect_for_block as ayrshare_connect_for_block+from .ayrshare_managed import is_ayrsharefrom .base import GATE_APPROVED, BaseToolfrom .capability_gates import gate_denied, gate_denied_errorfrom .describe_capability import (@@ -255,6 +258,19 @@ async def _run_block(),session_id=session.session_id,)+ block = get_block(block_id)+ # Connecting creates the user's real Ayrshare profile; neither mode may.+ managed = block is not None and is_ayrshare(get_block_provider(block))+ if managed and (validate_only or session.dry_run):+ return CapabilityDetailsResponse(+ message=(+ f"Connecting {entry.name} creates the user's Ayrshare profile, "+ "so validate_only and dry runs skip it. Nothing was created."+ ),+ capability=entry.listing(),+ parameters={},+ session_id=session.session_id,+ )prep = await prepare_block_for_execution(block_id=block_id,input_data=payload,@@ -270,6 +286,12 @@ async def _run_block()if isinstance(prep, ToolResponseBase) and not picker_only:return prep+ # Holding the managed Ayrshare credential says nothing about which+ # networks are linked, so connecting shows the connect card.+ if managed and block is not None:+ return await ayrshare_connect_for_block(+ user_id, block, block_id, session.session_id, session.expert_id+ )return CapabilityDetailsResponse(message=(f"The user is already connected for {entry.name}. "diff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability_connect_test.py b/autogpt_platform/backend/backend/copilot/tools/run_capability_connect_test.pyindex 724bb91570..d56b68a967 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_capability_connect_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability_connect_test.py@@ -3,6 +3,9 @@from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch+import pytest++from backend.blocks.ayrshare.post_to_linkedin import PostToLinkedInBlockfrom backend.copilot.capabilities.models import (CapabilityEntry,Connection,@@ -162,3 +165,66 @@ async def test_a_connect_call_on_a_block_has_no_gate_subject():USER, session, {"id": entry.id, "input": {"connect": True}})assert subject is NO_OP+++async def test_connect_on_an_ayrshare_block_shows_the_connect_card():+ # The managed credential exists, but which networks are linked is only+ # visible on Ayrshare's page, so "connected" would be a guess.+ session = make_session(USER)+ link_card = _card(session.session_id)+ connect = AsyncMock(return_value=link_card)+ with (+ patch("backend.copilot.tools.run_capability.gate_denied", return_value=False),+ patch(+ "backend.copilot.tools.run_capability.prepare_block_for_execution",+ AsyncMock(return_value=object()),+ ),+ patch(+ "backend.copilot.tools.run_capability.get_block",+ return_value=PostToLinkedInBlock(),+ ),+ patch(+ "backend.copilot.tools.run_capability.ayrshare_connect_for_block",+ connect,+ ),+ ):+ result = await _run_block(+ _entry(), USER, session, {"connect": True}, False, False+ )++ assert result is link_card+ connect.assert_awaited_once()++[email protected]("validate_only, dry_run", [(True, False), (False, True)])+async def test_connect_on_an_ayrshare_block_creates_nothing_when_simulating(+ validate_only, dry_run+):+ # Connecting provisions a real Ayrshare profile, so neither mode may.+ session = make_session(USER)+ session.metadata.dry_run = dry_run+ prepare = AsyncMock(return_value=object())+ connect = AsyncMock()+ with (+ patch("backend.copilot.tools.run_capability.gate_denied", return_value=False),+ patch(+ "backend.copilot.tools.run_capability.prepare_block_for_execution",+ prepare,+ ),+ patch(+ "backend.copilot.tools.run_capability.get_block",+ return_value=PostToLinkedInBlock(),+ ),+ patch(+ "backend.copilot.tools.run_capability.ayrshare_connect_for_block",+ connect,+ ),+ ):+ result = await _run_block(+ _entry(), USER, session, {"connect": True}, validate_only, False+ )++ assert isinstance(result, CapabilityDetailsResponse)+ assert "nothing was created" in result.message.lower()+ prepare.assert_not_awaited()+ connect.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py b/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.pyindex 4cee6a72e9..f5ba740c60 100644--- a/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py+++ b/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py@@ -78,10 +78,6 @@ class TestRunBlockToolSessionDryRun:"backend.copilot.tools.run_block.prepare_block_for_execution") as mock_prep,patch("backend.copilot.tools.run_block.execute_block") as mock_exec,- patch(- "backend.copilot.tools.run_block.get_current_permissions",- return_value=None,- ),):# Set up prepare_block_for_execution to return a mock prepmock_prep_result = MagicMock()@@ -123,10 +119,6 @@ class TestRunBlockToolSessionDryRun:"backend.copilot.tools.run_block.prepare_block_for_execution") as mock_prep,patch("backend.copilot.tools.run_block.execute_block") as mock_exec,- patch(- "backend.copilot.tools.run_block.get_current_permissions",- return_value=None,- ),patch("backend.copilot.tools.run_block.check_hitl_review") as mock_hitl,):mock_prep_result = MagicMock()diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.pyindex 34fc1a72f1..492f5ba4df 100644--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py@@ -258,7 +258,16 @@ from ._test_data import make_session# The margin is deliberate and is the same exception the wire budget's #14476# note names: this is queued while dev is still moving, and a measured-plus-one# ceiling reds the queue's merge ref on the next reworded description.-_CHAR_BUDGET = 77_014+# Bumped 77_014 -> 77_176 for connect_integration's managed `ayrshare`+# provider (SECRT-2878): the enum entry, its place in the supported list, one+# sentence telling the model it returns the account-linking link (never a key+# field), and scoping the sandbox-failure-only rule to the other providers so+# it no longer forbids the ayrshare call. No tool was added (89 either side).+# Measured on the branch, whose merge with dev 0cddeafd8d is unchanged here:+# dev 583fc0bb4e 76,975 (89 tools)+# + this PR's connect_integration +200 77,175 (89 tools)+# Plus one.+_CHAR_BUDGET = 77_176@pytest.fixture(scope="module")diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.pyindex ce94f70ed1..c37b48d6d0 100644--- a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py+++ b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py@@ -33,13 +33,17 @@ from __future__ import annotationsimport loggingimport secrets+from datetime import datetime, timedelta, timezone-from pydantic import SecretStr+from pydantic import BaseModel, SecretStrfrom backend.data.model import APIKeyCredentials, Credentials-from backend.integrations.ayrshare import AyrshareClient+from backend.integrations.ayrshare import AyrshareClient, SocialPlatformfrom backend.integrations.credentials_store import IntegrationCredentialsStore-from backend.integrations.managed_credentials import ManagedCredentialProvider+from backend.integrations.managed_credentials import (+ ManagedCredentialProvider,+ ensure_managed_credential,+)from backend.util.exceptions import MissingConfigErrorfrom backend.util.settings import Settings@@ -50,8 +54,9 @@ class AyrshareManagedProvider(ManagedCredentialProvider):provider_name = "ayrshare"# Opt out of the credentials sweep — each Ayrshare profile counts- # against our subscription quota, so we only provision when the user- # explicitly triggers the SSO flow from a block. See+ # against our subscription quota, so we only provision through+ # :func:`provision_profile`, when the user opens the SSO flow from a block+ # or AutoPilot runs an Ayrshare block for them. See# ``ManagedCredentialProvider.auto_provision`` for the gate semantics.auto_provision = False@@ -176,3 +181,120 @@ def settings_available() -> bool:"""settings = Settings()return bool(settings.secrets.ayrshare_api_key and settings.secrets.ayrshare_jwt_key)+++# Ayrshare JWT max lifetime is 2880 minutes (48 h).+SSO_MAX_EXPIRY_MINUTES = 2880++# The networks the Ayrshare-hosted social-linking page will *offer* the user+# to connect. Blocks exist for more platforms than are listed here; the list+# is deliberately narrower so the rollout can verify each network end-to-end+# before widening the user-visible surface. Keep in sync with tested+# platforms — extend as each is verified against the block + Ayrshare's+# network-specific quirks.+SSO_ALLOWED_SOCIAL = [+ SocialPlatform.TWITTER,+ SocialPlatform.LINKEDIN,+ SocialPlatform.INSTAGRAM,+ SocialPlatform.YOUTUBE,+ SocialPlatform.TIKTOK,+]+++class AyrshareNotConfiguredError(Exception):+ """The org-level Ayrshare secrets are not set on this deployment."""+++class AyrshareProvisioningError(Exception):+ """The per-user profile or its SSO link could not be created."""+++class AyrshareSSOLink(BaseModel):+ url: str+ expires_at: datetime+++def _configured_client() -> AyrshareClient:+ if not settings_available():+ raise AyrshareNotConfiguredError("Ayrshare integration is not configured")+ try:+ return AyrshareClient()+ except MissingConfigError as exc:+ raise AyrshareNotConfiguredError(+ "Ayrshare integration is not configured"+ ) from exc+++async def _provision_profile(+ user_id: str, store: IntegrationCredentialsStore+) -> APIKeyCredentials:+ # On-demand provisioning: AyrshareManagedProvider opts out of the+ # credentials sweep (profile quota is per-user subscription-bound), so a+ # profile is only created for a user who actually needs one.+ provisioned = await ensure_managed_credential(+ user_id, store, AyrshareManagedProvider()+ )+ if not provisioned:+ raise AyrshareProvisioningError("Failed to provision Ayrshare profile")++ ayrshare_creds = [+ c+ for c in await store.get_creds_by_provider(user_id, "ayrshare")+ if c.is_managed and isinstance(c, APIKeyCredentials)+ ]+ if not ayrshare_creds:+ logger.error(+ "Ayrshare credential provisioning did not produce a credential for user %s",+ user_id,+ )+ raise AyrshareProvisioningError("Failed to provision Ayrshare profile")+ return ayrshare_creds[0]+++async def provision_profile(+ user_id: str, store: IntegrationCredentialsStore+) -> APIKeyCredentials:+ """Provision the user's managed profile if needed, without signing a link.++ For callers that only need the profile to exist, such as AutoPilot, which+ sends the user to the card's connect button (it fetches its own link+ from ``/ayrshare/sso_url``) instead of putting a link in the chat.++ Raises the same errors as :func:`get_sso_link`.+ """+ _configured_client()+ return await _provision_profile(user_id, store)+++async def get_sso_link(+ user_id: str, store: IntegrationCredentialsStore+) -> AyrshareSSOLink:+ """Provision the user's managed profile if needed and sign an SSO link.++ The path the builder's ``/ayrshare/sso_url`` route takes to hand a user+ the Ayrshare page where they link their social networks.++ Raises :class:`AyrshareNotConfiguredError` when the org secrets are+ missing, and :class:`AyrshareProvisioningError` when provisioning or+ signing fails.+ """+ client = _configured_client()+ profile = await _provision_profile(user_id, store)++ try:+ jwt_response = await client.generate_jwt(+ private_key=Settings().secrets.ayrshare_jwt_key,+ profile_key=profile.api_key.get_secret_value(),+ allowed_social=SSO_ALLOWED_SOCIAL,+ expires_in=SSO_MAX_EXPIRY_MINUTES,+ verify=True,+ )+ except Exception as exc:+ logger.error("Error generating Ayrshare JWT for user %s: %s", user_id, exc)+ raise AyrshareProvisioningError("Failed to generate JWT") from exc++ return AyrshareSSOLink(+ url=jwt_response.url,+ expires_at=datetime.now(timezone.utc)+ + timedelta(minutes=SSO_MAX_EXPIRY_MINUTES),+ )diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.pyindex aab97bd55d..4352f6fd73 100644--- a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py+++ b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py@@ -6,9 +6,14 @@ import pytestfrom pydantic import SecretStrfrom backend.data.model import APIKeyCredentials+from backend.integrations.ayrshare import JWTResponsefrom backend.integrations.managed_providers.ayrshare import (AyrshareManagedProvider,+ AyrshareNotConfiguredError,+ AyrshareProvisioningError,_migrate_legacy_or_create_profile_key,+ get_sso_link,+ provision_profile,settings_available,)@@ -290,3 +295,102 @@ class TestMigrationOrderingSafety:# The legacy key MUST still be populated — otherwise a retry would# create a fresh Ayrshare profile and orphan the user's socials.assert user_integrations.managed_credentials.ayrshare_profile_key is legacy+++class TestGetSSOLink:+ """The builder route's path, and AutoPilot's provisioning without a link."""++ _MODULE = "backend.integrations.managed_providers.ayrshare"++ @staticmethod+ def _store(creds: list) -> MagicMock:+ store = MagicMock()+ store.get_creds_by_provider = AsyncMock(return_value=creds)+ return store++ @staticmethod+ def _managed() -> APIKeyCredentials:+ return APIKeyCredentials(+ provider="ayrshare",+ title="Ayrshare (managed by AutoGPT)",+ api_key=SecretStr("profile-key"),+ expires_at=None,+ is_managed=True,+ )++ def _patches(self, *, configured=True, provisioned=True, jwt=None):+ client = MagicMock()+ client.generate_jwt = jwt or AsyncMock(+ return_value=JWTResponse(+ status="success", title="t", token="tok", url="https://sso"+ )+ )+ ensure = AsyncMock(return_value=provisioned)+ return (+ patch(f"{self._MODULE}.settings_available", return_value=configured),+ patch(f"{self._MODULE}.AyrshareClient", return_value=client),+ patch(f"{self._MODULE}.ensure_managed_credential", ensure),+ client,+ ensure,+ )++ @pytest.mark.asyncio(loop_scope="session")+ async def test_provisions_then_signs_the_link(self):+ available, client_cls, ensure_patch, client, ensure = self._patches()+ with available, client_cls, ensure_patch:+ link = await get_sso_link(_USER_ID, self._store([self._managed()]))++ assert link.url == "https://sso"+ ensure.assert_awaited_once()+ kwargs = client.generate_jwt.await_args.kwargs+ assert kwargs["profile_key"] == "profile-key"+ assert kwargs["expires_in"] == 2880++ @pytest.mark.asyncio(loop_scope="session")+ async def test_not_configured_provisions_nothing(self):+ available, client_cls, ensure_patch, _, ensure = self._patches(configured=False)+ with available, client_cls, ensure_patch:+ with pytest.raises(AyrshareNotConfiguredError):+ await get_sso_link(_USER_ID, self._store([]))+ ensure.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_failed_provisioning(self):+ available, client_cls, ensure_patch, _, _ = self._patches(provisioned=False)+ with available, client_cls, ensure_patch:+ with pytest.raises(AyrshareProvisioningError):+ await get_sso_link(_USER_ID, self._store([]))++ @pytest.mark.asyncio(loop_scope="session")+ async def test_failed_jwt(self):+ available, client_cls, ensure_patch, _, _ = self._patches(+ jwt=AsyncMock(side_effect=RuntimeError("upstream"))+ )+ with available, client_cls, ensure_patch:+ with pytest.raises(AyrshareProvisioningError, match="JWT"):+ await get_sso_link(_USER_ID, self._store([self._managed()]))++ @pytest.mark.asyncio(loop_scope="session")+ async def test_provision_profile_signs_no_link(self):+ available, client_cls, ensure_patch, client, ensure = self._patches()+ with available, client_cls, ensure_patch:+ profile = await provision_profile(_USER_ID, self._store([self._managed()]))++ assert profile.api_key.get_secret_value() == "profile-key"+ ensure.assert_awaited_once()+ client.generate_jwt.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_provision_profile_not_configured_provisions_nothing(self):+ available, client_cls, ensure_patch, _, ensure = self._patches(configured=False)+ with available, client_cls, ensure_patch:+ with pytest.raises(AyrshareNotConfiguredError):+ await provision_profile(_USER_ID, self._store([]))+ ensure.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_provision_profile_failed(self):+ available, client_cls, ensure_patch, _, _ = self._patches(provisioned=False)+ with available, client_cls, ensure_patch:+ with pytest.raises(AyrshareProvisioningError):+ await provision_profile(_USER_ID, self._store([]))diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsxindex a561cb5687..c42b4c766e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/ConnectorRow.tsx@@ -4,6 +4,7 @@ import { useGrantExpertCredentials } from "@/app/api/__generated__/endpoints/expimport type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";+import { useAyrshareConnect } from "@/components/contextual/CredentialsInput/components/AyrshareConnectButton/useAyrshareConnect";import { ConnectCredentialDialog } from "@/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog";import { findSavedUserCredentialByProviderAndType } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";import { filterSystemCredentials } from "@/components/contextual/CredentialsInput/helpers";@@ -28,6 +29,7 @@ interface Props {type Grantable = ExpertGrant["credentials"][number];type SavedCredential = CredentialsProviderData["savedCredentials"][number];+const AYRSHARE = "ayrshare";const UNUSABLE_ACCOUNT_ERROR ="That account is missing the access this needs. Try connecting again.";const GRANT_FAILED_ERROR = "Couldn't grant access. Try again.";@@ -56,6 +58,7 @@ export function ConnectorRow({ row }: Props) {useGrantExpertCredentials();const expertGrant = row.expertGrant;const grantedCredentials = useExpertCredentialSelection(row, allProviders);+ const ayrshare = useAyrshareConnect();const rejectedIds = row.rejectedCredentialIds.filter((id) => !renewedIds.includes(id),@@ -252,6 +255,15 @@ export function ConnectorRow({ row }: Props) {? grantedCredentials.isSelectionGranted: !!row.selected && !rejectedIds.includes(row.selected.id));+ // AutoGPT holds the Ayrshare account, so there is no key to ask for: the+ // user links their networks on Ayrshare's own page. Having the managed+ // profile says nothing about which networks are linked, so the row keeps+ // offering that page once it is satisfied. Only an expert still waiting for+ // its grant goes through the dialog.+ const linksOnAyrshare =+ row.provider === AYRSHARE &&+ !(expertGrant && !isSatisfied && grantableOptions.length > 0);+function openDialog() {knownIds.current = allProviders? new Set(@@ -290,7 +302,7 @@ export function ConnectorRow({ row }: Props) {)}</div>- {isSatisfied ? (+ {isSatisfied && !linksOnAyrshare ? (<span className="flex shrink-0 items-center gap-1.5 text-sm font-medium text-zinc-500"><Icon icon={CheckmarkCircle02Icon} size={16} />{expertGrant ? "Granted" : "Connected"}@@ -302,17 +314,20 @@ export function ConnectorRow({ row }: Props) {className="shrink-0"disabled={isGranting ||+ ayrshare.isLoading ||Boolean(expertGrant && (grantedCredentials.isPending || !allProviders),)}- onClick={openDialog}+ onClick={linksOnAyrshare ? ayrshare.connect : openDialog}>- {buttonLabel({- canGrant: grantableOptions.length > 0,- awaitingReconnect,- hasChoice,- })}+ {linksOnAyrshare+ ? "Connect"+ : buttonLabel({+ canGrant: grantableOptions.length > 0,+ awaitingReconnect,+ hasChoice,+ })}</Button>)}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.ayrshare.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.ayrshare.test.tsxnew file mode 100644index 0000000000..db5e609d58--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ConnectorRow.ayrshare.test.tsx@@ -0,0 +1,141 @@+import { getGetV1GetAyrshareSsoUrlMockHandler200 } from "@/app/api/__generated__/endpoints/integrations/integrations.msw";+import { server } from "@/mocks/mock-server";+import {+ CredentialsActionsContext,+ CredentialsProvidersContext,+} from "@/providers/agent-credentials/credentials-provider";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useState, type ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ConnectorRow } from "../ConnectorRow";+import type { ConnectorRow as Row } from "../helpers";++const SSO_URL = "https://profile.ayrshare.com/social-accounts?jwt=fake";++const managed = {+ id: "cred-managed",+ provider: "ayrshare",+ type: "api_key",+ title: "Ayrshare (managed by AutoGPT)",+ is_managed: true,+};++function providers(saved: (typeof managed)[]) {+ return {+ ayrshare: {+ provider: "ayrshare",+ providerName: "Ayrshare",+ savedCredentials: saved,+ oAuthCallback: vi.fn(),+ createAPIKeyCredentials: vi.fn(),+ createUserPasswordCredentials: vi.fn(),+ createHostScopedCredentials: vi.fn(),+ deleteCredentials: vi.fn(),+ },+ } as unknown as React.ContextType<typeof CredentialsProvidersContext>;+}++function row(overrides: Partial<Row> = {}): Row {+ return {+ provider: "ayrshare",+ displayName: "Ayrshare",+ description: "Post to every social network",+ schema: {+ credentials_provider: ["ayrshare"],+ credentials_types: ["api_key"],+ },+ selected: undefined,+ hasUnansweredTarget: false,+ rejectedCredentialIds: [],+ select: vi.fn(),+ onConnected: vi.fn(),+ ...overrides,+ };+}++function StatefulRow({ current }: { current: Row }) {+ const [selected, setSelected] = useState(current.selected);+ return (+ <ConnectorRow+ row={{+ ...current,+ selected,+ select: (value) => {+ current.select(value);+ setSelected(value);+ },+ }}+ />+ );+}++function renderRow(current: Row, saved: (typeof managed)[], reload = vi.fn()) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>+ <CredentialsActionsContext.Provider value={{ reload, upsert: vi.fn() }}>+ <CredentialsProvidersContext.Provider value={providers(saved)}>+ {children}+ </CredentialsProvidersContext.Provider>+ </CredentialsActionsContext.Provider>+ </QueryClientProvider>+ );+ }+ return render(<StatefulRow current={current} />, { wrapper: Wrapper });+}++let open: ReturnType<typeof vi.fn>;++beforeEach(() => {+ open = vi.fn(() => ({}) as Window);+ vi.stubGlobal("open", open);+ server.use(+ getGetV1GetAyrshareSsoUrlMockHandler200({+ sso_url: SSO_URL,+ expires_at: new Date("2026-10-14T00:00:00Z"),+ }),+ );+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("ConnectorRow for the managed Ayrshare profile", () => {+ it("opens Ayrshare's linking page instead of the API key dialog", async () => {+ const reload = vi.fn();+ renderRow(row(), [], reload);++ fireEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(() =>+ expect(open).toHaveBeenCalledWith(SSO_URL, "_blank", "popup=true"),+ );+ expect(reload).toHaveBeenCalled();+ expect(screen.queryByText("API Key")).toBeNull();+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("keeps Connect once the managed profile exists, since it says nothing about linked networks", async () => {+ const current = row();+ renderRow(current, [managed]);++ await waitFor(() =>+ expect(current.select).toHaveBeenCalledWith(+ expect.objectContaining({ id: managed.id }),+ ),+ );+ expect(screen.queryByText("Connected")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(() =>+ expect(open).toHaveBeenCalledWith(SSO_URL, "_blank", "popup=true"),+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/AyrshareConnectButton.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/AyrshareConnectButton.tsxindex a22f55050a..ae4624955c 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/AyrshareConnectButton.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/AyrshareConnectButton.tsx@@ -1,14 +1,10 @@"use client";-import { useContext, useState } from "react";-import { Key01Icon } from "@hugeicons/core-free-icons";-import { getV1GetAyrshareSsoUrl } from "@/app/api/__generated__/endpoints/integrations/integrations";-import { useToast } from "@/components/molecules/Toast/use-toast";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";-import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";import { cn } from "@/lib/utils";+import { useAyrshareConnect } from "./useAyrshareConnect";interface Props {className?: string;@@ -16,47 +12,13 @@ interface Props {// This SSO button is not a part of inputSchema - that's why we are not rendering it using Input rendererexport function AyrshareConnectButton({ className }: Props) {- const [isLoading, setIsLoading] = useState(false);- const { toast } = useToast();- const credentialsActions = useContext(CredentialsActionsContext);-- async function handleSSOLogin() {- setIsLoading(true);- try {- const { data, status } = await getV1GetAyrshareSsoUrl();- if (status !== 200) {- throw new Error(data.detail);- }- // The SSO endpoint provisions the managed Ayrshare credential as a- // side effect — reload the credentials context so the block's- // dropdown picks it up without a page refresh.- credentialsActions?.reload();- const popup = window.open(data.sso_url, "_blank", "popup=true");- if (!popup) {- throw new Error(- "Please allow popups for this site to be able to login with Ayrshare",- );- }- toast({- title: "Success",- description: "Please complete the authentication in the popup window",- });- } catch (error) {- toast({- title: "Error",- description: `Error getting SSO URL: ${error}`,- variant: "destructive",- });- } finally {- setIsLoading(false);- }- }+ const { connect, isLoading } = useAyrshareConnect();// TODO :Need better UI to show user which social media accounts are connectedreturn (<Buttontype="button"- onClick={handleSSOLogin}+ onClick={connect}disabled={isLoading}className={cn("h-fit w-full py-2", className)}loading={isLoading}diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/useAyrshareConnect.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/useAyrshareConnect.tsnew file mode 100644index 0000000000..25a3e239d7--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/AyrshareConnectButton/useAyrshareConnect.ts@@ -0,0 +1,45 @@+import { useContext, useState } from "react";++import { getV1GetAyrshareSsoUrl } from "@/app/api/__generated__/endpoints/integrations/integrations";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";++export function useAyrshareConnect() {+ const [isLoading, setIsLoading] = useState(false);+ const { toast } = useToast();+ const credentialsActions = useContext(CredentialsActionsContext);++ async function connect() {+ setIsLoading(true);+ try {+ const { data, status } = await getV1GetAyrshareSsoUrl();+ if (status !== 200) {+ throw new Error(data.detail);+ }+ // The SSO endpoint provisions the managed Ayrshare credential as a+ // side effect — reload the credentials context so the block's+ // dropdown picks it up without a page refresh.+ credentialsActions?.reload();+ const popup = window.open(data.sso_url, "_blank", "popup=true");+ if (!popup) {+ throw new Error(+ "Please allow popups for this site to be able to login with Ayrshare",+ );+ }+ toast({+ title: "Success",+ description: "Please complete the authentication in the popup window",+ });+ } catch (error) {+ toast({+ title: "Error",+ description: `Error getting SSO URL: ${error}`,+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ }+ }++ return { connect, isLoading };+}