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(platform): accounts without an active plan can't upload, preview, publish or connect tools (#15676)
Reinier van der Leer9ebab80bf53b
diff --git a/autogpt_platform/backend/backend/api/conftest.py b/autogpt_platform/backend/backend/api/conftest.pyindex 5258f1c2a0..f378dc95d1 100644--- a/autogpt_platform/backend/backend/api/conftest.py+++ b/autogpt_platform/backend/backend/api/conftest.py@@ -5,9 +5,24 @@ setup_test_user, and setup_admin_user are defined in the parent conftest.py(backend/conftest.py) and are available here automatically."""+from types import SimpleNamespace+import pytest+from prisma.enums import SubscriptionTierfrom pytest_snapshot.plugin import Snapshot+from backend.copilot import rate_limit+from backend.copilot.rate_limit import is_user_paywalled as _REAL_IS_USER_PAYWALLED+from backend.data.pro_activation import UsageActivationState+from backend.util.feature_flag import Flag++# Every module that imports the check by name.+_PAYWALL_CHECK_SITES = (+ "backend.copilot.rate_limit.is_user_paywalled",+ "backend.executor.utils.is_user_paywalled",+ "backend.api.features.integrations.router.is_user_paywalled",+)+@pytest.fixturedef configured_snapshot(snapshot: Snapshot) -> Snapshot:@@ -92,5 +107,31 @@ def _bypass_paywall(mocker):bypassing this helper."""paywall_off = mocker.AsyncMock(return_value=False)- mocker.patch("backend.copilot.rate_limit.is_user_paywalled", new=paywall_off)- mocker.patch("backend.executor.utils.is_user_paywalled", new=paywall_off)+ for site in _PAYWALL_CHECK_SITES:+ mocker.patch(site, new=paywall_off)+++def paywalled_user(mocker, test_user_id):+ """Make the signed-in test user one without a plan, judged by the real check.++ Undoes ``_bypass_paywall`` and stubs only the stored tier and the payments+ flag, so a 402 comes from the same ``is_user_paywalled`` production runs.+ """++ async def no_plan(user_id: str) -> UsageActivationState:+ return UsageActivationState(+ user_id=user_id, tier=SubscriptionTier.NO_TIER, ready=True+ )++ async def payments_on(flag: Flag, *args, **kwargs) -> bool:+ return flag == Flag.ENABLE_PLATFORM_PAYMENT++ for site in _PAYWALL_CHECK_SITES:+ mocker.patch(site, new=_REAL_IS_USER_PAYWALLED)+ mocker.patch(+ "backend.copilot.usage_activation.pro_activation_db",+ return_value=SimpleNamespace(get_usage_activation_state=no_plan),+ )+ mocker.patch.object(rate_limit, "is_feature_enabled", new=payments_on)+ return test_user_iddiff --git a/autogpt_platform/backend/backend/api/features/blocks/routes.py b/autogpt_platform/backend/backend/api/features/blocks/routes.pyindex e20abc5fe7..2e045475f5 100644--- a/autogpt_platform/backend/backend/api/features/blocks/routes.py+++ b/autogpt_platform/backend/backend/api/features/blocks/routes.py@@ -172,6 +172,7 @@ async def execute_graph_block(@router.post(+ dependencies=[Depends(enforce_payment_paywall)],path="/files/upload",summary="Upload file to cloud storage",tags=["files"],diff --git a/autogpt_platform/backend/backend/api/features/builder/routes.py b/autogpt_platform/backend/backend/api/features/builder/routes.pyindex a5afd79953..3407405e5a 100644--- a/autogpt_platform/backend/backend/api/features/builder/routes.py+++ b/autogpt_platform/backend/backend/api/features/builder/routes.py@@ -9,6 +9,7 @@ from autogpt_libs.auth.dependencies import ()from autogpt_libs.auth.models import RequestContext+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.integrations.providers import ProviderNamefrom backend.util.models import Pagination@@ -146,6 +147,7 @@ async def get_providers(@router.get("/search",+ dependencies=[fastapi.Depends(enforce_payment_paywall)],summary="Builder search",tags=["store", "private"],response_model=builder_model.SearchResponse,diff --git a/autogpt_platform/backend/backend/api/features/chat/at_reset.py b/autogpt_platform/backend/backend/api/features/chat/at_reset.pyindex 1701a29b34..584faaf371 100644--- a/autogpt_platform/backend/backend/api/features/chat/at_reset.py+++ b/autogpt_platform/backend/backend/api/features/chat/at_reset.py@@ -11,7 +11,7 @@ from datetime import datetimefrom typing import Annotatedfrom autogpt_libs import auth-from fastapi import APIRouter, HTTPException, Response, Security+from fastapi import APIRouter, Depends, HTTPException, Response, Securityfrom pydantic import BaseModel, Field, model_validatorfrom backend.api.features.chat.routes import (@@ -27,7 +27,7 @@ from backend.copilot.at_reset import (from backend.copilot.at_reset_lock import at_reset_job_lockfrom backend.copilot.continuation import RESUMED_AT_RESET_NOTE, as_model_promptfrom backend.copilot.model import ChatSessionInfo-from backend.copilot.rate_limit import RateLimitUnavailable+from backend.copilot.rate_limit import RateLimitUnavailable, enforce_payment_paywallfrom backend.executor.scheduler import CopilotTurnJobInfo, SchedulerClientfrom backend.util.clients import get_scheduler_client@@ -80,7 +80,7 @@ class AtResetTurnsResponse(BaseModel):@router.post("/sessions/{session_id}/at-reset",summary="Schedule turn at budget reset",- dependencies=[Security(auth.requires_user)],+ dependencies=[Security(auth.requires_user), Depends(enforce_payment_paywall)],responses={404: {"description": "Session not found, or not writable"},409: {diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 80efae1bf3..d0247a0b3d 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -8,7 +8,15 @@ from typing import Annotated, Any, Literalfrom uuid import uuid4from autogpt_libs import auth-from fastapi import APIRouter, HTTPException, Query, Request, Response, Security+from fastapi import (+ APIRouter,+ Depends,+ HTTPException,+ Query,+ Request,+ Response,+ Security,+)from fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, field_validator@@ -999,7 +1007,7 @@ async def get_session_computer(@router.post("/sessions/{session_id}/desktop",- dependencies=[Security(auth.requires_user)],+ dependencies=[Security(auth.requires_user), Depends(enforce_payment_paywall)],responses={404: {"description": "Session not found or access denied"},502: {"description": "The desktop could not be started"},@@ -2332,7 +2340,9 @@ async def queue_pending_message():"""Queue a follow-up message while the session has an active turn."""session = await _validate_and_get_writable_session(session_id, user_id)- if session.metadata.llm_auth_provider == "codex":+ if session.metadata.llm_auth_provider == "platform":+ await enforce_payment_paywall(user_id)+ elif session.metadata.llm_auth_provider == "codex":await enforce_codex_access_http(user_id)client_message_id = (scoped_client_message_id(user_id, session_id, request.message_id)diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex c82ee6c502..760212508c 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -24,7 +24,7 @@ from backend.copilot.config import CopilotLlmAuthProviderfrom backend.copilot.continuation import KEEP_GOING_NOTEfrom backend.copilot.model import AutopilotMode, ChatSessionfrom backend.copilot.offers import EntitlementUnavailable-from backend.copilot.rate_limit import SubscriptionTier+from backend.copilot.rate_limit import SubscriptionTier, UserPaywalledErrorfrom backend.copilot.response_model import StreamFinish, StreamStatus, StreamTextDeltafrom backend.copilot.tools.models import ExpertSoulUpdatedResponsefrom backend.data.model import OAuth2Credentials@@ -2842,6 +2842,22 @@ def test_queue_pending_message_returns_200_when_turn_in_flight(assert "turn_in_flight" in data+def test_queue_pending_message_on_the_platform_route_needs_a_plan(+ mocker: pytest_mock.MockerFixture, paywalled_user+) -> None:+ session = _mock_stream_queue_internals(mocker)+ session.metadata.llm_auth_provider = "platform"+ push = mocker.patch(+ "backend.copilot.pending_message_helpers.push_pending_message_if_session_running",+ new_callable=AsyncMock,+ return_value=1,+ )++ with pytest.raises(UserPaywalledError):+ client.post("/sessions/sess-1/messages/pending", json={"message": "more"})+ push.assert_not_awaited()++def test_queue_pending_message_same_message_id_is_buffered_once(mocker: pytest_mock.MockerFixture,) -> None:diff --git a/autogpt_platform/backend/backend/api/features/experts/avatar_routes.py b/autogpt_platform/backend/backend/api/features/experts/avatar_routes.pyindex fdead906ac..eada5b588b 100644--- a/autogpt_platform/backend/backend/api/features/experts/avatar_routes.py+++ b/autogpt_platform/backend/backend/api/features/experts/avatar_routes.py@@ -1,11 +1,12 @@import uuidfrom autogpt_libs.auth import get_user_id, requires_user-from fastapi import APIRouter, BackgroundTasks, HTTPException, Security+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Securityfrom backend.api.features.experts import avatar_jobsfrom backend.api.features.experts.avatar_generation import ExpertAvatarRequestfrom backend.api.features.experts.avatar_jobs import ExpertAvatarJob+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.util.settings import Settingsrouter = APIRouter(@@ -13,7 +14,12 @@ router = APIRouter()[email protected]("/generations", operation_id="generate_expert_avatar", status_code=202)+ "/generations",+ operation_id="generate_expert_avatar",+ status_code=202,+ dependencies=[Depends(enforce_payment_paywall)],+)async def generate_expert_avatar(request: ExpertAvatarRequest,background_tasks: BackgroundTasks,diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.pyindex 0217905009..4309ab9657 100644--- a/autogpt_platform/backend/backend/api/features/experts/routes.py+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py@@ -2,7 +2,7 @@ import loggingimport autogpt_libs.auth as autogpt_auth_libimport fastapi-from fastapi import APIRouter, Security+from fastapi import APIRouter, Depends, Securityfrom pydantic import BaseModel, Field, field_validator, model_validatorfrom backend.api.features.experts import avatar_routes@@ -45,6 +45,7 @@ from backend.copilot.computer import (open_desktop,)from backend.copilot.config import ChatConfig+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.copilot.tools.e2b_sandbox import SandboxOwner, kill_expert_sandboxfrom backend.copilot.tools.skills import SkillVersionConflictError, SkillWriteLockErrorfrom backend.util.exceptions import NotFoundError@@ -207,6 +208,7 @@ async def hire_expert(@router.post("/raise",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="create_raised_expert",responses={404: {"description": "Attachment not found or unavailable"},@@ -400,6 +402,7 @@ async def get_expert_computer(@router.post("/{expert_id}/computer/desktop",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="postV2StartExpertDesktop",responses={404: {"description": "Expert not found"},@@ -470,6 +473,7 @@ async def list_expert_credentials(@router.post("/{expert_id}/credentials",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="grant_expert_credentials",responses={404: {"description": "Expert not found"},@@ -527,6 +531,7 @@ async def update_expert_soul(@router.put("/{expert_id}/skills",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="update_expert_skills",responses={400: {"description": "A marketplace skill is both attached and removed"},@@ -624,6 +629,7 @@ async def update_expert_mode(@router.post("/{expert_id}/workflows",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="install_expert_workflow",responses={404: {"description": "Expert or workflow not found"}},)@@ -687,6 +693,7 @@ async def get_expert_detach_preview(@router.post("/{expert_id}/schedules/resume",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="resume_expert_schedules",responses={404: {"description": "Expert not found"}},)diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.pyindex 146a946413..8db529bcc6 100644--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py@@ -3,13 +3,14 @@ import loggingfrom typing import Any, Listimport autogpt_libs.auth as autogpt_auth_lib-from fastapi import APIRouter, HTTPException, Query, Security, status+from fastapi import APIRouter, Depends, HTTPException, Query, Security, statusfrom prisma.enums import ReviewStatusfrom backend.copilot.constants import legacy_chat_session_id, parse_node_id_from_exec_idfrom backend.copilot.gate.chat_rules import set_answer_rules as set_chat_rulesfrom backend.copilot.gate.held import subject_keys as held_subject_keysfrom backend.copilot.gate.held import wake as wake_for_held_calls+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data.execution import (ExecutionContext,ExecutionStatus,@@ -184,7 +185,11 @@ async def list_pending_reviews_for_chat_session(return await get_pending_reviews_for_chat_session(chat_session_id, user_id)[email protected]("/action", response_model=ReviewResponse)+ "/action",+ response_model=ReviewResponse,+ dependencies=[Depends(enforce_payment_paywall)],+)async def process_review_action(request: ReviewRequest,user_id: str = Security(autogpt_auth_lib.get_user_id),diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes.py b/autogpt_platform/backend/backend/api/features/graphs/routes.pyindex 023cb53f19..8886de2842 100644--- a/autogpt_platform/backend/backend/api/features/graphs/routes.py+++ b/autogpt_platform/backend/backend/api/features/graphs/routes.py@@ -98,6 +98,7 @@ async def get_graph_all_versions(@router.post(+ dependencies=[Depends(enforce_payment_paywall)],path="/graphs",summary="Create new graph",)@@ -151,6 +152,7 @@ async def delete_graph(@router.put(+ dependencies=[Depends(enforce_payment_paywall)],path="/graphs/{graph_id}",summary="Update graph version",)@@ -224,6 +226,7 @@ async def update_graph(@router.put(+ dependencies=[Depends(enforce_payment_paywall)],path="/graphs/{graph_id}/versions/active",summary="Set active graph version",)diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex 37fdb9803c..11128cbb26 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -9,6 +9,7 @@ from autogpt_libs.auth import get_optional_user_id, get_user_idfrom fastapi import (APIRouter,Body,+ Depends,HTTPException,Path,Query,@@ -21,6 +22,7 @@ from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR, HTTP_502_BAD_GATEWAfrom backend.api.features.library.db import set_preset_webhook, update_presetfrom backend.api.features.library.model import LibraryAgentPreset+from backend.copilot.rate_limit import enforce_payment_paywall, is_user_paywalledfrom backend.data.db_accessors import experts_dbfrom backend.data.execution import ExecutionTriggerfrom backend.data.graph import NodeModel, get_graph, set_node_webhook@@ -132,7 +134,11 @@ class LoginResponse(BaseModel):cancel_url: str | None = None[email protected]("/{provider}/login", summary="Initiate OAuth flow")+ "/{provider}/login",+ summary="Initiate OAuth flow",+ dependencies=[Depends(enforce_payment_paywall)],+)async def login(provider: Annotated[ProviderName, Path(title="The provider to initiate an OAuth flow for")@@ -341,7 +347,11 @@ async def _complete_codex_login(return to_meta_response(credentials)[email protected]("/{provider}/callback", summary="Exchange OAuth code for tokens")+ "/{provider}/callback",+ summary="Exchange OAuth code for tokens",+ dependencies=[Depends(enforce_payment_paywall)],+)async def callback(provider: Annotated[ProviderName, Path(title="The target provider for this OAuth exchange")@@ -630,6 +640,7 @@ def _get_device_auth_handler(provider: ProviderName) -> BaseDeviceAuthHandler:@router.post("/{provider}/device-auth/initiate",+ dependencies=[Depends(enforce_payment_paywall)],summary="Initiate device code OAuth flow",)async def device_auth_initiate(@@ -708,6 +719,7 @@ async def device_auth_initiate(@router.post("/{provider}/device-auth/poll",+ dependencies=[Depends(enforce_payment_paywall)],summary="Poll device code OAuth flow for completion",)async def device_auth_poll(@@ -1049,7 +1061,12 @@ async def get_picker_token()[email protected]("/{provider}/credentials", status_code=201, summary="Create Credentials")+ "/{provider}/credentials",+ status_code=201,+ summary="Create Credentials",+ dependencies=[Depends(enforce_payment_paywall)],+)async def create_credentials(user_id: Annotated[str, Security(get_user_id)],provider: Annotated[@@ -1261,10 +1278,15 @@ async def webhook_ingress_generic(event_type=event_type,payload=payload,)+ has_triggers = bool(webhook.triggered_nodes or webhook.triggered_presets)+ # Each run would refuse a paywalled owner anyway. Stop before publishing and+ # the reward, so a retried delivery after a failed lookup repeats neither.+ if has_triggers and await is_user_paywalled(user_id):+ returnawait publish_webhook_event(webhook_event)logger.debug(f"Webhook event published: {webhook_event}")- if not (webhook.triggered_nodes or webhook.triggered_presets):+ if not has_triggers:returnawait complete_onboarding_step(user_id, OnboardingStep.TRIGGER_WEBHOOK)@@ -1286,7 +1308,9 @@ async def webhook_ingress_generic(await asyncio.gather(*tasks, return_exceptions=True)[email protected]("/webhooks/{webhook_id}/ping")+ "/webhooks/{webhook_id}/ping", dependencies=[Depends(enforce_payment_paywall)]+)async def webhook_ping(webhook_id: Annotated[str, Path(title="Our ID for the webhook")],user_id: Annotated[str, Security(get_user_id)], # require auth@@ -1935,7 +1959,7 @@ def _get_provider_oauth_handler()[email protected]("/ayrshare/sso_url")[email protected]("/ayrshare/sso_url", dependencies=[Depends(enforce_payment_paywall)])async def get_ayrshare_sso_url(user_id: Annotated[str, Security(get_user_id)],) -> AyrshareSSOResponse:diff --git a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.pyindex c38f7b6600..599e7fbfbe 100644--- a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py@@ -782,3 +782,28 @@ async def test_expert_preset_trigger_fails_closed_when_tenancy_lookup_fails(mockget_graph.assert_not_awaited()add_exec.assert_not_awaited()++[email protected]("paywalled", [True, False])+def test_a_webhook_runs_only_for_an_owner_with_a_plan(paywalled: bool, request):+ if paywalled:+ request.getfixturevalue("paywalled_user")+ node = MagicMock()+ node.input_default = {}+ webhook = _make_webhook(ProviderName("generic_webhook"), triggered_nodes=[node])+ patches = _patch_ingress(webhook) + [+ patch(+ "backend.api.features.integrations.router.get_webhook_manager",+ return_value=_manager(webhook.provider),+ )+ ]+ with ExitStack() as stack:+ _, _, publish, reward, run_node, _, _ = [+ stack.enter_context(p) for p in patches+ ]+ resp = _post("generic_webhook")++ assert resp.status_code == 200, resp.text+ expected = 0 if paywalled else 1+ assert publish.await_count == reward.await_count == run_node.await_count+ assert run_node.await_count == expecteddiff --git a/autogpt_platform/backend/backend/api/features/library/routes/agents.py b/autogpt_platform/backend/backend/api/features/library/routes/agents.pyindex c2e6a76232..b04406848e 100644--- a/autogpt_platform/backend/backend/api/features/library/routes/agents.py+++ b/autogpt_platform/backend/backend/api/features/library/routes/agents.py@@ -1,10 +1,11 @@from typing import Literal, Optionalimport autogpt_libs.auth as autogpt_auth_lib-from fastapi import APIRouter, Body, HTTPException, Query, Security, status+from fastapi import APIRouter, Body, Depends, HTTPException, Query, Security, statusfrom fastapi.responses import Responseimport backend.api.features.library._get_many as get_many+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data.onboarding import OnboardingStep, complete_onboarding_stepfrom .. import db as library_db@@ -164,6 +165,7 @@ async def get_library_agent_by_store_listing_version_id(@router.post("",+ dependencies=[Depends(enforce_payment_paywall)],summary="Add Marketplace Agent",status_code=status.HTTP_201_CREATED,)@@ -228,7 +230,11 @@ async def delete_library_agent(return Response(status_code=status.HTTP_204_NO_CONTENT)[email protected]("/{library_agent_id}/fork", summary="Fork Library Agent")+ "/{library_agent_id}/fork",+ summary="Fork Library Agent",+ dependencies=[Depends(enforce_payment_paywall)],+)async def fork_library_agent(library_agent_id: str,user_id: str = Security(autogpt_auth_lib.get_user_id),diff --git a/autogpt_platform/backend/backend/api/features/library/routes/presets.py b/autogpt_platform/backend/backend/api/features/library/routes/presets.pyindex 8b37329059..c386645a67 100644--- a/autogpt_platform/backend/backend/api/features/library/routes/presets.py+++ b/autogpt_platform/backend/backend/api/features/library/routes/presets.py@@ -94,6 +94,7 @@ async def get_preset(@router.post("/presets",+ dependencies=[Depends(enforce_payment_paywall)],summary="Create a new preset",description="Create a new preset for the current user.",)@@ -127,7 +128,7 @@ async def create_preset(return await db.create_preset_from_graph_execution(user_id, preset)[email protected]("/presets/setup-trigger")[email protected]("/presets/setup-trigger", dependencies=[Depends(enforce_payment_paywall)])async def setup_trigger(params: models.TriggeredPresetSetupRequest = Body(),user_id: str = Security(autogpt_auth_lib.get_user_id),@@ -169,6 +170,7 @@ async def setup_trigger(@router.patch("/presets/{preset_id}",+ dependencies=[Depends(enforce_payment_paywall)],summary="Update an existing preset",description="Update an existing preset by its ID.",)diff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.pyindex ce22447ef7..1732ef1047 100644--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py@@ -40,6 +40,7 @@ from backend.blocks.mcp.helpers import (server_host,)from backend.blocks.mcp.oauth import MCPOAuthHandler, MCPTokenEndpointAuthMethod+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data.model import OAuth2Credentialsfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.integrations.mcp_catalog import get_mcp_catalog_entry_for_url@@ -57,7 +58,10 @@ from backend.util.settings import Settingslogger = logging.getLogger(__name__)settings = Settings()-router = fastapi.APIRouter(tags=["mcp"])+# Every route here reaches a server the user names.+router = fastapi.APIRouter(+ tags=["mcp"], dependencies=[fastapi.Depends(enforce_payment_paywall)]+)creds_manager = IntegrationCredentialsManager()# Verifying a token is best-effort; it must never outlast a user's patience.diff --git a/autogpt_platform/backend/backend/api/features/oauth.py b/autogpt_platform/backend/backend/api/features/oauth.pyindex 091067913a..89fc7b9b70 100644--- a/autogpt_platform/backend/backend/api/features/oauth.py+++ b/autogpt_platform/backend/backend/api/features/oauth.py@@ -22,12 +22,21 @@ from typing import Literal, Optionalfrom urllib.parse import unquote, urlencode, urlparsefrom autogpt_libs.auth import get_user_id-from fastapi import APIRouter, Body, HTTPException, Security, UploadFile, status+from fastapi import (+ APIRouter,+ Body,+ Depends,+ HTTPException,+ Security,+ UploadFile,+ status,+)from gcloud.aio import storage as async_storagefrom PIL import Imagefrom prisma.enums import APIKeyPermissionfrom pydantic import BaseModel, Field+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data.auth.oauth import (InvalidClientError,InvalidGrantError,@@ -666,7 +675,9 @@ LOGO_ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"}LOGO_MAX_FILE_SIZE = 3 * 1024 * 1024 # 3MB[email protected]("/apps/{app_id}/logo/upload")+ "/apps/{app_id}/logo/upload", dependencies=[Depends(enforce_payment_paywall)]+)async def upload_app_logo(app_id: str,file: UploadFile,diff --git a/autogpt_platform/backend/backend/api/features/otto/routes.py b/autogpt_platform/backend/backend/api/features/otto/routes.pyindex 18d160c72d..4856d25513 100644--- a/autogpt_platform/backend/backend/api/features/otto/routes.py+++ b/autogpt_platform/backend/backend/api/features/otto/routes.py@@ -1,7 +1,9 @@import loggingfrom autogpt_libs.auth import get_user_id, requires_user-from fastapi import APIRouter, HTTPException, Security+from fastapi import APIRouter, Depends, HTTPException, Security++from backend.copilot.rate_limit import enforce_payment_paywallfrom .models import ApiResponse, ChatRequestfrom .service import OttoService@@ -14,7 +16,7 @@ router = APIRouter()@router.post("/ask",response_model=ApiResponse,- dependencies=[Security(requires_user)],+ dependencies=[Security(requires_user), Depends(enforce_payment_paywall)],summary="Proxy Otto Chat Request",)async def proxy_otto_request(diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes.py b/autogpt_platform/backend/backend/api/features/schedules/routes.pyindex bf4b8aa7a5..dcea041fb1 100644--- a/autogpt_platform/backend/backend/api/features/schedules/routes.py+++ b/autogpt_platform/backend/backend/api/features/schedules/routes.py@@ -2,7 +2,7 @@ from typing import Annotated, Anyfrom autogpt_libs.auth import get_request_context, get_user_id, requires_userfrom autogpt_libs.auth.models import RequestContext-from fastapi import APIRouter, Body, HTTPException, Path, Security+from fastapi import APIRouter, Body, Depends, HTTPException, Path, Securityfrom starlette.status import HTTP_404_NOT_FOUNDfrom backend.api.features.experts import experts_db@@ -11,6 +11,7 @@ from backend.api.features.schedules.model import (ScheduleCreationRequest,ScheduleUpdateRequest,)+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data import graph as graph_dbfrom backend.data.onboarding import OnboardingStep, complete_onboarding_stepfrom backend.data.tenancy import get_user_team_ids@@ -30,6 +31,7 @@ router = APIRouter(dependencies=[Security(requires_user)])@router.post(+ dependencies=[Depends(enforce_payment_paywall)],path="/graphs/{graph_id}/schedules",summary="Create execution schedule",)@@ -185,6 +187,7 @@ async def delete_graph_execution_schedule(@router.patch(+ dependencies=[Depends(enforce_payment_paywall)],path="/schedules/{schedule_id}",summary="Update execution schedule",)diff --git a/autogpt_platform/backend/backend/api/features/search/routes.py b/autogpt_platform/backend/backend/api/features/search/routes.pyindex 5cfffc1fdd..4cd38e0298 100644--- a/autogpt_platform/backend/backend/api/features/search/routes.py+++ b/autogpt_platform/backend/backend/api/features/search/routes.py@@ -16,6 +16,8 @@ from __future__ import annotationsimport autogpt_libs.auth as autogpt_auth_libfrom fastapi import APIRouter, Query, Security+from backend.copilot.rate_limit import enforce_payment_paywall+from . import servicefrom .model import GlobalSearchResponsefrom .rate_limit import enforce_global_search_rate_limit@@ -60,10 +62,10 @@ async def global_search_endpoint(),user_id: str = Security(autogpt_auth_lib.get_user_id),) -> GlobalSearchResponse:- # Skip rate-limit on the empty-query branch — it hits the per-user- # cache, not OpenAI. Only the non-empty path triggers paid embedding- # calls, so that's where the QPS cap matters.+ # Only a query makes a paid embedding call; the empty one reads the+ # per-user cache, so it skips the paywall and the QPS cap.if q.strip():+ await enforce_payment_paywall(user_id)await enforce_global_search_rate_limit(user_id)return await service.global_search(query=q, user_id=user_id, per_type_limit=per_type_limitdiff --git a/autogpt_platform/backend/backend/api/features/skill_learning/routes.py b/autogpt_platform/backend/backend/api/features/skill_learning/routes.pyindex f8cb297718..cbb25dcd00 100644--- a/autogpt_platform/backend/backend/api/features/skill_learning/routes.py+++ b/autogpt_platform/backend/backend/api/features/skill_learning/routes.py@@ -11,7 +11,7 @@ import loggingfrom typing import Annotatedimport autogpt_libs.auth as autogpt_auth_lib-from fastapi import APIRouter, HTTPException, Path, Query, Security+from fastapi import APIRouter, Depends, HTTPException, Path, Query, Securityfrom backend.api.features.experts import experts_dbfrom backend.api.features.skill_learning.models import (@@ -51,6 +51,7 @@ from backend.copilot.learning.owner_actions import ()from backend.copilot.learning.publish import PublishOutcomefrom backend.copilot.learning.revocation import invalidate_versions_for_source+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.copilot.tools.skills import invalidate_skills_index_cachefrom backend.data import skill_learning as learning_datafrom backend.data import skill_reviews as reviews_data@@ -312,7 +313,11 @@ async def update_policy()[email protected]("/skills/{name}/edit", operation_id="edit_learned_skill")+ "/skills/{name}/edit",+ operation_id="edit_learned_skill",+ dependencies=[Depends(enforce_payment_paywall)],+)async def edit_skill(name: Annotated[str, _NAME_PATH],body: EditSkillRequest,@@ -342,7 +347,11 @@ async def edit_skill(return await _with_version(_action_result(outcome, user_id), outcome, user_id)[email protected]("/skills/{name}/restore", operation_id="restore_learned_skill_version")+ "/skills/{name}/restore",+ operation_id="restore_learned_skill_version",+ dependencies=[Depends(enforce_payment_paywall)],+)async def restore(name: Annotated[str, _NAME_PATH],body: RestoreVersionRequest,@@ -369,6 +378,7 @@ async def restore(@router.post("/skills/{name}/decisions/{version_id}",+ dependencies=[Depends(enforce_payment_paywall)],operation_id="decide_skill_learning_proposal",)async def decide(@@ -476,7 +486,11 @@ async def exclude_source()[email protected]("/run", operation_id="run_skill_learning_now")+ "/run",+ operation_id="run_skill_learning_now",+ dependencies=[Depends(enforce_payment_paywall)],+)async def run_now(user_id: str = Security(autogpt_auth_lib.get_user_id),) -> SkillLearningResult:diff --git a/autogpt_platform/backend/backend/api/features/skills/routes.py b/autogpt_platform/backend/backend/api/features/skills/routes.pyindex 4e959f1373..6d408fabd2 100644--- a/autogpt_platform/backend/backend/api/features/skills/routes.py+++ b/autogpt_platform/backend/backend/api/features/skills/routes.py@@ -4,6 +4,7 @@ from typing import Annotatedfrom autogpt_libs.auth import get_user_id, requires_userfrom fastapi import (APIRouter,+ Depends,HTTPException,Path,Query,@@ -27,6 +28,7 @@ from backend.api.features.skills.model import (UploadCopilotSkillRequest,)from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.copilot.tools.skills import (BuiltInSkillError,ParsedSkill,@@ -97,6 +99,7 @@ async def list_copilot_skills(@router.post(+ dependencies=[Depends(enforce_payment_paywall)],path="",summary="Upload a copilot skill from a SKILL.md file",operation_id="uploadCopilotSkill",@@ -140,6 +143,7 @@ async def upload_copilot_skill(@router.post(+ dependencies=[Depends(enforce_payment_paywall)],path="/package",summary="Upload a copilot skill as a zipped package",operation_id="uploadCopilotSkillPackage",diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.pyindex a2d09264ab..eb5da0bf52 100644--- a/autogpt_platform/backend/backend/api/features/store/routes.py+++ b/autogpt_platform/backend/backend/api/features/store/routes.py@@ -7,13 +7,14 @@ import autogpt_libs.authimport fastapiimport fastapi.responsesimport prisma.enums-from fastapi import Query, Security+from fastapi import Depends, Query, Securityfrom pydantic import BaseModelfrom starlette.datastructures import Headersimport backend.data.graphimport backend.util.jsonfrom backend.api.features.search import hybrid_search as search_engine+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.util.exceptions import NotFoundErrorfrom backend.util.models import Paginationfrom backend.util.product_analytics import track_listing_downloaded@@ -231,7 +232,10 @@ async def get_agent_by_name("/agents/{username}/{agent_name}/review",summary="Create agent review",tags=["store"],- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def post_user_review_for_agent(username: str,@@ -462,7 +466,10 @@ def _parse_status_filter("/submissions",summary="Create store submission",tags=["store", "private"],- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def create_submission(submission_request: store_model.StoreSubmissionRequest,@@ -501,7 +508,10 @@ async def create_submission("/submissions/{store_listing_version_id}",summary="Edit store submission",tags=["store", "private"],- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def edit_submission(store_listing_version_id: str,@@ -567,7 +577,10 @@ def get_store_media("/submissions/media",summary="Upload submission media",tags=["store", "private"],- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def upload_submission_media(file: fastapi.UploadFile,@@ -723,7 +736,10 @@ class ImageURLResponse(BaseModel):"/submissions/generate_image",summary="Generate submission image",tags=["store", "private"],- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def generate_image(graph_id: str,diff --git a/autogpt_platform/backend/backend/api/features/store/skill_routes.py b/autogpt_platform/backend/backend/api/features/store/skill_routes.pyindex de35df2e20..8ffa16d51e 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_routes.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_routes.py@@ -5,6 +5,7 @@ import fastapifrom fastapi import Depends, Path, Query, Securityfrom backend.api.features.experts import experts_db+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.copilot.tools.skills import SkillLimitError, SkillOwnedErrorfrom backend.util.feature_flag import Flag, is_feature_enabled@@ -64,7 +65,10 @@ async def list_marketplace_skills(404: {"description": "Skill not in the caller's library"},428: {"description": "Marketplace profile required, or slug taken"},},- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def submit_skill(request: skill_model.SkillSubmissionRequest,@@ -95,7 +99,10 @@ async def list_my_skill_submissions(404: {"description": "Submission not found"},428: {"description": "Only a pending submission can be edited"},},- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def edit_skill_submission(request: skill_model.SkillSubmissionRequest,@@ -236,7 +243,10 @@ _TEXT_APPLICATION_TYPES = frozenset()},},- dependencies=[Security(autogpt_libs.auth.requires_user)],+ dependencies=[+ Security(autogpt_libs.auth.requires_user),+ Depends(enforce_payment_paywall),+ ],)async def install_marketplace_skill(slug: str = Path(..., description="Slug of the skill listing"),diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes.py b/autogpt_platform/backend/backend/api/features/workspace/routes.pyindex c8ebba0263..612a340d11 100644--- a/autogpt_platform/backend/backend/api/features/workspace/routes.py+++ b/autogpt_platform/backend/backend/api/features/workspace/routes.py@@ -12,7 +12,7 @@ from urllib.parse import quoteimport aiohttpimport fastapifrom autogpt_libs.auth.dependencies import get_user_id, requires_user-from fastapi import Query, UploadFile+from fastapi import Depends, Query, UploadFilefrom fastapi.responses import Responsefrom prisma.errors import UniqueViolationErrorfrom pydantic import BaseModel, Field, field_validator@@ -20,7 +20,10 @@ from pydantic import BaseModel, Field, field_validatorfrom backend.api.features.store.exceptions import VirusDetectedError, VirusScanErrorfrom backend.api.features.workspace.preview import build_preview_responsefrom backend.copilot.db import get_chat_session_expert_ids-from backend.copilot.rate_limit import get_workspace_storage_limit_bytes+from backend.copilot.rate_limit import (+ enforce_payment_paywall,+ get_workspace_storage_limit_bytes,+)from backend.data.skill_capacity import SkillLimitErrorfrom backend.data.workspace import (WorkspaceFile,@@ -251,6 +254,7 @@ async def download_file(@router.get("/files/{file_id}/preview",+ dependencies=[Depends(enforce_payment_paywall)],summary="Preview file by ID",operation_id="getWorkspaceFilePreview",)@@ -338,6 +342,7 @@ async def rename_workspace_file_route(@router.post("/files/upload",+ dependencies=[Depends(enforce_payment_paywall)],summary="Upload file to workspace",operation_id="uploadWorkspaceFile",)diff --git a/autogpt_platform/backend/backend/api/paywall_routes_test.py b/autogpt_platform/backend/backend/api/paywall_routes_test.pynew file mode 100644index 0000000000..8421c6bc00--- /dev/null+++ b/autogpt_platform/backend/backend/api/paywall_routes_test.py@@ -0,0 +1,420 @@+"""Every REST route either checks the paywall or is listed here as open.++An account without a plan may still sign in, pay, finish onboarding, read and+tidy what it already has, and leave. Anything that runs compute, calls an+outside service or stores new files or rows checks ``enforce_payment_paywall``.+A new route fails ``test_every_route_checks_the_paywall_or_is_listed_open``+until it does one or the other.+"""++import fastapi.testclient+import pytest+from autogpt_libs.auth import requires_admin_user+from autogpt_libs.auth.jwt_utils import get_jwt_payload+from fastapi.dependencies.models import Dependant+from fastapi.routing import APIRoute++from backend.api.rest_api import app+from backend.copilot.rate_limit import enforce_payment_paywall++# These check in the handler, because whether the request does paid work+# depends on its input: a chat's model route (the platform needs a plan, a+# ChatGPT connection needs Max via enforce_codex_access_http), or a search+# with a query to embed.+CHECKED_IN_HANDLER = {+ "POST /api/chat/sessions",+ "POST /api/chat/sessions/{session_id}/continue",+ "POST /api/chat/sessions/{session_id}/messages/pending",+ "POST /api/chat/sessions/{session_id}/stream",+ "POST /api/chat/speech",+ "GET /api/integrations/codex/credentials/{credential_id}/account",+ "GET /api/integrations/codex/credentials/{credential_id}/rate-limits",+ "GET /api/search/global",+}++OPEN_WHILE_PAYWALLED = {+ # Signing in and managing the account, its organisations and its links.+ "POST /api/analytics/attribution",+ "GET /api/api-keys",+ "POST /api/api-keys",+ "DELETE /api/api-keys/{key_id}",+ "GET /api/api-keys/{key_id}",+ "PUT /api/api-keys/{key_id}/permissions",+ "POST /api/api-keys/{key_id}/suspend",+ "POST /api/auth/user",+ "POST /api/auth/user/consent",+ "POST /api/auth/user/email",+ "GET /api/auth/user/preferences",+ "POST /api/auth/user/preferences",+ "GET /api/auth/user/timezone",+ "POST /api/auth/user/timezone",+ "PUT /api/chat/transports/default",+ "GET /api/experiments/assignments",+ "POST /api/experiments/assignments",+ "GET /api/invitations/pending",+ "POST /api/invitations/{token}/accept",+ "POST /api/invitations/{token}/decline",+ "DELETE /api/memory",+ "GET /api/memory/experts/{expert_id}/facts",+ "DELETE /api/memory/experts/{expert_id}",+ "DELETE /api/memory/experts/{expert_id}/facts/{fact_uuid}",+ "GET /api/memory/experts/{expert_id}/overview",+ "GET /api/memory/facts",+ "DELETE /api/memory/facts/{fact_uuid}",+ "GET /api/memory/overview",+ "GET /api/oauth/app/{client_id}",+ "PATCH /api/oauth/apps/{app_id}/logo",+ "PATCH /api/oauth/apps/{app_id}/status",+ "GET /api/oauth/apps/mine",+ "POST /api/oauth/authorize",+ "GET /api/orgs",+ "POST /api/orgs",+ "DELETE /api/orgs/{org_id}",+ "GET /api/orgs/{org_id}",+ "PATCH /api/orgs/{org_id}",+ "GET /api/orgs/{org_id}/aliases",+ "POST /api/orgs/{org_id}/aliases",+ "POST /api/orgs/{org_id}/convert",+ "GET /api/orgs/{org_id}/invitations",+ "POST /api/orgs/{org_id}/invitations",+ "DELETE /api/orgs/{org_id}/invitations/{invitation_id}",+ "GET /api/orgs/{org_id}/members",+ "POST /api/orgs/{org_id}/members",+ "DELETE /api/orgs/{org_id}/members/{uid}",+ "PATCH /api/orgs/{org_id}/members/{uid}",+ "POST /api/orgs/{org_id}/transfer-ownership",+ "GET /api/orgs/{org_id}/workspaces",+ "POST /api/orgs/{org_id}/workspaces",+ "DELETE /api/orgs/{org_id}/workspaces/{ws_id}",+ "GET /api/orgs/{org_id}/workspaces/{ws_id}",+ "PATCH /api/orgs/{org_id}/workspaces/{ws_id}",+ "POST /api/orgs/{org_id}/workspaces/{ws_id}/join",+ "POST /api/orgs/{org_id}/workspaces/{ws_id}/leave",+ "GET /api/orgs/{org_id}/workspaces/{ws_id}/members",+ "POST /api/orgs/{org_id}/workspaces/{ws_id}/members",+ "DELETE /api/orgs/{org_id}/workspaces/{ws_id}/members/{uid}",+ "PATCH /api/orgs/{org_id}/workspaces/{ws_id}/members/{uid}",+ "GET /api/platform-linking/links",+ "DELETE /api/platform-linking/links/{link_id}",+ "GET /api/platform-linking/platforms",+ "POST /api/platform-linking/tokens/{token}/confirm",+ "GET /api/platform-linking/tokens/{token}/info",+ "GET /api/platform-linking/user-links",+ "DELETE /api/platform-linking/user-links/{link_id}",+ "POST /api/platform-linking/user-tokens/{token}/confirm",+ "POST /api/push/subscribe",+ "POST /api/push/unsubscribe",+ "GET /api/store/profile",+ "POST /api/store/profile",+ "GET /api/transfers",+ "POST /api/transfers",+ "POST /api/transfers/{transfer_id}/approve",+ "POST /api/transfers/{transfer_id}/execute",+ "POST /api/transfers/{transfer_id}/reject",+ # Paying, and seeing what the account is billed.+ "POST /api/chat/usage/reset",+ "GET /api/credits",+ "PATCH /api/credits",+ "POST /api/credits",+ "GET /api/credits/auto-top-up",+ "POST /api/credits/auto-top-up",+ "GET /api/credits/invoices",+ "GET /api/credits/manage",+ "GET /api/credits/pro-activation/current",+ "POST /api/credits/pro-activation/preview",+ "GET /api/credits/pro-activation/{attempt_id}",+ "POST /api/credits/pro-activation/{attempt_id}/confirm",+ "GET /api/credits/refunds",+ "GET /api/credits/subscription",+ "POST /api/credits/subscription",+ "POST /api/credits/subscription/preview",+ "GET /api/credits/transactions",+ "GET /api/credits/trial",+ "POST /api/credits/trial",+ "POST /api/credits/trial/cancel",+ "POST /api/credits/trial/confirm",+ "POST /api/credits/trial/resume",+ "POST /api/credits/{transaction_key}/refund",+ # Onboarding, which reaches the plan picker only after hiring the team.+ "POST /api/experts",+ "GET /api/onboarding",+ "PATCH /api/onboarding",+ "GET /api/onboarding/agents",+ "DELETE /api/onboarding/brain-dump",+ "POST /api/onboarding/brain-dump/finalize",+ "GET /api/onboarding/brain-dump/intro",+ "POST /api/onboarding/brain-dump/intro/complete",+ "POST /api/onboarding/brain-dump/parts",+ "GET /api/onboarding/brain-dump/recommended-experts",+ "GET /api/onboarding/brain-dump/recommended-providers",+ "GET /api/onboarding/brain-dump/recording",+ "GET /api/onboarding/brain-dump/status",+ "GET /api/onboarding/completed",+ "POST /api/onboarding/profile",+ "POST /api/onboarding/reset",+ "POST /api/onboarding/step",+ # Reading the account's own data, or the catalog.+ "GET /api/blocks",+ "GET /api/briefings/latest",+ "GET /api/builder/blocks",+ "GET /api/builder/blocks/batch",+ "GET /api/builder/categories",+ "GET /api/builder/counts",+ "GET /api/builder/providers",+ "GET /api/builder/suggestions",+ "GET /api/chat/connections",+ "GET /api/chat/model-tiers",+ "GET /api/chat/sessions",+ "GET /api/chat/sessions/{session_id}",+ "GET /api/chat/sessions/{session_id}/at-reset",+ "GET /api/chat/sessions/{session_id}/computer",+ "GET /api/chat/sessions/{session_id}/messages/pending",+ "GET /api/chat/sessions/{session_id}/share/state",+ "GET /api/chat/sessions/{session_id}/stream",+ "GET /api/chat/suggested-prompts",+ "GET /api/chat/transports",+ "GET /api/chat/usage",+ "GET /api/desktop-preview",+ "GET /api/executions",+ "GET /api/executions/cost-summary",+ "GET /api/experts",+ "GET /api/experts/avatars/generations/{job_id}",+ "GET /api/experts/identities",+ "GET /api/experts/pods",+ "GET /api/experts/setup",+ "GET /api/experts/{expert_id}",+ "GET /api/experts/{expert_id}/activity",+ "GET /api/experts/{expert_id}/computer",+ "GET /api/experts/{expert_id}/credentials",+ "GET /api/experts/{expert_id}/detach-preview",+ "GET /api/experts/{expert_id}/onboarding",+ "GET /api/experts/{expert_id}/runs",+ "GET /api/graphs",+ "GET /api/graphs/{graph_id}",+ "GET /api/graphs/{graph_id}/executions",+ "GET /api/graphs/{graph_id}/executions/{graph_exec_id}",+ "GET /api/graphs/{graph_id}/schedules",+ "GET /api/graphs/{graph_id}/versions",+ "GET /api/graphs/{graph_id}/versions/{version}",+ "GET /api/home",+ "GET /api/integrations/codex/device-login/{login_id}",+ "GET /api/integrations/codex/device-login/{login_id}/status",+ "GET /api/integrations/credentials",+ "GET /api/integrations/{provider}/credentials",+ "GET /api/integrations/{provider}/credentials/{cred_id}",+ "POST /api/integrations/{provider}/credentials/{cred_id}/picker-token",+ "GET /api/library/agents",+ "GET /api/library/agents/batch",+ "GET /api/library/agents/by-graph/{graph_id}",+ "GET /api/library/agents/favorites",+ "GET /api/library/agents/marketplace/{store_listing_version_id}",+ "GET /api/library/agents/{library_agent_id}",+ "GET /api/library/agents/{library_agent_id}/triggers",+ "GET /api/library/folders",+ "GET /api/library/folders/tree",+ "GET /api/library/folders/{folder_id}",+ "GET /api/library/presets",+ "GET /api/library/presets/{preset_id}",+ "GET /api/review/execution/{graph_exec_id}",+ "GET /api/review/pending",+ "GET /api/review/session/{chat_session_id}",+ "GET /api/schedules",+ "GET /api/schedules/followups",+ "GET /api/skill-learning/decisions",+ "GET /api/skill-learning/history",+ "GET /api/skill-learning/skills/{name}",+ "GET /api/skill-learning/status",+ "GET /api/skills",+ "GET /api/skills/{name}",+ "GET /api/skills/{name}/package",+ "GET /api/store/listings/versions/{store_listing_version_id}/graph",+ "GET /api/store/my-unpublished-agents",+ "GET /api/store/skills/submissions",+ "GET /api/store/submissions",+ "GET /api/store/submissions/media/{owner_user_id}/{media_type}/{filename}",+ "GET /api/workspace/files",+ "GET /api/workspace/files/{file_id}/download",+ "GET /api/workspace/folders",+ "GET /api/workspace/storage/usage",+ # Stopping, deleting or revoking.+ "DELETE /api/chat/sessions/{session_id}",+ "DELETE /api/chat/sessions/{session_id}/at-reset/{kind}",+ "POST /api/chat/sessions/{session_id}/cancel",+ "DELETE /api/chat/sessions/{session_id}/share",+ "DELETE /api/chat/sessions/{session_id}/stream",+ "DELETE /api/executions/{graph_exec_id}",+ "DELETE /api/experts/{expert_id}",+ "DELETE /api/experts/{expert_id}/credentials/{credential_id}",+ "DELETE /api/experts/{expert_id}/workflows/{workflow_id}",+ "DELETE /api/graphs/{graph_id}",+ "DELETE /api/graphs/{graph_id}/executions/{graph_exec_id}/share",+ "POST /api/graphs/{graph_id}/executions/{graph_exec_id}/stop",+ "POST /api/integrations/codex/device-login/{login_id}/cancel",+ "DELETE /api/integrations/{provider}/credentials/{cred_id}",+ "DELETE /api/library/agents/{library_agent_id}",+ "DELETE /api/library/folders/{folder_id}",+ "DELETE /api/library/presets/{preset_id}",+ "DELETE /api/schedules/{schedule_id}",+ "POST /api/skill-learning/sources/{source_kind}/{source_ref}/exclude",+ "DELETE /api/skills/{name}",+ "DELETE /api/store/submissions/{submission_id}",+ "DELETE /api/workspace/files/{file_id}",+ "DELETE /api/workspace/folders/{folder_id}",+ # Organising what the account already has: names, places, settings.+ "PATCH /api/chat/sessions/{session_id}/assign-user",+ "PUT /api/chat/sessions/{session_id}/connection",+ "PUT /api/chat/sessions/{session_id}/credential-selection",+ "POST /api/chat/sessions/{session_id}/feedback",+ "PATCH /api/chat/sessions/{session_id}/pinned",+ "POST /api/chat/sessions/{session_id}/share",+ "PATCH /api/chat/sessions/{session_id}/title",+ "POST /api/experts/pods",+ "PATCH /api/experts/{expert_id}/avatar",+ "PATCH /api/experts/{expert_id}/budget",+ "PATCH /api/experts/{expert_id}/mode",+ "PATCH /api/experts/{expert_id}/pod",+ "PATCH /api/experts/{expert_id}/soul",+ "POST /api/graphs/{graph_id}/executions/{graph_exec_id}/share",+ "PATCH /api/graphs/{graph_id}/settings",+ "PATCH /api/library/agents/{library_agent_id}",+ "POST /api/library/folders",+ "POST /api/library/folders/agents/bulk-move",+ "PATCH /api/library/folders/{folder_id}",+ "POST /api/library/folders/{folder_id}/move",+ "POST /api/skill-learning/experts/{expert_id}/policy",+ "POST /api/skill-learning/skills/{name}/outcome",+ "POST /api/skill-learning/skills/{name}/policy",+ "PATCH /api/workspace/files/{file_id}",+ "POST /api/workspace/folders",+ "POST /api/workspace/folders/files/bulk-move",+ "PATCH /api/workspace/folders/{folder_id}",+ # No signed-in user to check: public pages, provider webhooks and token+ # endpoints. A webhook's runs check their owner (add_graph_execution).+ "POST /api/auth/email/send",+ "POST /api/auth/user/preferences/from-email",+ "GET /api/chat/config/ttl",+ "GET /api/chat/health",+ "GET /api/chat/schema/tool-responses",+ "POST /api/credits/stripe_webhook",+ "POST /api/email/",+ "POST /api/email/mailerlite/webhook",+ "POST /api/email/unsubscribe",+ "GET /api/experts/templates",+ "GET /api/feature-flags",+ "GET /api/integrations/providers",+ "GET /api/integrations/providers/constants",+ "GET /api/integrations/providers/enum-example",+ "GET /api/integrations/providers/names",+ "GET /api/integrations/providers/system",+ "POST /api/integrations/{provider}/webhooks/{webhook_id}/ingress",+ "POST /api/oauth/introspect",+ "POST /api/oauth/revoke",+ "POST /api/oauth/token",+ "GET /api/public/shared/chats/{share_token}",+ "GET /api/public/shared/chats/{share_token}/files/{file_id}/download",+ "GET /api/public/shared/chats/{share_token}/messages",+ "GET /api/public/shared/{share_token}",+ "GET /api/public/shared/{share_token}/files/{file_id}/download",+ "GET /api/push/vapid-key",+ "GET /api/store/agents",+ "GET /api/store/agents/{username}/{agent_name}",+ "GET /api/store/categories",+ "GET /api/store/creators",+ "GET /api/store/creators/{username}",+ "GET /api/store/listings/versions/{store_listing_version_id}",+ "GET /api/store/listings/versions/{store_listing_version_id}/graph/download",+ "GET /api/store/media/{user_id}/{media_type}/{filename}",+ "GET /api/store/metrics/cache",+ "GET /api/store/search",+ "GET /api/store/skills",+ "GET /api/store/skills/{slug}",+ "GET /api/store/skills/{slug}/files/{path:path}",+ "GET /health",+}++# One closed route per router, as the client calls it.+CLOSED_SAMPLES = [+ "GET /api/builder/search",+ "POST /api/chat/sessions/s-1/at-reset",+ "POST /api/chat/sessions/s-1/desktop",+ "POST /api/experts/avatars/generations",+ "POST /api/experts/raise",+ "POST /api/files/upload",+ "POST /api/graphs",+ "POST /api/graphs/g-1/schedules",+ "GET /api/integrations/github/login",+ "POST /api/library/agents/la-1/fork",+ "POST /api/library/presets/setup-trigger",+ "POST /api/mcp/discover-tools",+ "POST /api/oauth/apps/a-1/logo/upload",+ "POST /api/otto/ask",+ "POST /api/review/action",+ "GET /api/search/global?q=weekly report",+ "POST /api/skill-learning/run",+ "POST /api/skills",+ "POST /api/store/skills/submissions",+ "POST /api/store/submissions/media",+ "POST /api/workspace/files/upload",+ "GET /api/workspace/files/f-1/preview",+]+++def test_every_route_checks_the_paywall_or_is_listed_open():+ unlisted, checked_but_listed = [], []+ for key, route in _routes_with_a_user():+ checked = _depends_on(route.dependant, enforce_payment_paywall)+ listed = key in OPEN_WHILE_PAYWALLED or key in CHECKED_IN_HANDLER+ if checked and listed:+ checked_but_listed.append(key)+ elif not checked and not listed:+ unlisted.append(key)++ assert not unlisted, (+ "Add Depends(enforce_payment_paywall) to these routes, or list them in "+ f"OPEN_WHILE_PAYWALLED with the reason they stay open: {sorted(unlisted)}"+ )+ assert not checked_but_listed, (+ f"These routes check the paywall, so drop them from the open lists: "+ f"{sorted(checked_but_listed)}"+ )+++def test_the_open_lists_name_only_routes_that_exist():+ served = {key for key, _ in _routes_with_a_user()}+ assert not (OPEN_WHILE_PAYWALLED | CHECKED_IN_HANDLER) - served+ assert OPEN_WHILE_PAYWALLED.isdisjoint(CHECKED_IN_HANDLER)++[email protected]("call", CLOSED_SAMPLES)+def test_an_account_without_a_plan_gets_402_from_a_closed_route(+ call: str, mock_jwt_user, paywalled_user, mocker+):+ mocker.patch(+ "backend.api.features.store.skill_routes.is_feature_enabled",+ new=mocker.AsyncMock(return_value=True),+ )+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ try:+ method, path = call.split(" ", 1)+ response = fastapi.testclient.TestClient(app).request(method, path)+ finally:+ app.dependency_overrides.clear()++ assert response.status_code == 402, response.text+ assert "subscription is required" in response.json()["detail"]+++def _routes_with_a_user():+ for route in app.routes:+ if not isinstance(route, APIRoute):+ continue+ if _depends_on(route.dependant, requires_admin_user):+ continue+ for method in route.methods:+ yield f"{method} {route.path}", route+++def _depends_on(dependant: Dependant, call) -> bool:+ return any(+ dep.call is call or _depends_on(dep, call) for dep in dependant.dependencies+ )diff --git a/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.py b/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.pyindex 410ead6230..c3309e485a 100644--- a/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.py+++ b/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.py@@ -16,6 +16,7 @@ from backend.api.features.mcp.routes import routerfrom backend.blocks.mcp.block import TEST_CREDENTIALS_INPUT, MCPToolBlockfrom backend.blocks.mcp.client import MCPClient, normalize_mcp_authorizationfrom backend.blocks.mcp.helpers import mcp_authorization_header+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data.model import OAuth2Credentialsfrom backend.executor.utils import _validate_node_input_credentials@@ -116,6 +117,8 @@ async def test_schema_optional_mcp_credentials_do_not_skip_execution(app = fastapi.FastAPI()app.include_router(router)app.dependency_overrides[get_user_id] = lambda: "test-user-id"+# The paywall has its own tests, in backend/api/paywall_routes_test.py.+app.dependency_overrides[enforce_payment_paywall] = lambda: None@pytest_asyncio.fixture(scope="module")diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.pyindex 3362549300..a934717748 100644--- a/autogpt_platform/backend/backend/copilot/briefing/generate.py+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py@@ -11,6 +11,7 @@ from pydantic import ValidationErrorfrom backend.api.features.experts.models import Expertfrom backend.api.features.graph_executions.review.model import PendingHumanReviewModel+from backend.copilot.rate_limit import is_user_paywalledfrom backend.copilot.usage_activation import UsageActivationUnavailablefrom backend.data.db_accessors import (execution_db,@@ -274,6 +275,9 @@ async def generate_and_deliver_briefing(user_id: str) -> BriefingResult:return {"status": "skipped", "reason": "flag_unavailable"}return {"status": "skipped", "reason": "flag_disabled"}+ if await is_user_paywalled(user_id):+ return {"status": "skipped", "reason": "paywalled"}+user = await user_db().get_user_by_id(user_id)tz_name = get_user_timezone_or_utc(user.timezone)now_local = datetime.now(ZoneInfo(tz_name))diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py b/autogpt_platform/backend/backend/copilot/briefing/generate_test.pyindex 1414496b66..6d7732cb4c 100644--- a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py+++ b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py@@ -30,6 +30,13 @@ def stub_narrative(monkeypatch):return mock[email protected](autouse=True)+def paid_user(monkeypatch):+ mock = AsyncMock(return_value=False)+ monkeypatch.setattr(generate_module, "is_user_paywalled", mock)+ return mock++def make_expert(id="exp-1", name="Ana", avatar="https://a/x.png", workflows=None):# Build a minimal backend.api.features.experts.models.Expertfrom backend.api.features.experts.models import Expert@@ -279,6 +286,22 @@ async def test_generate_skips_when_flag_off(monkeypatch):assert result == {"status": "skipped", "reason": "flag_disabled"}+async def test_generate_skips_a_paywalled_user_before_reading_anything(+ monkeypatch, paid_user+):+ paid_user.return_value = True+ monkeypatch.setattr(+ generate_module, "evaluate_feature_flag", AsyncMock(return_value=(True, True))+ )+ db = MagicMock()+ monkeypatch.setattr(generate_module, "user_db", lambda: db)+ result = await generate_module.generate_and_deliver_briefing("user-1")+ assert result == {"status": "skipped", "reason": "paywalled"}+ paid_user.assert_awaited_once_with("user-1")+ db.get_user_by_id.assert_not_called()++@pytest.mark.asyncioasync def test_generate_reports_an_unevaluated_flag_separately(monkeypatch):"""A flag read that FAILED yields False, same as a real "off". Only thediff --git a/autogpt_platform/backend/backend/copilot/tools/mcp_manual_token_e2e_test.py b/autogpt_platform/backend/backend/copilot/tools/mcp_manual_token_e2e_test.pyindex 4bae34d9da..2d2ab38ffe 100644--- a/autogpt_platform/backend/backend/copilot/tools/mcp_manual_token_e2e_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/mcp_manual_token_e2e_test.py@@ -27,6 +27,7 @@ import pytest_asynciofrom autogpt_libs.auth import get_user_idfrom backend.api.features.mcp.routes import router+from backend.copilot.rate_limit import enforce_payment_paywallfrom backend.data.model import Credentialsfrom ._test_data import make_session@@ -42,6 +43,8 @@ _AUTHORIZATION = f"Bearer {_TOKEN}"app = fastapi.FastAPI()app.include_router(router)app.dependency_overrides[get_user_id] = lambda: _USER_ID+# The paywall has its own tests, in backend/api/paywall_routes_test.py.+app.dependency_overrides[enforce_payment_paywall] = lambda: Noneclass FakeCredentialsStore:diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsxindex 7fcf57d7bb..ad3c30bce2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paywall-send.test.tsx@@ -7,7 +7,9 @@ import {} from "@/tests/integrations/test-utils";import { http, HttpResponse } from "msw";import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { useChatInput } from "../components/ChatInput/useChatInput";+import { sendWithAttachments } from "../helpers/sendWithAttachments";import { useChatSession } from "../useChatSession";// The first send of a new chat creates the session, and two layers used to@@ -24,6 +26,12 @@ vi.mock("@/hooks/useIsBillingEnabled", () => ({useIsBillingEnabled: () => billing.enabled,}));+const uploadFileDirect = vi.hoisted(() => vi.fn());+vi.mock("@/lib/direct-upload", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/direct-upload")>()),+ uploadFileDirect,+}));+vi.mock("@/components/molecules/Toast/use-toast", () => ({toast: (...args: unknown[]) => toast(...args),useToast: () => ({ toast, dismiss: vi.fn() }),@@ -174,3 +182,45 @@ describe("a refused first send", () => {expect(textarea.value).toBe("too quick");});});++describe("a refused attachment", () => {+ function ComposerWithFile() {+ const sendMessage = vi.fn();+ const { value, handleChange, handleSubmit } = useChatInput({+ onSend: (text) =>+ sendWithAttachments({+ sessionId: "sess-1",+ message: {+ text,+ files: [new File(["x"], "notes.pdf", { type: "application/pdf" })],+ parts: [],+ },+ sendMessage,+ }),+ });+ return (+ <form onSubmit={handleSubmit}>+ <textarea aria-label="Message" value={value} onChange={handleChange} />+ </form>+ );+ }++ it("offers plans once for a paywalled account instead of an upload failure", async () => {+ uploadFileDirect.mockRejectedValue(+ new ApiError("A subscription is required.", 402, null),+ );+ render(<ComposerWithFile />);+ const textarea = screen.getByRole<HTMLTextAreaElement>("textbox", {+ name: "Message",+ });+ fireEvent.change(textarea, { target: { value: "summarise this" } });+ fireEvent.submit(textarea.closest("form")!);++ await waitFor(() => expect(toast).toHaveBeenCalled());+ expect(toast).toHaveBeenCalledOnce();+ expect(toast.mock.calls[0][0]).toMatchObject({+ title: "Sending needs an active plan",+ });+ await waitFor(() => expect(textarea.value).toBe("summarise this"));+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-flow.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-flow.test.tsxindex 6c696594c8..cc9d8f828e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-flow.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-flow.test.tsx@@ -515,6 +515,72 @@ describe("ConnectToolsPanel — inline API key flow", () => {});});+describe("ConnectToolsPanel — without a plan", () => {+ it("points to the plans instead of reporting a failed save", async () => {+ stubPanel();+ server.use(+ http.post(CREATE_CREDENTIALS_URL, () =>+ HttpResponse.json(+ { detail: "A subscription is required." },+ { status: 402 },+ ),+ ),+ );++ renderPanel();+ const user = await openGithub();+ await user.click(screen.getByRole("button", { name: /API Key/ }));+ await user.type(await screen.findByLabelText("Name"), "Work key");+ await user.type(+ screen.getByLabelText("API key", { selector: "input" }),+ "<test-api-key>",+ );+ await user.click(screen.getByRole("button", { name: "Continue" }));++ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Connecting a service needs an active plan",+ }),+ ),+ );+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "Couldn't save API key" }),+ );+ });+});++describe("ConnectToolsPanel — OAuth without a plan", () => {+ it("points to the plans before any sign-in window opens", async () => {+ stubPanel();+ server.use(+ http.get(OAUTH_LOGIN_URL, () =>+ HttpResponse.json(+ { detail: "A subscription is required." },+ { status: 402 },+ ),+ ),+ );++ renderPanel();+ const user = await openGithub();+ await user.click(screen.getByRole("button", { name: /OAuth/ }));+ await user.click(screen.getByRole("button", { name: "Continue" }));++ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Connecting a service needs an active plan",+ }),+ ),+ );+ expect(openOAuthPopup).not.toHaveBeenCalled();+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "OAuth connection failed" }),+ );+ });+});+describe("ConnectToolsPanel — inline OAuth flow", () => {it("runs the whole OAuth exchange without leaving the panel", async () => {stubPanel();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsxindex 569291fec3..7b770c3abd 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendFailureToast.tsx@@ -1,23 +1,17 @@-import { toast } from "@/components/molecules/Toast/use-toast";-import { ApiError } from "@/lib/autogpt-server-api/helpers";-import { describeSendFailure } from "../components/ChatInput/helpers";import {PAYWALL_TOAST_KEY,PaywallToastAction,PaywallToastDescription,-} from "../components/PaywallToast/PaywallToast";+} from "@/components/contextual/PaywallToast/PaywallToast";+import {+ isPaywallError,+ PAYWALL_TOAST_DURATION_MS,+} from "@/components/contextual/PaywallToast/helpers";+import { toast } from "@/components/molecules/Toast/use-toast";+import { describeSendFailure } from "../components/ChatInput/helpers";import { SentNowError } from "../components/SendAtReset/helpers";import { ReportedSendError } from "./reportedSendError";-const PAYWALL_TOAST_DURATION_MS = 15_000;--/** The backend answers 402 when the account has no plan (or its trial- * lapsed). Retrying can never succeed, so it gets an upgrade path instead of- * a "try again". */-export function isPaywallError(error: unknown) {- return error instanceof ApiError && error.status === 402;-}-interface Args {title: string;error: unknown;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendWithAttachments.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendWithAttachments.tsindex f6bef8aa8b..3dec7c6894 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendWithAttachments.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/sendWithAttachments.ts@@ -1,3 +1,4 @@+import { isPaywallError } from "@/components/contextual/PaywallToast/helpers";import { toast } from "@/components/molecules/Toast/use-toast";import { uploadFileDirect } from "@/lib/direct-upload";import type { FileUIPart, UIMessage } from "ai";@@ -167,6 +168,8 @@ async function uploadFiles(mime_type: data.mime_type || "application/octet-stream",} as UploadedFile;} catch (err) {+ // The send's own failure toast says a plan is needed.+ if (isPaywallError(err)) throw err;console.error("File upload failed:", err);toast({title: "File upload failed",@@ -177,6 +180,11 @@ async function uploadFiles(}}),);+ const paywalled = results.find(+ (r): r is PromiseRejectedResult =>+ r.status === "rejected" && isPaywallError(r.reason),+ );+ if (paywalled) throw paywalled.reason;return results.filter((r): r is PromiseFulfilledResult<UploadedFile> =>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex a537ea213f..b1f9e40f91 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -21,7 +21,7 @@ import {type TurnStatsMap,} from "./helpers/convertChatSessionToUiMessages";import { resolveSessionDryRun } from "./helpers";-import { isPaywallError } from "./helpers/sendFailureToast";+import { isPaywallError } from "@/components/contextual/PaywallToast/helpers";import { getSessionSentFrom } from "./sentFrom";import {getAvailableLLMTransports,diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsxindex 9f73b2ddcc..4cb067d8fb 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/__tests__/OAuthAppsSection.test.tsx@@ -7,6 +7,8 @@ import {waitFor,} from "@/tests/integrations/test-utils";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { OAuthAppsSection } from "../OAuthAppsSection";const toastSpy = vi.hoisted(() => vi.fn());@@ -17,10 +19,15 @@ vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {>();return {...actual,+ toast: (...args: unknown[]) => toastSpy(...args),useToast: () => ({ toast: toastSpy, dismiss: () => {}, toasts: [] }),};});+vi.mock("@/hooks/useIsBillingEnabled", () => ({+ useIsBillingEnabled: () => false,+}));+const uploadSpy = vi.hoisted(() => vi.fn());vi.mock("@/lib/direct-upload", async (importOriginal) => {const actual = await importOriginal<typeof import("@/lib/direct-upload")>();@@ -94,6 +101,36 @@ describe("OAuthAppsSection - logo upload", () => {expect(uploadSpy).not.toHaveBeenCalled();});+ it("sends an account without a plan to whoever runs this server, where nothing bills", async () => {+ uploadSpy.mockRejectedValueOnce(+ new ApiError("A subscription is required.", 402, null),+ );++ render(<OAuthAppsSection />);+ await screen.findByText("My App");+ const file = new File(["x"], "logo.png", { type: "image/png" });+ fireEvent.change(logoInput(), { target: { files: [file] } });++ await waitFor(() => expect(toastSpy).toHaveBeenCalled());+ const [paywall] = toastSpy.mock.calls[0];+ expect(paywall).toMatchObject({+ title: "Uploading a logo needs an active plan",+ });+ render(+ <>+ {paywall.description}+ {paywall.action}+ </>,+ );+ expect(+ screen.getByText("Ask whoever runs this server to set one up."),+ ).toBeDefined();+ expect(screen.queryByRole("link", { name: "See plans" })).toBeNull();+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "Error" }),+ );+ });+it("surfaces a destructive toast when the upload fails", async () => {uploadSpy.mockRejectedValueOnce(new Error("boom"));diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.tsindex aa76e6fcf1..eae138d66c 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/oauth-apps/components/useOAuthApps.ts@@ -1,5 +1,6 @@"use client";+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useState } from "react";import {useGetOauthListMyOauthApps,@@ -74,6 +75,8 @@ export const useOAuthApps = () => {description: "Logo uploaded successfully",});} catch (error) {+ if (toastIfPlanRequired(error, "Uploading a logo needs an active plan"))+ return;console.error("Failed to upload logo:", error);const errorMessage =error instanceof Error ? error.message : "Failed to upload logo";diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsxindex 458af869c3..460bb9252c 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx@@ -9,6 +9,8 @@ import {within,} from "@/tests/integrations/test-utils";import { server } from "@/mocks/mock-server";+import { PAYWALL_TOAST_KEY } from "@/components/contextual/PaywallToast/PaywallToast";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import {getGetV2GetUserProfileMockHandler200,getGetV2GetUserProfileMockHandler401,@@ -655,6 +657,35 @@ describe("SettingsProfilePage - avatar upload", () => {});});+ test("an account without a plan is sent to the plans, not told the upload failed", async () => {+ server.use(getGetV2GetUserProfileMockHandler200(makeProfile()));+ toastSpy.mockClear();+ uploadAvatarSpy.mockRejectedValueOnce(+ new ApiError("A subscription is required.", 402, null),+ );++ render(<SettingsProfilePage />);++ await screen.findByLabelText(/display name/i);+ const fileInput = document.querySelector(+ 'input[type="file"]',+ ) as HTMLInputElement;+ const file = new File(["x"], "avatar.png", { type: "image/png" });+ fireEvent.change(fileInput, { target: { files: [file] } });++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Uploading a photo needs an active plan",+ replaceKey: PAYWALL_TOAST_KEY,+ }),+ );+ });+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "Failed to upload photo" }),+ );+ });+test("rejects an oversized avatar before uploading and explains the limit", async () => {server.use(getGetV2GetUserProfileMockHandler200(makeProfile()));toastSpy.mockClear();diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.tsindex b10dbef286..a3fba91c48 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts@@ -1,5 +1,6 @@"use client";+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useEffect, useMemo, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";@@ -167,6 +168,8 @@ export function useProfilePage() {patchField("avatar_url", url);return url;} catch (err) {+ if (toastIfPlanRequired(err, "Uploading a photo needs an active plan"))+ return null;toast({title: "Failed to upload photo",description: err instanceof Error ? err.message : undefined,diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsxindex 94550b9196..967aecd52f 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsx@@ -39,7 +39,9 @@ vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({postV2InitiateOauthLoginForAnMcpServer: vi.fn(),}));+import { toast } from "@/components/molecules/Toast/use-toast";import useCredentials from "@/hooks/useCredentials";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { useBackendAPI } from "@/lib/autogpt-server-api/context";import {openOAuthPopup,@@ -207,6 +209,37 @@ describe("credential connect failures the card reports instead of throwing", ());});+ it("points a missing plan to the plans and counts no failed connection", async () => {+ mockUseBackendAPI.mockReturnValue({+ oAuthLogin: vi.fn(+ () =>+ new Promise<never>((_resolve, reject) =>+ setTimeout(+ () =>+ reject(new ApiError("A subscription is required.", 402, null)),+ 0,+ ),+ ),+ ),+ onWebSocketMessage: vi.fn().mockReturnValue(() => {}),+ connectWebSocket: vi.fn().mockResolvedValue(undefined),+ sendWebSocketMessage: vi.fn(),+ });++ renderCard();++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Connecting a service needs an active plan",+ }),+ ),+ );+ expect(mockOpenOAuthPopup).not.toHaveBeenCalled();+ expect(screen.queryByText(/OAuth error/)).toBeNull();+ expect(capturedFailures()).toHaveLength(0);+ });+it("counts nothing when the sign-in completes with the scopes it asked for", async () => {mockOpenOAuthPopup.mockReturnValue({promise: Promise.resolve({ code: "code-1", state: "state-xyz" }),diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.tsindex a193f15341..96f7ae91fb 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts@@ -1,3 +1,4 @@+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import useCredentials from "@/hooks/useCredentials";import { useBackendAPI } from "@/lib/autogpt-server-api/context";import {@@ -356,6 +357,10 @@ export function useCredentialsInput({}// A superseded flow must not surface its errors over the newer flow.if (flowId !== oauthFlowIdRef.current) return;+ if (+ toastIfPlanRequired(error, "Connecting a service needs an active plan")+ )+ return;const message = error instanceof Error ? error.message : String(error);if (message === OAUTH_ERROR_WINDOW_CLOSED ||diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.tsindex f66ee19dd4..8ace069d2b 100644--- a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts@@ -1,5 +1,6 @@"use client";+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useCallback, useContext, useEffect, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";@@ -191,6 +192,10 @@ export function useDeviceAuthConnect({ provider, onSuccess }: Args) {} catch (error) {if (isUnmountedRef.current || runId !== runIdRef.current) return;setPhase("error");+ if (+ toastIfPlanRequired(error, "Connecting a service needs an active plan")+ )+ return;toast({title: "Device auth initiation failed",description:diff --git a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.tsindex 97cff9312d..11f504afb5 100644--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts@@ -1,3 +1,4 @@+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import * as Sentry from "@sentry/nextjs";import {getGetV2ListMySubmissionsQueryKey,@@ -148,6 +149,7 @@ export const useEditAgentForm = ({throw new Error("Failed to update submission");}} catch (error) {+ if (toastIfPlanRequired(error, "Publishing needs an active plan")) return;Sentry.captureException(error);toast({title: "Edit Workflow Error",diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/useInlineConnectForm.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/useInlineConnectForm.tsindex d577bfdcaf..da3152fc89 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/useInlineConnectForm.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/useInlineConnectForm.ts@@ -1,5 +1,6 @@"use client";+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useContext, useState } from "react";import { useQueryClient } from "@tanstack/react-query";@@ -44,6 +45,10 @@ export function useInlineConnectForm({// this; only the success payload carries an id.onSuccess("id" in created.data ? created.data : undefined);} catch (error) {+ if (+ toastIfPlanRequired(error, "Connecting a service needs an active plan")+ )+ return;toast({title: failureTitle,description:diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.tsindex b409ece055..7a2d2e9420 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useApiKeyConnectForm.ts@@ -1,5 +1,6 @@"use client";+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useContext, useState } from "react";import { zodResolver } from "@hookform/resolvers/zod";import { useForm } from "react-hook-form";@@ -60,6 +61,10 @@ export function useApiKeyConnectForm({ provider, onSuccess }: Args) {// this; only the success payload carries an id.onSuccess("id" in created.data ? created.data : undefined);} catch (error) {+ if (+ toastIfPlanRequired(error, "Connecting a service needs an active plan")+ )+ return;toast({title: "Couldn't save API key",description:diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.tsindex d576b6fddd..186ad75355 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect.ts@@ -1,5 +1,6 @@"use client";+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useContext, useEffect, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";@@ -157,6 +158,10 @@ export function useOAuthConnect({}}if (isUnmountedRef.current) return;+ if (+ toastIfPlanRequired(error, "Connecting a service needs an active plan")+ )+ return;toast({title: "OAuth connection failed",description: getOAuthErrorMessage(error),diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PaywallToast/PaywallToast.tsx b/autogpt_platform/frontend/src/components/contextual/PaywallToast/PaywallToast.tsxsimilarity index 85%rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/PaywallToast/PaywallToast.tsxrename to autogpt_platform/frontend/src/components/contextual/PaywallToast/PaywallToast.tsxindex dfab64a5b8..e8191023ed 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PaywallToast/PaywallToast.tsx+++ b/autogpt_platform/frontend/src/components/contextual/PaywallToast/PaywallToast.tsx@@ -21,6 +21,13 @@ export function PaywallToastDescription({ recovery }: DescriptionProps) {: `Ask whoever runs this server to set one up — ${recovery}.`;}+export function PlanRequiredDescription() {+ const isBillingEnabled = useIsBillingEnabled();+ return isBillingEnabled+ ? "Choose one to continue."+ : "Ask whoever runs this server to set one up.";+}+export function PaywallToastAction() {const isBillingEnabled = useIsBillingEnabled();if (!isBillingEnabled) return null;diff --git a/autogpt_platform/frontend/src/components/contextual/PaywallToast/helpers.tsx b/autogpt_platform/frontend/src/components/contextual/PaywallToast/helpers.tsxnew file mode 100644index 0000000000..1738b37a68--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/PaywallToast/helpers.tsx@@ -0,0 +1,31 @@+import { toast } from "@/components/molecules/Toast/use-toast";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import {+ PAYWALL_TOAST_KEY,+ PaywallToastAction,+ PlanRequiredDescription,+} from "./PaywallToast";++export const PAYWALL_TOAST_DURATION_MS = 15_000;++/** The backend answers 402 when the account has no plan (or its trial+ * lapsed). Retrying can never succeed, so it gets an upgrade path instead of+ * a "try again". */+export function isPaywallError(error: unknown) {+ return error instanceof ApiError && error.status === 402;+}++/** Shows the plan toast and returns true when `error` is a 402, so a caller+ * can skip its own failure toast. */+export function toastIfPlanRequired(error: unknown, title: string) {+ if (!isPaywallError(error)) return false;+ toast({+ title,+ description: <PlanRequiredDescription />,+ variant: "destructive",+ duration: PAYWALL_TOAST_DURATION_MS,+ replaceKey: PAYWALL_TOAST_KEY,+ action: <PaywallToastAction />,+ });+ return true;+}diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsxindex 8aebf3ab6f..65c450b25b 100644--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.test.tsx@@ -1,5 +1,8 @@import { describe, expect, it, vi } from "vitest";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { http, HttpResponse } from "msw";+import { getPostV2GenerateSubmissionImageMockHandler } from "@/app/api/__generated__/endpoints/store/store.msw";import { server } from "@/mocks/mock-server";import {@@ -19,6 +22,7 @@ vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {>();return {...actual,+ toast: (...args: unknown[]) => toastSpy(...args),useToast: () => ({toast: toastSpy,dismiss: () => {},@@ -27,6 +31,10 @@ vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {};});+vi.mock("@/hooks/useIsBillingEnabled", () => ({+ useIsBillingEnabled: () => true,+}));+const uploadSpy = vi.hoisted(() => vi.fn());vi.mock("@/lib/direct-upload", async (importOriginal) => {const actual = await importOriginal<typeof import("@/lib/direct-upload")>();@@ -133,6 +141,74 @@ describe("ThumbnailImages", () => {});});+ it("points an account without a plan to the plans when an upload is refused", async () => {+ toastSpy.mockClear();+ uploadSpy.mockRejectedValueOnce(+ new ApiError("A subscription is required.", 402, null),+ );++ render(+ <ThumbnailImages+ agentId="agent-1"+ onImagesChange={() => {}}+ initialImages={[]}+ />,+ );+ const input = document.getElementById("image-upload") as HTMLInputElement;+ selectFile(input, new File(["data"], "thumb.png", { type: "image/png" }));++ await waitFor(() => expect(toastSpy).toHaveBeenCalled());+ const [paywall] = toastSpy.mock.calls[0];+ expect(paywall).toMatchObject({+ title: "Uploading images needs an active plan",+ });+ render(+ <>+ {paywall.description}+ {paywall.action}+ </>,+ );+ expect(screen.getByText("Choose one to continue.")).toBeDefined();+ expect(+ screen.getByRole("link", { name: "See plans" }).getAttribute("href"),+ ).toBe("/settings/billing");+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "Upload failed" }),+ );+ });++ it("points an account without a plan to the plans when generating is refused", async () => {+ toastSpy.mockClear();+ server.use(+ http.post("*/api/store/submissions/generate_image", () =>+ HttpResponse.json(+ { detail: "A subscription is required." },+ { status: 402 },+ ),+ ),+ );++ render(+ <ThumbnailImages+ agentId="agent-1"+ onImagesChange={() => {}}+ initialImages={[]}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /generate/i }));++ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Generating an image needs an active plan",+ }),+ ),+ );+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "Generation failed" }),+ );+ });+it("rejects an oversized file before uploading and explains the size limit", async () => {toastSpy.mockClear();uploadSpy.mockClear();diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.tsindex 1c690dcae1..8957c167a1 100644--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts@@ -1,3 +1,4 @@+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useState, useRef, useEffect } from "react";import { postV2GenerateSubmissionImage } from "@/app/api/__generated__/endpoints/store/store";import { resolveResponse } from "@/app/api/helpers";@@ -118,6 +119,8 @@ export function useThumbnailImages({setSelectedImage(imageUrl);}} catch (error) {+ if (toastIfPlanRequired(error, "Uploading images needs an active plan"))+ return;const detail =error instanceof Error ? error.message : "Please try again.";toast({@@ -145,7 +148,11 @@ export function useThumbnailImages({if (!selectedImage) {setSelectedImage(image_url);}- } catch (_error) {+ } catch (error) {+ if (+ toastIfPlanRequired(error, "Generating an image needs an active plan")+ )+ return;toast({title: "Generation failed",description: "Failed to generate image. Please try again.",diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.tsindex dd0aec67f6..6743c189e5 100644--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts@@ -1,3 +1,4 @@+import { toastIfPlanRequired } from "@/components/contextual/PaywallToast/helpers";import { useEffect, useCallback, useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";@@ -140,6 +141,7 @@ export function useAgentInfoStep({onSuccess(response);} catch (error) {+ if (toastIfPlanRequired(error, "Publishing needs an active plan")) return;Sentry.captureException(error);toast({title: "Submit Workflow Error",diff --git a/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts b/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.tsindex c0a838e3e4..936772cc99 100644--- a/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts+++ b/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { isPaywallError } from "@/components/contextual/PaywallToast/helpers";+import {getFileSizeError,OAUTH_LOGO_MAX_SIZE_MB,@@ -138,6 +140,21 @@ describe("uploadSubmissionMediaDirect", () => {"File too large. Maximum size is 50MB",);});++ it("keeps the status, so a missing plan reads as one", async () => {+ mockFetchOnce({+ ok: false,+ status: 402,+ text: () => JSON.stringify({ detail: "A subscription is required." }),+ });++ const error = await uploadSubmissionMediaDirect(makeFile(10)).catch(+ (e: unknown) => e,+ );++ expect(isPaywallError(error)).toBe(true);+ expect((error as Error).message).toBe("A subscription is required.");+ });});describe("uploadOAuthAppLogoDirect", () => {diff --git a/autogpt_platform/frontend/src/lib/direct-upload.ts b/autogpt_platform/frontend/src/lib/direct-upload.tsindex c3414fccd1..6272afa7ef 100644--- a/autogpt_platform/frontend/src/lib/direct-upload.ts+++ b/autogpt_platform/frontend/src/lib/direct-upload.ts@@ -1,4 +1,5 @@import { getWebSocketToken } from "@/lib/auth/actions";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { environment } from "@/services/environment";interface WorkspaceUploadResponse {@@ -98,6 +99,11 @@ async function postFileToBackend({});}+// Keeps the status, so a caller can tell a missing plan (402) from a failure.+async function uploadError(res: Response): Promise<ApiError> {+ return new ApiError(await readUploadError(res), res.status, null);+}+async function readUploadError(res: Response): Promise<string> {// A proxy/ingress in front of the backend may still reject an oversized body// with a 413 whose payload isn't backend JSON — surface a clear size message@@ -135,7 +141,7 @@ export async function uploadFileDirect(...(sessionID ? { session_id: sessionID } : {}),},});- if (!res.ok) throw new Error(await readUploadError(res));+ if (!res.ok) throw await uploadError(res);return res.json();}@@ -152,7 +158,7 @@ export async function uploadSubmissionMediaDirect(file,searchParams: purpose === "expert-avatar" ? { purpose } : undefined,});- if (!res.ok) throw new Error(await readUploadError(res));+ if (!res.ok) throw await uploadError(res);// The endpoint returns the URL as a JSON string.const url = (await res.json()) as unknown;return typeof url === "string" ? url : String(url);@@ -167,5 +173,5 @@ export async function uploadOAuthAppLogoDirect(path: `/api/oauth/apps/${encodeURIComponent(appId)}/logo/upload`,file,});- if (!res.ok) throw new Error(await readUploadError(res));+ if (!res.ok) throw await uploadError(res);}