Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(platform): resolve merge conflicts with dev branch

Zamil Majdy4942249a6085
diff --cc autogpt_platform/backend/backend/api/features/v1.py
index 2dc0aa8ef8,d208114f95..fcda163555
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@@ -50,11 -50,9 +50,13 @@@ from backend.data.credit import
RefundRequest,
TransactionHistory,
UserCredit,
++ create_subscription_checkout,
get_auto_top_up,
+ get_subscription_cost,
get_user_credit_model,
set_auto_top_up,
+ set_subscription_tier,
++ sync_subscription_from_stripe,
)
from backend.data.graph import GraphSettings
from backend.data.model import CredentialsMetaInput, UserOnboarding
@@@ -649,89 -679,6 +686,102 @@@ async def get_user_auto_top_up
return await get_auto_top_up(user_id)
+class SubscriptionTierRequest(BaseModel):
+ tier: str
++ success_url: str = ""
++ cancel_url: str = ""
++
++
++class SubscriptionCheckoutResponse(BaseModel):
++ url: str
+
+
+class SubscriptionStatusResponse(BaseModel):
+ tier: str
+ monthly_cost: int
+ tier_costs: dict[str, int]
+
+
+@v1_router.get(
+ path="/credits/subscription",
+ summary="Get subscription tier, current cost, and all tier costs",
+ operation_id="getSubscriptionStatus",
+ tags=["credits"],
+ dependencies=[Security(requires_user)],
+)
+async def get_subscription_status(
+ user_id: Annotated[str, Security(get_user_id)],
+) -> SubscriptionStatusResponse:
+ from prisma.enums import SubscriptionTier
+
+ from backend.data.user import get_user_by_id
+
+ user = await get_user_by_id(user_id)
+ tier = user.subscription_tier or SubscriptionTier.FREE
+ cost = await get_subscription_cost(user_id, tier)
+ pro_cost, biz_cost = await asyncio.gather(
+ get_subscription_cost(user_id, SubscriptionTier.PRO),
+ get_subscription_cost(user_id, SubscriptionTier.BUSINESS),
+ )
+ return SubscriptionStatusResponse(
+ tier=tier.value,
+ monthly_cost=cost,
+ tier_costs={"FREE": 0, "PRO": pro_cost, "BUSINESS": biz_cost, "ENTERPRISE": 0},
+ )
+
+
+@v1_router.post(
+ path="/credits/subscription",
- summary="Upgrade or downgrade subscription tier",
++ summary="Start a Stripe Checkout session to upgrade subscription tier",
+ operation_id="updateSubscriptionTier",
+ tags=["credits"],
+ dependencies=[Security(requires_user)],
+)
+async def update_subscription_tier(
+ request: SubscriptionTierRequest,
+ user_id: Annotated[str, Security(get_user_id)],
- ) -> SubscriptionStatusResponse:
++) -> SubscriptionCheckoutResponse:
+ from prisma.enums import SubscriptionTier
+
++ from backend.util.feature_flag import Flag, is_feature_enabled
++
+ _SELF_SERVICE_TIERS = {"FREE", "PRO", "BUSINESS"}
+ if request.tier.upper() not in _SELF_SERVICE_TIERS:
+ raise HTTPException(
+ status_code=422,
+ detail=f"Invalid tier '{request.tier}'. Valid values: {sorted(_SELF_SERVICE_TIERS)}",
+ )
+
+ try:
+ tier = SubscriptionTier(request.tier.upper())
+ except ValueError:
+ raise HTTPException(
+ status_code=422,
+ detail=f"Invalid tier '{request.tier}'. Valid values: {sorted(_SELF_SERVICE_TIERS)}",
+ )
+
- try:
++ # Downgrade to FREE or beta users (payment not enabled) → update tier directly.
++ payment_enabled = await is_feature_enabled(
++ Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False
++ )
++ if tier == SubscriptionTier.FREE or not payment_enabled:
+ await set_subscription_tier(user_id, tier)
++ return SubscriptionCheckoutResponse(url="")
++
++ # Paid upgrade → create Stripe Checkout Session.
++ try:
++ url = await create_subscription_checkout(
++ user_id=user_id,
++ tier=tier,
++ success_url=request.success_url,
++ cancel_url=request.cancel_url,
++ )
+ except ValueError as e:
+ raise HTTPException(status_code=422, detail=str(e))
+
- cost, pro_cost, biz_cost = await asyncio.gather(
- get_subscription_cost(user_id, tier),
- get_subscription_cost(user_id, SubscriptionTier.PRO),
- get_subscription_cost(user_id, SubscriptionTier.BUSINESS),
- )
- return SubscriptionStatusResponse(
- tier=tier.value,
- monthly_cost=cost,
- tier_costs={"FREE": 0, "PRO": pro_cost, "BUSINESS": biz_cost, "ENTERPRISE": 0},
- )
++ return SubscriptionCheckoutResponse(url=url)
+
+
@v1_router.post(
path="/credits/stripe_webhook", summary="Handle Stripe webhooks", tags=["credits"]
)
@@@ -762,6 -709,6 +812,12 @@@ async def stripe_webhook(request: Reque
):
await UserCredit().fulfill_checkout(session_id=event["data"]["object"]["id"])
++ if event["type"] in (
++ "customer.subscription.updated",
++ "customer.subscription.deleted",
++ ):
++ await sync_subscription_from_stripe(event["data"]["object"])
++
if event["type"] == "charge.dispute.created":
await UserCredit().handle_dispute(event["data"]["object"])
diff --cc autogpt_platform/backend/backend/data/credit.py
index 8b240e3a6e,04f91d8d61..3e2cb835f9
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@@ -1272,51 -1250,7 +1258,17 @@@ async def set_auto_top_up(user_id: str
where={"id": user_id},
data={"topUpConfig": SafeJson(config.model_dump())},
)
+ get_user_by_id.cache_delete(user_id) # type: ignore[attr-defined]
+
+
+async def set_subscription_tier(user_id: str, tier: SubscriptionTier) -> None:
- """
- Upgrade or downgrade a user's subscription tier.
-
- Upgrade: validates auto top-up is configured with amount >= subscription cost,
- sets the tier immediately, and charges the first month's subscription.
- Downgrade: sets the new tier immediately (takes effect on next monthly cycle).
- No proration — full month is charged on upgrade.
- """
- current_user = await get_user_by_id(user_id)
- current_tier = current_user.subscription_tier or SubscriptionTier.FREE
-
- sub_cost = await get_subscription_cost(user_id, tier)
-
- if sub_cost > 0:
- auto_top_up = await get_auto_top_up(user_id)
- if auto_top_up.amount < sub_cost:
- cost_fmt = f"${sub_cost / 100:.2f}/mo"
- raise ValueError(
- f"Auto top-up must be configured with amount >= {cost_fmt} "
- f"before upgrading to {tier.value}. "
- f"Current amount: ${auto_top_up.amount / 100:.2f}/mo."
- )
-
++ """Set the user's subscription tier (used by webhook and admin flows)."""
+ await User.prisma().update(
+ where={"id": user_id},
+ data={"subscriptionTier": tier},
+ )
+ get_user_by_id.cache_delete(user_id) # type: ignore[attr-defined]
- # Charge immediately on upgrade (full month, no proration).
- # Downgrade resets cleanly on next monthly cycle.
- tier_order = [
- SubscriptionTier.FREE,
- SubscriptionTier.PRO,
- SubscriptionTier.BUSINESS,
- SubscriptionTier.ENTERPRISE,
- ]
- is_upgrade = tier_order.index(tier) > tier_order.index(current_tier)
- if is_upgrade and sub_cost > 0:
- await ensure_subscription_paid(user_id)
-
async def get_auto_top_up(user_id: str) -> AutoTopUpConfig:
user = await get_user_by_id(user_id)
@@@ -1327,67 -1261,6 +1279,88 @@@
return AutoTopUpConfig.model_validate(user.top_up_config)
+async def get_subscription_cost(user_id: str, tier: SubscriptionTier) -> int:
+ """Return monthly subscription cost in credits from LD. 0 = free or disabled."""
+ flag_map = {
+ SubscriptionTier.PRO: Flag.SUBSCRIPTION_COST_PRO,
+ SubscriptionTier.BUSINESS: Flag.SUBSCRIPTION_COST_BUSINESS,
+ }
+ flag = flag_map.get(tier)
+ if flag is None:
+ return 0
+
+ cost = await get_feature_flag_value(flag.value, user_id, default=0)
+ return int(cost) if isinstance(cost, (int, float)) else 0
+
+
- async def ensure_subscription_paid(user_id: str) -> None:
- """
- Lazy monthly subscription deduction. Idempotent — safe to call from
- spend_credits() and rate-limit checks. Triggers auto top-up when balance
- drops below threshold after deduction.
-
- On auto top-up failure: logs only (grace period). Does not downgrade tier.
- """
- user = await get_user_by_id(user_id)
- tier = user.subscription_tier or SubscriptionTier.FREE
- sub_cost = await get_subscription_cost(user_id, tier)
- if sub_cost == 0:
- return
++async def get_subscription_price_id(tier: SubscriptionTier) -> str | None:
++ """Return Stripe Price ID for a tier from LaunchDarkly. None = not configured."""
++ flag_map = {
++ SubscriptionTier.PRO: Flag.STRIPE_PRICE_PRO,
++ SubscriptionTier.BUSINESS: Flag.STRIPE_PRICE_BUSINESS,
++ }
++ flag = flag_map.get(tier)
++ if flag is None:
++ return None
++ price_id = await get_feature_flag_value(flag.value, user_id="", default="")
++ return price_id if isinstance(price_id, str) and price_id else None
++
++
++async def create_subscription_checkout(
++ user_id: str,
++ tier: SubscriptionTier,
++ success_url: str,
++ cancel_url: str,
++) -> str:
++ """Create a Stripe Checkout Session for a subscription. Returns the redirect URL."""
++ price_id = await get_subscription_price_id(tier)
++ if not price_id:
++ raise ValueError(f"Subscription not available for tier {tier.value}")
++ customer_id = await get_stripe_customer_id(user_id)
++ session = stripe.checkout.Session.create(
++ customer=customer_id,
++ mode="subscription",
++ line_items=[{"price": price_id, "quantity": 1}],
++ success_url=success_url,
++ cancel_url=cancel_url,
++ subscription_data={"metadata": {"user_id": user_id, "tier": tier.value}},
++ )
++ return session.url or ""
+
- cur_month = datetime.now(UTC).strftime("%Y-%m")
- key = f"SUBSCRIPTION-{user_id}-{cur_month}"
+
- credit = UserCredit()
- try:
- balance, _ = await credit._add_transaction(
- user_id=user_id,
- amount=-sub_cost,
- transaction_type=CreditTransactionType.SUBSCRIPTION,
- transaction_key=key,
- fail_insufficient_credits=False,
- metadata=SafeJson({"reason": f"Monthly {tier.value} subscription"}),
++async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:
++ """Update User.subscriptionTier from a Stripe subscription object."""
++ customer_id = stripe_subscription["customer"]
++ user = await User.prisma().find_first(where={"stripeCustomerId": customer_id})
++ if not user:
++ logger.warning(
++ "sync_subscription_from_stripe: no user for customer %s", customer_id
+ )
- except UniqueViolationError:
- return # already paid this month
-
- auto_top_up = await get_auto_top_up(user_id)
- if auto_top_up.threshold and balance < auto_top_up.threshold:
- try:
- await credit._top_up_credits(
- user_id=user_id,
- amount=auto_top_up.amount,
- key=f"AUTO-TOP-UP-SUB-{user_id}-{cur_month}",
- ceiling_balance=auto_top_up.threshold,
- top_up_type=TopUpType.AUTO,
- )
- except Exception as e:
- logger.error(
- f"Auto top-up failed during subscription deduction for {user_id}: {e}. "
- f"Balance: {balance}, subscription cost: {sub_cost}."
++ return
++ status = stripe_subscription.get("status", "")
++ if status in ("active", "trialing"):
++ price_id = ""
++ items = stripe_subscription.get("items", {}).get("data", [])
++ if items:
++ price_id = items[0].get("price", {}).get("id", "")
++ pro_price = await get_subscription_price_id(SubscriptionTier.PRO)
++ biz_price = await get_subscription_price_id(SubscriptionTier.BUSINESS)
++ if price_id and price_id == pro_price:
++ tier = SubscriptionTier.PRO
++ elif price_id and price_id == biz_price:
++ tier = SubscriptionTier.BUSINESS
++ else:
++ logger.warning(
++ "sync_subscription_from_stripe: unknown price %s for customer %s",
++ price_id,
++ customer_id,
+ )
++ return
++ else:
++ tier = SubscriptionTier.FREE
++ await set_subscription_tier(user.id, tier)
+
+
async def admin_get_user_history(
page: int = 1,
page_size: int = 20,
diff --cc autogpt_platform/backend/backend/data/credit_subscription_test.py
index 9eec8e0619,0000000000..b583e2bc07
mode 100644,000000..100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@@ -1,182 -1,0 +1,155 @@@
+"""
- Tests for subscription tier billing: ensure_subscription_paid idempotency,
- BetaUserCredit grant offset, and tier-change validation.
++Tests for Stripe-based subscription tier billing.
+"""
+
- from unittest.mock import AsyncMock, patch
++from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
- from prisma.enums import CreditTransactionType, SubscriptionTier
- from prisma.models import CreditTransaction, User, UserBalance
++from prisma.enums import SubscriptionTier
++from prisma.models import User
+
+from backend.data.credit import (
- BetaUserCredit,
- ensure_subscription_paid,
++ create_subscription_checkout,
+ set_subscription_tier,
++ sync_subscription_from_stripe,
+)
- from backend.data.user import get_user_by_id
- from backend.util.test import SpinTestServer
-
- SUB_TEST_USER_ID = "sub-test-user"
- SUB_COST = 500 # $5.00 in cents
-
-
- async def setup_sub_test_user(
- tier: SubscriptionTier = SubscriptionTier.FREE,
- balance: int = 1000,
- top_up_amount: int = 0,
- top_up_threshold: int = 0,
- ) -> None:
- await CreditTransaction.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})
- await UserBalance.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})
- await User.prisma().delete_many(where={"id": SUB_TEST_USER_ID})
-
- await User.prisma().create(
- data={
- "id": SUB_TEST_USER_ID,
- "email": f"{SUB_TEST_USER_ID}@example.com",
- "name": "Sub Test User",
- "subscriptionTier": tier,
- "topUpConfig": {
- "amount": top_up_amount,
- "threshold": top_up_threshold,
- },
- }
- )
- await UserBalance.prisma().create(
- data={"userId": SUB_TEST_USER_ID, "balance": balance}
- )
- get_user_by_id.cache_delete(SUB_TEST_USER_ID) # type: ignore[attr-defined]
-
-
- async def cleanup_sub_test_user() -> None:
- await CreditTransaction.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})
- await UserBalance.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})
- await User.prisma().delete_many(where={"id": SUB_TEST_USER_ID})
- get_user_by_id.cache_delete(SUB_TEST_USER_ID) # type: ignore[attr-defined]
-
-
- @pytest.mark.asyncio(loop_scope="session")
- async def test_ensure_subscription_paid_idempotent(server: SpinTestServer):
- """Second call within the same month must not create a second transaction."""
- await setup_sub_test_user(tier=SubscriptionTier.PRO, balance=2000)
+
- with patch(
- "backend.data.credit.get_feature_flag_value",
- new=AsyncMock(return_value=SUB_COST),
- ):
- await ensure_subscription_paid(SUB_TEST_USER_ID)
- await ensure_subscription_paid(SUB_TEST_USER_ID)
-
- txns = await CreditTransaction.prisma().find_many(
- where={"userId": SUB_TEST_USER_ID, "type": CreditTransactionType.SUBSCRIPTION}
- )
- assert len(txns) == 1, f"Expected 1 SUBSCRIPTION txn, got {len(txns)}"
- assert txns[0].amount == -SUB_COST
-
- await cleanup_sub_test_user()
+
-
- @pytest.mark.asyncio(loop_scope="session")
- async def test_ensure_subscription_paid_free_tier_skips(server: SpinTestServer):
- """FREE tier (cost=0) must not create any subscription transaction."""
- await setup_sub_test_user(tier=SubscriptionTier.FREE, balance=500)
-
- with patch(
- "backend.data.credit.get_feature_flag_value",
- new=AsyncMock(return_value=0),
++async def test_set_subscription_tier_updates_db():
++ with (
++ patch(
++ "backend.data.credit.User.prisma",
++ return_value=MagicMock(update=AsyncMock()),
++ ) as mock_prisma,
++ patch("backend.data.credit.get_user_by_id"),
+ ):
- await ensure_subscription_paid(SUB_TEST_USER_ID)
-
- txns = await CreditTransaction.prisma().find_many(
- where={"userId": SUB_TEST_USER_ID, "type": CreditTransactionType.SUBSCRIPTION}
- )
- assert len(txns) == 0
-
- await cleanup_sub_test_user()
-
-
- @pytest.mark.asyncio(loop_scope="session")
- async def test_beta_user_credit_grant_offsets_subscription(server: SpinTestServer):
- """BetaUserCredit grant must equal refill_amount + subscription_cost so the
- monthly subscription deduction does not reduce the user's effective usage budget."""
- from datetime import datetime, timezone
-
- refill = 1000
- beta_credit = BetaUserCredit(refill)
-
- await setup_sub_test_user(tier=SubscriptionTier.PRO, balance=0)
-
- # Force the balance updatedAt to old date so monthly refill triggers
- from datetime import timedelta
-
- old_date = datetime.now(timezone.utc) - timedelta(days=35)
- await UserBalance.prisma().update(
- where={"userId": SUB_TEST_USER_ID},
- data={"updatedAt": old_date, "balance": 0},
- )
- get_user_by_id.cache_delete(SUB_TEST_USER_ID) # type: ignore[attr-defined]
-
- with patch(
- "backend.data.credit.get_feature_flag_value",
- new=AsyncMock(return_value=SUB_COST),
++ await set_subscription_tier("user-1", SubscriptionTier.PRO)
++ mock_prisma.return_value.update.assert_awaited_once_with(
++ where={"id": "user-1"},
++ data={"subscriptionTier": SubscriptionTier.PRO},
++ )
++
++
++async def test_set_subscription_tier_downgrade():
++ with (
++ patch(
++ "backend.data.credit.User.prisma",
++ return_value=MagicMock(update=AsyncMock()),
++ ),
++ patch("backend.data.credit.get_user_by_id"),
+ ):
- balance = await beta_credit.get_credits(SUB_TEST_USER_ID)
-
- # The grant should cover refill + sub cost; balance should be at least refill_amount
- assert balance >= refill, (
- f"After grant+subscription deduction, balance {balance} < refill {refill}. "
- "Beta grant must offset subscription cost."
- )
-
- await cleanup_sub_test_user()
-
++ # Downgrade to FREE should not raise
++ await set_subscription_tier("user-1", SubscriptionTier.FREE)
++
++
++async def test_sync_subscription_from_stripe_active():
++ mock_user = MagicMock(spec=User)
++ mock_user.id = "user-1"
++ stripe_sub = {
++ "customer": "cus_123",
++ "status": "active",
++ "items": {"data": [{"price": {"id": "price_pro_monthly"}}]},
++ }
++ with (
++ patch(
++ "backend.data.credit.User.prisma",
++ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),
++ ),
++ patch(
++ "backend.data.credit.get_subscription_price_id",
++ side_effect=lambda tier: AsyncMock(
++ return_value=(
++ "price_pro_monthly"
++ if tier == SubscriptionTier.PRO
++ else "price_biz_monthly"
++ )
++ )(),
++ ),
++ patch(
++ "backend.data.credit.set_subscription_tier", new_callable=AsyncMock
++ ) as mock_set,
++ ):
++ await sync_subscription_from_stripe(stripe_sub)
++ mock_set.assert_awaited_once_with("user-1", SubscriptionTier.PRO)
++
++
++async def test_sync_subscription_from_stripe_cancelled():
++ mock_user = MagicMock(spec=User)
++ mock_user.id = "user-1"
++ stripe_sub = {
++ "customer": "cus_123",
++ "status": "canceled",
++ "items": {"data": []},
++ }
++ with (
++ patch(
++ "backend.data.credit.User.prisma",
++ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),
++ ),
++ patch(
++ "backend.data.credit.set_subscription_tier", new_callable=AsyncMock
++ ) as mock_set,
++ ):
++ await sync_subscription_from_stripe(stripe_sub)
++ mock_set.assert_awaited_once_with("user-1", SubscriptionTier.FREE)
+
- @pytest.mark.asyncio(loop_scope="session")
- async def test_set_subscription_tier_requires_auto_top_up(server: SpinTestServer):
- """Upgrading to PRO without sufficient auto top-up must raise ValueError."""
- await setup_sub_test_user(
- tier=SubscriptionTier.FREE,
- balance=2000,
- top_up_amount=100, # $1 — less than SUB_COST $5
- top_up_threshold=50,
- )
+
++async def test_sync_subscription_from_stripe_unknown_customer():
++ stripe_sub = {
++ "customer": "cus_unknown",
++ "status": "active",
++ "items": {"data": []},
++ }
+ with patch(
- "backend.data.credit.get_feature_flag_value",
- new=AsyncMock(return_value=SUB_COST),
++ "backend.data.credit.User.prisma",
++ return_value=MagicMock(find_first=AsyncMock(return_value=None)),
+ ):
- with pytest.raises(ValueError, match=r"\$5\.00/mo"):
- await set_subscription_tier(SUB_TEST_USER_ID, SubscriptionTier.PRO)
-
- await cleanup_sub_test_user()
-
++ # Should not raise even if user not found
++ await sync_subscription_from_stripe(stripe_sub)
++
++
++async def test_create_subscription_checkout_returns_url():
++ mock_session = MagicMock()
++ mock_session.url = "https://checkout.stripe.com/pay/cs_test_abc123"
++ with (
++ patch(
++ "backend.data.credit.get_subscription_price_id",
++ new_callable=AsyncMock,
++ return_value="price_pro_monthly",
++ ),
++ patch(
++ "backend.data.credit.get_stripe_customer_id",
++ new_callable=AsyncMock,
++ return_value="cus_123",
++ ),
++ patch("stripe.checkout.Session.create", return_value=mock_session),
++ ):
++ url = await create_subscription_checkout(
++ user_id="user-1",
++ tier=SubscriptionTier.PRO,
++ success_url="https://app.example.com/success",
++ cancel_url="https://app.example.com/cancel",
++ )
++ assert url == "https://checkout.stripe.com/pay/cs_test_abc123"
+
- @pytest.mark.asyncio(loop_scope="session")
- async def test_set_subscription_tier_upgrade_charges_immediately(
- server: SpinTestServer,
- ):
- """Successful upgrade to PRO must immediately create a SUBSCRIPTION transaction."""
- await setup_sub_test_user(
- tier=SubscriptionTier.FREE,
- balance=2000,
- top_up_amount=SUB_COST + 100, # Sufficient
- top_up_threshold=50,
- )
+
- # Patch auto top-up Stripe call so the test does not need Stripe credentials.
++async def test_create_subscription_checkout_no_price_raises():
+ with patch(
- "backend.data.credit.get_feature_flag_value",
- new=AsyncMock(return_value=SUB_COST),
- ), patch(
- "backend.data.credit.UserCredit._top_up_credits",
- new=AsyncMock(),
++ "backend.data.credit.get_subscription_price_id",
++ new_callable=AsyncMock,
++ return_value=None,
+ ):
- await set_subscription_tier(SUB_TEST_USER_ID, SubscriptionTier.PRO)
-
- txns = await CreditTransaction.prisma().find_many(
- where={"userId": SUB_TEST_USER_ID, "type": CreditTransactionType.SUBSCRIPTION}
- )
- assert len(txns) == 1, f"Expected 1 SUBSCRIPTION txn on upgrade, got {len(txns)}"
-
- await cleanup_sub_test_user()
++ with pytest.raises(ValueError, match="not available"):
++ await create_subscription_checkout(
++ user_id="user-1",
++ tier=SubscriptionTier.PRO,
++ success_url="https://app.example.com/success",
++ cancel_url="https://app.example.com/cancel",
++ )
diff --cc autogpt_platform/backend/backend/util/feature_flag.py
index 3777a76985,47ad704fc3..7c7f06ea87
--- a/autogpt_platform/backend/backend/util/feature_flag.py
+++ b/autogpt_platform/backend/backend/util/feature_flag.py
@@@ -41,8 -43,6 +43,10 @@@ class Flag(str, Enum)
COPILOT_SDK = "copilot-sdk"
COPILOT_DAILY_TOKEN_LIMIT = "copilot-daily-token-limit"
COPILOT_WEEKLY_TOKEN_LIMIT = "copilot-weekly-token-limit"
+ SUBSCRIPTION_COST_PRO = "subscription-cost-pro"
+ SUBSCRIPTION_COST_BUSINESS = "subscription-cost-business"
++ STRIPE_PRICE_PRO = "stripe-price-id-pro"
++ STRIPE_PRICE_BUSINESS = "stripe-price-id-business"
def is_configured() -> bool:
diff --cc autogpt_platform/backend/pyrightconfig.json
index 0000000000,0000000000..2241b990d2
new file mode 100644
--- /dev/null
+++ b/autogpt_platform/backend/pyrightconfig.json
@@@ -1,0 -1,0 +1,30 @@@
++{
++ "pythonVersion": "3.12",
++ "venvPath": ".",
++ "venv": ".venv",
++ "include": ["backend"],
++ "ignore": [
++ "backend/**/*_test.py",
++ "backend/**/*conftest.py",
++ "backend/**/conftest.py",
++ "backend/**/_test_data.py",
++ "backend/**/*test_data*.py",
++ "backend/api/features/library/_add_to_library.py",
++ "backend/api/features/library/db.py",
++ "backend/api/features/store/db.py",
++ "backend/blocks/sql_query_helpers.py",
++ "backend/blocks/stagehand/blocks.py",
++ "backend/cli/oauth_tool.py",
++ "backend/copilot/db.py",
++ "backend/copilot/rate_limit.py",
++ "backend/data/auth/api_key.py",
++ "backend/data/auth/oauth.py",
++ "backend/data/execution.py",
++ "backend/data/graph.py",
++ "backend/data/human_review.py",
++ "backend/data/onboarding.py",
++ "backend/data/understanding.py",
++ "backend/data/workspace.py",
++ "backend/sdk/__init__.py"
++ ]
++}
diff --cc autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts
index 0000000000,eb20732f24..77c031b211
mode 000000,100644..100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts
@@@ -1,0 -1,318 +1,318 @@@
+ /**
+ * React artifact preview — security model
+ *
+ * AI-generated TSX source is transpiled (TypeScript) and executed inside a
+ * sandboxed iframe (`sandbox="allow-scripts"` without `allow-same-origin`).
+ *
+ * What's isolated:
+ * - No access to parent page cookies, localStorage, or sessionStorage
+ * - No form submissions or popups (no allow-forms / allow-popups)
+ * - Treated as a unique opaque origin by the browser
+ *
+ * What's allowed inside the iframe:
+ * - Inline script execution (needed to render React components)
+ * - `new Function()` is used to evaluate the compiled code (eval-equivalent)
+ * - Full DOM access within the iframe
+ * - Network requests via fetch/XHR (allowed — only artifact content is
+ * visible inside the sandbox, no secret data to exfiltrate)
+ *
+ * React is loaded from unpkg with pinned version and SRI integrity hashes.
+ */
+
+ import { TAILWIND_CDN_URL } from "@/lib/iframe-sandbox-csp";
+
+ export { transpileReactArtifactSource } from "./transpileReactArtifact";
+
+ export function escapeHtml(value: string): string {
+ return value
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;")
+ .replaceAll("'", "&#39;");
+ }
+
+ /** Minimal CSS reset for React artifact previews.
+ *
+ * Previously this copied ALL host stylesheets (200KB+ Tailwind) into every
+ * preview iframe. Now we provide a self-contained reset and let artifacts
+ * declare their own styles. This avoids tight coupling between the app's CSS
+ * and artifact rendering, and keeps the srcdoc size small.
+ */
+ export function collectPreviewStyles() {
+ return `<style>
+ *, *::before, *::after { box-sizing: border-box; }
+ body { margin: 0; font-family: ui-sans-serif, system-ui, sans-serif; }
+ </style>`;
+ }
+
+ export function buildReactArtifactSrcDoc(
+ compiledCode: string,
+ title: string,
+ stylesMarkup: string,
+ ) {
+ const safeTitle = escapeHtml(title);
+ const runtime = JSON.stringify(compiledCode).replace(/</g, "\\u003c");
+
+ return `<!doctype html>
+ <html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>${safeTitle}</title>
+ ${stylesMarkup}
+ <style>
+ html, body, #root {
+ height: 100%;
+ margin: 0;
+ }
+
+ body {
+ background:
+ radial-gradient(circle at top, rgba(148, 163, 184, 0.18), transparent 35%),
+ #f8fafc;
+ color: #18181b;
+ font-family: ui-sans-serif, system-ui, sans-serif;
+ }
+
+ #root {
+ box-sizing: border-box;
+ min-height: 100%;
+ isolation: isolate;
+ }
+
+ #error {
+ display: none;
+ box-sizing: border-box;
+ margin: 24px;
+ padding: 16px;
+ border: 1px solid #fecaca;
+ border-radius: 16px;
+ background: #fff1f2;
+ color: #991b1b;
+ font-family: ui-monospace, SFMono-Regular, monospace;
+ white-space: pre-wrap;
+ }
+ </style>
+ <script src="${TAILWIND_CDN_URL}"></script>
- <script crossorigin="anonymous" src="https://unpkg.com/[email protected]/umd/react.production.min.js" integrity="sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z"></script>
- <script crossorigin="anonymous" src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" integrity="sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1"></script>
++ <script crossorigin="anonymous" src="https://unpkg.com/[email protected]/umd/react.production.min.js" integrity="sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z"></script><!-- pragma: allowlist secret -->
++ <script crossorigin="anonymous" src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" integrity="sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1"></script><!-- pragma: allowlist secret -->
+ </head>
+ <body>
+ <div id="root"></div>
+ <div id="error"></div>
+ <script>
+ (function () {
+ const compiledCode = ${runtime};
+ const rootElement = document.getElementById("root");
+ const errorElement = document.getElementById("error");
+
+ function showError(error) {
+ rootElement.style.display = "none";
+ errorElement.style.display = "block";
+ errorElement.textContent =
+ error instanceof Error && error.stack
+ ? error.stack
+ : error instanceof Error
+ ? error.message
+ : String(error);
+ }
+
+ function getModuleExports(module, exports) {
+ return {
+ ...exports,
+ ...(typeof module.exports === "object" ? module.exports : {}),
+ };
+ }
+
+ function getRenderableCandidate(moduleExports) {
+ if (typeof moduleExports.default === "function") {
+ return moduleExports.default;
+ }
+
+ if (typeof moduleExports.App === "function") {
+ return moduleExports.App;
+ }
+
+ const namedCandidate = Object.entries(moduleExports).find(
+ ([name, value]) =>
+ name !== "default" &&
+ !name.endsWith("Provider") &&
+ /^[A-Z]/.test(name) &&
+ typeof value === "function",
+ );
+
+ if (namedCandidate) {
+ return namedCandidate[1];
+ }
+
+ if (typeof App !== "undefined" && typeof App === "function") {
+ return App;
+ }
+
+ throw new Error(
+ "No renderable component found. Export a default component, export App, or export a named component.",
+ );
+ }
+
+ function wrapWithProviders(Component, moduleExports) {
+ const providers = Object.entries(moduleExports)
+ .filter(
+ ([name, value]) =>
+ name !== "default" &&
+ name.endsWith("Provider") &&
+ typeof value === "function",
+ )
+ .map(([, value]) => value);
+
+ if (providers.length === 0) {
+ return Component;
+ }
+
+ return function WrappedArtifactPreview() {
+ let tree = React.createElement(Component);
+
+ for (let i = providers.length - 1; i >= 0; i -= 1) {
+ tree = React.createElement(providers[i], null, tree);
+ }
+
+ return tree;
+ };
+ }
+
+ function require(name) {
+ if (name === "react") {
+ return React;
+ }
+
+ if (name === "react-dom") {
+ return ReactDOM;
+ }
+
+ if (name === "react-dom/client") {
+ return { createRoot: ReactDOM.createRoot };
+ }
+
+ if (name === "react/jsx-runtime" || name === "react/jsx-dev-runtime") {
+ // jsx/jsxs signature: (type, config, key) where config.children is
+ // the children (single value for jsx, array for jsxs). createElement
+ // wants variadic children, so we have to unpack config.children.
+ function jsx(type, config, key) {
+ var props = {};
+ if (config != null) {
+ for (var k in config) {
+ if (k !== "children") props[k] = config[k];
+ }
+ }
+ if (key !== undefined) props.key = key;
+ var children =
+ config != null && "children" in config ? config.children : undefined;
+ if (Array.isArray(children)) {
+ return React.createElement.apply(
+ null,
+ [type, props].concat(children),
+ );
+ }
+ return children === undefined
+ ? React.createElement(type, props)
+ : React.createElement(type, props, children);
+ }
+ return { Fragment: React.Fragment, jsx: jsx, jsxs: jsx };
+ }
+
+ throw new Error("Unsupported import in artifact preview: " + name);
+ }
+
+ class PreviewErrorBoundary extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = { error: null };
+ }
+
+ static getDerivedStateFromError(error) {
+ return { error };
+ }
+
+ render() {
+ if (this.state.error) {
+ return React.createElement(
+ "div",
+ {
+ style: {
+ margin: "24px",
+ padding: "16px",
+ border: "1px solid #fecaca",
+ borderRadius: "16px",
+ background: "#fff1f2",
+ color: "#991b1b",
+ fontFamily: "ui-monospace, SFMono-Regular, monospace",
+ whiteSpace: "pre-wrap",
+ },
+ },
+ this.state.error.stack || this.state.error.message || String(this.state.error),
+ );
+ }
+
+ return this.props.children;
+ }
+ }
+
+ try {
+ const exports = {};
+ const module = { exports };
+ const factory = new Function(
+ "React",
+ "ReactDOM",
+ "module",
+ "exports",
+ "require",
+ \`
+ "use strict";
+ \${compiledCode}
+ return {
+ module,
+ exports,
+ app: typeof App !== "undefined" ? App : undefined,
+ };
+ \`,
+ );
+
+ const executionResult = factory(
+ React,
+ ReactDOM,
+ module,
+ exports,
+ require,
+ );
+ const moduleExports = getModuleExports(
+ executionResult.module,
+ executionResult.exports,
+ );
+
+ if (
+ executionResult.app &&
+ typeof moduleExports.App !== "function"
+ ) {
+ moduleExports.App = executionResult.app;
+ }
+
+ const Component = wrapWithProviders(
+ getRenderableCandidate(moduleExports),
+ moduleExports,
+ );
+
+ ReactDOM.createRoot(rootElement).render(
+ React.createElement(
+ PreviewErrorBoundary,
+ null,
+ React.createElement(Component),
+ ),
+ );
+ } catch (error) {
+ showError(error);
+ }
+ })();
+ </script>
+ </body>
+ </html>`;
+ }
diff --cc autogpt_platform/frontend/src/app/api/openapi.json
index 2a32a20b1a,3f013c4509..3589e7ccc1
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@@ -1785,68 -2171,6 +2171,68 @@@
}
}
},
+ "/api/credits/subscription": {
+ "get": {
+ "tags": ["v1", "credits"],
+ "summary": "Get subscription tier, current cost, and all tier costs",
+ "operationId": "getSubscriptionStatus",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SubscriptionStatusResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ },
+ "post": {
+ "tags": ["v1", "credits"],
- "summary": "Upgrade or downgrade subscription tier",
++ "summary": "Start a Stripe Checkout session to upgrade subscription tier",
+ "operationId": "updateSubscriptionTier",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SubscriptionTierRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
- "$ref": "#/components/schemas/SubscriptionStatusResponse"
++ "$ref": "#/components/schemas/SubscriptionCheckoutResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/credits/transactions": {
"get": {
"tags": ["v1", "credits"],
@@@ -12901,26 -13621,12 +13690,50 @@@
"enum": ["DRAFT", "PENDING", "APPROVED", "REJECTED"],
"title": "SubmissionStatus"
},
++ "SubscriptionCheckoutResponse": {
++ "properties": { "url": { "type": "string", "title": "Url" } },
++ "type": "object",
++ "required": ["url"],
++ "title": "SubscriptionCheckoutResponse"
++ },
+ "SubscriptionStatusResponse": {
+ "properties": {
+ "tier": { "type": "string", "title": "Tier" },
+ "monthly_cost": { "type": "integer", "title": "Monthly Cost" },
+ "tier_costs": {
+ "additionalProperties": { "type": "integer" },
+ "type": "object",
+ "title": "Tier Costs"
+ }
+ },
+ "type": "object",
+ "required": ["tier", "monthly_cost", "tier_costs"],
+ "title": "SubscriptionStatusResponse"
+ },
+ "SubscriptionTier": {
+ "type": "string",
+ "enum": ["FREE", "PRO", "BUSINESS", "ENTERPRISE"],
+ "title": "SubscriptionTier",
+ "description": "Subscription tiers with increasing token allowances.\n\nMirrors the ``SubscriptionTier`` enum in ``schema.prisma``.\nOnce ``prisma generate`` is run, this can be replaced with::\n\n from prisma.enums import SubscriptionTier"
+ },
+ "SubscriptionTierRequest": {
- "properties": { "tier": { "type": "string", "title": "Tier" } },
++ "properties": {
++ "tier": { "type": "string", "title": "Tier" },
++ "success_url": {
++ "type": "string",
++ "title": "Success Url",
++ "default": ""
++ },
++ "cancel_url": {
++ "type": "string",
++ "title": "Cancel Url",
++ "default": ""
++ }
++ },
+ "type": "object",
+ "required": ["tier"],
+ "title": "SubscriptionTierRequest"
+ },
"SuggestedGoalResponse": {
"properties": {
"type": {