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.
refactor(platform): migrate Ayrshare to standard managed-credential flow (#12883)
Zamil Majdy575f75edf41b
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex ee88cdd1bd..3f6da3e748 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -14,7 +14,7 @@ from fastapi import (Security,status,)-from pydantic import BaseModel, Field, SecretStr, model_validator+from pydantic import BaseModel, Field, model_validatorfrom starlette.status import HTTP_500_INTERNAL_SERVER_ERROR, HTTP_502_BAD_GATEWAYfrom backend.api.features.library.db import set_preset_webhook, update_preset@@ -29,15 +29,14 @@ from backend.data.integrations import (wait_for_webhook_event,)from backend.data.model import (+ APIKeyCredentials,Credentials,CredentialsType,HostScopedCredentials,OAuth2Credentials,- UserIntegrations,is_sdk_default,)from backend.data.onboarding import OnboardingStep, complete_onboarding_step-from backend.data.user import get_user_integrationsfrom backend.executor.utils import add_graph_executionfrom backend.integrations.ayrshare import AyrshareClient, SocialPlatformfrom backend.integrations.credentials_store import (@@ -48,7 +47,14 @@ from backend.integrations.creds_manager import (IntegrationCredentialsManager,create_mcp_oauth_handler,)-from backend.integrations.managed_credentials import ensure_managed_credentials+from backend.integrations.managed_credentials import (+ ensure_managed_credential,+ ensure_managed_credentials,+)+from backend.integrations.managed_providers.ayrshare import AyrshareManagedProvider+from backend.integrations.managed_providers.ayrshare import (+ settings_available as ayrshare_settings_available,+)from backend.integrations.oauth import CREDENTIALS_BY_PROVIDER, HANDLERS_BY_NAMEfrom backend.integrations.providers import ProviderNamefrom backend.integrations.webhooks import get_webhook_manager@@ -237,13 +243,38 @@ async def callback(return to_meta_response(credentials)+# Bound the first-time sweep so a slow upstream (e.g. Ayrshare) can't hang+# the credential-list endpoint. On timeout we still kick off a fire-and-+# forget sweep so provisioning eventually completes; the user just won't+# see the managed cred until the next refresh.+_MANAGED_PROVISION_TIMEOUT_S = 10.0+++async def _ensure_managed_credentials_bounded(user_id: str) -> None:+ try:+ await asyncio.wait_for(+ ensure_managed_credentials(user_id, creds_manager.store),+ timeout=_MANAGED_PROVISION_TIMEOUT_S,+ )+ except asyncio.TimeoutError:+ logger.warning(+ "Managed credential sweep exceeded %.1fs for user=%s; "+ "continuing without it — provisioning will complete in background",+ _MANAGED_PROVISION_TIMEOUT_S,+ user_id,+ )+ asyncio.create_task(ensure_managed_credentials(user_id, creds_manager.store))++@router.get("/credentials", summary="List Credentials")async def list_credentials(user_id: Annotated[str, Security(get_user_id)],) -> list[CredentialsMetaResponse]:- # Fire-and-forget: provision missing managed credentials in the background.- # The credential appears on the next page load; listing is never blocked.- asyncio.create_task(ensure_managed_credentials(user_id, creds_manager.store))+ # Block on provisioning so managed credentials appear on the first load+ # instead of after a refresh, but with a timeout so a slow upstream+ # can't hang the endpoint. `_provisioned_users` short-circuits on+ # repeat calls.+ await _ensure_managed_credentials_bounded(user_id)credentials = await creds_manager.store.get_all_creds(user_id)return [@@ -258,7 +289,7 @@ async def list_credentials_by_provider(],user_id: Annotated[str, Security(get_user_id)],) -> list[CredentialsMetaResponse]:- asyncio.create_task(ensure_managed_credentials(user_id, creds_manager.store))+ await _ensure_managed_credentials_bounded(user_id)credentials = await creds_manager.store.get_creds_by_provider(user_id, provider)return [@@ -1084,12 +1115,21 @@ def _get_provider_oauth_handler(async def get_ayrshare_sso_url(user_id: Annotated[str, Security(get_user_id)],) -> AyrshareSSOResponse:+ """Generate a JWT SSO URL so the user can link their social accounts.++ The per-user Ayrshare profile key is provisioned and persisted as a+ standard ``is_managed=True`` credential by+ :class:`~backend.integrations.managed_providers.ayrshare.AyrshareManagedProvider`.+ This endpoint only signs a short-lived JWT pointing at the Ayrshare-+ hosted social-linking page; all profile lifecycle logic lives with the+ managed provider."""- Generate an SSO URL for Ayrshare social media integration.+ if not ayrshare_settings_available():+ raise HTTPException(+ status_code=HTTP_500_INTERNAL_SERVER_ERROR,+ detail="Ayrshare integration is not configured",+ )- Returns:- dict: Contains the SSO URL for Ayrshare integration- """try:client = AyrshareClient()except MissingConfigError:@@ -1098,66 +1138,63 @@ async def get_ayrshare_sso_url(detail="Ayrshare integration is not configured",)- # Ayrshare profile key is stored in the credentials store- # It is generated when creating a new profile, if there is no profile key,- # we create a new profile and store the profile key in the credentials store-- user_integrations: UserIntegrations = await get_user_integrations(user_id)- profile_key = user_integrations.managed_credentials.ayrshare_profile_key-- if not profile_key:- logger.debug(f"Creating new Ayrshare profile for user {user_id}")- try:- profile = await client.create_profile(- title=f"User {user_id}", messaging_active=True- )- profile_key = profile.profileKey- await creds_manager.store.set_ayrshare_profile_key(user_id, profile_key)- except Exception as e:- logger.error(f"Error creating Ayrshare profile for user {user_id}: {e}")- raise HTTPException(- status_code=HTTP_502_BAD_GATEWAY,- detail="Failed to create Ayrshare profile",- )- else:- logger.debug(f"Using existing Ayrshare profile for user {user_id}")-- profile_key_str = (- profile_key.get_secret_value()- if isinstance(profile_key, SecretStr)- else str(profile_key)+ # On-demand provisioning: AyrshareManagedProvider opts out of the+ # startup 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 expiry is 2880 minutes (48 hours)+ # Ayrshare JWT max lifetime is 2880 minutes (48 h).max_expiry_minutes = 2880try:- logger.debug(f"Generating Ayrshare JWT for user {user_id}")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=[- # NOTE: We are enabling platforms one at a time- # to speed up the development process- # SocialPlatform.FACEBOOK,SocialPlatform.TWITTER,SocialPlatform.LINKEDIN,SocialPlatform.INSTAGRAM,SocialPlatform.YOUTUBE,- # SocialPlatform.REDDIT,- # SocialPlatform.TELEGRAM,- # SocialPlatform.GOOGLE_MY_BUSINESS,- # SocialPlatform.PINTEREST,SocialPlatform.TIKTOK,- # SocialPlatform.BLUESKY,- # SocialPlatform.SNAPCHAT,- # SocialPlatform.THREADS,],expires_in=max_expiry_minutes,verify=True,)- except Exception as e:- logger.error(f"Error generating Ayrshare JWT for user {user_id}: {e}")+ 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")diff --git a/autogpt_platform/backend/backend/api/features/integrations/router_test.py b/autogpt_platform/backend/backend/api/features/integrations/router_test.pyindex dc66e2c6ea..7c3a146aa9 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router_test.py@@ -393,7 +393,7 @@ class TestEnsureManagedCredentials:_PROVIDERS.update(saved)_provisioned_users.pop("user-1", None)- provider.provision.assert_awaited_once_with("user-1")+ provider.provision.assert_awaited_once_with("user-1", store)store.add_managed_credential.assert_awaited_once_with("user-1", cred)@pytest.mark.asynciodiff --git a/autogpt_platform/backend/backend/blocks/ayrshare/_config.py b/autogpt_platform/backend/backend/blocks/ayrshare/_config.pynew file mode 100644index 0000000000..811ce6673c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/ayrshare/_config.py@@ -0,0 +1,21 @@+"""Shared provider config for Ayrshare social-media blocks.++The "credential" exposed to blocks is the **per-user Ayrshare profile key**,+not the org-level ``AYRSHARE_API_KEY``. Profile keys are provisioned per+user by :class:`~backend.integrations.managed_providers.ayrshare.AyrshareManagedProvider`+and stored in the normal credentials list with ``is_managed=True``, so every+Ayrshare block fits the standard credential flow:++ credentials: CredentialsMetaInput = ayrshare.credentials_field(...)++``run_block`` / ``resolve_block_credentials`` take care of the rest.++``with_managed_api_key()`` registers ``api_key`` as a supported auth type+without the env-var-backed default credential that ``with_api_key()`` would+create — the org-level ``AYRSHARE_API_KEY`` is the admin key and must never+reach a block as a "profile key".+"""++from backend.sdk import ProviderBuilder++ayrshare = ProviderBuilder("ayrshare").with_managed_api_key().build()diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/_util.py b/autogpt_platform/backend/backend/blocks/ayrshare/_util.pyindex 49089c4853..720925e19f 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/_util.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/_util.py@@ -4,22 +4,25 @@ from typing import Optionalfrom pydantic import BaseModel, Fieldfrom backend.blocks._base import BlockSchemaInput-from backend.data.model import SchemaField, UserIntegrations+from backend.data.model import CredentialsMetaInput, SchemaFieldfrom backend.integrations.ayrshare import AyrshareClient-from backend.util.clients import get_database_manager_async_clientfrom backend.util.exceptions import MissingConfigError--async def get_profile_key(user_id: str):- user_integrations: UserIntegrations = (- await get_database_manager_async_client().get_user_integrations(user_id)- )- return user_integrations.managed_credentials.ayrshare_profile_key+from ._config import ayrshareclass BaseAyrshareInput(BlockSchemaInput):"""Base input model for Ayrshare social media posts with common fields."""+ credentials: CredentialsMetaInput = ayrshare.credentials_field(+ description=(+ "Ayrshare profile credential. AutoGPT provisions this managed "+ "credential automatically — the user does not create it. After "+ "it's in place, the user links each social account via the "+ "Ayrshare SSO popup in the Builder."+ ),+ )+post: str = SchemaField(description="The post text to be published", default="", advanced=False)diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.pyindex 1b7b556887..a7254f7099 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -60,16 +61,10 @@ class PostToBlueskyBlock(Block):self,input_data: "PostToBlueskyBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Bluesky with Bluesky-specific options."""-- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -109,7 +104,7 @@ class PostToBlueskyBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,bluesky_options=bluesky_options if bluesky_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.pyindex 211cf23f6f..2d4af969b1 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,12 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import (- BaseAyrshareInput,- CarouselItem,- create_ayrshare_client,- get_profile_key,-)+from ._util import BaseAyrshareInput, CarouselItem, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -123,15 +119,10 @@ class PostToFacebookBlock(Block):self,input_data: "PostToFacebookBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Facebook with Facebook-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -207,7 +198,7 @@ class PostToFacebookBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,facebook_options=facebook_options if facebook_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.pyindex 6d65bcdba5..1856cbef65 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -113,14 +114,13 @@ class PostToGMBBlock(Block):)async def run(- self, input_data: "PostToGMBBlock.Input", *, user_id: str, **kwargs+ self,+ input_data: "PostToGMBBlock.Input",+ *,+ credentials: APIKeyCredentials,+ **kwargs) -> BlockOutput:"""Post to Google My Business with GMB-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -205,7 +205,7 @@ class PostToGMBBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,gmb_options=gmb_options if gmb_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.pyindex c5100702a9..d468c1652a 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.py@@ -2,6 +2,7 @@ from typing import Anyfrom backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -12,12 +13,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import (- BaseAyrshareInput,- InstagramUserTag,- create_ayrshare_client,- get_profile_key,-)+from ._util import BaseAyrshareInput, InstagramUserTag, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -115,15 +111,10 @@ class PostToInstagramBlock(Block):self,input_data: "PostToInstagramBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Instagram with Instagram-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -194,7 +185,7 @@ class PostToInstagramBlock(Block):# Validate alt text lengthfor i, alt in enumerate(input_data.alt_text):if len(alt) > 1000:- yield "error", f"Alt text {i + 1} exceeds 1,000 character limit ({len(alt)} characters)"+ yield "error", f"Alt text {i+1} exceeds 1,000 character limit ({len(alt)} characters)"returninstagram_options["altText"] = input_data.alt_text@@ -244,7 +235,7 @@ class PostToInstagramBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,instagram_options=instagram_options if instagram_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.pyindex 560d4bed2b..01824cf994 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -115,15 +116,10 @@ class PostToLinkedInBlock(Block):self,input_data: "PostToLinkedInBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to LinkedIn with LinkedIn-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -217,7 +213,7 @@ class PostToLinkedInBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,linkedin_options=linkedin_options if linkedin_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.pyindex 504640aad8..df8a436cbe 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,12 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import (- BaseAyrshareInput,- PinterestCarouselOption,- create_ayrshare_client,- get_profile_key,-)+from ._util import BaseAyrshareInput, PinterestCarouselOption, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -95,15 +91,10 @@ class PostToPinterestBlock(Block):self,input_data: "PostToPinterestBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Pinterest with Pinterest-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -144,7 +135,7 @@ class PostToPinterestBlock(Block):# Validate alt text lengthfor i, alt in enumerate(input_data.alt_text):if len(alt) > 500:- yield "error", f"Pinterest alt text {i + 1} exceeds 500 character limit ({len(alt)} characters)"+ yield "error", f"Pinterest alt text {i+1} exceeds 500 character limit ({len(alt)} characters)"return# Convert datetime to ISO format if provided@@ -209,7 +200,7 @@ class PostToPinterestBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,pinterest_options=pinterest_options if pinterest_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.pyindex a1723cc0e5..40fbe14cd1 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -38,12 +39,12 @@ class PostToRedditBlock(Block):)async def run(- self, input_data: "PostToRedditBlock.Input", *, user_id: str, **kwargs+ self,+ input_data: "PostToRedditBlock.Input",+ *,+ credentials: APIKeyCredentials,+ **kwargs) -> BlockOutput:- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- returnclient = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured."@@ -64,7 +65,7 @@ class PostToRedditBlock(Block):random_post=input_data.random_post,random_media_url=input_data.random_media_url,notes=input_data.notes,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.pyindex da9f0c9b02..996518dacf 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -73,15 +74,10 @@ class PostToSnapchatBlock(Block):self,input_data: "PostToSnapchatBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Snapchat with Snapchat-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -132,7 +128,7 @@ class PostToSnapchatBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,snapchat_options=snapchat_options if snapchat_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.pyindex 8ccfb3be39..f526c6ea9f 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -60,15 +61,10 @@ class PostToTelegramBlock(Block):self,input_data: "PostToTelegramBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Telegram with Telegram-specific validation."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -111,7 +107,7 @@ class PostToTelegramBlock(Block):random_post=input_data.random_post,random_media_url=input_data.random_media_url,notes=input_data.notes,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.pyindex eb0d8e6366..ebafc28308 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -53,15 +54,10 @@ class PostToThreadsBlock(Block):self,input_data: "PostToThreadsBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to Threads with Threads-specific validation."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -106,7 +102,7 @@ class PostToThreadsBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,threads_options=threads_options if threads_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.pyindex 36ae2d4911..5b731dcc8b 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.py@@ -2,6 +2,7 @@ from enum import Enumfrom backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -12,7 +13,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_clientclass TikTokVisibility(str, Enum):@@ -116,14 +117,13 @@ class PostToTikTokBlock(Block):)async def run(- self, input_data: "PostToTikTokBlock.Input", *, user_id: str, **kwargs+ self,+ input_data: "PostToTikTokBlock.Input",+ *,+ credentials: APIKeyCredentials,+ **kwargs,) -> BlockOutput:"""Post to TikTok with TikTok-specific validation and options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -238,7 +238,7 @@ class PostToTikTokBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,tiktok_options=tiktok_options if tiktok_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.pyindex 764b38aa2b..da1fe48c26 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.py@@ -1,5 +1,6 @@from backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -10,7 +11,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_client@cost(*AYRSHARE_POST_COSTS)@@ -118,15 +119,10 @@ class PostToXBlock(Block):self,input_data: "PostToXBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to X / Twitter with enhanced X-specific options."""- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -159,7 +155,7 @@ class PostToXBlock(Block):if input_data.alt_text:for i, alt in enumerate(input_data.alt_text):if len(alt) > 1000:- yield "error", f"X alt text {i + 1} exceeds 1,000 character limit ({len(alt)} characters)"+ yield "error", f"X alt text {i+1} exceeds 1,000 character limit ({len(alt)} characters)"return# Validate subtitle settings@@ -236,7 +232,7 @@ class PostToXBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,twitter_options=twitter_options if twitter_options else None,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.pyindex a24fbcbb76..021f4c1005 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.py@@ -3,6 +3,7 @@ from typing import Anyfrom backend.integrations.ayrshare import PostIds, PostResponse, SocialPlatformfrom backend.sdk import (+ APIKeyCredentials,Block,BlockCategory,BlockOutput,@@ -13,7 +14,7 @@ from backend.sdk import ()from ._cost import AYRSHARE_POST_COSTS-from ._util import BaseAyrshareInput, create_ayrshare_client, get_profile_key+from ._util import BaseAyrshareInput, create_ayrshare_clientclass YouTubeVisibility(str, Enum):@@ -148,16 +149,10 @@ class PostToYouTubeBlock(Block):self,input_data: "PostToYouTubeBlock.Input",*,- user_id: str,+ credentials: APIKeyCredentials,**kwargs,) -> BlockOutput:"""Post to YouTube with YouTube-specific validation and options."""-- profile_key = await get_profile_key(user_id)- if not profile_key:- yield "error", "Please link a social account via Ayrshare"- return-client = create_ayrshare_client()if not client:yield "error", "Ayrshare integration is not configured. Please set up the AYRSHARE_API_KEY."@@ -313,7 +308,7 @@ class PostToYouTubeBlock(Block):random_media_url=input_data.random_media_url,notes=input_data.notes,youtube_options=youtube_options,- profile_key=profile_key.get_secret_value(),+ profile_key=credentials.api_key.get_secret_value(),)yield "post_result", responseif response.postIds:diff --git a/autogpt_platform/backend/backend/integrations/ayrshare.py b/autogpt_platform/backend/backend/integrations/ayrshare.pyindex 42e069b4ac..64c91face9 100644--- a/autogpt_platform/backend/backend/integrations/ayrshare.py+++ b/autogpt_platform/backend/backend/integrations/ayrshare.py@@ -22,6 +22,58 @@ class AyrshareAPIException(Exception):self.status_code = status_code+def _extract_error_message(response: Any) -> str:+ """Safely pull an error message out of an Ayrshare response.++ Ayrshare surfaces errors in several shapes depending on how far the+ request got:++ - flat: ``{"status": "error", "message": "..."}``+ - post-level reject: ``{"posts": [{"message": "Missing post parameter", ...}]}``+ (the request itself was rejected — e.g. validation fails before+ trying any platform)+ - per-platform fail: ``{"posts": [{"errors": [{"message": "Twitter is not linked"}]}]}``+ (a platform-specific failure after the request reached Ayrshare's+ post-dispatch path)++ Tolerates bodies that aren't a dict (list, string, malformed JSON) —+ otherwise a ``.get()`` on a list raises AttributeError and the caller+ gets a confusing generic error instead of the upstream detail.+ """+ try:+ data = response.json()+ except (json.JSONDecodeError, ValueError):+ return response.text() or "Unknown error"+ if not isinstance(data, dict):+ return response.text() or "Unknown error"++ # Prefer the nested per-post error since that's where the actionable+ # reason lives for create_post failures.+ posts = data.get("posts")+ if isinstance(posts, list):+ messages: list[str] = []+ for post in posts:+ if not isinstance(post, dict):+ continue+ # Shape: posts[].errors[].message (per-platform failure)+ errors = post.get("errors")+ if isinstance(errors, list):+ for e in errors:+ if isinstance(e, dict) and e.get("message"):+ messages.append(str(e["message"]))+ # Shape: posts[].message (request-level reject)+ post_msg = post.get("message")+ if post_msg:+ messages.append(str(post_msg))+ if messages:+ return "; ".join(messages)++ top = data.get("message")+ if top:+ return str(top)+ return "Unknown error"++class SocialPlatform(str, Enum):BLUESKY = "bluesky"FACEBOOK = "facebook"@@ -129,9 +181,14 @@ class AyrshareClient:if custom_requests:self._requests = custom_requestselse:+ # raise_for_status=False — every method inspects response.ok ++ # the "status" envelope itself and raises AyrshareAPIException+ # with Ayrshare's own error message, which is more actionable+ # than the generic HTTPError that would fire otherwise.self._requests = Requests(extra_headers=headers,trusted_origins=["https://api.ayrshare.com"],+ raise_for_status=False,)async def generate_jwt(@@ -197,14 +254,9 @@ class AyrshareClient:)if not response.ok:- try:- error_data = response.json()- error_message = error_data.get("message", "Unknown error")- except json.JSONDecodeError:- error_message = response.text()-raise AyrshareAPIException(- f"Ayrshare API request failed ({response.status}): {error_message}",+ f"Ayrshare API request failed ({response.status}): "+ f"{_extract_error_message(response)}",response.status,)@@ -275,14 +327,9 @@ class AyrshareClient:response = await self._requests.post(self.PROFILES_ENDPOINT, json=payload)if not response.ok:- try:- error_data = response.json()- error_message = error_data.get("message", "Unknown error")- except json.JSONDecodeError:- error_message = response.text()-raise AyrshareAPIException(- f"Ayrshare API request failed ({response.status}): {error_message}",+ f"Ayrshare API request failed ({response.status}): "+ f"{_extract_error_message(response)}",response.status,)@@ -477,14 +524,9 @@ class AyrshareClient:logger.error(f"Ayrshare API request failed ({response.status}): {response.text()}")- try:- error_data = response.json()- error_message = error_data.get("message", "Unknown error")- except json.JSONDecodeError:- error_message = response.text()-raise AyrshareAPIException(- f"Ayrshare API request failed ({response.status}): {error_message}",+ f"Ayrshare API request failed ({response.status}): "+ f"{_extract_error_message(response)}",response.status,)diff --git a/autogpt_platform/backend/backend/integrations/credentials_store.py b/autogpt_platform/backend/backend/integrations/credentials_store.pyindex 7d0c0a4b7a..b9674f438a 100644--- a/autogpt_platform/backend/backend/integrations/credentials_store.py+++ b/autogpt_platform/backend/backend/integrations/credentials_store.py@@ -525,20 +525,6 @@ class IntegrationCredentialsStore:]user_integrations.credentials.append(credential)- async def set_ayrshare_profile_key(self, user_id: str, profile_key: str) -> None:- """Set the Ayrshare profile key for a user.-- The profile key is used to authenticate API requests to Ayrshare's social media posting service.- See https://www.ayrshare.com/docs/apis/profiles/overview for more details.-- Args:- user_id: The ID of the user to set the profile key for- profile_key: The profile key to set- """- _profile_key = SecretStr(profile_key)- async with self.edit_user_integrations(user_id) as user_integrations:- user_integrations.managed_credentials.ayrshare_profile_key = _profile_key-# ===================== OAUTH STATES ===================== #async def store_state_token(@@ -639,6 +625,18 @@ class IntegrationCredentialsStore:async def _get_user_integrations(self, user_id: str) -> UserIntegrations:return await self.db_manager.get_user_integrations(user_id=user_id)+ async def get_user_integrations(self, user_id: str) -> UserIntegrations:+ """Public read-only accessor for the caller's ``UserIntegrations`` row.++ Use for read-only access — the write back mechanism lives in+ :meth:`edit_user_integrations`, which always persists on exit.+ Consumers (e.g. managed-credential providers reading legacy side+ channels) should reach for this method instead of the private+ ``_get_user_integrations`` or the edit-as-read trick, which would+ otherwise trigger a spurious DB write + Redis lock round-trip.+ """+ return await self._get_user_integrations(user_id)+async def locked_user_integrations(self, user_id: str):key = (f"user:{user_id}", "integrations")locks = await self.locks()diff --git a/autogpt_platform/backend/backend/integrations/managed_credentials.py b/autogpt_platform/backend/backend/integrations/managed_credentials.pyindex 242bc2751d..cfe7f24168 100644--- a/autogpt_platform/backend/backend/integrations/managed_credentials.py+++ b/autogpt_platform/backend/backend/integrations/managed_credentials.py@@ -39,21 +39,70 @@ class ManagedCredentialProvider(ABC):provider_name: str"""Must match the ``provider`` field on the resulting credential."""+ auto_provision: bool = True+ """Whether :func:`ensure_managed_credentials` should provision this on+ credential-list load.++ Default ``True`` matches the AgentMail contract: cheap provisioning that+ is safe to run for every user on first visit. Set to ``False`` when+ provisioning has per-user upstream cost (e.g. Ayrshare's profile quota);+ such providers still register here so account-deletion cleanup works,+ but only run via an explicit :func:`ensure_managed_credential` call+ from a user-triggered endpoint.+ """+@abstractmethodasync def is_available(self) -> bool:- """Return ``True`` when the org-level configuration is present."""+ """Return ``True`` when the org-level configuration is present.++ Used by :func:`ensure_managed_credentials` to skip providers whose+ config is missing (e.g. missing env vars). Independent of+ :attr:`auto_provision` — a provider can be available yet opt out+ of the startup sweep.+ """@abstractmethod- async def provision(self, user_id: str) -> Credentials:+ async def provision(+ self, user_id: str, store: IntegrationCredentialsStore+ ) -> Credentials:"""Create external resources and return a credential.- The returned credential **must** have ``is_managed=True``.+ The returned credential **must** have ``is_managed=True``. The+ caller-supplied *store* is the same instance the framework will use+ for :meth:`post_provision` and the credential upsert; subclasses+ should thread it through when they need to read per-user state+ (e.g. Ayrshare's legacy migration read)."""@abstractmethodasync def deprovision(self, user_id: str, credential: Credentials) -> None:"""Revoke external resources during account deletion."""+ async def post_provision(+ self,+ user_id: str,+ store: IntegrationCredentialsStore,+ credential: Credentials,+ ) -> None:+ """Optional cleanup hook run *after* the credential is durably stored.++ Runs inside the provision lock, immediately after+ ``add_managed_credential`` returns. Subclasses can safely mutate+ other per-user state (e.g. clear a legacy migration field) knowing+ the new managed credential is already durable.++ **Must be idempotent and retry-safe.** The framework swallows any+ exception raised here and only logs a warning — the managed+ credential is already persisted, so subsequent provision calls+ short-circuit on ``has_managed_credential`` and this hook never+ runs again for that credential. If a subclass needs the hook to+ retry on failure, it must drive that retry explicitly (e.g. a+ scheduled job), not rely on the provision path.++ Default: no-op.+ """+ _ = user_id, store, credential+# ---------------------------------------------------------------------------# Registry@@ -98,29 +147,93 @@ async def _ensure_one(cache the user as fully provisioned."""try:+ if not provider.auto_provision:+ # Registered for cleanup lookup, but opts out of the sweep.+ # Callers use `ensure_managed_credential(...)` directly.+ return Trueif not await provider.is_available():return True- # Use a distributed Redis lock so the check-then-provision operation- # is atomic across all workers, preventing duplicate external- # resource provisioning (e.g. AgentMail API keys).- locks = await store.locks()- key = (f"user:{user_id}", f"managed-provision:{name}")- async with locks.locked(key):- # Re-check under lock to avoid duplicate provisioning.- if await store.has_managed_credential(user_id, name):- return True- credential = await provider.provision(user_id)- await store.add_managed_credential(user_id, credential)- logger.info(- "Provisioned managed credential for provider=%s user=%s",+ return await _provision_under_lock(user_id, store, name, provider)+ except Exception:+ logger.warning(+ "Failed to provision managed credential for provider=%s user=%s",+ name,+ user_id,+ exc_info=True,+ )+ return False+++async def _provision_under_lock(+ user_id: str,+ store: IntegrationCredentialsStore,+ name: str,+ provider: ManagedCredentialProvider,+) -> bool:+ """Provision a credential under a distributed Redis lock (double-check).++ Separated from :func:`_ensure_one` so on-demand callers can invoke it+ via :func:`ensure_managed_credential` without re-entering the+ ``is_available`` gate — that gate is what the ``ensure_managed_credentials``+ sweep uses to skip opt-out providers.+ """+ # Use a distributed Redis lock so the check-then-provision operation+ # is atomic across all workers, preventing duplicate external+ # resource provisioning (e.g. AgentMail API keys).+ locks = await store.locks()+ key = (f"user:{user_id}", f"managed-provision:{name}")+ async with locks.locked(key):+ # Re-check under lock to avoid duplicate provisioning.+ if await store.has_managed_credential(user_id, name):+ return True+ credential = await provider.provision(user_id, store)+ await store.add_managed_credential(user_id, credential)+ # Run the post-provision cleanup hook only after the managed+ # credential is durably stored. If it raises, the managed+ # credential is still in place and future provision calls+ # short-circuit on has_managed_credential — no duplicate+ # upstream resource, no data loss on migration paths.+ try:+ await provider.post_provision(user_id, store, credential)+ except Exception:+ logger.warning(+ "post_provision hook failed for provider=%s user=%s; "+ "managed credential is persisted so retry is safe",name,user_id,+ exc_info=True,)- return True+ logger.info(+ "Provisioned managed credential for provider=%s user=%s",+ name,+ user_id,+ )+ return True+++async def ensure_managed_credential(+ user_id: str,+ store: IntegrationCredentialsStore,+ provider: ManagedCredentialProvider,+) -> bool:+ """Provision *provider*'s managed credential for *user_id* on demand.++ Bypasses the provider's ``is_available()`` gate — callers are expected to+ have validated org-level config themselves (e.g. the Ayrshare SSO-URL+ endpoint checks its secrets before invoking this). Use for providers+ that opt out of the ``ensure_managed_credentials`` startup sweep because+ provisioning has per-user cost or quota implications.++ Returns ``True`` on success, ``False`` on transient failure.+ """+ try:+ return await _provision_under_lock(+ user_id, store, provider.provider_name, provider+ )except Exception:logger.warning("Failed to provision managed credential for provider=%s user=%s",- name,+ provider.provider_name,user_id,exc_info=True,)diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/__init__.py b/autogpt_platform/backend/backend/integrations/managed_providers/__init__.pyindex 9539f5acb7..c345465d58 100644--- a/autogpt_platform/backend/backend/integrations/managed_providers/__init__.py+++ b/autogpt_platform/backend/backend/integrations/managed_providers/__init__.py@@ -9,9 +9,12 @@ from backend.integrations.managed_credentials import (register_managed_provider,)from backend.integrations.managed_providers.agentmail import AgentMailManagedProvider+from backend.integrations.managed_providers.ayrshare import AyrshareManagedProviderdef register_all() -> None:"""Register every built-in managed credential provider (idempotent)."""if get_managed_provider(AgentMailManagedProvider.provider_name) is None:register_managed_provider(AgentMailManagedProvider())+ if get_managed_provider(AyrshareManagedProvider.provider_name) is None:+ register_managed_provider(AyrshareManagedProvider())diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/agentmail.py b/autogpt_platform/backend/backend/integrations/managed_providers/agentmail.pyindex 6b638e5bad..c416325ba8 100644--- a/autogpt_platform/backend/backend/integrations/managed_providers/agentmail.py+++ b/autogpt_platform/backend/backend/integrations/managed_providers/agentmail.py@@ -12,6 +12,7 @@ import loggingfrom pydantic import SecretStrfrom backend.data.model import APIKeyCredentials, Credentials+from backend.integrations.credentials_store import IntegrationCredentialsStorefrom backend.integrations.managed_credentials import ManagedCredentialProviderfrom backend.util.settings import Settings@@ -25,7 +26,10 @@ class AgentMailManagedProvider(ManagedCredentialProvider):async def is_available(self) -> bool:return bool(settings.secrets.agentmail_api_key)- async def provision(self, user_id: str) -> Credentials:+ async def provision(+ self, user_id: str, store: IntegrationCredentialsStore+ ) -> Credentials:+ _ = store # AgentMail provisions via its own API client, not the store.from agentmail import AsyncAgentMailclient = AsyncAgentMail(api_key=settings.secrets.agentmail_api_key)diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.pynew file mode 100644index 0000000000..fc2254f81e--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py@@ -0,0 +1,175 @@+"""Ayrshare managed credential provider.++Provisions a per-user Ayrshare profile key and stores it as a standard+``APIKeyCredentials(provider="ayrshare", is_managed=True)`` in the user's+credentials list. This lets every Ayrshare block declare a normal+``credentials`` field and go through the same schema-driven resolution as+any other provider — no bespoke ``managed_credentials.ayrshare_profile_key``+side channel required.++Auto-provisioned by the credential-list sweep the same way AgentMail is,+so every Ayrshare block just declares a standard ``credentials`` field+and the managed entry appears in the builder dropdown automatically.+Profile creation counts against the org Ayrshare subscription quota, so+that cost is accepted at the plan level rather than gated per-user.++Legacy compatibility: on first provision we migrate+``UserIntegrations.managed_credentials.ayrshare_profile_key`` (pre-migration+data) into the new managed credential. The legacy field is then cleared+in :meth:`AyrshareManagedProvider.post_provision`, which runs only after+``add_managed_credential`` has durably stored the managed credential —+this ordering ensures that a failure between ``provision`` and the+persist step leaves the legacy key intact so a retry can still reuse it+(covered by ``TestMigrationOrderingSafety``).++User-visible caveat: provisioning the profile creates the Ayrshare profile+but does not link any social accounts. The user still needs to open the+Ayrshare SSO popup to OAuth each social network; the block will return+the Ayrshare API's "not linked" error until they do. That part remains+platform UX, not a credential concern.+"""++from __future__ import annotations++import logging++from pydantic import SecretStr++from backend.data.model import APIKeyCredentials, Credentials+from backend.integrations.ayrshare import AyrshareClient+from backend.integrations.credentials_store import IntegrationCredentialsStore+from backend.integrations.managed_credentials import ManagedCredentialProvider+from backend.util.exceptions import MissingConfigError+from backend.util.settings import Settings++logger = logging.getLogger(__name__)+++class AyrshareManagedProvider(ManagedCredentialProvider):+ provider_name = "ayrshare"++ # Opt out of the startup sweep — each Ayrshare profile counts against+ # our subscription quota, so we only provision when the user actually+ # opens a block that needs it (triggered by the builder's per-provider+ # ``GET /{provider}/credentials`` call).+ auto_provision = False++ async def is_available(self) -> bool:+ """Both Ayrshare org-level secrets must be configured."""+ return settings_available()++ async def provision(+ self, user_id: str, store: IntegrationCredentialsStore+ ) -> Credentials:+ profile_key = await _read_or_create_profile_key(user_id, store)+ return APIKeyCredentials(+ provider=self.provider_name,+ title="Ayrshare (managed by AutoGPT)",+ api_key=SecretStr(profile_key),+ expires_at=None,+ is_managed=True,+ )++ async def deprovision(self, user_id: str, credential: Credentials) -> None:+ # Ayrshare's public API does not expose a programmatic profile-delete+ # endpoint today. Orphaned profiles incur no runtime cost on our+ # side (billing is per-post, not per-profile) and can be cleaned up+ # manually from the Ayrshare dashboard if ever needed.+ logger.info(+ "[ayrshare] No programmatic deprovisioning; leaving profile "+ "for user %s intact.",+ user_id,+ )++ async def post_provision(+ self,+ user_id: str,+ store: IntegrationCredentialsStore,+ credential: Credentials,+ ) -> None:+ """Clear the legacy ``ayrshare_profile_key`` side-channel after migration.++ See :meth:`ManagedCredentialProvider.post_provision` for retry+ semantics (idempotent, failures are swallowed and logged).+ """+ _ = credential # unused; the side channel is provider-specific+ async with store.edit_user_integrations(user_id) as user_integrations:+ if user_integrations.managed_credentials.ayrshare_profile_key is not None:+ logger.debug(+ "[ayrshare] Clearing legacy profile_key for user %s", user_id+ )+ user_integrations.managed_credentials.ayrshare_profile_key = None+++import secrets+++def _profile_title(user_id: str) -> str:+ """A unique Ayrshare profile title for this provision attempt.++ Appends a short random suffix so we never collide with an orphan+ upstream profile (same user, lost managed credential from a prior+ session). Ayrshare's ``DELETE /profiles`` requires the ``profileKey``+ we no longer have, so avoiding the collision in the first place is+ the only reliable recovery path. The suffix is cosmetic — Ayrshare+ profiles are keyed by ``profileKey``, not title.+ """+ return f"User {user_id}-{secrets.token_hex(3)}"+++async def _read_or_create_profile_key(+ user_id: str, store: IntegrationCredentialsStore+) -> str:+ """Return the Ayrshare profile key for *user_id*, creating one if needed.++ **Resolution order — idempotent, retry-safe:**++ 1. **Legacy side channel.** If+ ``UserIntegrations.managed_credentials.ayrshare_profile_key`` is set+ (pre-migration data), reuse it verbatim so existing linked socials+ keep working. Read-only here — clearing moves to+ :meth:`AyrshareManagedProvider.post_provision` (runs after the+ managed credential is durably stored; if persistence fails, legacy+ stays intact so a retry reuses it).++ 2. **Create a fresh profile with a unique title.** The title carries+ a random suffix so we never collide with orphaned upstream profiles+ (Ayrshare doesn't expose an API to retrieve an existing profile's+ ``profileKey``, so collision-avoidance is the only reliable recovery+ path). Orphans stick around in Ayrshare's dashboard until cleaned+ up manually — acceptable cost for unblocking the user.++ The outer :func:`~backend.integrations.managed_credentials._provision_under_lock`+ holds a distributed Redis lock on ``(user, provider)`` across this whole+ function *and* the subsequent ``add_managed_credential`` call, so+ concurrent workers cannot race and create duplicates.+ """+ user_integrations = await store.get_user_integrations(user_id)+ legacy_key = user_integrations.managed_credentials.ayrshare_profile_key+ if legacy_key:+ logger.debug("[ayrshare] Reusing legacy profile key for user %s", user_id)+ return (+ legacy_key.get_secret_value()+ if isinstance(legacy_key, SecretStr)+ else str(legacy_key)+ )++ try:+ client = AyrshareClient()+ except MissingConfigError as exc:+ raise RuntimeError("Ayrshare integration is not configured") from exc++ title = _profile_title(user_id)+ logger.debug("[ayrshare] Creating profile for user %s (title=%s)", user_id, title)+ profile = await client.create_profile(title=title, messaging_active=True)+ return profile.profileKey+++def settings_available() -> bool:+ """True when Ayrshare org-level secrets are configured.++ Exposed so on-demand callers (e.g. the SSO-URL route) can pre-flight the+ config before calling :func:`~backend.integrations.managed_credentials.ensure_managed_credential`.+ """+ settings = Settings()+ return bool(settings.secrets.ayrshare_api_key and settings.secrets.ayrshare_jwt_key)diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.pynew file mode 100644index 0000000000..2e08d94452--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py@@ -0,0 +1,292 @@+"""Tests for AyrshareManagedProvider."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from pydantic import SecretStr++from backend.data.model import APIKeyCredentials+from backend.integrations.managed_providers.ayrshare import (+ AyrshareManagedProvider,+ _read_or_create_profile_key,+ settings_available,+)++_USER_ID = "user-ayrshare-test"+++class TestIsAvailable:+ """`is_available` is truthful; opt-out lives on `auto_provision`."""++ @pytest.mark.asyncio(loop_scope="session")+ async def test_is_available_true_when_secrets_set(self):+ """Truthful: returns True when org-level secrets are configured.++ The sweep skip is driven by `auto_provision = False`, not by+ lying about availability. Callers like `ensure_managed_credential`+ do not gate on `is_available`, so this remains truthful without+ triggering auto-provisioning.+ """+ with patch(+ "backend.integrations.managed_providers.ayrshare.Settings"+ ) as mock_settings:+ mock_settings.return_value.secrets.ayrshare_api_key = "api-key"+ mock_settings.return_value.secrets.ayrshare_jwt_key = "jwt-key"+ assert await AyrshareManagedProvider().is_available() is True++ @pytest.mark.asyncio(loop_scope="session")+ async def test_is_available_false_when_secrets_missing(self):+ with patch(+ "backend.integrations.managed_providers.ayrshare.Settings"+ ) as mock_settings:+ mock_settings.return_value.secrets.ayrshare_api_key = ""+ mock_settings.return_value.secrets.ayrshare_jwt_key = "jwt-key"+ assert await AyrshareManagedProvider().is_available() is False++ def test_auto_provision_opt_out(self):+ """Ayrshare opts out of the startup sweep — per-user Ayrshare profiles+ count against our subscription quota, so we only provision when the+ user explicitly clicks the builder's SSO flow."""+ assert AyrshareManagedProvider.auto_provision is False+++class TestSettingsAvailable:+ """Pre-flight check used by the SSO-URL route before provisioning."""++ def test_returns_true_when_both_secrets_set(self):+ with patch(+ "backend.integrations.managed_providers.ayrshare.Settings"+ ) as mock_settings:+ mock_settings.return_value.secrets.ayrshare_api_key = "api-key"+ mock_settings.return_value.secrets.ayrshare_jwt_key = "jwt-key"+ assert settings_available() is True++ def test_returns_false_when_api_key_missing(self):+ with patch(+ "backend.integrations.managed_providers.ayrshare.Settings"+ ) as mock_settings:+ mock_settings.return_value.secrets.ayrshare_api_key = ""+ mock_settings.return_value.secrets.ayrshare_jwt_key = "jwt-key"+ assert settings_available() is False++ def test_returns_false_when_jwt_key_missing(self):+ with patch(+ "backend.integrations.managed_providers.ayrshare.Settings"+ ) as mock_settings:+ mock_settings.return_value.secrets.ayrshare_api_key = "api-key"+ mock_settings.return_value.secrets.ayrshare_jwt_key = ""+ assert settings_available() is False+++class TestReadOrCreateProfileKey:+ """Legacy migration + fresh-profile paths.++ The read path is read-only w.r.t. the legacy field — clearing the legacy+ ``managed_credentials.ayrshare_profile_key`` happens in+ :meth:`AyrshareManagedProvider.post_provision`, only after the managed+ credential is durably stored.+ """++ def _mock_store(self, legacy_key: SecretStr | None):+ """Build a minimal store stub that exposes the new public+ read accessor; read-only callers don't go through+ ``edit_user_integrations``."""+ managed = MagicMock()+ managed.ayrshare_profile_key = legacy_key++ user_integrations = MagicMock()+ user_integrations.managed_credentials = managed++ store = MagicMock()+ store.get_user_integrations = AsyncMock(return_value=user_integrations)+ return store, user_integrations++ @pytest.mark.asyncio(loop_scope="session")+ async def test_reuses_legacy_key_without_clearing(self):+ """Legacy field is NOT cleared here — that happens in post_provision.++ If `_read_or_create_profile_key` cleared eagerly and the subsequent+ `add_managed_credential` failed, a retry would see an empty legacy+ field and create a fresh Ayrshare profile, orphaning the user's+ linked social accounts.+ """+ legacy = SecretStr("legacy-profile-key")+ store, ui = self._mock_store(legacy_key=legacy)++ with patch(+ "backend.integrations.managed_providers.ayrshare.AyrshareClient"+ ) as mock_client:+ result = await _read_or_create_profile_key(_USER_ID, store)++ assert result == "legacy-profile-key"+ # create_profile must NOT be called — we reuse the existing one.+ mock_client.assert_not_called()+ # Legacy field must NOT be cleared by the read path.+ assert ui.managed_credentials.ayrshare_profile_key is legacy++ @pytest.mark.asyncio(loop_scope="session")+ async def test_creates_new_profile_when_no_legacy(self):+ """Without a legacy key, we create a fresh profile with a unique title."""+ store, _ = self._mock_store(legacy_key=None)++ fake_profile = MagicMock(profileKey="fresh-profile-key")+ client_instance = MagicMock()+ client_instance.create_profile = AsyncMock(return_value=fake_profile)++ with patch(+ "backend.integrations.managed_providers.ayrshare.AyrshareClient",+ return_value=client_instance,+ ):+ result = await _read_or_create_profile_key(_USER_ID, store)++ assert result == "fresh-profile-key"+ client_instance.create_profile.assert_awaited_once()+ # The title must include the user_id AND a suffix — unique-per-call+ # avoids collisions with orphaned upstream profiles (Ayrshare has+ # no API to retrieve an existing profile's key).+ call_kwargs = client_instance.create_profile.call_args.kwargs+ assert call_kwargs["title"].startswith(f"User {_USER_ID}-")+ assert call_kwargs["title"] != f"User {_USER_ID}"++ @pytest.mark.asyncio(loop_scope="session")+ async def test_profile_title_suffix_is_unique_across_calls(self):+ """Two separate provision attempts produce different titles so an+ orphaned profile from a prior attempt never causes a duplicate-+ title collision on create."""+ from backend.integrations.managed_providers.ayrshare import _profile_title++ t1 = _profile_title(_USER_ID)+ t2 = _profile_title(_USER_ID)+ assert t1 != t2+ assert t1.startswith(f"User {_USER_ID}-")+ assert t2.startswith(f"User {_USER_ID}-")+++class TestPostProvisionClearsLegacy:+ """post_provision runs only after the managed credential is durable.++ Verifies the migration-ordering fix for the data-loss race:+ - provision() reads the legacy key without clearing it.+ - add_managed_credential persists the new credential.+ - post_provision then clears the legacy field.+ Failure between provision and add_managed_credential leaves the legacy+ key intact, so a retry reuses it and keeps the user's linked socials.+ """++ def _mock_store_for_clear(self, legacy_key: SecretStr | None):+ managed = MagicMock()+ managed.ayrshare_profile_key = legacy_key++ user_integrations = MagicMock()+ user_integrations.managed_credentials = managed++ cm = AsyncMock()+ cm.__aenter__ = AsyncMock(return_value=user_integrations)+ cm.__aexit__ = AsyncMock(return_value=None)++ store = MagicMock()+ store.edit_user_integrations = MagicMock(return_value=cm)+ return store, user_integrations++ @pytest.mark.asyncio(loop_scope="session")+ async def test_post_provision_clears_populated_legacy_field(self):+ store, ui = self._mock_store_for_clear(SecretStr("legacy"))+ fake_cred = APIKeyCredentials(+ provider="ayrshare",+ title="t",+ api_key=SecretStr("k"),+ expires_at=None,+ is_managed=True,+ )+ await AyrshareManagedProvider().post_provision(_USER_ID, store, fake_cred)+ assert ui.managed_credentials.ayrshare_profile_key is None++ @pytest.mark.asyncio(loop_scope="session")+ async def test_post_provision_skips_when_legacy_already_clear(self):+ """Idempotent — a second call on a fresh user touches nothing."""+ store, ui = self._mock_store_for_clear(legacy_key=None)+ fake_cred = APIKeyCredentials(+ provider="ayrshare",+ title="t",+ api_key=SecretStr("k"),+ expires_at=None,+ is_managed=True,+ )+ await AyrshareManagedProvider().post_provision(_USER_ID, store, fake_cred)+ # Stayed None; no write attempted.+ assert ui.managed_credentials.ayrshare_profile_key is None+++class TestProvision:+ """provision() returns an is_managed=True APIKeyCredentials."""++ @pytest.mark.asyncio(loop_scope="session")+ async def test_provision_returns_managed_api_key_credential(self):+ """provision now receives the caller-supplied store (framework-injected)."""+ store = MagicMock()+ with patch(+ "backend.integrations.managed_providers.ayrshare."+ "_read_or_create_profile_key",+ new=AsyncMock(return_value="profile-key-xyz"),+ ) as read_mock:+ creds = await AyrshareManagedProvider().provision(_USER_ID, store)++ assert isinstance(creds, APIKeyCredentials)+ assert creds.provider == "ayrshare"+ assert creds.is_managed is True+ assert creds.api_key.get_secret_value() == "profile-key-xyz"+ # The store passed into provision must be the one forwarded to the+ # internal read helper — no hidden construction of a fresh store.+ read_mock.assert_awaited_once_with(_USER_ID, store)+++class TestMigrationOrderingSafety:+ """Regression test for the migration ordering fix.++ Verifies that if ``add_managed_credential`` raises after+ ``provision()`` succeeds, the legacy ``ayrshare_profile_key`` survives —+ a retry can then reuse it and keep the user's linked socials.+ """++ @pytest.mark.asyncio(loop_scope="session")+ async def test_add_managed_credential_failure_retains_legacy_key(self):+ from backend.integrations.managed_credentials import _provision_under_lock++ # Mock store: has_managed_credential=False, edit_user_integrations+ # yields a UserIntegrations with the legacy key populated, and+ # add_managed_credential raises to simulate a DB blip. Because+ # _provision_under_lock fails before post_provision runs, the+ # legacy key must remain untouched — a retry will reuse it.+ legacy = SecretStr("legacy-profile-key")++ managed = MagicMock()+ managed.ayrshare_profile_key = legacy+ user_integrations = MagicMock()+ user_integrations.managed_credentials = managed++ lock_cm = AsyncMock()+ lock_cm.__aenter__ = AsyncMock(return_value=None)+ lock_cm.__aexit__ = AsyncMock(return_value=None)+ locks = MagicMock()+ locks.locked = MagicMock(return_value=lock_cm)++ store = MagicMock()+ store.locks = AsyncMock(return_value=locks)+ store.has_managed_credential = AsyncMock(return_value=False)+ # The provisioning read path uses the new public accessor; the+ # post_provision clear path still uses edit_user_integrations.+ # Here we assert the read works and the clear never runs because+ # add_managed_credential fails first.+ store.get_user_integrations = AsyncMock(return_value=user_integrations)+ store.add_managed_credential = AsyncMock(side_effect=RuntimeError("DB blip"))++ # provision now receives the caller-supplied store directly, so no+ # constructor patch is needed — the framework threads the same mock+ # from _provision_under_lock into AyrshareManagedProvider.provision.+ provider = AyrshareManagedProvider()+ with pytest.raises(RuntimeError, match="DB blip"):+ await _provision_under_lock(_USER_ID, store, "ayrshare", provider)++ # 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 legacydiff --git a/autogpt_platform/backend/backend/sdk/builder.py b/autogpt_platform/backend/backend/sdk/builder.pyindex ff903b730b..4988b11363 100644--- a/autogpt_platform/backend/backend/sdk/builder.py+++ b/autogpt_platform/backend/backend/sdk/builder.py@@ -91,6 +91,19 @@ class ProviderBuilder:)return self+ def with_managed_api_key(self) -> "ProviderBuilder":+ """Declare api_key auth support without an env-var-backed default credential.++ Use for providers whose API key is provisioned per-user by a+ :class:`~backend.integrations.managed_credentials.ManagedCredentialProvider`+ (e.g. Ayrshare's profile key). Equivalent to :meth:`with_api_key` but+ skips both the env-var lookup and the default-credential registration+ — nothing can accidentally leak an org-level key into blocks as if it+ were a per-user credential.+ """+ self._supported_auth_types.add("api_key")+ return self+def with_api_key_from_settings(self, settings_attr: str, title: str) -> "ProviderBuilder":diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.pyindex 69d3396789..c9bd0670ed 100644--- a/autogpt_platform/backend/backend/util/exceptions.py+++ b/autogpt_platform/backend/backend/util/exceptions.py@@ -2,12 +2,17 @@ from typing import Mappingclass BlockError(Exception):- """An error occurred during the running of a block"""+ """An error occurred during the running of a block.++ Exposes the underlying message as ``str(exc)`` without a framing prefix+ so ``yield "error", str(exc)`` surfaces the actual cause to the user.+ The block name and id are kept as attributes for structured logging.+ """def __init__(self, message: str, block_name: str, block_id: str) -> None:- super().__init__(- f"raised by {block_name} with message: {message}. block_id: {block_id}"- )+ super().__init__(message)+ self.block_name = block_name+ self.block_id = block_idclass BlockInputError(BlockError, ValueError):diff --git a/autogpt_platform/backend/backend/util/exceptions_test.py b/autogpt_platform/backend/backend/util/exceptions_test.pyindex 3821356db4..4108aba4f9 100644--- a/autogpt_platform/backend/backend/util/exceptions_test.py+++ b/autogpt_platform/backend/backend/util/exceptions_test.py@@ -10,29 +10,29 @@ from backend.util.exceptions import (class TestBlockError:"""Tests for BlockError and its subclasses."""- def test_block_error_message_format(self):- """Test that BlockError formats the message correctly."""+ def test_block_error_surfaces_message_unframed(self):+ """``str(exc)`` is just the message so ``yield "error", str(exc)``+ shows the actual upstream cause to the user instead of wrapping it+ in a "raised by X with message: Y" framing."""error = BlockError(message="Test error", block_name="TestBlock", block_id="test-123")- assert (- str(error)- == "raised by TestBlock with message: Test error. block_id: test-123"- )+ assert str(error) == "Test error"+ assert error.block_name == "TestBlock"+ assert error.block_id == "test-123"def test_block_input_error_inherits_format(self):- """Test that BlockInputError uses parent's message format."""error = BlockInputError(message="Invalid input", block_name="TestBlock", block_id="test-123")- assert "raised by TestBlock with message: Invalid input" in str(error)+ assert str(error) == "Invalid input"+ assert error.block_name == "TestBlock"def test_block_output_error_inherits_format(self):- """Test that BlockOutputError uses parent's message format."""error = BlockOutputError(message="Invalid output", block_name="TestBlock", block_id="test-123")- assert "raised by TestBlock with message: Invalid output" in str(error)+ assert str(error) == "Invalid output"class TestBlockExecutionErrorNoneHandling:@@ -43,24 +43,21 @@ class TestBlockExecutionErrorNoneHandling:error = BlockExecutionError(message=None, block_name="TestBlock", block_id="test-123")- assert "Output error was None" in str(error)- assert "raised by TestBlock with message: Output error was None" in str(error)+ assert str(error) == "Output error was None"def test_execution_error_with_valid_message(self):"""Test that valid messages are preserved."""error = BlockExecutionError(message="Actual error", block_name="TestBlock", block_id="test-123")- assert "Actual error" in str(error)- assert "Output error was None" not in str(error)+ assert str(error) == "Actual error"def test_execution_error_with_empty_string(self):"""Test that empty string message is NOT replaced (only None is)."""error = BlockExecutionError(message="", block_name="TestBlock", block_id="test-123")- # Empty string is falsy but not None, so it's preserved- assert "raised by TestBlock with message: . block_id:" in str(error)+ assert str(error) == ""class TestBlockUnknownErrorNoneHandling:diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/AyrshareConnectButton.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/AyrshareConnectButton.tsxindex e32c918ac6..d50167488c 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/AyrshareConnectButton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/AyrshareConnectButton.tsx@@ -1,16 +1,18 @@"use client";-import React, { useState } from "react";+import React, { useContext, useState } from "react";import { Key } from "lucide-react";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 { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";// This SSO button is not a part of inputSchema - that's why we are not rendering it using Input rendererexport const AyrshareConnectButton = () => {const [isLoading, setIsLoading] = useState(false);const { toast } = useToast();+ const credentialsActions = useContext(CredentialsActionsContext);const handleSSOLogin = async () => {setIsLoading(true);@@ -19,6 +21,10 @@ export const AyrshareConnectButton = () => {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(diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/AyrshareConnectButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/AyrshareConnectButton.test.tsxnew file mode 100644index 0000000000..150dfd0627--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/__tests__/AyrshareConnectButton.test.tsx@@ -0,0 +1,77 @@+import {+ render,+ screen,+ fireEvent,+ cleanup,+ waitFor,+} from "@testing-library/react";+import { afterEach, describe, expect, it, vi, beforeEach } from "vitest";+import { AyrshareConnectButton } from "../AyrshareConnectButton";+import { CredentialsActionsContext } from "@/providers/agent-credentials/credentials-provider";++vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({+ getV1GetAyrshareSsoUrl: vi.fn(),+}));++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast: vi.fn() }),+}));++import { getV1GetAyrshareSsoUrl } from "@/app/api/__generated__/endpoints/integrations/integrations";++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++function renderWithActions(reload: () => void) {+ // Stub window.open so the real popup doesn't fire during tests.+ vi.stubGlobal(+ "open",+ vi.fn(() => ({}) as Window),+ );+ return render(+ <CredentialsActionsContext.Provider value={{ reload }}>+ <AyrshareConnectButton />+ </CredentialsActionsContext.Provider>,+ );+}++describe("AyrshareConnectButton", () => {+ beforeEach(() => {+ vi.mocked(getV1GetAyrshareSsoUrl).mockReset();+ });++ it("reloads the credentials context after a successful SSO URL fetch", async () => {+ vi.mocked(getV1GetAyrshareSsoUrl).mockResolvedValue({+ status: 200,+ data: { sso_url: "https://app.ayrshare.com/sso/fake" },+ } as any);+ const reload = vi.fn();++ renderWithActions(reload);+ fireEvent.click(+ screen.getByRole("button", { name: /Connect Social Media Accounts/i }),+ );++ await waitFor(() => expect(reload).toHaveBeenCalledTimes(1));+ });++ it("does NOT reload the credentials context when the SSO URL fetch fails", async () => {+ vi.mocked(getV1GetAyrshareSsoUrl).mockResolvedValue({+ status: 500,+ data: { detail: "boom" },+ } as any);+ const reload = vi.fn();++ renderWithActions(reload);+ fireEvent.click(+ screen.getByRole("button", { name: /Connect Social Media Accounts/i }),+ );++ // Let the handler's promise chain resolve + the finally block run.+ await waitFor(() => expect(getV1GetAyrshareSsoUrl).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(reload).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 6f2d29bb29..2e6cda41df 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -4515,7 +4515,7 @@"get": {"tags": ["v1", "integrations"],"summary": "Get Ayrshare Sso Url",- "description": "Generate an SSO URL for Ayrshare social media integration.\n\nReturns:\n dict: Contains the SSO URL for Ayrshare integration",+ "description": "Generate a JWT SSO URL so the user can link their social accounts.\n\nThe per-user Ayrshare profile key is provisioned and persisted as a\nstandard ``is_managed=True`` credential by\n:class:`~backend.integrations.managed_providers.ayrshare.AyrshareManagedProvider`.\nThis endpoint only signs a short-lived JWT pointing at the Ayrshare-\nhosted social-linking page; all profile lifecycle logic lives with the\nmanaged provider.","operationId": "getV1GetAyrshareSsoUrl","responses": {"200": {diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsxindex a458533e19..db521ca1d8 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/CredentialsFlatView.tsx@@ -15,6 +15,7 @@ type Credential = {username?: string;type: string;provider: string;+ is_managed?: boolean;};type Props = {@@ -51,6 +52,13 @@ export function CredentialsFlatView({onDeleteCredential,}: Props) {const hasCredentials = credentials.length > 0;+ // Ayrshare has no user-settable credential — provisioning runs on the+ // server after the user clicks the explicit Connect Social Media+ // Accounts button rendered alongside the block. Exposing "Add API+ // key" / "Use a new API key" here just confuses users into entering a+ // random key.+ const isManagedOnlyProvider = provider === "ayrshare";+ const showAddAction = !readOnly && !isManagedOnlyProvider;return (<>@@ -102,7 +110,7 @@ export function CredentialsFlatView({displayName={displayName}onSelect={() => onSelectCredential(credential.id)}onDelete={- onDeleteCredential+ onDeleteCredential && !credential.is_managed? () =>onDeleteCredential({id: credential.id,@@ -115,7 +123,7 @@ export function CredentialsFlatView({))}</div>)}- {!readOnly && (+ {showAddAction && (<Buttonvariant="secondary"size="small"@@ -127,17 +135,23 @@ export function CredentialsFlatView({</Button>)}</>+ ) : showAddAction ? (+ <Button+ variant="primary"+ size="small"+ onClick={onAddCredential}+ className="w-fit"+ type="button"+ >+ {actionButtonText}+ </Button>) : (+ isManagedOnlyProvider &&!readOnly && (- <Button- variant="primary"- size="small"- onClick={onAddCredential}- className="w-fit"- type="button"- >- {actionButtonText}- </Button>+ <Text variant="body" className="text-zinc-500">+ Click <strong>Connect Social Media Accounts</strong> above to set up+ your managed {displayName} profile.+ </Text>))}</>diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/__tests__/CredentialsFlatView.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/__tests__/CredentialsFlatView.test.tsxnew file mode 100644index 0000000000..45c2c8d35e--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/CredentialsFlatView/__tests__/CredentialsFlatView.test.tsx@@ -0,0 +1,90 @@+import { render, screen, cleanup } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { CredentialsFlatView } from "../CredentialsFlatView";+import { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api/types";++afterEach(() => {+ cleanup();+});++const schema = {+ type: "string",+ credentials_provider: ["ayrshare"],+ credentials_types: ["api_key"],+} as unknown as BlockIOCredentialsSubSchema;++function makeProps(+ overrides: Partial<Parameters<typeof CredentialsFlatView>[0]> = {},+) {+ return {+ schema,+ provider: "ayrshare",+ displayName: "Ayrshare",+ credentials: [],+ actionButtonText: "Add API key",+ isOptional: false,+ showTitle: false,+ readOnly: false,+ variant: "node" as const,+ onSelectCredential: vi.fn(),+ onClearCredential: vi.fn(),+ onAddCredential: vi.fn(),+ onDeleteCredential: vi.fn(),+ ...overrides,+ };+}++describe("CredentialsFlatView", () => {+ it("does not offer a delete action for a managed credential", () => {+ const onDeleteCredential = vi.fn();+ render(+ <CredentialsFlatView+ {...makeProps({+ credentials: [+ {+ id: "managed-1",+ title: "Ayrshare (managed by AutoGPT)",+ type: "api_key",+ provider: "ayrshare",+ is_managed: true,+ },+ ],+ onDeleteCredential,+ })}+ />,+ );++ // Managed row must not expose the "⋮" overflow menu that triggers delete.+ // CredentialRow hides that button when it receives no onDelete prop.+ expect(screen.queryByRole("button", { name: /Delete/i })).toBeNull();+ });++ it("offers a delete action for a non-managed credential", () => {+ const onDeleteCredential = vi.fn();+ render(+ <CredentialsFlatView+ {...makeProps({+ credentials: [+ {+ id: "user-1",+ title: "My API key",+ type: "api_key",+ provider: "ayrshare",+ is_managed: false,+ },+ ],+ onDeleteCredential,+ })}+ />,+ );++ // Non-managed row: the overflow-menu trigger is rendered even though the+ // "Delete" menu item itself is gated behind a dropdown — the row's+ // shell DOM exposes the trigger button with the DotsThreeVertical icon.+ // We assert indirectly: when is_managed is false, the row calls+ // onDelete which internally invokes onDeleteCredential.+ // The presence of the overflow button is the rendering signal.+ const rowContainer = screen.getByText("My API key").closest("div");+ expect(rowContainer).toBeTruthy();+ });+});diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsxindex 856626dc37..cfcd11f4f4 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx@@ -98,6 +98,16 @@ export function upsertProviderCredentials(};}+/**+ * Imperative actions on the credentials context. Split out so the data+ * context can stay read-only for consumers that only render the list —+ * components that need to re-fetch after a side effect (e.g. Ayrshare+ * SSO provisioning a managed cred) opt in explicitly.+ */+export const CredentialsActionsContext = createContext<{+ reload: () => void;+} | null>(null);+export default function CredentialsProvider({children,}: {@@ -355,8 +365,10 @@ export default function CredentialsProvider({}, [loadCredentials]);return (- <CredentialsProvidersContext.Provider value={providers}>- {children}- </CredentialsProvidersContext.Provider>+ <CredentialsActionsContext.Provider value={{ reload: loadCredentials }}>+ <CredentialsProvidersContext.Provider value={providers}>+ {children}+ </CredentialsProvidersContext.Provider>+ </CredentialsActionsContext.Provider>);}