AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): subscription credit grants + paywall gate + dialog UX + cross-pod cache (#12933)
Zamil Majdyfe3d6fb11836
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.pyindex e353a2e777..f9a4d954b1 100644--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py@@ -245,11 +245,12 @@ def test_get_subscription_status_tier_multipliers_ld_override(assert "BUSINESS" not in data["tier_multipliers"]-def test_get_subscription_status_defaults_to_basic(+def test_get_subscription_status_defaults_to_no_tier(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,) -> None:- """When all LD price IDs are unset, tier_costs is empty and the caller sees cost=0."""+ """When user has no subscription_tier, defaults to NO_TIER (the explicit+ no-active-subscription state)."""mock_user = Mock()mock_user.subscription_tier = None@@ -273,7 +274,7 @@ def test_get_subscription_status_defaults_to_basic(assert response.status_code == 200data = response.json()- assert data["tier"] == SubscriptionTier.BASIC.value+ assert data["tier"] == SubscriptionTier.NO_TIER.valueassert data["monthly_cost"] == 0assert data["tier_costs"] == {}assert data["proration_credit_cents"] == 0@@ -326,11 +327,11 @@ def test_get_subscription_status_stripe_error_falls_back_to_zero(assert data["tier_costs"]["PRO"] == 0-def test_update_subscription_tier_basic_no_payment(+def test_update_subscription_tier_no_tier_no_payment(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,) -> None:- """POST /credits/subscription to BASIC tier when payment disabled skips Stripe."""+ """POST /credits/subscription to NO_TIER (cancel) when payment disabled skips Stripe."""mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO@@ -351,7 +352,7 @@ def test_update_subscription_tier_basic_no_payment(new_callable=AsyncMock,)- response = client.post("/credits/subscription", json={"tier": "BASIC"})+ response = client.post("/credits/subscription", json={"tier": "NO_TIER"})assert response.status_code == 200assert response.json()["url"] == ""@@ -404,6 +405,11 @@ def test_update_subscription_tier_paid_requires_urls("backend.api.features.v1.is_feature_enabled",side_effect=mock_feature_enabled,)+ mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )response = client.post("/credits/subscription", json={"tier": "PRO"})@@ -430,6 +436,11 @@ def test_update_subscription_tier_creates_checkout("backend.api.features.v1.is_feature_enabled",side_effect=mock_feature_enabled,)+ mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )mocker.patch("backend.api.features.v1.create_subscription_checkout",new_callable=AsyncMock,@@ -469,6 +480,11 @@ def test_update_subscription_tier_rejects_open_redirect("backend.api.features.v1.is_feature_enabled",side_effect=mock_feature_enabled,)+ mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )checkout_mock = mocker.patch("backend.api.features.v1.create_subscription_checkout",new_callable=AsyncMock,@@ -649,14 +665,14 @@ def test_update_subscription_tier_same_tier_stripe_error_returns_502(assert "contact support" in response.json()["detail"].lower()-def test_update_subscription_tier_basic_with_payment_schedules_cancel_and_does_not_update_db(+def test_update_subscription_tier_no_tier_with_payment_schedules_cancel_and_does_not_update_db(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,) -> None:- """Downgrading to BASIC schedules Stripe cancellation at period end.+ """Cancelling to NO_TIER schedules Stripe cancellation at period end.The DB tier must NOT be updated immediately — the customer.subscription.deleted- webhook fires at period end and downgrades to BASIC then.+ webhook fires at period end and downgrades to NO_TIER then."""mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO@@ -682,18 +698,18 @@ def test_update_subscription_tier_basic_with_payment_schedules_cancel_and_does_nside_effect=mock_feature_enabled,)- response = client.post("/credits/subscription", json={"tier": "BASIC"})+ response = client.post("/credits/subscription", json={"tier": "NO_TIER"})assert response.status_code == 200mock_cancel.assert_awaited_once()mock_set_tier.assert_not_awaited()-def test_update_subscription_tier_basic_cancel_failure_returns_502(+def test_update_subscription_tier_no_tier_cancel_failure_returns_502(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,) -> None:- """Downgrading to BASIC returns 502 with a generic error (no Stripe detail leakage)."""+ """Cancelling to NO_TIER returns 502 with a generic error (no Stripe detail leakage)."""mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO@@ -716,7 +732,7 @@ def test_update_subscription_tier_basic_cancel_failure_returns_502(side_effect=mock_feature_enabled,)- response = client.post("/credits/subscription", json={"tier": "BASIC"})+ response = client.post("/credits/subscription", json={"tier": "NO_TIER"})assert response.status_code == 502detail = response.json()["detail"]@@ -921,29 +937,20 @@ def test_update_subscription_tier_max_checkout(checkout_mock.assert_not_awaited()-def test_update_subscription_tier_admin_granted_paid_to_paid_updates_db_directly(+def test_update_subscription_tier_no_active_sub_falls_through_to_checkout(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,) -> None:- """Admin-granted paid tier users are NOT sent to Stripe checkout for paid→paid changes.+ """Any tier change from a user with no active Stripe sub goes through Checkout.- When modify_stripe_subscription_for_tier returns False (no Stripe subscription- found — admin-granted tier), the endpoint must update the DB tier directly and- return 200 with url="", rather than falling through to Checkout Session creation.+ Admin-granted users (no Stripe sub yet) and never-paid users follow the+ exact same path: modify returns False → Checkout to set up payment. The+ endpoint has no admin-specific branch — admin tier grants happen out-of-band+ via the admin portal, not this user-facing route."""mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO- async def price_id_with_business(tier: SubscriptionTier) -> str | None:- return {- **_DEFAULT_TIER_PRICES,- SubscriptionTier.BUSINESS: "price_business",- }.get(tier)-- mocker.patch(- "backend.api.features.v1.get_subscription_price_id",- side_effect=price_id_with_business,- )mocker.patch("backend.api.features.v1.get_user_by_id",new_callable=AsyncMock,@@ -954,7 +961,6 @@ def test_update_subscription_tier_admin_granted_paid_to_paid_updates_db_directlynew_callable=AsyncMock,return_value=True,)- # Return False = no Stripe subscription (admin-granted tier)modify_mock = mocker.patch("backend.api.features.v1.modify_stripe_subscription_for_tier",new_callable=AsyncMock,@@ -967,23 +973,24 @@ def test_update_subscription_tier_admin_granted_paid_to_paid_updates_db_directlycheckout_mock = mocker.patch("backend.api.features.v1.create_subscription_checkout",new_callable=AsyncMock,+ return_value="https://checkout.stripe.com/pay/cs_test_no_sub",)response = client.post("/credits/subscription",json={- "tier": "BUSINESS",+ "tier": "MAX","success_url": f"{TEST_FRONTEND_ORIGIN}/success","cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",},)assert response.status_code == 200- assert response.json()["url"] == ""- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.BUSINESS)- # DB tier updated directly — no Stripe Checkout Session created- set_tier_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.BUSINESS)- checkout_mock.assert_not_awaited()+ assert response.json()["url"] == "https://checkout.stripe.com/pay/cs_test_no_sub"+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX)+ # No DB-flip — payment must be collected via Checkout regardless of direction.+ set_tier_mock.assert_not_awaited()+ checkout_mock.assert_awaited_once()def test_update_subscription_tier_priced_basic_no_sub_falls_through_to_checkout(@@ -1154,14 +1161,14 @@ def test_update_subscription_tier_paid_to_paid_stripe_error_returns_502(assert response.status_code == 502-def test_update_subscription_tier_basic_no_stripe_subscription(+def test_update_subscription_tier_no_tier_no_stripe_subscription(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,) -> None:- """Downgrading to BASIC when no Stripe subscription exists updates DB tier directly.+ """Cancelling to NO_TIER when no Stripe subscription exists updates DB tier directly.Admin-granted paid tiers have no associated Stripe subscription. When such a- user requests a self-service downgrade, cancel_stripe_subscription returns False+ user requests a self-service cancel, cancel_stripe_subscription returns False(nothing to cancel), so the endpoint must immediately call set_subscription_tierrather than waiting for a webhook that will never arrive."""@@ -1189,13 +1196,13 @@ def test_update_subscription_tier_basic_no_stripe_subscription(new_callable=AsyncMock,)- response = client.post("/credits/subscription", json={"tier": "BASIC"})+ response = client.post("/credits/subscription", json={"tier": "NO_TIER"})assert response.status_code == 200assert response.json()["url"] == ""cancel_mock.assert_awaited_once_with(TEST_USER_ID)# DB tier must be updated immediately — no webhook will fire for a missing sub- set_tier_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.BASIC)+ set_tier_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.NO_TIER)def test_get_subscription_status_includes_pending_tier(diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex e47b05fa3d..396b39f39f 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -57,12 +57,14 @@ from backend.data.credit import (UserCredit,cancel_stripe_subscription,create_subscription_checkout,+ get_active_subscription_period_end,get_auto_top_up,get_pending_subscription_change,get_proration_credit_cents,get_subscription_price_id,get_user_credit_model,handle_subscription_payment_failure,+ handle_subscription_payment_success,modify_stripe_subscription_for_tier,release_pending_subscription_schedule,set_auto_top_up,@@ -700,13 +702,13 @@ async def get_user_auto_top_up(class SubscriptionTierRequest(BaseModel):- tier: Literal["BASIC", "PRO", "MAX", "BUSINESS"]+ tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]success_url: str = ""cancel_url: str = ""class SubscriptionStatusResponse(BaseModel):- tier: Literal["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]+ tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]monthly_cost: int # amount in cents (Stripe convention)tier_costs: dict[str, int] # tier name -> amount in centstier_multipliers: dict[str, float] = Field(@@ -719,7 +721,23 @@ class SubscriptionStatusResponse(BaseModel):),)proration_credit_cents: int # unused portion of current sub to convert on upgrade- pending_tier: Optional[Literal["BASIC", "PRO", "MAX", "BUSINESS"]] = None+ has_active_stripe_subscription: bool = Field(+ default=False,+ description=(+ "True when the user has an active/trialing Stripe subscription. The"+ " frontend uses this to branch upgrade UX: modify-in-place + saved-card"+ " auto-charge when True, redirect to Stripe Checkout when False."+ ),+ )+ current_period_end: Optional[int] = Field(+ default=None,+ description=(+ "Unix timestamp of the active subscription's current_period_end. Used"+ " to show the date Stripe will issue the next invoice (with prorated"+ " upgrade charges, if any). None when no active sub."+ ),+ )+ pending_tier: Optional[Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]] = Nonepending_tier_effective_at: Optional[datetime] = Noneurl: str = Field(default="",@@ -804,8 +822,11 @@ async def get_subscription_status(user_id: Annotated[str, Security(get_user_id)],) -> SubscriptionStatusResponse:user = await get_user_by_id(user_id)- tier = user.subscription_tier or SubscriptionTier.BASIC+ tier = user.subscription_tier or SubscriptionTier.NO_TIER+ # Tiers that *can* have a Stripe price configured (and therefore appear+ # in the tier picker if the LD flag exposes a price-id). NO_TIER is not+ # priceable — it's the implicit "no active subscription" state.priceable_tiers = [SubscriptionTier.BASIC,SubscriptionTier.PRO,@@ -839,7 +860,10 @@ async def get_subscription_status(}current_monthly_cost = tier_costs.get(tier.value, 0)- proration_credit = await get_proration_credit_cents(user_id, current_monthly_cost)+ proration_credit, current_period_end = await asyncio.gather(+ get_proration_credit_cents(user_id, current_monthly_cost),+ get_active_subscription_period_end(user_id),+ )try:pending = await get_pending_subscription_change(user_id)@@ -861,10 +885,13 @@ async def get_subscription_status(tier_costs=tier_costs,tier_multipliers=tier_multipliers,proration_credit_cents=proration_credit,+ has_active_stripe_subscription=current_period_end is not None,+ current_period_end=current_period_end,)if pending is not None:pending_tier_enum, pending_effective_at = pendingif pending_tier_enum in (+ SubscriptionTier.NO_TIER,SubscriptionTier.BASIC,SubscriptionTier.PRO,SubscriptionTier.MAX,@@ -892,7 +919,7 @@ async def update_subscription_tier(# ENTERPRISE tier is admin-managed — block self-service changes from ENTERPRISE users.user = await get_user_by_id(user_id)if (- user.subscription_tier or SubscriptionTier.BASIC+ user.subscription_tier or SubscriptionTier.NO_TIER) == SubscriptionTier.ENTERPRISE:raise HTTPException(status_code=403,@@ -904,7 +931,7 @@ async def update_subscription_tier(# collapsed behaviour that replaces the old /credits/subscription/cancel-pending# route. Safe when no pending change exists: release_pending_subscription_schedule# returns False and we simply return the current status.- if (user.subscription_tier or SubscriptionTier.BASIC) == tier:+ if (user.subscription_tier or SubscriptionTier.NO_TIER) == tier:try:await release_pending_subscription_schedule(user_id)except stripe.StripeError as e:@@ -926,18 +953,14 @@ async def update_subscription_tier(Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False)- current_tier = user.subscription_tier or SubscriptionTier.BASIC- target_price_id, current_tier_price_id = await asyncio.gather(- get_subscription_price_id(tier),- get_subscription_price_id(current_tier),- )+ target_price_id = await get_subscription_price_id(tier)- # Legacy cancel: target BASIC + stripe-price-id-basic unset. Schedule Stripe- # cancellation at period end; cancel_at_period_end=True lets the webhook flip- # the DB tier. No active sub (admin-granted) or payment disabled → DB flip.- # Once stripe-price-id-basic is configured, BASIC becomes a real sub and falls- # through to the modify/checkout flow below.- if tier == SubscriptionTier.BASIC and target_price_id is None:+ # Cancel: target NO_TIER. Schedule Stripe cancellation at period end;+ # cancel_at_period_end=True lets the webhook flip the DB tier. No active+ # sub (admin-granted or never-paid) or payment disabled → DB flip.+ # NO_TIER is never priceable, so this branch always fires for cancel+ # requests regardless of LD config.+ if tier == SubscriptionTier.NO_TIER:if payment_enabled:try:had_subscription = await cancel_stripe_subscription(user_id)@@ -973,32 +996,24 @@ async def update_subscription_tier(detail=f"Subscription not available for tier {tier.value}",)- # User has an active Stripe subscription (current tier has an LD price):- # modify it in-place. modify_stripe_subscription_for_tier returns False when no- # active sub exists — that's only a "DB-only flip is OK" signal for admin-granted- # paid tiers (PRO/BUSINESS with no Stripe record). Priced-BASIC users without a- # sub must still go through Checkout so they set up payment.- if current_tier_price_id is not None:- try:- modified = await modify_stripe_subscription_for_tier(user_id, tier)- if modified:- return await get_subscription_status(user_id)- if current_tier != SubscriptionTier.BASIC:- await set_subscription_tier(user_id, tier)- return await get_subscription_status(user_id)- except ValueError as e:- raise HTTPException(status_code=422, detail=str(e))- except stripe.StripeError as e:- logger.exception(- "Stripe error modifying subscription for user %s: %s", user_id, e- )- raise HTTPException(- status_code=502,- detail=(- "Unable to update your subscription right now. "- "Please try again or contact support."- ),- )+ # Modify in place if there's a sub; else fall through to Checkout below.+ try:+ modified = await modify_stripe_subscription_for_tier(user_id, tier)+ if modified:+ return await get_subscription_status(user_id)+ except ValueError as e:+ raise HTTPException(status_code=422, detail=str(e))+ except stripe.StripeError as e:+ logger.exception(+ "Stripe error modifying subscription for user %s: %s", user_id, e+ )+ raise HTTPException(+ status_code=502,+ detail=(+ "Unable to update your subscription right now. "+ "Please try again or contact support."+ ),+ )# No active Stripe subscription → create Stripe Checkout Session.if not request.success_url or not request.cancel_url:@@ -1134,6 +1149,9 @@ async def stripe_webhook(request: Request):):await sync_subscription_schedule_from_stripe(data_object)+ if event_type == "invoice.payment_succeeded":+ await handle_subscription_payment_success(data_object)+if event_type == "invoice.payment_failed":await handle_subscription_payment_failure(data_object)diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.pyindex 33f9809d34..ca99346725 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py@@ -72,6 +72,7 @@ class SubscriptionTier(str, Enum):from prisma.enums import SubscriptionTier"""+ NO_TIER = "NO_TIER"BASIC = "BASIC"PRO = "PRO"MAX = "MAX"@@ -87,6 +88,14 @@ class SubscriptionTier(str, Enum):# eventual ``int(base * multiplier)`` in ``get_global_rate_limits`` keeps the# downstream microdollar math integer._DEFAULT_TIER_MULTIPLIERS: dict[SubscriptionTier, float] = {+ # NO_TIER is the explicit "no active Stripe subscription" state —+ # multiplier 0.0 collapses the per-period limit to int(base * 0) = 0, so+ # all rate-limited routes (CoPilot chat, AutoPilot) refuse with 429+ # before any business logic runs. This is the backend half of the+ # paywall (the frontend modal nudges UI users; this gate enforces+ # server-side regardless of client). BASIC stays as a future paid-tier+ # option; for now it falls back to the same baseline as paid tiers.+ SubscriptionTier.NO_TIER: 0.0,SubscriptionTier.BASIC: 1.0,SubscriptionTier.PRO: 5.0,SubscriptionTier.MAX: 20.0,@@ -99,7 +108,7 @@ _DEFAULT_TIER_MULTIPLIERS: dict[SubscriptionTier, float] = {# ``get_tier_multipliers`` so LD overrides are honoured.TIER_MULTIPLIERS = _DEFAULT_TIER_MULTIPLIERS-DEFAULT_TIER = SubscriptionTier.BASIC+DEFAULT_TIER = SubscriptionTier.NO_TIER@cached(ttl_seconds=60, maxsize=1, cache_none=False)@@ -788,6 +797,16 @@ async def get_global_rate_limits(tier = await get_user_tier(user_id)multipliers = await get_tier_multipliers()multiplier = multipliers.get(tier.value, 1.0)+ # NO_TIER's 0.0 multiplier is the backend half of the paywall — it+ # collapses limits to zero so unsubscribed users can't run the chat.+ # Only enforce that gate when the platform-payment flag is on for this+ # user; in the beta cohort (flag off) NO_TIER falls back to BASIC's+ # baseline so the e2e suite and beta testers retain access.+ if tier == SubscriptionTier.NO_TIER:+ from backend.util.feature_flag import Flag, is_feature_enabled++ if not await is_feature_enabled(Flag.ENABLE_PLATFORM_PAYMENT, user_id):+ multiplier = multipliers.get(SubscriptionTier.BASIC.value, 1.0)if multiplier != 1.0:# Cast back to int to preserve the microdollar integer contract# downstream — fractional LD multipliers (e.g. 8.5×) truncate at thediff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.pyindex 7cd9b2ec5f..5bfdf80eef 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py@@ -359,6 +359,9 @@ class TestSubscriptionTier:def test_tier_multipliers(self):# Float-typed so LD-provided fractional multipliers compose naturally;# equality against int literals still holds for the whole defaults.+ # NO_TIER is 0.0 — explicit "no active subscription" state;+ # rate-limited routes refuse with 429 (backend half of the paywall).+ assert TIER_MULTIPLIERS[SubscriptionTier.NO_TIER] == 0.0assert TIER_MULTIPLIERS[SubscriptionTier.BASIC] == 1.0assert TIER_MULTIPLIERS[SubscriptionTier.PRO] == 5.0assert TIER_MULTIPLIERS[SubscriptionTier.MAX] == 20.0@@ -366,8 +369,8 @@ class TestSubscriptionTier:assert TIER_MULTIPLIERS[SubscriptionTier.ENTERPRISE] == 60.0assert TIER_MULTIPLIERS is _DEFAULT_TIER_MULTIPLIERS- def test_default_tier_is_basic(self):- assert DEFAULT_TIER == SubscriptionTier.BASIC+ def test_default_tier_is_no_tier(self):+ assert DEFAULT_TIER == SubscriptionTier.NO_TIERdef test_usage_status_includes_tier(self):now = datetime.now(UTC)@@ -375,7 +378,7 @@ class TestSubscriptionTier:daily=UsageWindow(used=0, limit=100, resets_at=now + timedelta(hours=1)),weekly=UsageWindow(used=0, limit=500, resets_at=now + timedelta(days=1)),)- assert status.tier == SubscriptionTier.BASIC+ assert status.tier == SubscriptionTier.NO_TIERdef test_usage_status_with_custom_tier(self):now = datetime.now(UTC)diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex 2750233ff4..b9241cd9cc 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -949,24 +949,45 @@ class UserCredit(UserCreditBase):f"Top up amount must be at least 500 credits and multiple of 100 but is {amount}")- # Create checkout session- # https://docs.stripe.com/checkout/quickstart?client=react- # unit_amount param is always in the smallest currency unit (so cents for usd)- # which is equal to amount of credits- checkout_session = stripe.checkout.Session.create(- customer=await get_stripe_customer_id(user_id),- line_items=[+ # Resolve the Stripe Product ID from LD; when unset (default), keep the+ # legacy inline product_data path (Stripe creates an ephemeral product+ # per Checkout). When set, reference the canonical Product so all+ # top-ups group under one entity in Stripe Dashboard reporting; the+ # amount stays dynamic via unit_amount.+ topup_product_id = await get_feature_flag_value(+ Flag.STRIPE_PRODUCT_ID_TOPUP.value, user_id, default=None+ )+ line_items: list[stripe.checkout.Session.CreateParamsLineItem] = (+ [{"price_data": {"currency": "usd",- "product_data": {- "name": "AutoGPT Platform Credits",- },+ "product": topup_product_id,"unit_amount": amount,},"quantity": 1,}- ],+ ]+ if isinstance(topup_product_id, str) and topup_product_id+ else [+ {+ "price_data": {+ "currency": "usd",+ "product_data": {"name": "AutoGPT Platform Credits"},+ "unit_amount": amount,+ },+ "quantity": 1,+ }+ ]+ )++ # Create checkout session+ # https://docs.stripe.com/checkout/quickstart?client=react+ # unit_amount param is always in the smallest currency unit (so cents for usd)+ # which is equal to amount of credits+ checkout_session = stripe.checkout.Session.create(+ customer=await get_stripe_customer_id(user_id),+ line_items=line_items,mode="payment",ui_mode="hosted",payment_intent_data={"setup_future_usage": "off_session"},@@ -1442,6 +1463,7 @@ async def get_proration_credit_cents(user_id: str, monthly_cost_cents: int) -> i# (move right) from downgrades (move left); ENTERPRISE is admin-managed and# never reached via self-service flows._TIER_ORDER: tuple[SubscriptionTier, ...] = (+ SubscriptionTier.NO_TIER,SubscriptionTier.BASIC,SubscriptionTier.PRO,SubscriptionTier.MAX,@@ -1479,6 +1501,30 @@ async def _get_active_subscription(customer_id: str) -> stripe.Subscription | Noreturn None+async def get_active_subscription_period_end(user_id: str) -> int | None:+ """Return the Unix timestamp of the active sub's current_period_end, or None.++ Used to surface "next invoice on {date}" in upgrade dialog UX. Returns None+ for users without a Stripe customer or active sub. Stripe failures swallow+ to None — UX falls back to generic copy if the lookup misfires.+ """+ user = await get_user_by_id(user_id)+ if not user.stripe_customer_id:+ return None+ try:+ sub = await _get_active_subscription(user.stripe_customer_id)+ except stripe.StripeError:+ logger.warning(+ "get_active_subscription_period_end: Stripe lookup failed for user %s",+ user_id,+ )+ return None+ if sub is None:+ return None+ period_end = sub.current_period_end+ return int(period_end) if period_end else None++# Substrings Stripe uses in InvalidRequestError messages when the schedule is# already in a terminal state (released / completed / canceled) and therefore# cannot be released again. We only swallow the error when one of these appears;@@ -1670,7 +1716,7 @@ async def modify_stripe_subscription_for_tier(user = await get_user_by_id(user_id)if not user.stripe_customer_id:return False- current_tier = user.subscription_tier or SubscriptionTier.BASIC+ current_tier = user.subscription_tier or SubscriptionTier.NO_TIERsub = await _get_active_subscription(user.stripe_customer_id)if sub is None:@@ -1891,7 +1937,7 @@ async def get_pending_subscription_change(return Noneeffective_at = datetime.fromtimestamp(period_end, tz=timezone.utc)if sub.cancel_at_period_end:- return SubscriptionTier.BASIC, effective_at+ return SubscriptionTier.NO_TIER, effective_atif not sub.schedule:return Noneschedule_id = sub.schedule if isinstance(sub.schedule, str) else sub.schedule.id@@ -1986,6 +2032,7 @@ async def create_subscription_checkout(success_url=success_url,cancel_url=cancel_url,subscription_data={"metadata": {"user_id": user_id, "tier": tier.value}},+ allow_promotion_codes=True,)if not session.url:# An empty checkout URL for a paid upgrade is always an error; surfacing it@@ -2071,7 +2118,7 @@ async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:# ENTERPRISE user to a different tier — if a user on ENTERPRISE somehow has# a self-service Stripe sub, it's a data-consistency issue for an operator,# not something the webhook should automatically "fix".- current_tier = user.subscriptionTier or SubscriptionTier.BASIC+ current_tier = user.subscriptionTier or SubscriptionTier.NO_TIERif current_tier == SubscriptionTier.ENTERPRISE:logger.warning("sync_subscription_from_stripe: refusing to overwrite ENTERPRISE tier"@@ -2170,7 +2217,7 @@ async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:current_tier.value,)return- tier = SubscriptionTier.BASIC+ tier = SubscriptionTier.NO_TIER# Idempotency: Stripe retries webhooks on delivery failure, and several event# types map to the same final tier. Skip the DB write + cache invalidation# when the tier is already correct to avoid redundant writes on replay.@@ -2269,7 +2316,7 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:)return- current_tier = user.subscriptionTier or SubscriptionTier.BASIC+ current_tier = user.subscriptionTier or SubscriptionTier.NO_TIERif current_tier == SubscriptionTier.ENTERPRISE:logger.warning("handle_subscription_payment_failure: skipping ENTERPRISE user %s"@@ -2310,12 +2357,19 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:}),)- # Balance covered the invoice. Pay the Stripe invoice so Stripe's dunning- # system stops retrying it — without this call Stripe would retry automatically- # and re-trigger this webhook, causing double-deductions each retry cycle.+ # Balance covered the invoice. Pay the Stripe invoice with+ # ``paid_out_of_band=True`` so Stripe marks the invoice paid without+ # retrying the card charge — the card already failed and the user is+ # paying via their AutoGPT balance, so a card retry here would+ # double-bill the user (card charge + balance debit). Stripe still+ # fires ``invoice.payment_succeeded`` on the transition; the success+ # handler reads ``paid_out_of_band`` and skips the credit grant so+ # the balance debit isn't reversed.if invoice_id:try:- await run_in_threadpool(stripe.Invoice.pay, invoice_id)+ await run_in_threadpool(+ stripe.Invoice.pay, invoice_id, paid_out_of_band=True+ )except stripe.StripeError:logger.warning("handle_subscription_payment_failure: balance deducted for user"@@ -2355,7 +2409,95 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:customer_id,)return- await set_subscription_tier(user.id, SubscriptionTier.BASIC)+ await set_subscription_tier(user.id, SubscriptionTier.NO_TIER)+++async def handle_subscription_payment_success(invoice: dict) -> None:+ """Grant AutoGPT credits equal to the paid Stripe invoice amount.++ Fires on every paid subscription invoice (initial signup, monthly renewal,+ and prorated upgrade charges). Credits = ``invoice.amount_paid`` cents,+ keyed by ``invoice_id`` for idempotency so Stripe retries don't double-grant.++ Skipped:+ - Non-subscription invoices (no ``subscription`` field).+ - Zero-amount invoices (e.g. card-validation checks, $0 trials).+ - ENTERPRISE users (admin-managed; they don't pay via self-service).+ """+ customer_id = invoice.get("customer")+ if not customer_id:+ logger.warning(+ "handle_subscription_payment_success: missing customer in invoice; skipping"+ )+ return+ sub_id: str = invoice.get("subscription") or ""+ if not sub_id:+ # Non-subscription invoices (one-off invoices, etc.) — no credit grant.+ return+ user = await User.prisma().find_first(where={"stripeCustomerId": customer_id})+ if not user:+ logger.warning(+ "handle_subscription_payment_success: no user for customer %s",+ customer_id,+ )+ return+ if (+ user.subscriptionTier or SubscriptionTier.NO_TIER+ ) == SubscriptionTier.ENTERPRISE:+ logger.warning(+ "handle_subscription_payment_success: skipping ENTERPRISE user %s"+ " (customer %s) — tier is admin-managed",+ user.id,+ customer_id,+ )+ return++ amount_paid: int = invoice.get("amount_paid", 0)+ invoice_id: str = invoice.get("id", "")+ if amount_paid <= 0 or not invoice_id:+ return++ # Skip when ``handle_subscription_payment_failure`` already covered this+ # invoice from the user's balance and marked it paid out of band — the+ # balance was debited there, granting matching credits here would reverse+ # the debit and give the user a free billing period.+ if invoice.get("paid_out_of_band"):+ logger.info(+ "handle_subscription_payment_success: skipping invoice %s for user %s"+ " (paid_out_of_band — covered by balance in failure handler)",+ invoice_id,+ user.id,+ )+ return++ try:+ await UserCredit()._add_transaction(+ user_id=user.id,+ amount=amount_paid,+ transaction_type=CreditTransactionType.GRANT,+ transaction_key=f"INVOICE-{invoice_id}",+ metadata=SafeJson(+ {+ "stripe_customer_id": customer_id,+ "stripe_subscription_id": sub_id,+ "stripe_invoice_id": invoice_id,+ "billing_reason": invoice.get("billing_reason", ""),+ "reason": "subscription_invoice_paid",+ }+ ),+ )+ logger.info(+ "handle_subscription_payment_success: granted %d credits to user %s"+ " for invoice %s (sub %s)",+ amount_paid,+ user.id,+ invoice_id,+ sub_id,+ )+ except UniqueViolationError:+ # Idempotency key collision — Stripe retried this invoice's webhook and+ # we already granted the credits. Safe to ignore.+ returnasync def admin_get_user_history(diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.pyindex e0f89df6c9..2c3205a10b 100644--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestimport stripefrom prisma.enums import SubscriptionTier+from prisma.errors import UniqueViolationErrorfrom prisma.models import Userfrom backend.data.credit import (@@ -15,6 +16,7 @@ from backend.data.credit import (get_pending_subscription_change,get_proration_credit_cents,handle_subscription_payment_failure,+ handle_subscription_payment_success,is_tier_downgrade,is_tier_upgrade,modify_stripe_subscription_for_tier,@@ -174,7 +176,7 @@ async def test_sync_subscription_from_stripe_enterprise_not_overwritten():@pytest.mark.asyncioasync def test_sync_subscription_from_stripe_cancelled():- """When the only active sub is cancelled, the user is downgraded to BASIC."""+ """When the only active sub is cancelled, the user is downgraded to NO_TIER."""mock_user = _make_user(tier=SubscriptionTier.PRO)stripe_sub = {"id": "sub_old",@@ -199,7 +201,7 @@ async def test_sync_subscription_from_stripe_cancelled():) as mock_set,):await sync_subscription_from_stripe(stripe_sub)- mock_set.assert_awaited_once_with("user-1", SubscriptionTier.BASIC)+ mock_set.assert_awaited_once_with("user-1", SubscriptionTier.NO_TIER)@pytest.mark.asyncio@@ -1284,7 +1286,10 @@ async def test_sync_subscription_from_stripe_no_metadata_user_id_skips_check():@pytest.mark.asyncioasync def test_handle_subscription_payment_failure_balance_covers_pays_invoice():- """When balance covers the invoice, Stripe Invoice.pay is called to stop retries."""+ """When balance covers the invoice, Stripe Invoice.pay is called with+ paid_out_of_band=True so the card isn't double-charged on top of the+ balance debit (the card already failed; retrying it would let the+ success-handler webhook reverse the debit via the credit grant)."""mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)invoice = {"id": "in_abc123",@@ -1305,7 +1310,7 @@ async def test_handle_subscription_payment_failure_balance_covers_pays_invoice()patch("backend.data.credit.stripe.Invoice.pay") as mock_pay,):await handle_subscription_payment_failure(invoice)- mock_pay.assert_called_once_with("in_abc123")+ mock_pay.assert_called_once_with("in_abc123", paid_out_of_band=True)@pytest.mark.asyncio@@ -1367,6 +1372,356 @@ async def test_handle_subscription_payment_failure_passes_invoice_id_as_transactassert kwargs.get("transaction_key") == "in_idempotency_test"+async def test_handle_subscription_payment_success_grants_credits():+ """A paid subscription invoice grants credits = amount_paid, keyed by invoice_id."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)+ invoice = {+ "id": "in_abc123",+ "customer": "cus_123",+ "subscription": "sub_abc123",+ "amount_paid": 5000,+ "billing_reason": "subscription_cycle",+ }++ add_tx_mock = AsyncMock()+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new=add_tx_mock,+ ),+ ):+ await handle_subscription_payment_success(invoice)++ add_tx_mock.assert_awaited_once()+ kwargs = add_tx_mock.await_args.kwargs+ assert kwargs["amount"] == 5000+ assert kwargs["transaction_key"] == "INVOICE-in_abc123"+++async def test_handle_subscription_payment_success_skips_non_subscription_invoice():+ """Invoices with no subscription field (one-off invoices) are no-ops."""+ invoice = {+ "id": "in_abc123",+ "customer": "cus_123",+ "amount_paid": 5000,+ # No 'subscription' field+ }++ prisma_mock = MagicMock()+ with patch("backend.data.credit.User.prisma", return_value=prisma_mock):+ await handle_subscription_payment_success(invoice)+ prisma_mock.find_first.assert_not_called()+++async def test_handle_subscription_payment_success_skips_paid_out_of_band():+ """When the failure handler covered the invoice from the user's balance and+ marked it ``paid_out_of_band=True``, the success-handler webhook that+ follows must NOT grant credits — doing so would reverse the balance debit+ and effectively give the user a free billing period."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)+ invoice = {+ "id": "in_oob_123",+ "customer": "cus_123",+ "subscription": "sub_abc123",+ "amount_paid": 5000,+ "billing_reason": "subscription_cycle",+ "paid_out_of_band": True,+ }++ add_tx_mock = AsyncMock()+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new=add_tx_mock,+ ),+ ):+ await handle_subscription_payment_success(invoice)+ add_tx_mock.assert_not_called()+++async def test_handle_subscription_payment_success_skips_zero_amount():+ """Zero-amount invoices (card validation, $0 trials) are no-ops."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)+ invoice = {+ "id": "in_abc123",+ "customer": "cus_123",+ "subscription": "sub_abc123",+ "amount_paid": 0,+ }++ add_tx_mock = AsyncMock()+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new=add_tx_mock,+ ),+ ):+ await handle_subscription_payment_success(invoice)+ add_tx_mock.assert_not_called()+++async def test_handle_subscription_payment_success_skips_missing_customer():+ """Invoices missing the customer field are dropped with a warning."""+ invoice = {+ "id": "in_abc",+ "subscription": "sub_abc",+ "amount_paid": 1000,+ }+ prisma_mock = MagicMock()+ with patch("backend.data.credit.User.prisma", return_value=prisma_mock):+ await handle_subscription_payment_success(invoice)+ prisma_mock.find_first.assert_not_called()+++async def test_handle_subscription_payment_success_skips_unknown_user():+ """Invoices for an unknown stripeCustomerId are dropped with a warning."""+ invoice = {+ "id": "in_abc",+ "customer": "cus_unknown",+ "subscription": "sub_abc",+ "amount_paid": 1000,+ }+ add_tx_mock = AsyncMock()+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=None)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new=add_tx_mock,+ ),+ ):+ await handle_subscription_payment_success(invoice)+ add_tx_mock.assert_not_called()+++async def test_handle_subscription_payment_success_skips_enterprise():+ """ENTERPRISE users don't get credit grants from Stripe invoices."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.ENTERPRISE)+ invoice = {+ "id": "in_abc",+ "customer": "cus_123",+ "subscription": "sub_abc",+ "amount_paid": 5000,+ }+ add_tx_mock = AsyncMock()+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new=add_tx_mock,+ ),+ ):+ await handle_subscription_payment_success(invoice)+ add_tx_mock.assert_not_called()+++async def test_handle_subscription_payment_success_idempotent_on_unique_violation():+ """If the GRANT transaction key already exists (Stripe webhook retry),+ UniqueViolationError is swallowed so the webhook returns 200 and Stripe+ stops retrying."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)+ invoice = {+ "id": "in_abc",+ "customer": "cus_123",+ "subscription": "sub_abc",+ "amount_paid": 5000,+ }+ add_tx_mock = AsyncMock(side_effect=UniqueViolationError({"error": "dup"}))+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new=add_tx_mock,+ ),+ ):+ await handle_subscription_payment_success(invoice)+ add_tx_mock.assert_awaited_once()+++async def test_get_active_subscription_period_end_returns_unix_timestamp():+ """Happy path: returns int(current_period_end) for an active sub."""+ mock_sub = stripe.Subscription.construct_from(+ {"id": "sub_abc", "current_period_end": 1779340148}, "k"+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]+ user = MagicMock(spec=User)+ user.stripe_customer_id = "cus_abc"++ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ return_value=mock_list,+ ),+ ):+ from backend.data.credit import get_active_subscription_period_end++ result = await get_active_subscription_period_end("user-1")+ assert result == 1779340148+++async def test_get_active_subscription_period_end_returns_none_without_customer():+ """Users without a Stripe customer ID return None — no Stripe API call."""+ user = MagicMock(spec=User)+ user.stripe_customer_id = None+ list_mock = AsyncMock()++ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new=list_mock,+ ),+ ):+ from backend.data.credit import get_active_subscription_period_end++ result = await get_active_subscription_period_end("user-1")+ assert result is None+ list_mock.assert_not_called()+++async def test_get_active_subscription_period_end_swallows_stripe_errors():+ """A Stripe error during the lookup returns None instead of raising."""+ user = MagicMock(spec=User)+ user.stripe_customer_id = "cus_abc"++ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ side_effect=stripe.StripeError("boom"),+ ),+ ):+ from backend.data.credit import get_active_subscription_period_end++ result = await get_active_subscription_period_end("user-1")+ assert result is None+++async def test_top_up_intent_uses_inline_product_data_when_flag_unset():+ """When STRIPE_PRODUCT_ID_TOPUP flag is undefined (default), top-up Checkout+ creates an ephemeral product per session via product_data."""+ from backend.data.credit import UserCredit++ mock_session = MagicMock()+ mock_session.id = "cs_test_topup"+ mock_session.url = "https://checkout.stripe.com/c/cs_test_topup"+ create_mock = MagicMock(return_value=mock_session)+ credit_system = UserCredit()+ with (+ patch(+ "backend.data.credit.get_stripe_customer_id",+ new_callable=AsyncMock,+ return_value="cus_123",+ ),+ patch(+ "backend.data.credit.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value=None,+ ),+ patch(+ "backend.data.credit.stripe.checkout.Session.create",+ new=create_mock,+ ),+ patch.object(credit_system, "_add_transaction", new_callable=AsyncMock),+ ):+ await credit_system.top_up_intent(user_id="user-1", amount=500)++ price_data = create_mock.call_args.kwargs["line_items"][0]["price_data"]+ assert price_data == {+ "currency": "usd",+ "unit_amount": 500,+ "product_data": {"name": "AutoGPT Platform Credits"},+ }+++async def test_top_up_intent_references_product_id_when_flag_set():+ """When STRIPE_PRODUCT_ID_TOPUP flag returns a string, top-up Checkout+ references the canonical Product ID and keeps the per-session amount via+ unit_amount."""+ from backend.data.credit import UserCredit++ mock_session = MagicMock()+ mock_session.id = "cs_test_topup"+ mock_session.url = "https://checkout.stripe.com/c/cs_test_topup"+ create_mock = MagicMock(return_value=mock_session)+ credit_system = UserCredit()+ with (+ patch(+ "backend.data.credit.get_stripe_customer_id",+ new_callable=AsyncMock,+ return_value="cus_123",+ ),+ patch(+ "backend.data.credit.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value="prod_abc123",+ ),+ patch(+ "backend.data.credit.stripe.checkout.Session.create",+ new=create_mock,+ ),+ patch.object(credit_system, "_add_transaction", new_callable=AsyncMock),+ ):+ await credit_system.top_up_intent(user_id="user-1", amount=2500)++ price_data = create_mock.call_args.kwargs["line_items"][0]["price_data"]+ assert price_data == {+ "currency": "usd",+ "unit_amount": 2500,+ "product": "prod_abc123",+ }+ # No product_data — that path is mutually exclusive with product reference.+ assert "product_data" not in price_data++@pytest.mark.asyncioasync def test_modify_stripe_subscription_for_tier_modifies_existing_sub():"""modify_stripe_subscription_for_tier calls Subscription.modify and returns True."""@@ -1845,7 +2200,7 @@ async def test_release_pending_subscription_schedule_no_stripe_customer_returns_@pytest.mark.asyncioasync def test_get_pending_subscription_change_cancel_at_period_end():- """cancel_at_period_end=True maps to pending BASIC at current_period_end."""+ """cancel_at_period_end=True maps to pending NO_TIER at current_period_end."""import time as time_modget_pending_subscription_change.cache_clear() # type: ignore[attr-defined]@@ -1894,7 +2249,7 @@ async def test_get_pending_subscription_change_cancel_at_period_end():assert result is not Nonepending_tier, effective_at = result- assert pending_tier == SubscriptionTier.BASIC+ assert pending_tier == SubscriptionTier.NO_TIERassert int(effective_at.timestamp()) == period_enddiff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex 86f9535f5d..b778efa910 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -28,7 +28,7 @@ logger = logging.getLogger(__name__)settings = Settings()# Cache decorator alias for consistent user lookup caching-cache_user_lookup = cached(maxsize=1000, ttl_seconds=300)+cache_user_lookup = cached(maxsize=1000, ttl_seconds=300, shared_cache=True)@cache_user_lookupdiff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex efbfb92027..9c8a592502 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -46,6 +46,12 @@ class Flag(str, Enum):COPILOT_TIER_MULTIPLIERS = "copilot-tier-multipliers"COPILOT_TIER_STRIPE_PRICES = "copilot-tier-stripe-prices"GRAPHITI_MEMORY = "graphiti-memory"+ # Stripe Product ID for top-up Checkout sessions. When unset (default),+ # top_up_intent uses inline product_data (creates ephemeral Stripe products+ # per Checkout). When set to a real Stripe Product ID, line items reference+ # that Product so dashboard reporting groups all top-ups under one entity;+ # the per-Checkout amount stays dynamic via price_data.unit_amount.+ STRIPE_PRODUCT_ID_TOPUP = "stripe-product-id-topup"# Copilot model routing — JSON-valued, returns the per-(mode, tier)# model identifier (e.g. ``"anthropic/claude-sonnet-4-6"`` ordiff --git a/autogpt_platform/backend/migrations/20260428141154_add_no_tier/migration.sql b/autogpt_platform/backend/migrations/20260428141154_add_no_tier/migration.sqlnew file mode 100644index 0000000000..ecb5f40991--- /dev/null+++ b/autogpt_platform/backend/migrations/20260428141154_add_no_tier/migration.sql@@ -0,0 +1,9 @@+-- Add SubscriptionTier.NO_TIER as the explicit "user has no active Stripe+-- subscription" state. Previously BASIC was overloaded for both this+-- semantic AND a potential entry-paid-tier slot; NO_TIER disambiguates.+-- BASIC stays in the enum as a future paid-tier option.+--+-- ADD VALUE BEFORE 'BASIC' keeps it as the lowest tier for ordering. RENAME+-- existing BASIC users to NO_TIER in the same migration so everyone who+-- previously had no-subscription state lands in the new explicit state.+ALTER TYPE "SubscriptionTier" ADD VALUE IF NOT EXISTS 'NO_TIER' BEFORE 'BASIC';diff --git a/autogpt_platform/backend/migrations/20260428141155_migrate_basic_users_to_no_tier/migration.sql b/autogpt_platform/backend/migrations/20260428141155_migrate_basic_users_to_no_tier/migration.sqlnew file mode 100644index 0000000000..f09ed63277--- /dev/null+++ b/autogpt_platform/backend/migrations/20260428141155_migrate_basic_users_to_no_tier/migration.sql@@ -0,0 +1,7 @@+-- Migrate existing users on BASIC (overloaded "no subscription" tier under+-- the old shape) to the new explicit NO_TIER. Users on PRO/MAX/BUSINESS/+-- ENTERPRISE keep their tier — they have active subs / admin grants.+-- Run after ADD VALUE 'NO_TIER' has committed (separate migration file+-- since Postgres requires the enum value to exist in a previously-+-- committed transaction before it can be referenced in DML).+UPDATE "User" SET "subscriptionTier" = 'NO_TIER' WHERE "subscriptionTier" = 'BASIC';diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex c578f8f74e..36ec6f9d27 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -89,6 +89,7 @@ model User {}enum SubscriptionTier {+ NO_TIERBASICPROMAXdiff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsxnew file mode 100644index 0000000000..1daac7603d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx@@ -0,0 +1,57 @@+"use client";++import { ReactNode } from "react";+import { usePathname } from "next/navigation";+import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { PaywallModal } from "./PaywallModal";++// Routes that bypass the paywall regardless of subscription state — primarily+// the credits page itself (the modal would render on top of itself), auth+// flows, account management, and admin areas the user needs even when locked+// out of AutoPilot.+const PAYWALL_EXEMPT_PREFIXES = [+ "/profile",+ "/admin",+ "/auth",+ "/login",+ "/signup",+ "/reset-password",+ "/error",+ "/unauthorized",+ "/health",+];++export function PaywallGate({ children }: { children: ReactNode }) {+ const pathname = usePathname();+ const isPaymentEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);+ const { data: subscription, isLoading } = useGetSubscriptionStatus({+ query: {+ select: (res) => (res.status === 200 ? res.data : null),+ // Skip the call entirely when the flag is off — beta cohort never hits+ // the paywall, no need to read /credits/subscription on every page load.+ enabled: isPaymentEnabled === true,+ },+ });++ const isExempt = PAYWALL_EXEMPT_PREFIXES.some((p) => pathname.startsWith(p));++ // Gate on the DB tier rather than has_active_stripe_subscription so a+ // transient Stripe outage (which would set the latter to False even for+ // active subscribers) doesn't lock out paying users. The DB tier is set+ // by Stripe webhooks and persists; only fresh users without any tier+ // change land on NO_TIER (the explicit "no active subscription" state).+ const shouldGate =+ !!isPaymentEnabled &&+ !isLoading &&+ !isExempt &&+ !!subscription &&+ subscription.tier === "NO_TIER";++ return (+ <>+ {children}+ {shouldGate && <PaywallModal />}+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsxnew file mode 100644index 0000000000..24105f7b4e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx@@ -0,0 +1,19 @@+"use client";++import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { SubscriptionTierSection } from "@/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection";++// Non-dismissable Stripe paywall. The user can only exit by picking a tier+// (Stripe Checkout or modify-in-place). Reuses the existing tier picker so+// the underlying Checkout / modify wiring stays in one place — the+// SubscriptionTierSection already renders its own "Pick a plan" banner ++// description when tier === "BASIC", so the dialog itself is title-less.+export function PaywallModal() {+ return (+ <Dialog forceOpen controlled={{ isOpen: true, set: () => {} }}>+ <Dialog.Content>+ <SubscriptionTierSection />+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsxnew file mode 100644index 0000000000..403b843277--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx@@ -0,0 +1,119 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi, beforeEach } from "vitest";++// Mock next/navigation — usePathname isn't available in jsdom.+let mockPathname = "/build";+vi.mock("next/navigation", () => ({+ usePathname: () => mockPathname,+ useRouter: () => ({ replace: vi.fn() }),+}));++// Mock the LD flag hook — toggle paid-cohort vs beta-cohort per test.+let mockIsPaymentEnabled: boolean | undefined = false;+vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: { ENABLE_PLATFORM_PAYMENT: "enable-platform-payment" },+ useGetFlag: () => mockIsPaymentEnabled,+}));++// Mock the generated subscription-status hook — control isLoading + tier per test.+type MockSubscription = { tier: string };+let mockSubscriptionResult: {+ data: MockSubscription | null | undefined;+ isLoading: boolean;+} = { data: null, isLoading: false };+vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({+ useGetSubscriptionStatus: () => mockSubscriptionResult,+}));++// Mock PaywallModal — actual rendering depends on Radix portals + the full+// SubscriptionTierSection, neither of which behave well under jsdom. Stand-in+// placeholder lets us assert the gate-vs-no-gate decision without booting the+// real modal.+vi.mock("../PaywallModal", () => ({+ PaywallModal: () => <div data-testid="paywall-modal">paywall</div>,+}));++import { PaywallGate } from "../PaywallGate";++describe("PaywallGate", () => {+ beforeEach(() => {+ mockPathname = "/build";+ mockIsPaymentEnabled = false;+ mockSubscriptionResult = { data: null, isLoading: false };+ });++ it("renders children without modal when ENABLE_PLATFORM_PAYMENT flag is off (beta cohort)", () => {+ mockIsPaymentEnabled = false;+ mockSubscriptionResult = { data: { tier: "NO_TIER" }, isLoading: false };+ render(+ <PaywallGate>+ <div>protected</div>+ </PaywallGate>,+ );+ expect(screen.getByText("protected")).toBeDefined();+ expect(screen.queryByTestId("paywall-modal")).toBeNull();+ });++ it("renders modal over children when paid cohort + tier is NO_TIER", () => {+ mockIsPaymentEnabled = true;+ mockSubscriptionResult = { data: { tier: "NO_TIER" }, isLoading: false };+ render(+ <PaywallGate>+ <div>protected</div>+ </PaywallGate>,+ );+ expect(screen.getByText("protected")).toBeDefined();+ expect(screen.getByTestId("paywall-modal")).toBeDefined();+ });++ it("does not render modal when paid cohort + tier is PRO/MAX/BUSINESS", () => {+ mockIsPaymentEnabled = true;+ for (const tier of ["PRO", "MAX", "BUSINESS"]) {+ mockSubscriptionResult = { data: { tier }, isLoading: false };+ const { unmount } = render(+ <PaywallGate>+ <div>protected</div>+ </PaywallGate>,+ );+ expect(screen.queryByTestId("paywall-modal")).toBeNull();+ unmount();+ }+ });++ it("does not render modal on exempt routes (/profile, /admin, /auth, /login, etc.)", () => {+ mockIsPaymentEnabled = true;+ mockSubscriptionResult = { data: { tier: "NO_TIER" }, isLoading: false };+ for (const path of [+ "/profile/credits",+ "/profile/account",+ "/admin/users",+ "/auth/callback",+ "/login",+ "/signup",+ "/reset-password",+ "/error",+ "/unauthorized",+ "/health",+ ]) {+ mockPathname = path;+ const { unmount } = render(+ <PaywallGate>+ <div>protected</div>+ </PaywallGate>,+ );+ expect(screen.queryByTestId("paywall-modal")).toBeNull();+ unmount();+ }+ });++ it("does not render modal while subscription status is still loading", () => {+ mockIsPaymentEnabled = true;+ mockSubscriptionResult = { data: undefined, isLoading: true };+ render(+ <PaywallGate>+ <div>protected</div>+ </PaywallGate>,+ );+ expect(screen.queryByTestId("paywall-modal")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsxnew file mode 100644index 0000000000..153981ee50--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx@@ -0,0 +1,56 @@+import { render } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++// Mock SubscriptionTierSection — its full render exercises the credits+// query, LD flag, and Stripe wiring which are out of scope for PaywallModal+// itself. The modal's job is to wrap the section in a non-dismissable Dialog;+// that's what we verify here.+vi.mock(+ "@/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection",+ () => ({+ SubscriptionTierSection: () => (+ <div data-testid="tier-section">tier picker</div>+ ),+ }),+);++// Mock the Dialog so we can introspect its props without booting Radix portals+// under jsdom (which doesn't reliably render them).+let lastDialogProps: Record<string, unknown> | null = null;+vi.mock("@/components/molecules/Dialog/Dialog", () => ({+ Dialog: Object.assign(+ function MockDialog(props: Record<string, unknown>) {+ lastDialogProps = props;+ return (+ <div data-testid="dialog">{props.children as React.ReactNode}</div>+ );+ },+ {+ Content: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="dialog-content">{children}</div>+ ),+ },+ ),+}));++import { PaywallModal } from "../PaywallModal";++describe("PaywallModal", () => {+ it("renders SubscriptionTierSection inside a forceOpen, non-dismissable Dialog", () => {+ const { getByTestId } = render(<PaywallModal />);+ expect(getByTestId("dialog")).toBeDefined();+ expect(getByTestId("dialog-content")).toBeDefined();+ expect(getByTestId("tier-section")).toBeDefined();+ expect(lastDialogProps?.forceOpen).toBe(true);+ // controlled.set is a no-op (set: () => {}) so the modal can never be+ // closed by the Dialog's own state machinery — only by subscription state+ // changing in the consuming PaywallGate.+ expect(+ typeof (lastDialogProps?.controlled as { set?: unknown } | undefined)+ ?.set,+ ).toBe("function");+ expect(+ (lastDialogProps?.controlled as { isOpen?: boolean } | undefined)?.isOpen,+ ).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsxindex c5db541ea8..e35514a629 100644--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx@@ -4,6 +4,7 @@ import { PushNotificationProvider } from "@/services/push-notifications/PushNotiimport { ReactNode } from "react";import { AdminImpersonationBanner } from "./admin/components/AdminImpersonationBanner";import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";+import { PaywallGate } from "./PaywallGate/PaywallGate";export default function PlatformLayout({ children }: { children: ReactNode }) {return (@@ -13,7 +14,9 @@ export default function PlatformLayout({ children }: { children: ReactNode }) {<PushNotificationProvider /><Navbar /><AdminImpersonationBanner />- <section className="flex-1">{children}</section>+ <section className="flex-1">+ <PaywallGate>{children}</PaywallGate>+ </section></main></AutoPilotBridgeProvider>);diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsxindex cba09d7c3c..b9c8b87830 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx@@ -120,10 +120,28 @@ export function SubscriptionTierSection() {handleTierChange(targetTierKey, currentTier, setConfirmDowngradeTo);}+ // Gate the "Pick a plan" banner on the DB tier rather than+ // has_active_stripe_subscription so a transient Stripe outage doesn't show+ // the banner to active subscribers. Same rationale as PaywallGate.+ const needsSubscription = isPaymentEnabled && subscription.tier === "NO_TIER";+return (<div className="space-y-4"><h3 className="text-lg font-medium">Subscription Plan</h3>+ {needsSubscription && (+ <div+ role="status"+ className="rounded-md border border-violet-300 bg-violet-50 px-4 py-3 text-sm text-violet-900 dark:border-violet-700 dark:bg-violet-900/20 dark:text-violet-200"+ >+ <p className="font-medium">Pick a plan to continue using AutoGPT.</p>+ <p className="mt-1">+ Your account doesn't have an active subscription. Choose a tier+ below to unlock AutoPilot and start running agents.+ </p>+ </div>+ )}+{tierError && (<prole="alert"@@ -215,12 +233,24 @@ export function SubscriptionTierSection() {})}</div>- {currentTier !== "BASIC" && isPaymentEnabled && (- <p className="text-sm text-neutral-500">- Your subscription is managed through Stripe. Upgrades take effect- immediately. Downgrades take effect at the end of your current billing- period.- </p>+ {currentTier !== "NO_TIER" && isPaymentEnabled && (+ <div className="flex items-center justify-between gap-3">+ <p className="text-sm text-neutral-500">+ Your subscription is managed through Stripe. Upgrades take effect+ immediately. Downgrades take effect at the end of your current+ billing period.+ </p>+ {!hasPendingChange && (+ <Button+ variant="ghost"+ className="shrink-0 text-sm text-neutral-600 hover:text-red-600 dark:text-neutral-400"+ disabled={isPending}+ onClick={() => setConfirmDowngradeTo("NO_TIER")}+ >+ Cancel subscription+ </Button>+ )}+ </div>)}<Dialog@@ -234,9 +264,9 @@ export function SubscriptionTierSection() {><Dialog.Content><p className="text-sm text-neutral-600 dark:text-neutral-400">- {confirmDowngradeTo === "BASIC"- ? "Downgrading to Basic will schedule your subscription to cancel at the end of your current billing period. You keep your current plan until then."- : `Switching to ${TIERS.find((t) => t.key === confirmDowngradeTo)?.label ?? confirmDowngradeTo} will take effect at the end of your current billing period. You keep your current plan until then.`}{" "}+ {confirmDowngradeTo === "NO_TIER"+ ? `Cancelling your subscription schedules it to end at the close of your current billing period${subscription.current_period_end ? ` on ${formatPendingDate(new Date(subscription.current_period_end * 1000))}` : ""} — no charge today and no further charges to your card. You keep your current plan and existing credits until then.`+ : `Switching to ${getTierLabel(confirmDowngradeTo ?? "")} takes effect at the end of your current billing period${subscription.current_period_end ? ` on ${formatPendingDate(new Date(subscription.current_period_end * 1000))}` : ""} — no charge today. You keep your current plan until then. From that date your saved card is billed at the ${getTierLabel(confirmDowngradeTo ?? "")} rate, and matching credits are added to your AutoGPT balance with each paid invoice.`}{" "}Are you sure?</p><Dialog.Footer>@@ -303,13 +333,9 @@ export function SubscriptionTierSection() {><Dialog.Content><p className="text-sm text-neutral-600 dark:text-neutral-400">- {subscription &&- subscription.proration_credit_cents > 0 &&- `Your unused ${currentTier.charAt(0) + currentTier.slice(1).toLowerCase()} subscription ($${(subscription.proration_credit_cents / 100).toFixed(2)}) will be applied as a credit to your next Stripe invoice. `}- You will be redirected to Stripe to complete your upgrade to{" "}- {TIERS.find((t) => t.key === pendingUpgradeTier)?.label ??- pendingUpgradeTier}- .+ {subscription.has_active_stripe_subscription+ ? `Your subscription is upgraded to ${getTierLabel(pendingUpgradeTier ?? "")} immediately. On your next invoice${subscription.current_period_end ? ` on ${formatPendingDate(new Date(subscription.current_period_end * 1000))}` : ""}, your saved card is charged for the upgrade proration since today plus the next month at the new rate, with the unused portion of your current plan automatically deducted. Credits matching the paid amount are added to your AutoGPT balance once Stripe confirms the charge.`+ : `You'll be redirected to Stripe to enter payment details and start your ${getTierLabel(pendingUpgradeTier ?? "")} subscription. The first invoice's amount is added to your AutoGPT balance once Stripe confirms the charge.`}</p><Dialog.Footer><Button@@ -319,7 +345,9 @@ export function SubscriptionTierSection() {Cancel</Button><Button onClick={() => void confirmUpgrade()}>- Continue to Checkout+ {subscription.has_active_stripe_subscription+ ? "Confirm Upgrade"+ : "Continue to Checkout"}</Button></Dialog.Footer></Dialog.Content>diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsxindex 9ee4a41742..fe17dabf47 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx@@ -197,7 +197,7 @@ describe("SubscriptionTierSection", () => {expect(screen.getByText("Free")).toBeDefined();});- it("shows 'Pricing available soon' when tier cost is 0 for a paid tier", () => {+ it("shows 'Free' for any tier with cost = 0", () => {setupMocks({subscription: makeSubscription({tier: "BASIC",@@ -205,8 +205,8 @@ describe("SubscriptionTierSection", () => {}),});render(<SubscriptionTierSection />);- // PRO and MAX with cost=0 should show "Pricing available soon"- expect(screen.getAllByText("Pricing available soon")).toHaveLength(2);+ // BASIC, PRO, MAX all with cost=0 should each render "Free".+ expect(screen.getAllByText("Free")).toHaveLength(3);});it("calls changeTier on upgrade click after confirmation dialog", async () => {@@ -533,11 +533,12 @@ describe("SubscriptionTierSection", () => {const dialog = screen.getByRole("dialog");expect(dialog.textContent).toMatch(- /switching to pro will take effect at the end of your current billing period/i,+ /switching to pro takes effect at the end of your current billing period/i,);expect(dialog.textContent).toMatch(/you keep your current plan until then/i,);+ expect(dialog.textContent).toMatch(/no charge today/i);expect(dialog.textContent).not.toMatch(/take effect immediately/i);});@@ -676,6 +677,65 @@ describe("SubscriptionTierSection", () => {expect(mutateFn).not.toHaveBeenCalled();});+ it("renders Cancel subscription button for paid users with no pending change", () => {+ setupMocks({ subscription: makeSubscription({ tier: "PRO" }) });+ render(<SubscriptionTierSection />);+ expect(+ screen.getByRole("button", { name: /cancel subscription/i }),+ ).toBeDefined();+ });++ it("hides Cancel subscription button for NO_TIER users (already cancelled)", () => {+ setupMocks({ subscription: makeSubscription({ tier: "NO_TIER" }) });+ render(<SubscriptionTierSection />);+ expect(+ screen.queryByRole("button", { name: /cancel subscription/i }),+ ).toBeNull();+ });++ it("hides Cancel subscription button when payment flag is disabled", () => {+ mockPaymentEnabled = false;+ setupMocks({ subscription: makeSubscription({ tier: "PRO" }) });+ render(<SubscriptionTierSection />);+ expect(+ screen.queryByRole("button", { name: /cancel subscription/i }),+ ).toBeNull();+ });++ it("hides Cancel subscription button when a pending change is already scheduled", () => {+ // Avoid double-cancelling: PendingChangeBanner exposes the cancel-pending+ // path; an extra Cancel button here would be redundant and confusing.+ setupMocks({+ subscription: makeSubscription({+ tier: "PRO",+ pendingTier: "NO_TIER",+ pendingTierEffectiveAt: new Date("2026-05-15T12:00:00Z"),+ }),+ });+ render(<SubscriptionTierSection />);+ expect(+ screen.queryByRole("button", { name: /cancel subscription/i }),+ ).toBeNull();+ });++ it("opens the cancel-confirm dialog with NO_TIER copy when Cancel subscription is clicked", () => {+ setupMocks({+ subscription: makeSubscription({+ tier: "PRO",+ // No current_period_end so the date suffix is absent — keeps the+ // matcher simple and exercises the optional-period branch.+ }),+ });+ render(<SubscriptionTierSection />);+ fireEvent.click(+ screen.getByRole("button", { name: /cancel subscription/i }),+ );+ expect(screen.getByRole("dialog")).toBeDefined();+ expect(+ screen.getByText(/cancelling your subscription schedules it to end/i),+ ).toBeDefined();+ });+it("renders BASIC cancellation copy in banner when pending_tier is BASIC", () => {setupMocks({subscription: makeSubscription({diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.tsindex 5d0c3204f3..34d8f3c2cf 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts@@ -10,21 +10,15 @@ import {} from "./helpers";describe("formatCost", () => {- it("returns 'Free' only when BASIC actually costs $0", () => {+ it("returns 'Free' for any tier with cost = 0", () => {expect(formatCost(0, "BASIC")).toBe("Free");+ expect(formatCost(0, "PRO")).toBe("Free");+ expect(formatCost(0, "MAX")).toBe("Free");+ expect(formatCost(0, "BUSINESS")).toBe("Free");});- it("formats BASIC to a dollars-per-month string when LD sets a non-zero price", () => {+ it("formats cents to a dollars-per-month string for any non-zero cost", () => {expect(formatCost(999, "BASIC")).toBe("$9.99/mo");- });-- it("returns a placeholder when paid tier has no price yet", () => {- expect(formatCost(0, "PRO")).toBe("Pricing available soon");- expect(formatCost(0, "MAX")).toBe("Pricing available soon");- expect(formatCost(0, "BUSINESS")).toBe("Pricing available soon");- });-- it("formats cents to a dollars-per-month string for paid tiers", () => {expect(formatCost(999, "PRO")).toBe("$9.99/mo");expect(formatCost(32000, "MAX")).toBe("$320.00/mo");expect(formatCost(4900, "BUSINESS")).toBe("$49.00/mo");@@ -45,6 +39,14 @@ describe("getTierLabel", () => {expect(getTierLabel("ENTERPRISE")).toBe("Enterprise");expect(getTierLabel("CUSTOM_TIER")).toBe("Custom_tier");});++ it("renders NO_TIER as 'No subscription' (not the title-case fallback)", () => {+ // The fallback would produce "No_tier" — surfaced in the pending-change+ // banner during cancel-at-period-end as "Scheduled to downgrade to+ // No_tier on …". Special-cased here so the user-facing copy matches the+ // semantic of the value.+ expect(getTierLabel("NO_TIER")).toBe("No subscription");+ });});describe("formatPendingDate", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.tsindex ab10abe4f9..87a1cab6df 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts@@ -27,15 +27,22 @@ export const TIERS: TierInfo[] = [},];-export const TIER_ORDER = ["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"];+export const TIER_ORDER = [+ "NO_TIER",+ "BASIC",+ "PRO",+ "MAX",+ "BUSINESS",+ "ENTERPRISE",+];-export function formatCost(cents: number, tierKey: string): string {- if (cents === 0)- return tierKey === "BASIC" ? "Free" : "Pricing available soon";+export function formatCost(cents: number, _tierKey: string): string {+ if (cents === 0) return "Free";return `$${(cents / 100).toFixed(2)}/mo`;}export function getTierLabel(tierKey: string): string {+ if (tierKey === "NO_TIER") return "No subscription";return (TIERS.find((t) => t.key === tierKey)?.label ??tierKey.charAt(0) + tierKey.slice(1).toLowerCase()diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.tsindex 8bdce215ff..e9d623e389 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts@@ -8,10 +8,11 @@ import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";import { useToast } from "@/components/molecules/Toast/use-toast";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { getTierLabel } from "./helpers";export type SubscriptionStatus = SubscriptionStatusResponse;-const TIER_ORDER = ["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"];+const TIER_ORDER = ["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"];export function useSubscriptionTierSection() {const isPaymentEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);@@ -82,12 +83,19 @@ export function useSubscriptionTierSection() {return;}await refetch();+ const currentIdx = subscription+ ? TIER_ORDER.indexOf(subscription.tier)+ : -1;+ const targetIdx = TIER_ORDER.indexOf(tier);+ const isDowngrade = targetIdx >= 0 && targetIdx < currentIdx;toast({title: "Subscription updated",description:- tier === "BASIC"- ? "Your plan will be downgraded to Basic at the end of your current billing period."- : "Your subscription has been updated.",+ tier === "NO_TIER"+ ? "Your subscription is cancelled at the end of your current billing period; no further charges."+ : isDowngrade+ ? `Your plan will be downgraded to ${getTierLabel(tier)} at the end of your current billing period; from then your saved card is billed at the new lower rate.`+ : `Upgraded to ${getTierLabel(tier)}. On the next invoice your saved card is charged for the upgrade proration plus the next month at the new rate; matching credits land in your AutoGPT balance once Stripe confirms the charge.`,});} catch (e: unknown) {const msg =diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 9554bc00c4..97a99e94e9 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -10510,7 +10510,7 @@},"tier": {"$ref": "#/components/schemas/SubscriptionTier",- "default": "BASIC"+ "default": "NO_TIER"},"reset_cost": {"type": "integer",@@ -16229,7 +16229,14 @@"properties": {"tier": {"type": "string",- "enum": ["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"],+ "enum": [+ "NO_TIER",+ "BASIC",+ "PRO",+ "MAX",+ "BUSINESS",+ "ENTERPRISE"+ ],"title": "Tier"},"monthly_cost": { "type": "integer", "title": "Monthly Cost" },@@ -16248,9 +16255,23 @@"type": "integer","title": "Proration Credit Cents"},+ "has_active_stripe_subscription": {+ "type": "boolean",+ "title": "Has Active Stripe Subscription",+ "description": "True when the user has an active/trialing Stripe subscription. The frontend uses this to branch upgrade UX: modify-in-place + saved-card auto-charge when True, redirect to Stripe Checkout when False.",+ "default": false+ },+ "current_period_end": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Current Period End",+ "description": "Unix timestamp of the active subscription's current_period_end. Used to show the date Stripe will issue the next invoice (with prorated upgrade charges, if any). None when no active sub."+ },"pending_tier": {"anyOf": [- { "type": "string", "enum": ["BASIC", "PRO", "MAX", "BUSINESS"] },+ {+ "type": "string",+ "enum": ["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]+ },{ "type": "null" }],"title": "Pending Tier"@@ -16280,7 +16301,7 @@},"SubscriptionTier": {"type": "string",- "enum": ["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"],+ "enum": ["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"],"title": "SubscriptionTier","description": "Subscription tiers with increasing cost 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"},@@ -16288,7 +16309,7 @@"properties": {"tier": {"type": "string",- "enum": ["BASIC", "PRO", "MAX", "BUSINESS"],+ "enum": ["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"],"title": "Tier"},"success_url": {diff --git a/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsx b/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsxindex a78aca17c4..038a7fce2e 100644--- a/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsx+++ b/autogpt_platform/frontend/src/components/molecules/Dialog/components/DialogWrap.tsx@@ -117,7 +117,7 @@ export function DialogWrap({</span>)}- {isForceOpen && !handleClose ? null : (+ {isForceOpen ? null : (<Buttonvariant="icon"size="icon"