AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): default-off the subscription credit grant + dedup stripe events (#13093)
Zamil Majdya0c4b072e0de
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex 56ecadcb99..869a750ba1 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -94,6 +94,7 @@ from backend.data.onboarding import (reset_user_onboarding,update_user_onboarding,)+from backend.data.redis_client import get_redis_asyncfrom backend.data.tally import extract_business_understandingfrom backend.data.understanding import (BusinessUnderstandingInput,@@ -1269,6 +1270,62 @@ async def update_subscription_tier(return status+def _stripe_event_dedup_key(event_id: str) -> str:+ return f"stripe_webhook_event:{event_id}"+++async def _claim_stripe_event(event_id: str) -> bool:+ """Mark a Stripe webhook event as claimed via Redis SETNX.++ Returns ``True`` when the caller acquired the claim (first time we've seen+ ``event_id``) and should proceed with handler dispatch. Returns ``False``+ when the event was already processed in a prior delivery — Stripe retries+ the same ``event.id`` on non-2xx responses, and we don't want downstream+ handlers (some of which only carry per-resource idempotency) to fire twice.++ Pair with ``_release_stripe_event`` in a try/except around handler dispatch:+ on handler failure we DELete the key so Stripe's retry isn't no-op'd, but+ a retry that arrives *during* in-flight processing still hits the live+ claim and is deduped.++ TTL of 24h comfortably exceeds Stripe's retry window. On Redis failure we+ fall open and let processing continue — better to risk a rare duplicate+ than to drop a real event.+ """+ if not event_id:+ # Malformed event without an id — fall open so the rest of the+ # handler can decide what to do (it'll log and 200 anyway).+ return True+ try:+ redis_client = await get_redis_async()+ claimed = await redis_client.set(+ _stripe_event_dedup_key(event_id), "1", nx=True, ex=86400+ )+ return bool(claimed)+ except Exception:+ logger.warning(+ "stripe_webhook: dedup claim failed for event %s; processing anyway",+ event_id,+ exc_info=True,+ )+ return True+++async def _release_stripe_event(event_id: str) -> None:+ """Release a previously-claimed dedup key so Stripe's retry can rerun."""+ if not event_id:+ return+ try:+ redis_client = await get_redis_async()+ await redis_client.delete(_stripe_event_dedup_key(event_id))+ except Exception:+ logger.warning(+ "stripe_webhook: dedup release failed for event %s",+ event_id,+ exc_info=True,+ )++@v1_router.post(path="/credits/stripe_webhook", summary="Handle Stripe webhooks", tags=["credits"])@@ -1302,7 +1359,20 @@ async def stripe_webhook(request: Request):# AFTER signature verification — which Stripe interprets as a delivery# failure and retries forever, while spamming Sentry with no useful info.# Acknowledge with 200 and a warning so Stripe stops retrying.+ event_id = event.get("id", "")event_type = event.get("type", "")++ # Event-level dedup: short-circuit identical re-deliveries before any+ # handler runs. Stripe retries the same event.id on non-2xx responses, and+ # not every downstream handler is independently idempotent.+ if not await _claim_stripe_event(event_id):+ logger.info(+ "stripe_webhook: event %s (%s) already processed; skipping",+ event_id,+ event_type,+ )+ return Response(status_code=200)+event_data = event.get("data") or {}data_object = event_data.get("object") if isinstance(event_data, dict) else Noneif not isinstance(data_object, dict):@@ -1312,76 +1382,82 @@ async def stripe_webhook(request: Request):)return Response(status_code=200)- if event_type in (- "checkout.session.completed",- "checkout.session.async_payment_succeeded",- ):- session_id = data_object.get("id")- if not session_id:- logger.warning(- "stripe_webhook: %s missing data.object.id; ignoring", event_type- )- return Response(status_code=200)- await UserCredit().fulfill_checkout(session_id=session_id)- await sync_tier_from_checkout_session(data_object)-- if event_type in (- "customer.subscription.created",- "customer.subscription.updated",- "customer.subscription.deleted",- ):- await sync_subscription_from_stripe(data_object)-- # `subscription_schedule.updated` is deliberately omitted: our own- # `SubscriptionSchedule.create` + `.modify` calls in- # `_schedule_downgrade_at_period_end` would fire that event right back at us- # and loop redundant traffic through this handler. We only care about state- # transitions (released / completed); phase advance to the new price is- # already covered by `customer.subscription.updated`.- if event_type in (- "subscription_schedule.released",- "subscription_schedule.completed",- ):- 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)-- # New Stripe API (≥2025-04-01) split the per-payment events off the Invoice- # resource. data.object is an InvoicePayment, not an Invoice, so we hydrate- # the underlying Invoice before delegating to the existing handlers.- if event_type in ("invoice_payment.paid", "invoice_payment.payment_failed"):- invoice_id = data_object.get("invoice")- if invoice_id:- try:- invoice = await run_in_threadpool(stripe.Invoice.retrieve, invoice_id)- except stripe.StripeError:- logger.exception(- "stripe_webhook: %s could not retrieve invoice %s; skipping",- event_type,- invoice_id,+ # Wrap handler dispatch so a downstream failure releases the dedup claim;+ # otherwise Stripe's retry would hit the live key and silently drop the+ # event. Concurrent retries that arrive *during* in-flight processing+ # still hit the live claim and are deduped.+ try:+ if event_type in (+ "checkout.session.completed",+ "checkout.session.async_payment_succeeded",+ ):+ session_id = data_object.get("id")+ if not session_id:+ logger.warning(+ "stripe_webhook: %s missing data.object.id; ignoring", event_type)return Response(status_code=200)- invoice_payload = cast(dict, invoice)- if event_type == "invoice_payment.paid":- await handle_subscription_payment_success(invoice_payload)- else:- await handle_subscription_payment_failure(invoice_payload)-- # `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects- # (Dispute/Refund). The Stripe webhook payload's `data.object` is a- # StripeObject (a dict subclass) carrying that runtime shape, so we cast- # to satisfy the type checker without changing runtime behaviour.- if event_type == "charge.dispute.created":- await UserCredit().handle_dispute(cast(stripe.Dispute, data_object))-- if event_type == "refund.created" or event_type == "charge.dispute.closed":- await UserCredit().deduct_credits(- cast("stripe.Refund | stripe.Dispute", data_object)- )+ await UserCredit().fulfill_checkout(session_id=session_id)+ await sync_tier_from_checkout_session(data_object)++ if event_type in (+ "customer.subscription.created",+ "customer.subscription.updated",+ "customer.subscription.deleted",+ ):+ await sync_subscription_from_stripe(data_object)++ # `subscription_schedule.updated` is deliberately omitted: our own+ # `SubscriptionSchedule.create` + `.modify` calls in+ # `_schedule_downgrade_at_period_end` would fire that event right back+ # at us and loop redundant traffic through this handler. We only care+ # about state transitions (released / completed); phase advance to+ # the new price is already covered by `customer.subscription.updated`.+ if event_type in (+ "subscription_schedule.released",+ "subscription_schedule.completed",+ ):+ 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)++ # New Stripe API (≥2025-04-01) split the per-payment events off the+ # Invoice resource. data.object is an InvoicePayment, not an Invoice,+ # so we hydrate the underlying Invoice before delegating to the+ # existing handlers. A transient ``stripe.StripeError`` here propagates+ # to the outer handler so the dedup claim is released and Stripe sees+ # a 5xx + retries — swallowing it with a 200 would silently drop the+ # event and leave the dedup key blocking the next delivery.+ if event_type in ("invoice_payment.paid", "invoice_payment.payment_failed"):+ invoice_id = data_object.get("invoice")+ if invoice_id:+ invoice = await run_in_threadpool(stripe.Invoice.retrieve, invoice_id)+ invoice_payload = cast(dict, invoice)+ if event_type == "invoice_payment.paid":+ await handle_subscription_payment_success(invoice_payload)+ else:+ await handle_subscription_payment_failure(invoice_payload)++ # `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects+ # (Dispute/Refund). The Stripe webhook payload's `data.object` is a+ # StripeObject (a dict subclass) carrying that runtime shape, so we+ # cast to satisfy the type checker without changing runtime behaviour.+ if event_type == "charge.dispute.created":+ await UserCredit().handle_dispute(cast(stripe.Dispute, data_object))++ if event_type == "refund.created" or event_type == "charge.dispute.closed":+ await UserCredit().deduct_credits(+ cast("stripe.Refund | stripe.Dispute", data_object)+ )+ except Exception:+ # Release the dedup claim so Stripe's retry isn't no-op'd. Re-raise+ # so the webhook returns 500 and Stripe retries (the normal contract).+ await _release_stripe_event(event_id)+ raisereturn Response(status_code=200)diff --git a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.pyindex 86b6b2bdf3..42d9d219f8 100644--- a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py@@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, MagicMockimport fastapiimport fastapi.testclient+import pytestimport pytest_mockimport stripe@@ -13,7 +14,7 @@ from backend.data.credit import (sync_tier_from_checkout_session,)-from .v1 import v1_router+from .v1 import _claim_stripe_event, _release_stripe_event, v1_routerapp = fastapi.FastAPI()app.include_router(v1_router)@@ -67,6 +68,51 @@ def test_stripe_webhook_checkout_calls_sync_tier_helper(mock_sync.assert_called_once()+def test_stripe_webhook_skips_handlers_on_replayed_event(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A second delivery of the same Stripe event.id must short-circuit.++ Stripe retries the same event on non-2xx responses, and not every+ downstream handler is independently idempotent (e.g. ``fulfill_checkout``+ relies on a checkout-state flag that races on concurrent retries). The+ webhook dedupes by event.id so retries don't re-run any handler.+ """+ event = _make_checkout_event("subscription", "sub_dedup")+ event["id"] = "evt_already_seen"+ mocker.patch(+ "stripe.Webhook.construct_event",+ return_value=event,+ )+ mocker.patch(+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",+ new="whsec_test",+ )+ # Simulate "this event was already processed".+ mocker.patch(+ "backend.api.features.v1._claim_stripe_event",+ new_callable=AsyncMock,+ return_value=False,+ )+ mock_fulfill = mocker.patch(+ "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock+ )+ mock_sync = mocker.patch(+ "backend.api.features.v1.sync_tier_from_checkout_session",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/credits/stripe_webhook",+ content=b"{}",+ headers={"stripe-signature": "t=1,v1=sig"},+ )++ assert response.status_code == 200+ mock_fulfill.assert_not_called()+ mock_sync.assert_not_called()++def test_stripe_webhook_checkout_propagates_sync_failure(mocker: pytest_mock.MockFixture,) -> None:@@ -102,6 +148,205 @@ def test_stripe_webhook_checkout_propagates_sync_failure(assert response.status_code >= 500+def test_stripe_webhook_releases_dedup_claim_on_handler_failure(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A handler exception must release the dedup claim so Stripe's retry+ can rerun the handler — otherwise the event is silently dropped.+ """+ event = _make_checkout_event("subscription", "sub_release")+ event["id"] = "evt_handler_fails"+ mocker.patch(+ "stripe.Webhook.construct_event",+ return_value=event,+ )+ mocker.patch(+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",+ new="whsec_test",+ )+ mocker.patch(+ "backend.api.features.v1._claim_stripe_event",+ new_callable=AsyncMock,+ return_value=True,+ )+ mock_release = mocker.patch(+ "backend.api.features.v1._release_stripe_event",+ new_callable=AsyncMock,+ )+ mocker.patch(+ "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock+ )+ mocker.patch(+ "backend.api.features.v1.sync_tier_from_checkout_session",+ new_callable=AsyncMock,+ side_effect=stripe.StripeError("downstream blew up"),+ )++ nonraising_client = fastapi.testclient.TestClient(+ app, raise_server_exceptions=False+ )+ response = nonraising_client.post(+ "/credits/stripe_webhook",+ content=b"{}",+ headers={"stripe-signature": "t=1,v1=sig"},+ )++ assert response.status_code >= 500+ mock_release.assert_awaited_once_with("evt_handler_fails")+++def test_stripe_webhook_releases_dedup_on_invoice_retrieve_failure(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A ``stripe.StripeError`` raised by ``Invoice.retrieve`` while hydrating+ an ``invoice_payment.paid`` event must propagate out so the outer handler+ releases the dedup claim. Swallowing it with a 200 would silently drop+ the event AND leave the dedup key blocking the next delivery for 24h.+ """+ event = {+ "id": "evt_retrieve_fails",+ "type": "invoice_payment.paid",+ "data": {"object": {"id": "ip_test", "invoice": "in_retrieve_fail"}},+ }+ mocker.patch(+ "stripe.Webhook.construct_event",+ return_value=event,+ )+ mocker.patch(+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",+ new="whsec_test",+ )+ mocker.patch(+ "backend.api.features.v1._claim_stripe_event",+ new_callable=AsyncMock,+ return_value=True,+ )+ mock_release = mocker.patch(+ "backend.api.features.v1._release_stripe_event",+ new_callable=AsyncMock,+ )+ mocker.patch(+ "backend.api.features.v1.stripe.Invoice.retrieve",+ side_effect=stripe.StripeError("stripe down"),+ )++ nonraising_client = fastapi.testclient.TestClient(+ app, raise_server_exceptions=False+ )+ response = nonraising_client.post(+ "/credits/stripe_webhook",+ content=b"{}",+ headers={"stripe-signature": "t=1,v1=sig"},+ )++ assert response.status_code >= 500+ mock_release.assert_awaited_once_with("evt_retrieve_fails")+++# ---------------------------------------------------------------------------+# _claim_stripe_event / _release_stripe_event unit tests+# ---------------------------------------------------------------------------+++async def test_claim_stripe_event_first_delivery_returns_true(+ mocker: pytest_mock.MockFixture,+) -> None:+ """First delivery acquires the dedup key — Redis ``SET nx=True`` reports+ success and the caller proceeds with handler dispatch."""+ redis_mock = MagicMock()+ redis_mock.set = AsyncMock(return_value=True)+ mocker.patch(+ "backend.api.features.v1.get_redis_async",+ new_callable=AsyncMock,+ return_value=redis_mock,+ )++ assert await _claim_stripe_event("evt_first") is True+ redis_mock.set.assert_awaited_once()+ _, kwargs = redis_mock.set.call_args+ assert kwargs.get("nx") is True+++async def test_claim_stripe_event_replay_returns_false(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Replay: ``SET nx=True`` returns ``None`` because the key already+ exists, so the caller short-circuits handler dispatch."""+ redis_mock = MagicMock()+ redis_mock.set = AsyncMock(return_value=None)+ mocker.patch(+ "backend.api.features.v1.get_redis_async",+ new_callable=AsyncMock,+ return_value=redis_mock,+ )++ assert await _claim_stripe_event("evt_replay") is False+++async def test_claim_stripe_event_empty_id_falls_open() -> None:+ """Empty ``event_id`` falls open (True) so the malformed-payload branch+ further down can decide what to do — Redis is never touched."""+ assert await _claim_stripe_event("") is True+++async def test_claim_stripe_event_redis_error_falls_open(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Redis unavailable → fall open and let processing continue. Better to+ risk a rare duplicate than to drop a real event during a Redis outage."""+ mocker.patch(+ "backend.api.features.v1.get_redis_async",+ new_callable=AsyncMock,+ side_effect=RuntimeError("redis cluster down"),+ )++ assert await _claim_stripe_event("evt_redis_down") is True+++async def test_release_stripe_event_deletes_key(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Successful release: DEL on the dedup key so the next delivery can+ re-acquire the claim."""+ redis_mock = MagicMock()+ redis_mock.delete = AsyncMock()+ mocker.patch(+ "backend.api.features.v1.get_redis_async",+ new_callable=AsyncMock,+ return_value=redis_mock,+ )++ await _release_stripe_event("evt_release")+ redis_mock.delete.assert_awaited_once()+++async def test_release_stripe_event_empty_id_noop() -> None:+ """Empty ``event_id`` is a no-op so a malformed event doesn't error+ while we're trying to clean up after it."""+ await _release_stripe_event("") # must not raise+++async def test_release_stripe_event_swallows_redis_error(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Redis errors during release must not propagate — we're already on+ the failure path and re-raising would mask the original error."""+ mocker.patch(+ "backend.api.features.v1.get_redis_async",+ new_callable=AsyncMock,+ side_effect=RuntimeError("redis cluster down"),+ )++ await _release_stripe_event("evt_release_fails") # must not raise++# ---------------------------------------------------------------------------# sync_tier_from_checkout_session unit tests# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex cf1e7d654e..4f032cb2ec 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -2723,8 +2723,8 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:# 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.+ # handler reads ``paid_out_of_band`` and skips its grant path so the+ # balance debit isn't reversed if the credit-grant flag is on.if invoice_id:try:await run_in_threadpool(@@ -2773,16 +2773,29 @@ async def handle_subscription_payment_failure(invoice: dict) -> None: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:+ """Optionally grant AutoGPT credits equal to the paid Stripe invoice amount.++ Gated behind ``settings.config.enable_subscription_credit_grant`` which+ is OFF by default — Pro Monthly subscribers should not receive a matching+ automation-credit grant on every invoice, and prorated upgrade invoices+ were producing surprise grants (each fresh invoice id slipped past the+ per-invoice idempotency key). The handler stays wired into the webhook+ so the config can be flipped on per environment if/when product wants+ "$ paid == $ in AutoGPT balance"; turning it on without first revisiting+ proration/renewal accounting will reintroduce the same surprise grants.++ When enabled, grants ``invoice.amount_paid`` cents keyed by ``invoice_id``+ so Stripe webhook retries for the *same* invoice don't double-grant.+ Distinct invoices (e.g. prorated upgrade + monthly cycle) are *not*+ deduplicated against each other — that's an intentional behaviour of the+ paid-invoice grant, not a bug, and is why the flag should stay off until+ the accounting model around proration is settled.++ Skipped (even when the flag is on):- 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).+ - Invoices already covered from balance via ``paid_out_of_band``."""customer_id = invoice.get("customer")if not customer_id:@@ -2830,6 +2843,16 @@ async def handle_subscription_payment_success(invoice: dict) -> None:)return+ if not settings.config.enable_subscription_credit_grant:+ logger.debug(+ "handle_subscription_payment_success: credit grant disabled by config"+ " for user %s (invoice %s, sub %s); skipping",+ user.id,+ invoice_id,+ sub_id,+ )+ return+try:await UserCredit()._add_transaction(user_id=user.id,diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.pyindex f3f7b4ef02..8b185a6872 100644--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py@@ -1588,9 +1588,24 @@ async def test_handle_subscription_payment_failure_passes_invoice_id_as_transactassert kwargs.get("transaction_key") == "in_idempotency_test"+def _patch_credit_grant_config(enabled: bool):+ """Patch ``settings.config.enable_subscription_credit_grant`` for the+ success handler's gate check.++ The setting is OFF by default, so the success-handler tests that exercise+ the grant path must explicitly opt in; the disabled-path test below+ asserts the default behaviour.+ """+ return patch(+ "backend.data.credit.settings.config.enable_subscription_credit_grant",+ new=enabled,+ )++@pytest.mark.asyncio-async def test_handle_subscription_payment_success_grants_credits():- """A paid subscription invoice grants credits = amount_paid, keyed by invoice_id."""+async def test_handle_subscription_payment_success_grants_credits_when_enabled():+ """When the credit-grant config is on, a paid sub invoice grants credits+ equal to ``amount_paid`` keyed by invoice id."""mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)invoice = {"id": "in_abc123",@@ -1610,6 +1625,7 @@ async def test_handle_subscription_payment_success_grants_credits():"backend.data.credit.UserCredit._add_transaction",new=add_tx_mock,),+ _patch_credit_grant_config(True),):await handle_subscription_payment_success(invoice)@@ -1619,9 +1635,52 @@ async def test_handle_subscription_payment_success_grants_credits():assert kwargs["transaction_key"] == "INVOICE-in_abc123"+async def test_handle_subscription_payment_success_skips_when_disabled():+ """Default-off: with the config disabled, an otherwise grant-eligible+ invoice is a no-op. Guards against an accidental re-enablement of the+ post-#12933 behaviour (Pro Monthly subscribers receiving matching+ automation credits).++ Asserts against the REAL default (no patching of the flag) so flipping+ ``enable_subscription_credit_grant`` to True in settings.py fails this+ test rather than silently passing.+ """+ from backend.util.settings import Settings++ assert Settings().config.enable_subscription_credit_grant is False, (+ "Default flipped — this regression test asserts the OFF default; "+ "either revert the default or update the assertion intentionally."+ )++ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)+ invoice = {+ "id": "in_flag_off",+ "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_not_called()++@pytest.mark.asyncioasync def test_handle_subscription_payment_success_skips_non_subscription_invoice():- """Invoices with no subscription field (one-off invoices) are no-ops."""+ """Invoices with no subscription field (one-off invoices) are no-ops —+ short-circuit lands before the flag check, so no LD eval is needed."""invoice = {"id": "in_abc123","customer": "cus_123",@@ -1661,6 +1720,7 @@ async def test_handle_subscription_payment_success_skips_paid_out_of_band():"backend.data.credit.UserCredit._add_transaction",new=add_tx_mock,),+ _patch_credit_grant_config(True),):await handle_subscription_payment_success(invoice)add_tx_mock.assert_not_called()@@ -1687,6 +1747,7 @@ async def test_handle_subscription_payment_success_skips_zero_amount():"backend.data.credit.UserCredit._add_transaction",new=add_tx_mock,),+ _patch_credit_grant_config(True),):await handle_subscription_payment_success(invoice)add_tx_mock.assert_not_called()@@ -1725,6 +1786,7 @@ async def test_handle_subscription_payment_success_skips_unknown_user():"backend.data.credit.UserCredit._add_transaction",new=add_tx_mock,),+ _patch_credit_grant_config(True),):await handle_subscription_payment_success(invoice)add_tx_mock.assert_not_called()@@ -1750,6 +1812,7 @@ async def test_handle_subscription_payment_success_skips_enterprise():"backend.data.credit.UserCredit._add_transaction",new=add_tx_mock,),+ _patch_credit_grant_config(True),):await handle_subscription_payment_success(invoice)add_tx_mock.assert_not_called()@@ -1777,6 +1840,7 @@ async def test_handle_subscription_payment_success_idempotent_on_unique_violatio"backend.data.credit.UserCredit._add_transaction",new=add_tx_mock,),+ _patch_credit_grant_config(True),):await handle_subscription_payment_success(invoice)add_tx_mock.assert_awaited_once()diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex dacfcf8f6e..1431842154 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -124,6 +124,17 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):default=True,description="If authentication is enabled or not",)+ enable_subscription_credit_grant: bool = Field(+ default=False,+ description=(+ "If True, every paid Stripe subscription invoice grants AutoGPT"+ " credits equal to invoice.amount_paid. OFF by default — there is"+ " no product mandate for '$ paid == $ in credits', and prorated"+ " upgrade invoices each produce a separate grant (distinct"+ " invoice ids slip past the per-invoice idempotency key). Flip on"+ " per environment intentionally if/when product wants that UX."+ ),+ )enable_credit: bool = Field(default=False,description="If user credit system is enabled or not",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 b9c8b87830..27cf1e23b0 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@@ -266,7 +266,7 @@ export function SubscriptionTierSection() {<p className="text-sm text-neutral-600 dark:text-neutral-400">{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.`}{" "}+ : `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.`}{" "}Are you sure?</p><Dialog.Footer>@@ -334,8 +334,8 @@ export function SubscriptionTierSection() {<Dialog.Content><p className="text-sm text-neutral-600 dark:text-neutral-400">{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.`}+ ? `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.`+ : `You'll be redirected to Stripe to enter payment details and start your ${getTierLabel(pendingUpgradeTier ?? "")} subscription.`}</p><Dialog.Footer><Buttondiff --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 e9d623e389..8f0d39cad2 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@@ -95,7 +95,7 @@ export function useSubscriptionTierSection() {? "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.`,+ : `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.`,});} catch (e: unknown) {const msg =