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): redesign usage limits and review upgrade charges (#15215)
Toran Bruce Richards23f10ce008a7
diff --git a/.github/scripts/test_e2e_seed_cache_contract.py b/.github/scripts/test_e2e_seed_cache_contract.pyindex 62b3787536..6c88fd1918 100644--- a/.github/scripts/test_e2e_seed_cache_contract.py+++ b/.github/scripts/test_e2e_seed_cache_contract.py@@ -87,6 +87,15 @@ class E2ESeedCacheContractTests(unittest.TestCase):workflow.index("- name: Run Playwright E2E suite"),)+ def test_seed_dump_excludes_migration_owned_activation_policy(self):+ workflow = (+ Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"+ ).read_text(encoding="utf-8")+ dump = workflow.split("pg_dump -U postgres", 1)[1].split(+ "postgres > /tmp/e2e_test_data.sql", 1+ )[0]+ self.assertIn("--exclude-table='platform.\"PaidUsageActivationPolicy\"'", dump)+def test_seed_cache_key_uses_pristine_checkout(self):workflow = (Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"diff --git a/.github/workflows/platform-fullstack-ci.yml b/.github/workflows/platform-fullstack-ci.ymlindex 47da76b385..3e4fa70ee6 100644--- a/.github/workflows/platform-fullstack-ci.yml+++ b/.github/workflows/platform-fullstack-ci.yml@@ -495,6 +495,7 @@ jobs:pg_dump -U postgres --data-only --column-inserts \--schema=platform \--exclude-table='platform._prisma_migrations' \+ --exclude-table='platform."PaidUsageActivationPolicy"' \--exclude-table='platform.apscheduler_jobs' \--exclude-table='platform.apscheduler_jobs_batched_notifications' \postgres > /tmp/e2e_test_data.sqldiff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.pyindex e8ac028dfb..05b138a194 100644--- a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py@@ -65,6 +65,15 @@ from backend.data.subscription_trial_conversion import (get_cancel_pending_trial,is_trial_plan,)+from backend.data.subscription_upgrade import (+ preview_subscription_upgrade,+ validate_subscription_upgrade_preview,+)+from backend.data.subscription_upgrade_models import (+ SubscriptionUpgradePreview,+ SubscriptionUpgradePreviewRequest,+ UpgradePreviewUnavailable,+)from backend.data.user import get_user_by_idfrom backend.notifications import lifecyclefrom backend.notifications.queue import queue_pass_work@@ -87,6 +96,8 @@ class SubscriptionTierRequest(BaseModel):success_url: str = ""cancel_url: str = ""billing_cycle: Literal["monthly", "yearly"] = "monthly"+ proration_date: int | None = Field(default=None, gt=0)+ preview_id: str | None = Field(default=None, pattern=r"^[a-f0-9]{32}$")surface: Optional[Literal["onboarding", "paywall_gate", "billing"]] = Field(default=None,description="Where the plan was picked; analytics only.",@@ -355,6 +366,35 @@ async def get_subscription_status(return response+ path="/credits/subscription/preview",+ summary="Review the prorated charge for a paid Pro-to-Max upgrade",+ operation_id="previewSubscriptionUpgrade",+ dependencies=[+ Security(requires_user),+ Depends(enforce_subscription_status_rate_limit),+ ],+)+async def preview_tier_upgrade(+ request: SubscriptionUpgradePreviewRequest,+ user_id: Annotated[str, Security(get_user_id)],+) -> SubscriptionUpgradePreview:+ enabled, _ = await evaluate_feature_flag(+ Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False+ )+ if not enabled:+ raise HTTPException(422, "Subscription upgrades are unavailable.")+ try:+ return await preview_subscription_upgrade(user_id, request)+ except UpgradePreviewUnavailable as exc:+ raise HTTPException(409, str(exc)) from exc+ except (stripe.StripeError, ValueError) as exc:+ logger.exception("Could not preview subscription upgrade for user %s", user_id)+ raise HTTPException(+ 502, "Unable to review the charge. Please try again."+ ) from exc++@router.post(path="/credits/subscription",summary="Update subscription tier or start a Stripe Checkout session",@@ -512,12 +552,38 @@ async def update_subscription_tier(tier,None if converts_trial else target_price_id,)- if await modify_stripe_subscription_for_tier(- user_id, tier, request.billing_cycle- ):+ if request.preview_id is not None or request.proration_date is not None:+ if (+ request.preview_id is None+ or request.proration_date is None+ or tier != SubscriptionTier.MAX+ ):+ raise HTTPException(422, "A complete Max upgrade review is required.")+ quote = await validate_subscription_upgrade_preview(+ user_id,+ SubscriptionUpgradePreviewRequest(+ tier="MAX", billing_cycle=request.billing_cycle+ ),+ request.preview_id,+ request.proration_date,+ )+ modified = await modify_stripe_subscription_for_tier(+ user_id,+ tier,+ request.billing_cycle,+ proration_date=request.proration_date,+ upgrade_preview=quote,+ )+ else:+ modified = await modify_stripe_subscription_for_tier(+ user_id, tier, request.billing_cycle+ )+ if modified:return await get_subscription_status(user_id)except TrialConversionRefused as e:raise HTTPException(status_code=409, detail=str(e))+ except UpgradePreviewUnavailable as exc:+ raise HTTPException(409, str(exc)) from excexcept ValueError as e:raise HTTPException(status_code=422, detail=str(e))except stripe.CardError as e:diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/upgrade_preview_test.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/upgrade_preview_test.pynew file mode 100644index 0000000000..237bafd40a--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/upgrade_preview_test.py@@ -0,0 +1,205 @@+"""Upgrade previews expose the charge before an immediate paid-tier change."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import fastapi+import pytest+import stripe+from autogpt_libs.auth.jwt_utils import get_jwt_payload+from fastapi.testclient import TestClient+from prisma.enums import SubscriptionTier++from backend.api.features.billing.subscriptions import routes+from backend.data.subscription_upgrade_models import UpgradePreviewUnavailable++USER_ID = "3e53486c-cf57-477e-ba2a-cb02dc828e1a"+PREVIEW_ID = "a" * 32+DATE = 1791374400+PREVIEW = {+ "preview_id": PREVIEW_ID,+ "amount_due": 25258,+ "tax_amount": 0,+ "tax_included": False,+ "adjustment_amount": 0,+ "currency": "usd",+ "proration_date": DATE,+ "period_end": DATE + 2500000,+ "expires_at": DATE + 900,+ "recurring_amount": 32000,+ "recurring_tax_included": False,+ "billing_cycle": "monthly",+ "lines": [],+}++[email protected](autouse=True)+def graph_cleanup():+ """These ASGI tests mock data boundaries and never create graphs."""+ yield+++def client(monkeypatch):+ app = fastapi.FastAPI()+ app.include_router(routes.router)+ app.dependency_overrides[routes.enforce_subscription_status_rate_limit] = (+ lambda: None+ )+ app.dependency_overrides[get_jwt_payload] = lambda: {+ "sub": USER_ID,+ "role": "user",+ "email": "[email protected]",+ }+ monkeypatch.setattr(+ routes, "evaluate_feature_flag", AsyncMock(return_value=(True, True))+ )+ monkeypatch.setattr(+ routes,+ "get_user_by_id",+ AsyncMock(return_value=SimpleNamespace(subscription_tier=SubscriptionTier.PRO)),+ )+ monkeypatch.setattr(+ routes, "get_user_billing_cycle", AsyncMock(return_value="monthly")+ )+ monkeypatch.setattr(+ routes,+ "get_active_subscription_period_end",+ AsyncMock(return_value=DATE + 2500000),+ )+ monkeypatch.setattr(+ routes, "get_subscription_price_id", AsyncMock(return_value="price_max")+ )+ monkeypatch.setattr(+ routes,+ "get_subscription_status",+ AsyncMock(+ return_value=routes.SubscriptionStatusResponse(+ tier="MAX",+ monthly_cost=32000,+ tier_costs={"PRO": 5000, "MAX": 32000},+ proration_credit_cents=0,+ )+ ),+ )+ with TestClient(app) as client:+ yield client+++def test_preview_uses_authenticated_user_and_requested_cycle(client, monkeypatch):+ preview = AsyncMock(return_value={**PREVIEW, "billing_cycle": "yearly"})+ monkeypatch.setattr(routes, "preview_subscription_upgrade", preview)+ response = client.post(+ "/credits/subscription/preview",+ json={"tier": "MAX", "billing_cycle": "yearly", "user_id": "other-user"},+ )+ assert response.status_code == 200+ assert response.json()["amount_due"] == 25258+ assert preview.await_args.args[0] == USER_ID+ assert preview.await_args.args[1].billing_cycle == "yearly"+++def test_failed_preview_does_not_mutate_subscription(client, monkeypatch):+ preview = AsyncMock(side_effect=UpgradePreviewUnavailable("Review unavailable"))+ modify = AsyncMock()+ monkeypatch.setattr(routes, "preview_subscription_upgrade", preview)+ monkeypatch.setattr(routes, "modify_stripe_subscription_for_tier", modify)+ response = client.post("/credits/subscription/preview", json={"tier": "MAX"})+ assert response.status_code == 409+ modify.assert_not_awaited()+++def test_confirmation_validates_review_and_passes_same_date(client, monkeypatch):+ quote = object()+ validate = AsyncMock(return_value=quote)+ modify = AsyncMock(return_value=True)+ monkeypatch.setattr(routes, "validate_subscription_upgrade_preview", validate)+ monkeypatch.setattr(routes, "modify_stripe_subscription_for_tier", modify)+ response = client.post(+ "/credits/subscription",+ json={"tier": "MAX", "preview_id": PREVIEW_ID, "proration_date": DATE},+ )+ assert response.status_code == 200+ assert validate.await_args.args[0] == USER_ID+ assert validate.await_args.args[2:] == (PREVIEW_ID, DATE)+ modify.assert_awaited_once_with(+ USER_ID,+ SubscriptionTier.MAX,+ "monthly",+ proration_date=DATE,+ upgrade_preview=quote,+ )+++def test_changed_quote_requires_review_before_any_charge(client, monkeypatch):+ monkeypatch.setattr(+ routes,+ "validate_subscription_upgrade_preview",+ AsyncMock(side_effect=UpgradePreviewUnavailable("Review again")),+ )+ modify = AsyncMock()+ monkeypatch.setattr(routes, "modify_stripe_subscription_for_tier", modify)+ response = client.post(+ "/credits/subscription",+ json={"tier": "MAX", "preview_id": PREVIEW_ID, "proration_date": DATE},+ )+ assert response.status_code == 409+ modify.assert_not_awaited()+++ "partial", [{"preview_id": PREVIEW_ID}, {"proration_date": DATE}]+)+def test_partial_review_cannot_backdate_a_charge(client, monkeypatch, partial):+ modify = AsyncMock()+ monkeypatch.setattr(routes, "modify_stripe_subscription_for_tier", modify)+ response = client.post("/credits/subscription", json={"tier": "MAX", **partial})+ assert response.status_code == 422+ modify.assert_not_awaited()+++ "failure,status",+ [+ (stripe.CardError("Declined", "payment_method", "card_declined"), 402),+ (+ stripe.CardError(+ "Authentication required",+ "payment_method",+ "subscription_payment_intent_requires_action",+ ),+ 402,+ ),+ (+ stripe.InvalidRequestError(+ "No payment method",+ "default_payment_method",+ code="resource_missing",+ http_status=400,+ ),+ 402,+ ),+ (stripe.APIConnectionError("Connection lost"), 502),+ (stripe.APIError("Internal server error", http_status=500), 502),+ (stripe.RateLimitError("Rate limited", http_status=429), 502),+ (stripe.IdempotencyError("Request in progress", http_status=409), 502),+ ],+)+def test_only_definite_payment_failures_return_402(+ client, monkeypatch, failure, status+):+ monkeypatch.setattr(+ routes,+ "validate_subscription_upgrade_preview",+ AsyncMock(return_value=object()),+ )+ monkeypatch.setattr(+ routes,+ "modify_stripe_subscription_for_tier",+ AsyncMock(side_effect=failure),+ )+ response = client.post(+ "/credits/subscription",+ json={"tier": "MAX", "preview_id": PREVIEW_ID, "proration_date": DATE},+ )+ assert response.status_code == statusdiff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_models.py b/autogpt_platform/backend/backend/api/features/subscription_trial_models.pyindex 31bfca36b4..4a42df663a 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_models.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_models.py@@ -4,6 +4,7 @@ from typing import Literalfrom pydantic import BaseModel, Fieldfrom backend.data.subscription_trial_config import AcceptedTrialOffer+from backend.data.subscription_trial_invoice import TrialPaymentDuefrom backend.data.subscription_trial_rejection import TrialRejectionReason@@ -30,9 +31,11 @@ class TrialStatusResponse(BaseModel):ends_at: datetime | None = Nonecancel_at_period_end: bool = Falseallowance_used_percent: float | None = None+ usage_policy: Literal["lifetime", "rolling"] | None = Noneactive: bool = Falseconverted: bool = Falseonboarding_credits_previously_received: bool = False+ payment_due: TrialPaymentDue | None = Noneclass TrialCheckoutRequest(BaseModel):diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.pyindex c59aa8c3bd..e2979b27c8 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py@@ -40,6 +40,7 @@ from backend.data.subscription_trial_checkout import (resolve_trial_price,)from backend.data.subscription_trial_config import get_trial_offer+from backend.data.subscription_trial_invoice import get_trial_payment_duefrom backend.data.user import get_user_by_idfrom backend.util.product_analytics import track_checkout_startedfrom backend.util.settings import Settings@@ -83,6 +84,13 @@ async def get_trial_status(allowance_used_percent=min(100, 100 * trial.cost_microdollars / trial.offer.total_cost_limit),+ usage_policy=(+ "lifetime"+ if trial.offer.daily_cost_limit >= trial.offer.total_cost_limit+ and trial.offer.weekly_cost_limit >= trial.offer.total_cost_limit+ else "rolling"+ ),+ payment_due=await get_trial_payment_due(trial),)offer = await get_trial_offer(user_id, country=country)if offer is None or not await trial_seat_available(offer):diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.pyindex 98cce63469..31db430ff4 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py@@ -15,6 +15,7 @@ from prisma.enums import SubscriptionTierfrom backend.api.features import subscription_trial_routes as routesfrom backend.data.subscription_trial import TrialStatefrom backend.data.subscription_trial_config import AcceptedTrialOffer+from backend.data.subscription_trial_invoice import TrialPaymentDue@pytest.fixture(autouse=True)@@ -127,6 +128,41 @@ async def test_status_never_exposes_internal_spend_or_stripe_identifiers(assert status.converted is (trial_status == "active")+ "daily,weekly,total,expected",+ [+ (100_000_000, 20_000_000, 20_000_000, "lifetime"),+ (250_000, 1_000_000, 1_000_000, "rolling"),+ (5_000_000, 1_000_000, 2_000_000, "rolling"),+ (2_000_000, 2_000_000, 2_000_000, "lifetime"),+ ],+)+async def test_status_exposes_accepted_usage_policy(+ trial, daily, weekly, total, expected+):+ trial = trial.model_copy(+ update={+ "status": "active",+ "offer": trial.offer.model_copy(+ update={+ "daily_cost_limit": daily,+ "weekly_cost_limit": weekly,+ "total_cost_limit": total,+ }+ ),+ }+ )+ with (+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),+ patch.object(+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)+ ),+ ):+ status = await routes.get_trial_status(trial.user_id)+ assert status.model_dump().get("usage_policy") == expected++@pytest.mark.asyncioasync def test_status_exposes_safe_rejection_reason(trial):trial = trial.model_copy(@@ -142,6 +178,41 @@ async def test_status_exposes_safe_rejection_reason(trial):assert status.model_dump().get("rejection_reason") == "intro_offer_already_used"+async def test_past_due_status_carries_the_open_invoice(trial):+ trial = trial.model_copy(update={"status": "past_due", "subscription_id": "sub_1"})+ due = TrialPaymentDue(+ amount_due=5000,+ currency="usd",+ payment_url="https://invoice.stripe.com/i/acct_1/test_inv_1",+ )+ with (+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),+ patch.object(+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)+ ),+ patch.object(+ routes, "get_trial_payment_due", AsyncMock(return_value=due)+ ) as lookup,+ ):+ status = await routes.get_trial_status(trial.user_id)+ assert status.payment_due == due+ lookup.assert_awaited_once_with(trial)+++async def test_status_without_a_failed_charge_has_no_payment_due(trial):+ with (+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=None)),+ patch.object(+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)+ ),+ ):+ status = await routes.get_trial_status(trial.user_id)+ assert status.payment_due is None++@pytest.mark.asyncioasync def test_checkout_uses_authenticated_identity_and_server_return_urls(trial):app = FastAPI()diff --git a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.pyindex 4779b5bc6f..6ce3cac72e 100644--- a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py@@ -385,6 +385,7 @@ PERSONAL_ACTIVATION_ROUTES = {POOLED_MODEL_UNREACHABLE_ROUTES: dict[str, str] = {"get_subscription_status": "subscriptions are user-level, not org-pooled","update_subscription_tier": "subscriptions are user-level, not org-pooled",+ "preview_tier_upgrade": "previews only the caller's owned personal subscription","get_user_auto_top_up": "reads the caller's own User.top_up_config, not org data","stripe_webhook": ("unauthenticated by design, verified by Stripe signature; it fulfils "diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex 9865414796..3ede573f97 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -55,6 +55,11 @@ from backend.data.subscription_pending_cache import (invalidate_pending_subscription_change,)from backend.data.subscription_trial import get_subscription_trial+from backend.data.subscription_upgrade_cache import discard_subscription_upgrade_preview+from backend.data.subscription_upgrade_models import (+ StoredUpgradePreview,+ UpgradePreviewUnavailable,+)from backend.data.user import get_user_by_id, get_user_email_by_idfrom backend.notifications.queue import queue_notification_asyncfrom backend.util import posthog_client@@ -2115,11 +2120,14 @@ async def modify_stripe_subscription_for_tier(user_id: str,tier: SubscriptionTier,billing_cycle: BillingCycle = "monthly",+ *,+ proration_date: int | None = None,+ upgrade_preview: StoredUpgradePreview | None = None,) -> bool:"""Change a Stripe subscription to a new paid tier.Upgrades (e.g. PRO→BUSINESS) apply immediately via ``stripe.Subscription.modify``- with ``proration_behavior="create_prorations"``: Stripe credits unused time on+ with ``proration_behavior="always_invoice"``: Stripe credits unused time onthe old plan and charges the pro-rated amount for the new plan in the samebilling cycle.@@ -2157,6 +2165,18 @@ async def modify_stripe_subscription_for_tier(if not items:return Falsesub_id = sub.id+ if upgrade_preview and (+ upgrade_preview.user_id != user_id+ or upgrade_preview.subscription_id != sub_id+ or upgrade_preview.target_price_id != price_id+ or upgrade_preview.item_id != items[0].id+ or upgrade_preview.current_price_id != items[0].price.id+ or upgrade_preview.quantity != items[0].quantity+ or upgrade_preview.preview.proration_date != proration_date+ ):+ raise UpgradePreviewUnavailable(+ "Your subscription changed. Review the upgrade again."+ )# Invalidate the cache unconditionally on exit (success OR failure): any# Stripe mutation below — clearing cancel_at_period_end, releasing an old@@ -2216,10 +2236,32 @@ async def modify_stripe_subscription_for_tier("billing_cycle": billing_cycle,},}+ if proration_date is not None:+ modify_kwargs["proration_date"] = proration_date+ if upgrade_preview is not None:+ modify_kwargs["items"][0]["quantity"] = upgrade_preview.quantity+ modify_kwargs["idempotency_key"] = (+ f"subscription-upgrade:{upgrade_preview.preview.preview_id}"+ )if sub.cancel_at_period_end:modify_kwargs["cancel_at_period_end"] = False- await stripe_call(stripe.Subscription.modify_async, sub_id, **modify_kwargs)+ # Retire definitive failures cached by Stripe. Connection errors and+ # 5xx may have charged, so they must retain the same idempotency key.+ try:+ await stripe_call(stripe.Subscription.modify_async, sub_id, **modify_kwargs)+ except stripe.CardError:+ if upgrade_preview is not None:+ await discard_subscription_upgrade_preview(+ user_id, upgrade_preview.preview.preview_id+ )+ raise+ except stripe.InvalidRequestError as exc:+ if upgrade_preview is not None and exc.http_status in {400, 402}:+ await discard_subscription_upgrade_preview(+ user_id, upgrade_preview.preview.preview_id+ )+ raise# Flip the DB tier immediately. The customer.subscription.updated webhook# will also fire and set it again — idempotent. Without this synchronous# update, the UI refetches before the webhook lands and shows the olddiff --git a/autogpt_platform/backend/backend/data/subscription_activation_attempt.py b/autogpt_platform/backend/backend/data/subscription_activation_attempt.pyindex 3ce2dbf867..cc8c85b9a6 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_attempt.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_attempt.py@@ -51,7 +51,7 @@ async def save_quote(user_id,subscription_id,customer_id,- terms.model_dump_json(),+ terms.persisted_json(),return_to,model=ActivationAttempt,)@@ -71,7 +71,7 @@ async def save_confirmation(attempt: ActivationAttempt) -> ActivationAttempt:+ _COLUMNS,attempt.id,attempt.user_id,- attempt.terms.model_dump_json(),+ attempt.terms.persisted_json(),attempt.subscription_id,attempt.customer_id,model=ActivationAttempt,diff --git a/autogpt_platform/backend/backend/data/subscription_activation_checkout_fixtures.py b/autogpt_platform/backend/backend/data/subscription_activation_checkout_fixtures.pyindex 9d66f5513b..8d956731df 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_checkout_fixtures.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_checkout_fixtures.py@@ -117,3 +117,20 @@ def max_attempt(attempt, boundaries, trial, live_subscription):update={"confirmed_at": datetime.now(UTC)})return attempt+++def preview_lines(price_id: str, interval: str = "month"):+ return {+ "data": [+ {+ "type": "subscription",+ "subscription": "sub_1",+ "price": {"id": price_id},+ "period": {+ "start": 1791374400,+ "end": 1822910400 if interval == "year" else 1794052800,+ },+ }+ ],+ "has_more": False,+ }diff --git a/autogpt_platform/backend/backend/data/subscription_activation_checkout_test.py b/autogpt_platform/backend/backend/data/subscription_activation_checkout_test.pyindex 6b0d03f75a..b85b5893d4 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_checkout_test.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_checkout_test.py@@ -254,7 +254,21 @@ async def test_partially_used_and_exhausted_trials_keep_accepted_offer():trial.cost_microdollars = costcall = AsyncMock(- return_value={"customer": "cus_1", "currency": "usd", "amount_due": 4200}+ return_value={+ "customer": "cus_1",+ "currency": "usd",+ "amount_due": 4200,+ "lines": {+ "data": [+ {+ "type": "subscription",+ "subscription": "sub_1",+ "price": {"id": "price_pro"},+ "period": {"start": 1791374400, "end": 1794052800},+ }+ ]+ },+ })monkeypatch.setattr(billing, "stripe_call", call)terms = await billing.quote_terms(trial, live_subscription)diff --git a/autogpt_platform/backend/backend/data/subscription_activation_confirmation_integration_test.py b/autogpt_platform/backend/backend/data/subscription_activation_confirmation_integration_test.pyindex 190d4963e8..673ed2ed1f 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_confirmation_integration_test.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_confirmation_integration_test.py@@ -38,7 +38,7 @@ async def test_confirmed_trial_to_max_uses_confirmed_price_and_one_reset("currency": "usd","recurring": {"interval": "month", "interval_count": 1},}- mock_billing_boundaries(case, mocker, max_price)+ period = mock_billing_boundaries(case, mocker, max_price)mutation = mocker.patch("stripe.Subscription.modify_async",side_effect=partial(settle_conversion, case, max_price),@@ -48,6 +48,11 @@ async def test_confirmed_trial_to_max_uses_confirmed_price_and_one_reset(assert preview.status == "confirmation_required" and preview.termsassert preview.terms.plan == "MAX" and preview.terms.price_id == "price_max"assert preview.terms.amount_due == 6000 and not preview.usage_reset+ assert preview.terms.period_starts_at == datetime.fromtimestamp(+ period["start"], UTC+ )+ assert preview.terms.next_payment_at == datetime.fromtimestamp(period["end"], UTC)+ assert preview.terms.tax_amount == 0mutation.assert_not_called()assert await case.counters(None) == (trial_cost, trial_cost)assert preview.id@@ -149,6 +154,10 @@ async def prepare_trial_checkout(case, cost, tier="PRO"):def mock_billing_boundaries(case, mocker, max_price):+ now = int(datetime.now(UTC).timestamp())+ period = {"start": now, "end": now + 30 * 86400}+ line = deepcopy(case.invoice["lines"]["data"][0])+ line.update(amount=6000, price=max_price, period=period)mocker.patch.object(credit,"build_price_to_tier_map",@@ -170,10 +179,13 @@ def mock_billing_boundaries(case, mocker, max_price):"customer": case.subscription["customer"],"currency": "usd","amount_due": 6000,+ "total_tax_amounts": [],+ "lines": {"data": [line], "has_more": False},},None,),)+ return periodasync def settle_conversion(diff --git a/autogpt_platform/backend/backend/data/subscription_activation_invoice.py b/autogpt_platform/backend/backend/data/subscription_activation_invoice.pynew file mode 100644index 0000000000..f5954bdf5d--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_activation_invoice.py@@ -0,0 +1,106 @@+"""The invoice fields used to disclose an early trial conversion."""++from datetime import UTC, datetime++from pydantic import BaseModel++from backend.data.subscription_activation_models import ActivationUnavailable+from backend.data.subscription_activation_models import (+ InvoicePreview as BaseInvoicePreview,+)+++class InvoicePreview(BaseInvoicePreview):+ lines: "PreviewLines"+ total_tax_amounts: list["TaxAmount"] | None = None+ total_taxes: list["TaxAmount"] | None = None+ tax: int | None = None++ def paid_period(self, subscription_id: str, price_id: str):+ candidates = [+ line.period+ for line in self.lines.data+ if line.matches(subscription_id, price_id)+ and line.period.end > line.period.start+ ]+ if self.lines.has_more or not candidates:+ raise ActivationUnavailable("The paid period could not be established")+ period = max(candidates, key=lambda value: value.start)+ return (+ datetime.fromtimestamp(period.start, UTC),+ datetime.fromtimestamp(period.end, UTC),+ )++ def tax_total(self) -> int | None:+ taxes = self.total_taxes+ if taxes is None:+ taxes = self.total_tax_amounts+ return sum(tax.amount for tax in taxes) if taxes is not None else self.tax+++class TaxAmount(BaseModel):+ amount: int+++class Period(BaseModel):+ start: int+ end: int+++class PriceReference(BaseModel):+ id: str+++class PriceDetails(BaseModel):+ price: str+++class Pricing(BaseModel):+ price_details: PriceDetails | None = None+++class SubscriptionItemDetails(BaseModel):+ subscription: str+ proration: bool = False+++class LineParent(BaseModel):+ type: str+ subscription_item_details: SubscriptionItemDetails | None = None+++class PreviewLine(BaseModel):+ period: Period+ type: str | None = None+ subscription: str | None = None+ price: PriceReference | None = None+ proration: bool = False+ parent: LineParent | None = None+ pricing: Pricing | None = None++ def matches(self, subscription_id: str, price_id: str) -> bool:+ if self.parent and self.parent.type == "subscription_item_details":+ details = self.parent.subscription_item_details+ price = self.pricing.price_details if self.pricing else None+ return bool(+ details+ and price+ and not details.proration+ and details.subscription == subscription_id+ and price.price == price_id+ )+ return bool(+ self.type == "subscription"+ and not self.proration+ and self.subscription == subscription_id+ and self.price+ and self.price.id == price_id+ )+++class PreviewLines(BaseModel):+ data: list[PreviewLine]+ has_more: bool = False+++InvoicePreview.model_rebuild()diff --git a/autogpt_platform/backend/backend/data/subscription_activation_models.py b/autogpt_platform/backend/backend/data/subscription_activation_models.pyindex d58faa3bd7..6c3bc17a3b 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_models.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_models.py@@ -56,15 +56,31 @@ class ActivationTerms(BaseModel):charge_timing: Literal["on_confirmation"] = "on_confirmation"renewal_terms: strexpires_at: datetime+ trial_ends_at: datetime | None = None+ period_starts_at: datetime | None = None+ next_payment_at: datetime | None = None+ tax_amount: int | None = None@propertydef token(self) -> str:- return sha256(self.model_dump_json().encode()).hexdigest()+ return sha256(self.persisted_json().encode()).hexdigest()++ def persisted_json(self) -> str:+ return self.model_dump_json(exclude=self._undisclosed_fields())def same_charge_as(self, other: "ActivationTerms") -> bool:- return self.model_dump(exclude={"expires_at"}) == other.model_dump(- exclude={"expires_at"}- )+ excluded = {"expires_at", "period_starts_at", "next_payment_at"}+ excluded |= self._undisclosed_fields() | other._undisclosed_fields()+ return self.model_dump(exclude=excluded) == other.model_dump(exclude=excluded)++ def _undisclosed_fields(self) -> set[str]:+ fields = {+ "trial_ends_at": self.trial_ends_at,+ "period_starts_at": self.period_starts_at,+ "next_payment_at": self.next_payment_at,+ "tax_amount": self.tax_amount,+ }+ return {name for name, value in fields.items() if value is None}class ActivationConfirmRequest(BaseModel):diff --git a/autogpt_platform/backend/backend/data/subscription_activation_quote_test.py b/autogpt_platform/backend/backend/data/subscription_activation_quote_test.pynew file mode 100644index 0000000000..b0f487b194--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_activation_quote_test.py@@ -0,0 +1,127 @@+"""Payment review dates and tax come from the accepted subscription preview."""++from datetime import UTC, datetime, timedelta+from hashlib import sha256+from unittest.mock import AsyncMock++import pytest++from backend.data import subscription_activation_stripe as billing+from backend.data.subscription_activation_models import (+ ActivationTerms,+ ActivationUnavailable,+)++pytest_plugins = ("backend.data.subscription_trial_fixtures",)+++def quote_context(trial, subscription, monkeypatch):+ trial.ends_at = datetime(2026, 10, 12, 12, tzinfo=UTC)+ subscription["items"]["data"][0]["price"].update(+ unit_amount=trial.offer.unit_amount,+ currency=trial.offer.currency,+ recurring={"interval": "month", "interval_count": 1},+ )+ preview = {+ "customer": "cus_1",+ "currency": "usd",+ "amount_due": 6000,+ "total_tax_amounts": [{"amount": 700}, {"amount": 300}],+ "lines": {+ "has_more": False,+ "data": [+ {+ "type": "subscription",+ "subscription": "sub_1",+ "price": {"id": "price_pro"},+ "proration": False,+ "period": {"start": 1791374400, "end": 1794052800},+ }+ ],+ },+ }+ call = AsyncMock(return_value=preview)+ monkeypatch.setattr(billing, "stripe_call", call)+ return trial, billing.BillingSubscription.model_validate(subscription), preview++[email protected]("api_version", ["acacia", "basil"])+async def test_quote_discloses_trial_end_paid_period_and_actual_tax(+ quote_context, api_version+):+ trial, subscription, preview = quote_context+ if api_version == "basil":+ preview["total_taxes"] = preview.pop("total_tax_amounts")+ line = preview["lines"]["data"][0]+ line.pop("type")+ line.pop("subscription")+ line.pop("price")+ line["parent"] = {+ "type": "subscription_item_details",+ "subscription_item_details": {"subscription": "sub_1", "proration": False},+ }+ line["pricing"] = {"price_details": {"price": "price_pro"}}+ terms = await billing.quote_terms(trial, subscription)+ assert terms.trial_ends_at == trial.ends_at+ assert terms.period_starts_at == datetime(2026, 10, 7, 12, tzinfo=UTC)+ assert terms.next_payment_at == datetime(2026, 11, 7, 12, tzinfo=UTC)+ assert terms.tax_amount == 1000+ assert terms.amount_due == 6000+++async def test_quote_does_not_invent_zero_tax(quote_context):+ trial, subscription, preview = quote_context+ preview.pop("total_tax_amounts")+ assert (await billing.quote_terms(trial, subscription)).tax_amount is None+ preview["total_taxes"] = []+ assert (await billing.quote_terms(trial, subscription)).tax_amount == 0++[email protected]("invalid", ["unrelated", "missing", "incomplete"])+async def test_quote_requires_the_owned_subscription_paid_period(+ quote_context, invalid+):+ trial, subscription, preview = quote_context+ if invalid == "unrelated":+ preview["lines"]["data"][0]["subscription"] = "sub_other"+ elif invalid == "missing":+ preview["lines"]["data"] = []+ else:+ preview["lines"]["has_more"] = True+ with pytest.raises(ActivationUnavailable, match="paid period"):+ await billing.quote_terms(trial, subscription)+++async def test_quote_time_moves_without_requiring_new_charge_consent(quote_context):+ trial, subscription, preview = quote_context+ original = await billing.quote_terms(trial, subscription)+ preview["lines"]["data"][0]["period"]["start"] += 60+ preview["lines"]["data"][0]["period"]["end"] += 60+ updated = await billing.quote_terms(trial, subscription)+ assert original.same_charge_as(updated)+ preview["total_tax_amounts"][0]["amount"] += 1+ assert not original.same_charge_as(await billing.quote_terms(trial, subscription))+++def test_previously_persisted_quote_retains_its_confirmation_token():+ terms = ActivationTerms(+ price_id="price_pro",+ accepted_offer_token="offer",+ amount_due=5000,+ currency="usd",+ billing_interval="month",+ renewal_unit_amount=5000,+ renewal_terms="Renews monthly.",+ expires_at=datetime.now(UTC) + timedelta(minutes=15),+ )+ original = terms.model_dump_json(+ exclude={"trial_ends_at", "period_starts_at", "next_payment_at", "tax_amount"}+ )+ restored = ActivationTerms.model_validate_json(original)+ assert restored.token == sha256(original.encode()).hexdigest()+ assert restored.persisted_json() == originaldiff --git a/autogpt_platform/backend/backend/data/subscription_activation_stripe.py b/autogpt_platform/backend/backend/data/subscription_activation_stripe.pyindex ecc4aef6b7..b35301b945 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_stripe.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_stripe.py@@ -9,6 +9,7 @@ from prisma.models import Userfrom backend.data import creditfrom backend.data.stripe_client import stripe_call+from backend.data.subscription_activation_invoice import InvoicePreviewfrom backend.data.subscription_activation_models import (ActivationItem,ActivationPlan,@@ -17,7 +18,6 @@ from backend.data.subscription_activation_models import (ActivationUnavailable,BillingInvoice,BillingSubscription,- InvoicePreview,RenewalDiscount,RenewalTax,)@@ -150,6 +150,7 @@ def _quoted_terms(price: ActivationPrice,preview: InvoicePreview,) -> ActivationTerms:+ period_start, period_end = preview.paid_period(sub.id, price.id)return ActivationTerms(plan=target,price_id=price.id,@@ -173,6 +174,10 @@ def _quoted_terms("the trial. Cancel before the next renewal to avoid the next charge."),expires_at=datetime.now(UTC) + timedelta(minutes=15),+ trial_ends_at=trial.ends_at,+ period_starts_at=period_start,+ next_payment_at=period_end,+ tax_amount=preview.tax_total(),)diff --git a/autogpt_platform/backend/backend/data/subscription_activation_stripe_test.py b/autogpt_platform/backend/backend/data/subscription_activation_stripe_test.pyindex 997df733e8..170f9016ae 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_stripe_test.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_stripe_test.py@@ -5,6 +5,7 @@ from unittest.mock import AsyncMockimport pytestfrom backend.data import subscription_activation_stripe as billing+from backend.data.subscription_activation_checkout_fixtures import preview_linespytest_plugins = ("backend.data.subscription_trial_fixtures",)@@ -67,6 +68,16 @@ async def test_discount_duration_and_tax_changes_require_new_consent("customer": "cus_1","currency": "usd","amount_due": 2500,+ "lines": {+ "data": [+ {+ "type": "subscription",+ "subscription": "sub_1",+ "price": {"id": "price_pro"},+ "period": {"start": 1791374400, "end": 1794052800},+ }+ ]+ },"discounts": [{"coupon": {"percent_off": 50, "duration": "forever"}}],}monkeypatch.setattr(billing, "stripe_call", AsyncMock(return_value=invoice))@@ -110,6 +121,7 @@ async def test_alternate_quote_only_discloses_applicable_discounts("customer": "cus_1","currency": "usd","amount_due": 9000,+ "lines": preview_lines("price_max"),"discounts": [{"coupon": {@@ -141,6 +153,7 @@ async def test_restricted_discount_requires_known_selected_product("customer": "cus_1","currency": "usd","amount_due": 2500,+ "lines": preview_lines("price_pro"),"discounts": [{"coupon": {diff --git a/autogpt_platform/backend/backend/data/subscription_activation_target_recovery_test.py b/autogpt_platform/backend/backend/data/subscription_activation_target_recovery_test.pyindex 436f7fa2f9..53280a2f42 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_target_recovery_test.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_target_recovery_test.py@@ -127,7 +127,14 @@ async def test_saved_max_price_survives_catalog_change("recurring": {"interval": "month", "interval_count": 1},}assert fn == stripe.Invoice.create_preview_async- return {"customer": "cus_1", "currency": "usd", "amount_due": 8700}+ return {+ "customer": "cus_1",+ "currency": "usd",+ "amount_due": 8700,+ "lines": fixtures.preview_lines(+ kwargs["subscription_details"]["items"][0]["price"]+ ),+ }prices = AsyncMock(return_value="price_max")reads = AsyncMock(side_effect=read_stripe)diff --git a/autogpt_platform/backend/backend/data/subscription_activation_target_test.py b/autogpt_platform/backend/backend/data/subscription_activation_target_test.pyindex dfac6b418e..0067ebf8a5 100644--- a/autogpt_platform/backend/backend/data/subscription_activation_target_test.py+++ b/autogpt_platform/backend/backend/data/subscription_activation_target_test.py@@ -52,6 +52,7 @@ async def test_default_quote_retains_original_max_offer("customer": "cus_1","currency": "usd","amount_due": 4800,+ "lines": fixtures.preview_lines("price_retired_max"),}),)@@ -93,6 +94,7 @@ async def test_alternate_plan_quote_matches_exact_owned_item_mutation("customer": "cus_1","currency": "usd","amount_due": 8700,+ "lines": fixtures.preview_lines("price_target", interval),},])diff --git a/autogpt_platform/backend/backend/data/subscription_trial_invoice.py b/autogpt_platform/backend/backend/data/subscription_trial_invoice.pynew file mode 100644index 0000000000..a2375b9091--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_invoice.py@@ -0,0 +1,63 @@+"""The open invoice a trial's failed first charge leaves behind."""++import logging++import stripe+from pydantic import BaseModel, ValidationError++from backend.data.stripe_client import stripe_call+from backend.data.subscription_trial import TrialState+from backend.data.subscription_trial_payment import SubscriptionSnapshot++logger = logging.getLogger(__name__)++PAYMENT_DUE_STATUSES = frozenset({"past_due", "unpaid"})+++class TrialPaymentDue(BaseModel):+ amount_due: int+ currency: str+ payment_url: str+++async def get_trial_payment_due(trial: TrialState) -> TrialPaymentDue | None:+ """Paying this invoice on Stripe's hosted page converts the trial through+ the usual invoice-paid path. Checkout refuses a second plan while it is+ open, so it is the one way back to the plan besides Stripe's own retries.+ """+ if (+ trial.converted_at is not None+ or trial.subscription_id is None+ or trial.status not in PAYMENT_DUE_STATUSES+ ):+ return None+ try:+ snapshot = SubscriptionSnapshot.model_validate(+ await stripe_call(+ stripe.Subscription.retrieve_async,+ trial.subscription_id,+ expand=["latest_invoice"],+ )+ )+ except (stripe.StripeError, ValidationError):+ logger.warning(+ f"Could not read the open invoice for trial {trial.id}", exc_info=True+ )+ return None+ invoice = snapshot.latest_invoice+ if (+ snapshot.customer != trial.customer_id+ or snapshot.metadata.get("trial_enrollment_id") != trial.id+ or invoice is None+ or invoice.status != "open"+ or invoice.customer != trial.customer_id+ or invoice.amount_due <= 0+ or not invoice.currency+ or not invoice.hosted_invoice_url+ ):+ return None+ return TrialPaymentDue(+ amount_due=invoice.amount_due,+ currency=invoice.currency,+ payment_url=invoice.hosted_invoice_url,+ )diff --git a/autogpt_platform/backend/backend/data/subscription_trial_invoice_test.py b/autogpt_platform/backend/backend/data/subscription_trial_invoice_test.pynew file mode 100644index 0000000000..4d24deee8c--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_invoice_test.py@@ -0,0 +1,131 @@+from unittest.mock import AsyncMock, patch++import pytest+import stripe++from backend.data.subscription_trial import TrialState+from backend.data.subscription_trial_invoice import (+ TrialPaymentDue,+ get_trial_payment_due,+)++pytest_plugins = ("backend.data.subscription_trial_fixtures",)++PAYMENT_URL = "https://invoice.stripe.com/i/acct_1/test_inv_1"+++def past_due(trial: TrialState) -> TrialState:+ return trial.model_copy(update={"status": "past_due", "subscription_id": "sub_1"})+++def subscription(past_due: TrialState) -> dict:+ return {+ "id": "sub_1",+ "customer": past_due.customer_id,+ "status": "past_due",+ "metadata": {"user_id": past_due.user_id, "trial_enrollment_id": past_due.id},+ "latest_invoice": {+ "id": "in_1",+ "created": 1_760_270_400,+ "customer": past_due.customer_id,+ "status": "open",+ "amount_due": 5413,+ "currency": "usd",+ "hosted_invoice_url": PAYMENT_URL,+ },+ }+++def retrieve(subscription: dict):+ with patch.object(+ stripe.Subscription, "retrieve_async", AsyncMock(return_value=subscription)+ ) as lookup:+ yield lookup+++async def test_past_due_trial_gets_its_open_invoice(past_due, retrieve):+ due = await get_trial_payment_due(past_due)+ assert due == TrialPaymentDue(+ amount_due=5413, currency="usd", payment_url=PAYMENT_URL+ )+ retrieve.assert_awaited_once_with("sub_1", expand=["latest_invoice"])+++async def test_unpaid_trial_gets_its_open_invoice(past_due, retrieve):+ due = await get_trial_payment_due(past_due.model_copy(update={"status": "unpaid"}))+ assert due is not None and due.payment_url == PAYMENT_URL+++ "update",+ [+ {"status": "trialing"},+ {"status": "active"},+ {"status": "canceled"},+ {"subscription_id": None},+ ],+)+async def test_no_lookup_without_a_failed_conversion(past_due, retrieve, update):+ assert await get_trial_payment_due(past_due.model_copy(update=update)) is None+ retrieve.assert_not_awaited()+++async def test_no_lookup_after_conversion(past_due, retrieve):+ converted = past_due.model_copy(+ update={"converted_at": past_due.offer.new_users_from}+ )+ assert await get_trial_payment_due(converted) is None+ retrieve.assert_not_awaited()+++ "invoice_update",+ [+ {"status": "paid"},+ {"status": "void"},+ {"status": "draft"},+ {"status": "uncollectible"},+ {"customer": "cus_other"},+ {"amount_due": 0},+ {"hosted_invoice_url": None},+ ],+)+async def test_only_an_open_invoice_owned_by_the_trial_customer(+ past_due, subscription, retrieve, invoice_update+):+ subscription["latest_invoice"].update(invoice_update)+ assert await get_trial_payment_due(past_due) is None+++ "subscription_update",+ [+ {"customer": "cus_other"},+ {"metadata": {"trial_enrollment_id": "trial-other"}},+ {"latest_invoice": None},+ ],+)+async def test_only_the_trial_enrollment_subscription(+ past_due, subscription, retrieve, subscription_update+):+ subscription.update(subscription_update)+ assert await get_trial_payment_due(past_due) is None+++async def test_stripe_error_leaves_the_status_readable(past_due):+ with patch.object(+ stripe.Subscription,+ "retrieve_async",+ AsyncMock(side_effect=stripe.APIConnectionError("timeout")),+ ):+ assert await get_trial_payment_due(past_due) is Nonediff --git a/autogpt_platform/backend/backend/data/subscription_trial_payment.py b/autogpt_platform/backend/backend/data/subscription_trial_payment.pyindex 2a28e37d62..b840110654 100644--- a/autogpt_platform/backend/backend/data/subscription_trial_payment.py+++ b/autogpt_platform/backend/backend/data/subscription_trial_payment.py@@ -81,6 +81,9 @@ class Invoice(BaseModel):id: strstatus: str | None = Nonecreated: int+ customer: str | None = None+ amount_due: int = 0+ currency: str | None = Nonebilling_reason: str | None = Nonehosted_invoice_url: str | None = Nonediff --git a/autogpt_platform/backend/backend/data/subscription_upgrade.py b/autogpt_platform/backend/backend/data/subscription_upgrade.pynew file mode 100644index 0000000000..fc9ac916cb--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_upgrade.py@@ -0,0 +1,206 @@+"""Preview and revalidate an owned Pro-to-Max invoice before charging."""++import time+from uuid import uuid4++import stripe+from prisma.enums import SubscriptionTier++from backend.data.credit import _get_active_subscription, get_subscription_price_id+from backend.data.redis_client import get_redis_async+from backend.data.stripe_client import stripe_call+from backend.data.subscription_upgrade_cache import subscription_upgrade_preview_key+from backend.data.subscription_upgrade_models import (+ StoredUpgradePreview,+ SubscriptionUpgradePreview,+ SubscriptionUpgradePreviewRequest,+ UpgradeInvoicePreview,+ UpgradePreviewUnavailable,+ UpgradePrice,+ UpgradeProrationLine,+ UpgradeSubscription,+)+from backend.data.user import get_user_by_id++PREVIEW_TTL = 15 * 60+++async def preview_subscription_upgrade(+ user_id: str, request: SubscriptionUpgradePreviewRequest+) -> SubscriptionUpgradePreview:+ quote = await _build_preview(user_id, request, int(time.time()), uuid4().hex)+ redis = await get_redis_async()+ await redis.setex(+ subscription_upgrade_preview_key(user_id, quote.preview.preview_id),+ PREVIEW_TTL,+ quote.model_dump_json(),+ )+ return quote.preview+++async def validate_subscription_upgrade_preview(+ user_id: str,+ request: SubscriptionUpgradePreviewRequest,+ preview_id: str,+ proration_date: int,+) -> StoredUpgradePreview:+ redis = await get_redis_async()+ raw = await redis.get(subscription_upgrade_preview_key(user_id, preview_id))+ if not raw:+ raise UpgradePreviewUnavailable("This review expired. Review the charge again.")+ saved = StoredUpgradePreview.model_validate_json(raw)+ if (+ saved.user_id != user_id+ or saved.preview.preview_id != preview_id+ or saved.preview.proration_date != proration_date+ or saved.preview.billing_cycle != request.billing_cycle+ or saved.preview.expires_at <= int(time.time())+ ):+ raise UpgradePreviewUnavailable("This review changed. Review the charge again.")+ current = await _build_preview(user_id, request, proration_date, preview_id)+ if current != saved:+ raise UpgradePreviewUnavailable(+ "Your billing details changed. Review the updated charge before paying."+ )+ return saved+++async def _owned_subscription(user_id: str) -> UpgradeSubscription:+ user = await get_user_by_id(user_id)+ if user.subscription_tier != SubscriptionTier.PRO or not user.stripe_customer_id:+ raise UpgradePreviewUnavailable("An active paid Pro plan is required.")+ raw = await _get_active_subscription(user.stripe_customer_id)+ if raw is None:+ raise UpgradePreviewUnavailable("No active paid subscription was found.")+ sub = UpgradeSubscription.model_validate(raw)+ if (+ sub.customer != user.stripe_customer_id+ or sub.status != "active"+ or sub.metadata.get("user_id", user_id) != user_id+ or sub.items.has_more+ or len(sub.items.data) != 1+ ):+ raise UpgradePreviewUnavailable("This subscription needs a billing review.")+ return sub+++async def _build_preview(+ user_id: str,+ request: SubscriptionUpgradePreviewRequest,+ proration_date: int,+ preview_id: str,+) -> StoredUpgradePreview:+ sub = await _owned_subscription(user_id)+ price_id = await get_subscription_price_id(+ SubscriptionTier(request.tier), request.billing_cycle+ )+ if not price_id:+ raise UpgradePreviewUnavailable("Max is unavailable for this billing cycle.")+ price = UpgradePrice.model_validate(+ await stripe_call(stripe.Price.retrieve_async, price_id)+ )+ interval = "year" if request.billing_cycle == "yearly" else "month"+ if price.recurring.interval != interval or price.recurring.interval_count != 1:+ raise UpgradePreviewUnavailable("This price needs a billing review.")+ item = sub.items.data[0]+ invoice = UpgradeInvoicePreview.model_validate(+ await stripe_call(+ stripe.Invoice.create_preview_async,+ customer=sub.customer,+ subscription=sub.id,+ subscription_details={+ "items": [+ {"id": item.id, "price": price_id, "quantity": item.quantity}+ ],+ "proration_behavior": "always_invoice",+ "proration_date": proration_date,+ },+ )+ )+ if invoice.customer != sub.customer or invoice.currency != price.currency:+ raise UpgradePreviewUnavailable("The invoice could not be verified.")+ if invoice.lines.has_more or not invoice.lines.data:+ raise UpgradePreviewUnavailable("The complete invoice could not be loaded.")+ period_end = _renewal_date(sub, price, invoice)+ if period_end <= proration_date:+ raise UpgradePreviewUnavailable("The billing period changed. Try again.")+ return StoredUpgradePreview(+ user_id=user_id,+ subscription_id=sub.id,+ item_id=item.id,+ current_price_id=item.price.id,+ target_price_id=price_id,+ quantity=item.quantity,+ preview=_public_preview(+ invoice,+ price,+ item.quantity,+ request,+ preview_id,+ proration_date,+ period_end,+ ),+ )+++def _renewal_date(+ sub: UpgradeSubscription,+ price: UpgradePrice,+ invoice: UpgradeInvoicePreview,+) -> int:+ item = sub.items.data[0]+ current_end = item.current_period_end or sub.current_period_end+ if item.price.recurring == price.recurring and current_end is not None:+ return current_end+ periods = [+ line.period.end+ for line in invoice.lines.data+ if line.amount >= 0+ and line.subscription_item_id == item.id+ and line.price_id == price.id+ ]+ if not periods:+ raise UpgradePreviewUnavailable("The next billing date could not be verified.")+ return max(periods)+++def _public_preview(+ invoice: UpgradeInvoicePreview,+ price: UpgradePrice,+ quantity: int,+ request: SubscriptionUpgradePreviewRequest,+ preview_id: str,+ proration_date: int,+ period_end: int,+) -> SubscriptionUpgradePreview:+ taxes = invoice.total_taxes+ if taxes is None:+ taxes = invoice.total_tax_amounts+ exclusive_tax = sum(tax.amount for tax in (taxes or []) if not tax.is_inclusive)+ lines = [+ UpgradeProrationLine(+ description=line.description or "Subscription adjustment",+ amount=line.amount,+ period_start=line.period.start,+ period_end=line.period.end,+ proration=line.is_proration,+ )+ for line in invoice.lines.data+ ]+ return SubscriptionUpgradePreview(+ preview_id=preview_id,+ amount_due=invoice.amount_due,+ tax_amount=sum(tax.amount for tax in taxes) if taxes is not None else None,+ tax_included=bool(taxes) and all(tax.is_inclusive for tax in taxes),+ adjustment_amount=invoice.amount_due+ - sum(line.amount for line in lines)+ - exclusive_tax,+ currency=invoice.currency,+ proration_date=proration_date,+ period_end=period_end,+ expires_at=proration_date + PREVIEW_TTL,+ recurring_amount=price.unit_amount * quantity,+ recurring_tax_included=price.tax_behavior == "inclusive",+ billing_cycle=request.billing_cycle,+ lines=lines,+ )diff --git a/autogpt_platform/backend/backend/data/subscription_upgrade_cache.py b/autogpt_platform/backend/backend/data/subscription_upgrade_cache.pynew file mode 100644index 0000000000..4e8186cb40--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_upgrade_cache.py@@ -0,0 +1,12 @@+"""User-scoped storage keys for reviewed subscription upgrades."""++from backend.data.redis_client import get_redis_async+++async def discard_subscription_upgrade_preview(user_id: str, preview_id: str) -> None:+ redis = await get_redis_async()+ await redis.delete(subscription_upgrade_preview_key(user_id, preview_id))+++def subscription_upgrade_preview_key(user_id: str, preview_id: str) -> str:+ return f"subscription-upgrade-preview:{user_id}:{preview_id}"diff --git a/autogpt_platform/backend/backend/data/subscription_upgrade_fixtures.py b/autogpt_platform/backend/backend/data/subscription_upgrade_fixtures.pynew file mode 100644index 0000000000..6ceb12181c--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_upgrade_fixtures.py@@ -0,0 +1,95 @@+"""Stripe and Redis boundaries for reviewed subscription upgrades."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+import stripe+from prisma.enums import SubscriptionTier++from backend.data import subscription_upgrade as billing++NOW = 1791374400+++def setup(monkeypatch):+ user = SimpleNamespace(+ stripe_customer_id="cus_owned", subscription_tier=SubscriptionTier.PRO+ )+ sub = {+ "id": "sub_owned",+ "customer": "cus_owned",+ "status": "active",+ "current_period_end": NOW + 2500000,+ "metadata": {"user_id": "user-1"},+ "schedule": None,+ "cancel_at_period_end": False,+ "items": {+ "data": [+ {+ "id": "si_owned",+ "price": {"id": "price_pro", "recurring": {"interval": "month"}},+ "quantity": 1,+ }+ ]+ },+ }+ invoice = {+ "customer": "cus_owned",+ "currency": "usd",+ "amount_due": 27278,+ "total": 27278,+ "total_tax_amounts": [{"amount": 2020, "inclusive": False}],+ "lines": {+ "data": [+ {+ "description": "Max",+ "amount": 29935,+ "proration": True,+ "period": {"start": NOW, "end": NOW + 2500000},+ },+ {+ "description": "Unused Pro time",+ "amount": -4677,+ "proration": True,+ "period": {"start": NOW, "end": NOW + 2500000},+ },+ ]+ },+ }+ price = {+ "id": "price_max",+ "unit_amount": 32000,+ "currency": "usd",+ "recurring": {"interval": "month"},+ "tax_behavior": "exclusive",+ }+ cache = {}++ async def setex(key, ttl, value):+ assert ttl == 900+ cache[key] = value++ redis = SimpleNamespace(+ setex=AsyncMock(side_effect=setex),+ get=AsyncMock(side_effect=lambda key: cache.get(key)),+ delete=AsyncMock(side_effect=lambda key: int(cache.pop(key, None) is not None)),+ )+ monkeypatch.setattr(billing.time, "time", lambda: NOW)+ monkeypatch.setattr(billing, "get_user_by_id", AsyncMock(return_value=user))+ monkeypatch.setattr(+ billing,+ "_get_active_subscription",+ AsyncMock(side_effect=lambda _: stripe.Subscription.construct_from(sub, "k")),+ )+ monkeypatch.setattr(+ billing, "get_subscription_price_id", AsyncMock(return_value="price_max")+ )+ monkeypatch.setattr(billing, "get_redis_async", AsyncMock(return_value=redis))+ monkeypatch.setattr(stripe.Price, "retrieve_async", AsyncMock(return_value=price))+ preview = AsyncMock(side_effect=lambda **_: invoice)+ monkeypatch.setattr(stripe.Invoice, "create_preview_async", preview)+ return SimpleNamespace(+ user=user, sub=sub, invoice=invoice, price=price, preview=preview, redis=redis+ )diff --git a/autogpt_platform/backend/backend/data/subscription_upgrade_models.py b/autogpt_platform/backend/backend/data/subscription_upgrade_models.pynew file mode 100644index 0000000000..33923a7db8--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_upgrade_models.py@@ -0,0 +1,169 @@+"""Public charge review and private ownership data for paid Max upgrades."""++from typing import Literal++from pydantic import BaseModel, Field+++class SubscriptionUpgradePreviewRequest(BaseModel):+ tier: Literal["MAX"]+ billing_cycle: Literal["monthly", "yearly"] = "monthly"+++class UpgradeProrationLine(BaseModel):+ description: str+ amount: int+ period_start: int+ period_end: int+ proration: bool+++class SubscriptionUpgradePreview(BaseModel):+ preview_id: str+ amount_due: int+ tax_amount: int | None+ tax_included: bool+ adjustment_amount: int+ currency: str+ proration_date: int+ period_end: int+ expires_at: int+ recurring_amount: int+ recurring_tax_included: bool+ billing_cycle: Literal["monthly", "yearly"]+ lines: list[UpgradeProrationLine]+++class StoredUpgradePreview(BaseModel):+ user_id: str+ subscription_id: str+ item_id: str+ current_price_id: str+ target_price_id: str+ quantity: int+ preview: SubscriptionUpgradePreview+++class UpgradePreviewUnavailable(ValueError):+ pass+++class PreviewPeriod(BaseModel):+ start: int+ end: int+++class PreviewProrationParent(BaseModel):+ proration: bool = False+ subscription_item: str | None = None+++class PreviewLineParent(BaseModel):+ subscription_item_details: PreviewProrationParent | None = None+++class PreviewLinePrice(BaseModel):+ id: str+++class PreviewPriceDetails(BaseModel):+ price: str+++class PreviewLinePricing(BaseModel):+ price_details: PreviewPriceDetails | None = None+++class PreviewLine(BaseModel):+ description: str | None = None+ amount: int+ period: PreviewPeriod+ proration: bool = False+ parent: PreviewLineParent | None = None+ subscription_item: str | None = None+ price: PreviewLinePrice | None = None+ pricing: PreviewLinePricing | None = None++ @property+ def subscription_item_id(self) -> str | None:+ if self.parent and self.parent.subscription_item_details:+ return self.parent.subscription_item_details.subscription_item+ return self.subscription_item++ @property+ def price_id(self) -> str | None:+ if self.pricing and self.pricing.price_details:+ return self.pricing.price_details.price+ return self.price.id if self.price else None++ @property+ def is_proration(self) -> bool:+ return self.proration or bool(+ self.parent+ and self.parent.subscription_item_details+ and self.parent.subscription_item_details.proration+ )+++class PreviewLines(BaseModel):+ data: list[PreviewLine]+ has_more: bool = False+++class PreviewTax(BaseModel):+ amount: int+ inclusive: bool = False+ tax_behavior: str | None = None++ @property+ def is_inclusive(self) -> bool:+ return self.inclusive or self.tax_behavior == "inclusive"+++class UpgradeInvoicePreview(BaseModel):+ customer: str+ currency: str+ amount_due: int+ total: int+ total_tax_amounts: list[PreviewTax] | None = None+ total_taxes: list[PreviewTax] | None = None+ lines: PreviewLines+++class UpgradeRecurringPrice(BaseModel):+ interval: Literal["month", "year"]+ interval_count: int = 1+++class UpgradePrice(BaseModel):+ id: str+ currency: str+ unit_amount: int+ tax_behavior: str = "unspecified"+ recurring: UpgradeRecurringPrice+++class UpgradeItemPrice(BaseModel):+ id: str+ recurring: UpgradeRecurringPrice | None = None+++class UpgradeSubscriptionItem(BaseModel):+ id: str+ price: UpgradeItemPrice+ quantity: int = 1+ current_period_end: int | None = None+++class UpgradeSubscriptionItems(BaseModel):+ data: list[UpgradeSubscriptionItem]+ has_more: bool = False+++class UpgradeSubscription(BaseModel):+ id: str+ customer: str+ status: str+ current_period_end: int | None = None+ metadata: dict[str, str] = Field(default_factory=dict)+ items: UpgradeSubscriptionItemsdiff --git a/autogpt_platform/backend/backend/data/subscription_upgrade_retry_test.py b/autogpt_platform/backend/backend/data/subscription_upgrade_retry_test.pynew file mode 100644index 0000000000..9b0235e33c--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_upgrade_retry_test.py@@ -0,0 +1,156 @@+"""Reviewed payment retries preserve Stripe's idempotency guarantees."""++from unittest.mock import AsyncMock, Mock++import pytest+import stripe+from prisma.enums import SubscriptionTier++from backend.data import credit+from backend.data import subscription_upgrade as billing+from backend.data import subscription_upgrade_cache as cache+from backend.data.subscription_upgrade_models import (+ SubscriptionUpgradePreviewRequest,+ UpgradePreviewUnavailable,+)++pytest_plugins = ("backend.data.subscription_upgrade_fixtures",)+REQUEST = SubscriptionUpgradePreviewRequest(tier="MAX")++[email protected](autouse=True)+def graph_cleanup():+ """No graph/database resources are used by these Stripe boundary tests."""+ yield+++def tier_change(monkeypatch):+ update = AsyncMock()+ monkeypatch.setattr(credit, "set_subscription_tier", update)+ return update+++def payment(setup, monkeypatch, tier_change):+ monkeypatch.setattr(cache, "get_redis_async", AsyncMock(return_value=setup.redis))+ monkeypatch.setattr(+ credit, "get_subscription_price_id", AsyncMock(return_value="price_max")+ )+ monkeypatch.setattr(credit, "get_user_by_id", AsyncMock(return_value=setup.user))+ monkeypatch.setattr(+ credit,+ "_get_active_subscription",+ AsyncMock(return_value=stripe.Subscription.construct_from(setup.sub, "k")),+ )+ monkeypatch.setattr(credit, "_track_billing_event", Mock())+ monkeypatch.setattr(credit, "invalidate_billing_lookups", AsyncMock())+ modify = AsyncMock()+ monkeypatch.setattr(stripe.Subscription, "modify_async", modify)+ return modify+++async def confirm(preview, user_id="user-1"):+ quote = await billing.validate_subscription_upgrade_preview(+ user_id, REQUEST, preview.preview_id, preview.proration_date+ )+ return await credit.modify_stripe_subscription_for_tier(+ user_id,+ SubscriptionTier.MAX,+ proration_date=preview.proration_date,+ upgrade_preview=quote,+ )+++ "failure",+ [+ stripe.CardError("Declined", "payment_method", "card_declined"),+ stripe.CardError(+ "Authentication required",+ "payment_method",+ "subscription_payment_intent_requires_action",+ ),+ stripe.InvalidRequestError(+ "No payment method",+ "default_payment_method",+ code="resource_missing",+ http_status=400,+ ),+ ],+)+async def test_rejected_payment_requires_new_review_before_retry(+ setup, payment, failure+):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ payment.side_effect = failure+ with pytest.raises(type(failure)) as error:+ await confirm(preview)+ assert error.value is failure+ with pytest.raises(UpgradePreviewUnavailable):+ await confirm(preview)+ assert payment.await_count == 1++ fresh = await billing.preview_subscription_upgrade("user-1", REQUEST)+ payment.side_effect = None+ assert await confirm(fresh) is True+ assert fresh.preview_id != preview.preview_id+ assert [call.kwargs["idempotency_key"] for call in payment.await_args_list] == [+ f"subscription-upgrade:{preview.preview_id}",+ f"subscription-upgrade:{fresh.preview_id}",+ ]+++ "failure",+ [+ stripe.APIConnectionError("Connection lost"),+ stripe.APIError("Internal server error", http_status=500),+ stripe.RateLimitError("Rate limited", http_status=429),+ stripe.InvalidRequestError("Request in progress", None, http_status=409),+ stripe.IdempotencyError("Request in progress", http_status=409),+ ],+)+async def test_ambiguous_or_retryable_errors_keep_the_review_and_key(+ setup, payment, failure+):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ payment.side_effect = failure+ with pytest.raises(type(failure)):+ await confirm(preview)+ payment.side_effect = None+ assert await confirm(preview) is True+ assert payment.await_args_list[0] == payment.await_args_list[1]+ setup.redis.delete.assert_not_awaited()+++async def test_other_user_cannot_retry_or_retire_an_owned_review(setup, payment):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ with pytest.raises(UpgradePreviewUnavailable):+ await confirm(preview, "user-2")+ payment.assert_not_awaited()+ setup.redis.delete.assert_not_awaited()+ assert await confirm(preview) is True+++async def test_cache_failure_preserves_the_stripe_failure_and_does_not_change_tier(+ setup, payment, tier_change+):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ failure = stripe.CardError("Declined", "payment_method", "card_declined")+ payment.side_effect = failure+ setup.redis.delete.side_effect = ConnectionError("Redis unavailable")+ with pytest.raises(ConnectionError) as error:+ await confirm(preview)+ assert error.value.__context__ is failure+ tier_change.assert_not_awaited()+ quote = await billing.validate_subscription_upgrade_preview(+ "user-1", REQUEST, preview.preview_id, preview.proration_date+ )+ assert quote.preview == preview+++async def test_retirement_cannot_delete_another_users_review(setup, payment):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ await cache.discard_subscription_upgrade_preview("user-2", preview.preview_id)+ assert await confirm(preview) is Truediff --git a/autogpt_platform/backend/backend/data/subscription_upgrade_test.py b/autogpt_platform/backend/backend/data/subscription_upgrade_test.pynew file mode 100644index 0000000000..94c7dea37b--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_upgrade_test.py@@ -0,0 +1,213 @@+"""Financial and ownership invariants of the Max upgrade charge review."""++from unittest.mock import AsyncMock, Mock++import pytest+import stripe+from prisma.enums import SubscriptionTier++from backend.data import credit+from backend.data import subscription_upgrade as billing+from backend.data.subscription_upgrade_models import (+ SubscriptionUpgradePreviewRequest,+ UpgradePreviewUnavailable,+)++NOW = 1791374400+REQUEST = SubscriptionUpgradePreviewRequest(tier="MAX")+++pytest_plugins = ("backend.data.subscription_upgrade_fixtures",)++[email protected](autouse=True)+def graph_cleanup():+ """No graph/database resources are used by these Stripe boundary tests."""+ yield+++async def test_preview_and_confirm_use_identical_stripe_proration_date(setup):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ assert preview.amount_due == 27278+ assert preview.tax_amount == 2020+ assert [line.amount for line in preview.lines] == [29935, -4677]+ assert preview.adjustment_amount == 0+ assert preview.recurring_amount == 32000+ quote = await billing.validate_subscription_upgrade_preview(+ "user-1", REQUEST, preview.preview_id, preview.proration_date+ )+ assert quote.preview == preview+ assert setup.preview.await_count == 2+ for call in setup.preview.await_args_list:+ assert call.kwargs["subscription_details"] == {+ "items": [{"id": "si_owned", "price": "price_max", "quantity": 1}],+ "proration_behavior": "always_invoice",+ "proration_date": NOW,+ }+++ "change", ["amount", "currency", "item", "price", "period", "tax"]+)+async def test_changed_invoice_requires_new_consent(setup, change):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ if change == "amount":+ setup.invoice["amount_due"] += 100+ elif change == "currency":+ setup.invoice["currency"] = "eur"+ elif change == "item":+ setup.sub["items"]["data"][0]["id"] = "si_changed"+ elif change == "price":+ setup.price["unit_amount"] += 100+ elif change == "period":+ setup.invoice["lines"]["data"][0]["period"]["end"] += 3600+ else:+ setup.invoice["total_tax_amounts"][0]["amount"] += 100+ with pytest.raises(UpgradePreviewUnavailable):+ await billing.validate_subscription_upgrade_preview(+ "user-1", REQUEST, preview.preview_id, preview.proration_date+ )+++async def test_quote_cannot_be_used_by_another_user_or_backdated(setup):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ with pytest.raises(UpgradePreviewUnavailable):+ await billing.validate_subscription_upgrade_preview(+ "user-2", REQUEST, preview.preview_id, preview.proration_date+ )+ with pytest.raises(UpgradePreviewUnavailable):+ await billing.validate_subscription_upgrade_preview(+ "user-1", REQUEST, preview.preview_id, preview.proration_date - 1+ )+ assert setup.preview.await_count == 1+++async def test_expired_preview_never_reaches_stripe(setup, monkeypatch):+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ monkeypatch.setattr(billing.time, "time", lambda: NOW + 901)+ with pytest.raises(UpgradePreviewUnavailable, match="Review"):+ await billing.validate_subscription_upgrade_preview(+ "user-1", REQUEST, preview.preview_id, preview.proration_date+ )+ assert setup.preview.await_count == 1+++async def test_basil_inclusive_tax_and_account_credit_are_disclosed(setup):+ setup.invoice.pop("total_tax_amounts")+ setup.invoice["total_taxes"] = [{"amount": 2020, "tax_behavior": "inclusive"}]+ setup.invoice["total"] = 25258+ setup.invoice["amount_due"] = 24258+ setup.price["tax_behavior"] = "inclusive"+ for line in setup.invoice["lines"]["data"]:+ line.pop("proration")+ line["parent"] = {"subscription_item_details": {"proration": True}}+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ assert preview.tax_amount == 2020+ assert preview.tax_included is True+ assert preview.recurring_tax_included is True+ assert preview.adjustment_amount == -1000+ assert all(line.proration for line in preview.lines)+++async def test_one_off_invoice_items_do_not_move_the_next_renewal(setup):+ setup.invoice["lines"]["data"].append(+ {+ "description": "One-off service",+ "amount": 1000,+ "period": {"start": NOW, "end": NOW + 5000000},+ }+ )+ setup.invoice["amount_due"] += 1000+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ assert preview.period_end == setup.sub["current_period_end"]+ assert preview.amount_due == 28278++[email protected]("basil", [False, True])+async def test_cycle_change_uses_only_the_owned_target_subscription_line(setup, basil):+ setup.price["recurring"]["interval"] = "year"+ end = NOW + 365 * 86400+ debit = setup.invoice["lines"]["data"][0]+ debit["period"]["end"] = end+ if basil:+ debit["parent"] = {+ "subscription_item_details": {+ "subscription_item": "si_owned",+ "proration": False,+ }+ }+ debit["pricing"] = {"price_details": {"price": "price_max"}}+ else:+ debit["subscription_item"] = "si_owned"+ debit["price"] = {"id": "price_max"}+ setup.invoice["lines"]["data"].append(+ {+ "description": "One-off service",+ "amount": 1000,+ "period": {"start": NOW, "end": end + 86400},+ }+ )+ preview = await billing.preview_subscription_upgrade(+ "user-1", SubscriptionUpgradePreviewRequest(tier="MAX", billing_cycle="yearly")+ )+ assert preview.period_end == end++[email protected]("change", ["customer", "metadata", "trial", "pagination"])+async def test_foreign_or_incomplete_subscription_is_not_previewed(setup, change):+ if change == "customer":+ setup.sub["customer"] = "cus_other"+ elif change == "metadata":+ setup.sub["metadata"]["user_id"] = "other"+ elif change == "trial":+ setup.sub["status"] = "trialing"+ else:+ setup.invoice["lines"]["has_more"] = True+ with pytest.raises(UpgradePreviewUnavailable):+ await billing.preview_subscription_upgrade("user-1", REQUEST)+++async def test_modify_passes_reviewed_date_and_idempotency_key_to_stripe(+ setup, monkeypatch+):+ setup.sub["items"]["data"][0]["quantity"] = 2+ preview = await billing.preview_subscription_upgrade("user-1", REQUEST)+ quote = await billing.validate_subscription_upgrade_preview(+ "user-1", REQUEST, preview.preview_id, preview.proration_date+ )+ monkeypatch.setattr(+ credit, "get_subscription_price_id", AsyncMock(return_value="price_max")+ )+ monkeypatch.setattr(credit, "get_user_by_id", AsyncMock(return_value=setup.user))+ monkeypatch.setattr(+ credit,+ "_get_active_subscription",+ AsyncMock(return_value=stripe.Subscription.construct_from(setup.sub, "k")),+ )+ monkeypatch.setattr(credit, "set_subscription_tier", AsyncMock())+ monkeypatch.setattr(credit, "_track_billing_event", Mock())+ invalidate = AsyncMock()+ monkeypatch.setattr(credit, "invalidate_billing_lookups", invalidate)+ modify = AsyncMock()+ monkeypatch.setattr(stripe.Subscription, "modify_async", modify)+ await credit.modify_stripe_subscription_for_tier(+ "user-1",+ SubscriptionTier.MAX,+ proration_date=preview.proration_date,+ upgrade_preview=quote,+ )+ invalidate.assert_awaited_once_with(setup.user.stripe_customer_id)+ assert modify.await_args.kwargs["proration_date"] == NOW+ assert (+ modify.await_args.kwargs["idempotency_key"]+ == f"subscription-upgrade:{preview.preview_id}"+ )+ assert modify.await_args.kwargs["proration_behavior"] == "always_invoice"+ assert modify.await_args.kwargs["payment_behavior"] == "error_if_incomplete"+ assert modify.await_args.kwargs["items"] == [+ {"id": "si_owned", "price": "price_max", "quantity": 2}+ ]+ assert quote.preview.recurring_amount == 64000+ assert setup.preview.await_args.kwargs["subscription_details"]["items"] == [+ {"id": "si_owned", "price": "price_max", "quantity": 2}+ ]diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsxindex 5627ad5a67..ed9b9f621b 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx@@ -15,6 +15,7 @@ import { WorkflowsMovedNotice } from "../components/WorkflowsMovedNotice/Workflo// out of Otto.const PAYWALL_EXEMPT_PREFIXES = ["/profile",+ "/settings","/admin","/auth","/login",diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsxindex b2a5e05706..6830a8c77c 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx@@ -6,14 +6,14 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { Dialog } from "@/components/molecules/Dialog/Dialog";import { SubscriptionPlans } from "@/components/organisms/SubscriptionPlans/SubscriptionPlans";import { TrialCardContent } from "@/components/organisms/TrialCard/TrialCard";+import { PaymentRecoveryCard } from "@/components/organisms/UsageExperience/PaymentRecoveryCard";+import { usePaymentRecovery } from "@/services/usageExperience/usePaymentRecovery";import { Logout03Icon } from "@hugeicons/core-free-icons";import { SwitchTierDialog } from "../settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog";+import { PaywallPlanChoices } from "./components/PaywallPlanChoices";import { PaywallHeader } from "./components/PaywallHeader";import { usePaywallModal } from "./usePaywallModal";-// Non-dismissable Stripe paywall for NO_TIER users. Renders the same-// SubscriptionPlans organism as the onboarding paywall, so both surfaces share-// one visual and one free-trial offer.export function PaywallModal() {const {isLoading,@@ -31,20 +31,30 @@ export function PaywallModal() {confirmPendingTier,cancelPendingTier,handleLogout,+ handleClose,trial,trialOffer,} = usePaywallModal();+ // The gate only opens this modal for accounts without a plan.+ const recovery = usePaymentRecovery("NO_TIER");return (- <Dialog forceOpen controlled={{ isOpen: true, set: () => {} }}>+ <Dialog+ variant="compact"+ title={recovery.paymentFailed ? "Your plan" : "Choose your plan"}+ styling={{+ maxWidth: trialOffer && !recovery.paymentFailed ? "1120px" : "700px",+ }}+ controlled={{+ isOpen: true,+ set: (open) => {+ if (!open) handleClose();+ },+ }}+ ><Dialog.Content><div className="relative flex w-full flex-col items-center gap-4 px-2 py-2">- {/* Sticky (not absolute) so the button pins to the top of the- dialog's scroll viewport instead of getting clipped or scrolled- away when the plan cards overflow on short screens. The negative- margin collapses the row's layout space so the title keeps its- position. */}- <div className="sticky top-0 z-10 -mb-[3.25rem] flex w-full justify-end">+ <div className="flex w-full justify-start"><Buttonvariant="ghost"size="small"@@ -55,56 +65,85 @@ export function PaywallModal() {Log out</Button></div>- <PaywallHeader />+ {recovery.paymentFailed ? (+ <PaymentRecoveryCard+ payment={recovery.payment}+ fallback="Update your payment method in billing to continue. Your chats, agents and results are saved."+ />+ ) : (+ <>+ <PaywallHeader />- <div className="relative mt-2 w-full">- {isLoading ? (- <div className="grid w-full grid-cols-1 gap-4 px-[1rem] md:grid-cols-3 md:px-0">- <Skeleton className="h-[26rem] rounded-2xl" />- <Skeleton className="h-[26rem] rounded-2xl" />- <Skeleton className="h-[26rem] rounded-2xl" />+ <div className="relative mt-2 w-full">+ {isLoading || trial.isLoading ? (+ <div className="grid w-full grid-cols-1 gap-4 px-[1rem] md:grid-cols-3 md:px-0">+ <Skeleton className="h-[26rem] rounded-2xl" />+ <Skeleton className="h-[26rem] rounded-2xl" />+ <Skeleton className="h-[26rem] rounded-2xl" />+ </div>+ ) : plans.length === 0 ? (+ <div className="flex flex-col items-center gap-3">+ <p className="text-center text-sm text-zinc-500">+ Subscriptions are temporarily unavailable. Please try+ again shortly.+ </p>+ <Button+ variant="secondary"+ size="small"+ onClick={retryLoadPlans}+ loading={isRetryingPlans}+ >+ Retry+ </Button>+ </div>+ ) : !trialOffer ? (+ <div className="space-y-4">+ <PaywallPlanChoices+ plans={plans}+ cycle={selectedCycle}+ onCycle={setSelectedCycle}+ onSelect={handleSelectPlan}+ pending={isPending}+ selectedTier={selectedTier}+ />+ {!trial.trial?.eligible && (+ <TrialCardContent returnTo="billing" controller={trial} />+ )}+ </div>+ ) : (+ <SubscriptionPlans+ // The modal renders its own title above, so the organism+ // contributes only the billing toggle.+ header={null}+ goalSurface="upgrade_modal"+ plans={plans}+ country={country}+ billing={selectedCycle}+ onBillingChange={setSelectedCycle}+ onSelectPlan={handleSelectPlan}+ isUpdatingTier={isPending}+ selectedPlan={selectedTier}+ trialOffer={trialOffer}+ onStartTrial={trial.startTrial}+ isStartingTrial={trial.isStarting}+ trialError={trial.error}+ trialStatus={+ !trialOffer && (+ <TrialCardContent+ returnTo="billing"+ controller={trial}+ />+ )+ }+ />+ )}</div>- ) : plans.length === 0 ? (- <div className="flex flex-col items-center gap-3">- <p className="text-center text-sm text-zinc-500">- Subscriptions are temporarily unavailable. Please try again- shortly.- </p>- <Button- variant="secondary"- size="small"- onClick={retryLoadPlans}- loading={isRetryingPlans}- >- Retry- </Button>- </div>- ) : (- <SubscriptionPlans- // The modal renders its own title above, so the organism- // contributes only the billing toggle.- header={null}- goalSurface="upgrade_modal"- plans={plans}- country={country}- billing={selectedCycle}- onBillingChange={setSelectedCycle}- onSelectPlan={handleSelectPlan}- isUpdatingTier={isPending}- selectedPlan={selectedTier}- trialOffer={trialOffer}- onStartTrial={trial.startTrial}- isStartingTrial={trial.isStarting}- trialError={trial.error}- trialStatus={- !trialOffer && (- <TrialCardContent returnTo="billing" controller={trial} />- )- }- />- )}- </div>+ </>+ )}</div>+ <Button variant="ghost" className="mt-3 w-full" onClick={handleClose}>+ Back to billing+ </Button></Dialog.Content>{pendingTier && pendingTierLabel ? (<SwitchTierDialogdiff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsxindex afe54a8818..159d16227d 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx@@ -142,6 +142,8 @@ describe("PaywallGate", () => {for (const path of ["/profile/credits","/profile/account",+ "/settings/billing",+ "/settings/profile","/admin/users","/auth/callback","/login",diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.payment.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.payment.test.tsxnew file mode 100644index 0000000000..d3228aca04--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.payment.test.tsx@@ -0,0 +1,149 @@+import { getGetTrialsGetTrialStatusMockHandler200 } from "@/app/api/__generated__/endpoints/trials/trials.msw";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { afterEach, beforeEach, expect, test, vi } from "vitest";++const mockUseGetSubscriptionStatus = vi.fn();+const mockUseUpdateSubscriptionTier = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({+ useGetSubscriptionStatus: (opts: unknown) =>+ mockUseGetSubscriptionStatus(opts),+ useUpdateSubscriptionTier: () => mockUseUpdateSubscriptionTier(),+ getGetSubscriptionStatusQueryKey: () => ["/api/credits/subscription"],+}));++vi.mock("@posthog/react", () => ({+ useFeatureFlagVariantKey: () => undefined,+ usePostHog: () => ({ capture: vi.fn() }),+}));++function MockDialog({+ title,+ children,+}: {+ title: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <div role="dialog">+ <div>{title}</div>+ {children}+ </div>+ );+}+function MockDialogContent({ children }: { children: React.ReactNode }) {+ return <div>{children}</div>;+}+function MockDialogFooter({ children }: { children: React.ReactNode }) {+ return <div>{children}</div>;+}+MockDialog.Content = MockDialogContent;+MockDialog.Footer = MockDialogFooter;+vi.mock("@/components/molecules/Dialog/Dialog", () => ({+ Dialog: MockDialog,+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ validateSession: vi.fn().mockResolvedValue(true),+ isLoggedIn: true,+ }),+}));++vi.mock("@/providers/onboarding/onboarding-provider", () => ({+ default: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),+ usePathname: () => "/copilot",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({}),+}));++import { PaywallModal } from "../PaywallModal";++const PAYMENT_URL = "https://invoice.stripe.com/i/acct_1/test_inv_1";++beforeEach(() => {+ setTrialUser();+ mockUseGetSubscriptionStatus.mockReturnValue({+ data: { tier: "NO_TIER", tier_costs: { PRO: 5000, MAX: 32000 } },+ isLoading: false,+ isFetching: false,+ refetch: vi.fn(),+ });+ mockUseUpdateSubscriptionTier.mockReturnValue({+ mutateAsync: vi.fn(),+ isPending: false,+ });+});++afterEach(() => {+ setTrialUser(null);+ vi.restoreAllMocks();+});++test("a failed first trial charge pays the open invoice instead of choosing a plan", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({+ active: false,+ status: "past_due",+ payment_due: {+ amount_due: 5000,+ currency: "usd",+ payment_url: PAYMENT_URL,+ },+ }),+ ),+ );++ render(<PaywallModal />);++ const pay = await screen.findByRole("link", { name: "Pay $50 now" });+ expect(pay.getAttribute("href")).toBe(PAYMENT_URL);+ expect(screen.getByText("Your payment didn’t go through")).toBeDefined();+ for (const amount of screen.getAllByText(/\$50/)) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ expect(screen.queryByText("Choose a plan to keep working")).toBeNull();+ expect(screen.queryByRole("region", { name: "Pro plan" })).toBeNull();+ expect(screen.queryByRole("button", { name: /^Start/ })).toBeNull();+ expect(screen.getByRole("button", { name: "Back to billing" })).toBeDefined();+});++test("sends a failed charge without a readable invoice to billing", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({ active: false, status: "past_due", payment_due: null }),+ ),+ );++ render(<PaywallModal />);++ expect(+ await screen.findByText(+ "Update your payment method in billing to continue. Your chats, agents and results are saved.",+ ),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: /^Start/ })).toBeNull();+ expect(screen.getByRole("button", { name: "Back to billing" })).toBeDefined();+});++test("keeps plan choices for a trial that simply ended", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({ active: false, status: "expired" }),+ ),+ );++ render(<PaywallModal />);++ expect(await screen.findByRole("region", { name: "Pro plan" })).toBeDefined();+ expect(screen.queryByText("Your payment didn’t go through")).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.tsxindex 4529f51c6c..f6f852b198 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx@@ -139,6 +139,15 @@ afterEach(async () => {});describe("PaywallModal — dynamic plan rendering", () => {+ it("keeps account and billing access available without starting a checkout", () => {+ const { mutateFn } = setupMocks({+ subscription: { tier: "NO_TIER", tier_costs: { PRO: 5000 } },+ });+ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: "Back to billing" }));+ expect(mockReplace).toHaveBeenCalledWith("/settings/billing");+ expect(mutateFn).not.toHaveBeenCalled();+ });it("renders one card per tier in tier_costs (PRO + MAX → 2 cards)", () => {setupMocks({subscription: {@@ -207,7 +216,7 @@ describe("PaywallModal — logout", () => {});describe("PaywallModal — Monthly/Yearly cycle toggle", () => {- it("defaults to monthly billing with the full monthly prices and a 'billed monthly' caption", () => {+ it("defaults to monthly billing with the actual monthly prices", () => {setupMocks({subscription: {tier: "NO_TIER",@@ -219,13 +228,13 @@ describe("PaywallModal — Monthly/Yearly cycle toggle", () => {render(<PaywallModal />);// PRO monthly = 5000 cents = $50.00, MAX monthly = 32000 cents = $320.00.- expect(screen.getByLabelText("$50.00")).toBeDefined();- expect(screen.getByLabelText("$320.00")).toBeDefined();- expect(screen.getAllByText("billed monthly").length).toBe(2);+ expect(screen.getByText("$50")).toBeDefined();+ expect(screen.getByText("$320")).toBeDefined();+ expect(screen.getAllByText("/ month").length).toBe(2);expect(screen.queryByText(/Charged today/i)).toBeNull();});- it("toggling Yearly switches to the discounted monthly-equivalent prices and a 'billed annually' caption", async () => {+ it("toggling Yearly shows the actual yearly charge and billing interval", async () => {setupMocks({subscription: {tier: "NO_TIER",@@ -238,11 +247,11 @@ describe("PaywallModal — Monthly/Yearly cycle toggle", () => {fireEvent.click(screen.getByRole("button", { name: /yearly/i }));- // PRO yearly = 51000 cents → $42.50/mo, MAX yearly = 326400 cents → $272.00/mo.+ // Show the full yearly payment, not a monthly equivalent.await waitFor(() => {- expect(screen.getByLabelText("$42.50")).toBeDefined();- expect(screen.getByLabelText("$272.00")).toBeDefined();- expect(screen.getAllByText("billed annually").length).toBe(2);+ expect(screen.getByText("$510")).toBeDefined();+ expect(screen.getByText("$3,264")).toBeDefined();+ expect(screen.getAllByText("/ year").length).toBe(2);});});});@@ -266,7 +275,7 @@ describe("PaywallModal — upgrade mutation", () => {});}- it("clicking Upgrade to Pro with the default monthly toggle fires {tier:PRO, billing_cycle:monthly}", async () => {+ it("clicking Start Pro with the default monthly toggle fires {tier:PRO, billing_cycle:monthly}", async () => {stubLocation();const { mutateFn } = setupMocks({subscription: {@@ -278,7 +287,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mutateFn).toHaveBeenCalledTimes(1);@@ -288,7 +297,7 @@ describe("PaywallModal — upgrade mutation", () => {expect(args.data.billing_cycle).toBe("monthly");});- it("clicking Upgrade to Pro after switching to yearly fires {tier:PRO, billing_cycle:yearly}", async () => {+ it("clicking Start Pro after switching to yearly fires {tier:PRO, billing_cycle:yearly}", async () => {stubLocation();const { mutateFn } = setupMocks({subscription: {@@ -301,7 +310,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);fireEvent.click(screen.getByRole("button", { name: /yearly/i }));- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mutateFn).toHaveBeenCalledTimes(1);@@ -327,7 +336,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(window.location.href).toBe("https://checkout.stripe.com/c/test");@@ -381,7 +390,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mutateFn).toHaveBeenCalledTimes(1);@@ -413,7 +422,7 @@ describe("PaywallModal — upgrade mutation", () => {});render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mutateFn).toHaveBeenCalledTimes(1);@@ -424,7 +433,7 @@ describe("PaywallModal — upgrade mutation", () => {status: 200,data: { url: "https://checkout.stripe.com/pay/cs_test" },});- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(gtagCalls).toContainEqual([@@ -463,7 +472,7 @@ describe("PaywallModal — upgrade mutation", () => {});render(<PaywallModal />);- const upgrade = screen.getByRole("button", { name: /upgrade to pro/i });+ const upgrade = screen.getByRole("button", { name: /start pro/i });fireEvent.click(upgrade);await waitFor(() =>expect(gtagCalls.some((call) => call[1] === "conversion")).toBe(true),@@ -498,7 +507,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mockReplace).toHaveBeenCalledWith("/login");@@ -522,7 +531,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mockToast).toHaveBeenCalledTimes(1);@@ -546,7 +555,7 @@ describe("PaywallModal — upgrade mutation", () => {render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mockToast).toHaveBeenCalledTimes(1);@@ -574,6 +583,21 @@ describe("PaywallModal — admin-overridden NO_TIER with active Stripe sub", ()});}+ it("routes a paid Pro user to the exact Max charge review without mutating", () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "PRO",+ tier_costs: { PRO: 5000, MAX: 32000 },+ has_active_stripe_subscription: true,+ },+ });+ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: /start max/i }));+ expect(mockReplace).toHaveBeenCalledWith("/settings/billing?upgrade=MAX");+ expect(mutateFn).not.toHaveBeenCalled();+ });+it("staging gate: clicking Upgrade with active Stripe sub opens confirm dialog and skips mutation", () => {stubLocation();const { mutateFn } = setupMocks({@@ -586,7 +610,7 @@ describe("PaywallModal — admin-overridden NO_TIER with active Stripe sub", ()});render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));// Confirmation dialog text surfaces; mutation has NOT fired yet.expect(@@ -608,7 +632,7 @@ describe("PaywallModal — admin-overridden NO_TIER with active Stripe sub", ()});render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));fireEvent.click(screen.getByRole("button", { name: /switch to pro/i }));await waitFor(() => {@@ -629,7 +653,7 @@ describe("PaywallModal — admin-overridden NO_TIER with active Stripe sub", ()});render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));fireEvent.click(screen.getByRole("button", { name: /cancel/i }));expect(mutateFn).not.toHaveBeenCalled();@@ -646,7 +670,7 @@ describe("PaywallModal — admin-overridden NO_TIER with active Stripe sub", ()});render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));await waitFor(() => {expect(mutateFn).toHaveBeenCalledTimes(1);@@ -747,7 +771,7 @@ describe("PaywallModal — PostHog paywall funnel", () => {});render(<PaywallModal />);- fireEvent.click(screen.getByRole("button", { name: /upgrade to max/i }));+ fireEvent.click(screen.getByRole("button", { name: /start max/i }));await waitFor(() => {expect(mutateFn).toHaveBeenCalledTimes(1);diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsxindex 5917234f84..ff6b7e7942 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx@@ -186,13 +186,13 @@ test("reports the offer impression against the billing surface", async () => {);});-test("keeps paid checkout reporting against the upgrade_modal surface", async () => {+test("labels paid signup Start Max and keeps checkout reporting against the upgrade_modal surface", async () => {server.use(getGetTrialsGetTrialStatusMockHandler200(eligible()));render(<PaywallModal />);const max = within(await screen.findByRole("region", { name: "Max plan" }));- const paid = max.getByRole("button", { name: "Upgrade to Max" });+ const paid = max.getByRole("button", { name: "Start Max" });expect(paid.getAttribute("data-fast-goal")).toBe("plan_cta_click");expect(paid.getAttribute("data-fast-goal-surface")).toBe("upgrade_modal");@@ -210,7 +210,7 @@ test("leaves the paid CTAs alone when the user is not eligible", async () => {render(<PaywallModal />);const pro = within(await screen.findByRole("region", { name: "Pro plan" }));- expect(pro.getByRole("button", { name: "Upgrade to Pro" })).toBeDefined();+ expect(pro.getByRole("button", { name: "Start Pro" })).toBeDefined();expect(screen.queryByRole("button", { name: /Start .*trial/ })).toBeNull();});@@ -224,7 +224,7 @@ test("leaves the paid CTAs alone when the trial status fails to load", async ()render(<PaywallModal />);const pro = within(await screen.findByRole("region", { name: "Pro plan" }));- expect(pro.getByRole("button", { name: "Upgrade to Pro" })).toBeDefined();+ expect(pro.getByRole("button", { name: "Start Pro" })).toBeDefined();expect(screen.queryByRole("button", { name: /Start .*trial/ })).toBeNull();});@@ -241,7 +241,7 @@ test("hides an offer for a tier the backend isn't pricing on this paywall", asynrender(<PaywallModal />);const pro = within(await screen.findByRole("region", { name: "Pro plan" }));- expect(pro.getByRole("button", { name: "Upgrade to Pro" })).toBeDefined();+ expect(pro.getByRole("button", { name: "Start Pro" })).toBeDefined();expect(screen.queryByRole("button", { name: /Start .*trial/ })).toBeNull();});diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallHeader.tsxindex b18e854b95..91c39fc451 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallHeader.tsx@@ -10,13 +10,10 @@ export function PaywallHeader() {variant="h3"className="!text-[1.375rem] !leading-[1.6rem] md:!text-[1.75rem] md:!leading-[2.5rem]">- Choose the plan that's right for{" "}- <span className="bg-gradient-to-r from-purple-500 to-indigo-500 bg-clip-text text-transparent">- you- </span>+ Choose a plan to keep working</Text><Text variant="body" className="!text-zinc-500">- Pick a plan to start working with experts and running workflows.+ Your chats, agents and files are saved.</Text><Linkhref="/tour/chat?utm_source=platform_paywall"@@ -27,11 +24,7 @@ export function PaywallHeader() {icon={PlayCircleIcon}className="size-5 shrink-0 text-violet-600"/>- <span>- Not sure yet?{" "}- <span className="font-semibold text-violet-700">Try it</span> —- Instant demo — No signup- </span>+ <span>Explore a quick demo</span></Link></div>);diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallPlanChoices.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallPlanChoices.tsxnew file mode 100644index 0000000000..a6f0cf558b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/components/PaywallPlanChoices.tsx@@ -0,0 +1,182 @@+"use client";++import { SparklesIcon, Tick02Icon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import {+ YEARLY_PRICE_FACTOR,+ type PlanDef,+} from "@/components/molecules/PlanCard/plans";++interface Props {+ plans: PlanDef[];+ cycle: "monthly" | "yearly";+ onCycle: (cycle: "monthly" | "yearly") => void;+ onSelect: (tier: string) => void;+ pending: boolean;+ selectedTier: string | null;+}++export function PaywallPlanChoices({+ plans,+ cycle,+ onCycle,+ onSelect,+ pending,+ selectedTier,+}: Props) {+ const team = plans.find((plan) => plan.key === "BUSINESS");+ return (+ <section aria-label="Choose your AutoGPT plan" className="w-full space-y-5">+ <div className="flex justify-center">+ <div+ role="group"+ aria-label="Billing period"+ className="inline-flex rounded-full border border-zinc-200 bg-zinc-100 p-1"+ >+ {(["monthly", "yearly"] as const).map((value) => (+ <Button+ key={value}+ variant="ghost"+ size="small"+ aria-pressed={cycle === value}+ onClick={() => onCycle(value)}+ disabled={pending}+ className={+ cycle === value ? "bg-white shadow-sm" : "text-zinc-500"+ }+ >+ {value === "monthly" ? "Monthly" : "Yearly"}+ {value === "yearly" && (+ <span className="text-xs text-emerald-600">+ Save {Math.round((1 - YEARLY_PRICE_FACTOR) * 100)}%+ </span>+ )}+ </Button>+ ))}+ </div>+ </div>+ <div className="grid gap-4 sm:grid-cols-2">+ {plans+ .filter((plan) => plan.key !== "BUSINESS")+ .map((plan) => (+ <PlanChoice+ key={plan.key}+ plan={plan}+ cycle={cycle}+ onSelect={onSelect}+ pending={pending}+ selectedTier={selectedTier}+ />+ ))}+ </div>+ {team && (+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-zinc-200 px-4 py-3">+ <div>+ <Text variant="small-medium">Team</Text>+ <Text variant="small" tone="secondary">+ Custom capacity for your organization.+ </Text>+ </div>+ <Button+ variant="secondary"+ size="small"+ onClick={() => onSelect(team.key)}+ >+ Talk to sales+ </Button>+ </div>+ )}+ <Text variant="small" tone="secondary" className="text-center text-xs">+ Your conversations and agents stay saved. Cancel anytime.+ </Text>+ </section>+ );+}++function PlanChoice({+ plan,+ cycle,+ onSelect,+ pending,+ selectedTier,+}: { plan: PlanDef } & Omit<Props, "plans" | "onCycle">) {+ const amount = cycle === "yearly" ? plan.usdYearly : plan.usdMonthly;+ const formatted =+ amount == null+ ? null+ : new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: "USD",+ maximumFractionDigits: amount % 1 ? 2 : 0,+ }).format(amount);+ const isPro = plan.key === "PRO";+ const features = isPro+ ? [+ "Experts for content, sales and research, with Otto coordinating",+ "Agents that keep working in the background on a schedule",+ ]+ : [+ plan.usage+ ? `${plan.usage.replace(/x|×/, "")} times the usage of Pro`+ : "More usage for demanding work",+ "More file storage and priority support",+ ];+ return (+ <section+ aria-label={`${plan.name} plan`}+ className={`flex flex-col rounded-2xl border p-5 sm:p-6 ${isPro ? "border-purple-200 bg-gradient-to-br from-purple-50 via-white to-blue-50" : "border-zinc-200 bg-white"}`}+ >+ <div className="mb-4 flex items-center gap-2">+ <Icon+ icon={SparklesIcon}+ size={18}+ className={isPro ? "text-purple-600" : "text-zinc-600"}+ />+ <Text variant="large-semibold" as="h2">+ {plan.name}+ </Text>+ </div>+ <Text variant="small" tone="secondary" className="mb-4">+ {isPro+ ? "For the work you do every day."+ : "For bigger ideas and heavier work."}+ </Text>+ <div className="mb-5">+ <Text variant="h3" as="span" className="tracking-tight">+ {formatted ?? "Unavailable"}+ </Text>+ {formatted && (+ <Text variant="small" as="span" tone="secondary">+ {" "}+ / {cycle === "yearly" ? "year" : "month"}+ </Text>+ )}+ </div>+ <ul className="mb-6 space-y-2.5">+ {features.map((feature) => (+ <li className="flex gap-2" key={feature}>+ <Icon+ icon={Tick02Icon}+ size={15}+ className="mt-0.5 shrink-0 text-purple-600"+ />+ <Text variant="small" className="text-zinc-700">+ {feature}+ </Text>+ </li>+ ))}+ </ul>+ <Button+ className="mt-auto w-full"+ variant={isPro ? "primary" : "secondary"}+ onClick={() => onSelect(plan.key)}+ loading={pending && selectedTier === plan.key}+ disabled={pending || !formatted}+ >+ Start {plan.name}+ </Button>+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.tsindex e3a1d3b91f..64265d2459 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts@@ -50,6 +50,8 @@ const PLAN_LABEL: Record<string, string> = {function deriveAvailablePlans(tierCosts: Record<string, number> | undefined,tierCostsYearly: Record<string, number> | undefined,+ multipliers: Record<string, number> | undefined,+ currentTier: string | undefined,): PlanDef[] {if (!tierCosts) return [];return TIER_DISPLAY_ORDER.filter(@@ -59,6 +61,14 @@ function deriveAvailablePlans(const yearlyCents = tierCostsYearly?.[tier];return {...PLAN_METADATA[tier],+ cta:+ currentTier === "NO_TIER" && tier !== "BUSINESS"+ ? `Start ${PLAN_METADATA[tier].name}`+ : PLAN_METADATA[tier].cta,+ usage:+ tier === "MAX" && multipliers?.MAX && multipliers?.PRO+ ? `${Math.round((multipliers.MAX / multipliers.PRO) * 10) / 10}x`+ : null,usdMonthly: monthlyCents / 100,usdYearly: typeof yearlyCents === "number" ? yearlyCents / 100 : null,};@@ -110,6 +120,8 @@ export function usePaywallModal() {const plans = deriveAvailablePlans(subscription?.tier_costs,subscription?.tier_costs_yearly,+ subscription?.tier_multipliers,+ subscription?.tier,);// Trial checkout returns to /settings/billing, which renders the trial@@ -193,6 +205,10 @@ export function usePaywallModal() {window.open(TEAM_INTAKE_FORM_URL, "_blank", "noopener,noreferrer");return;}+ if (tier === "MAX" && subscription?.tier === "PRO") {+ router.replace("/settings/billing?upgrade=MAX");+ return;+ }// Active Stripe sub → modify-in-place hits saved-card auto-charge; no// Stripe Checkout opens, so the click would otherwise be a silent// re-bill / refund. Stage the tier behind the confirmation dialog.@@ -246,6 +262,7 @@ export function usePaywallModal() {confirmPendingTier,cancelPendingTier,handleLogout,+ handleClose: () => router.replace("/settings/billing"),trial,trialOffer,};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex 1cce7603b0..caae9959c7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -7,6 +7,8 @@ import { useCopilotPage } from "./useCopilotPage";import { FlaskConicalIcon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useUsageExperience } from "@/services/usageExperience/useUsageExperience";+import { useRateLimitRefresh } from "./components/RateLimitResetDialog/useRateLimitRefresh";interface Props {droppedFiles: File[];@@ -80,6 +82,12 @@ function ChatHostBody({isKickoffStarting,followBackendTurn,} = useCopilotPage({ isStreamRuntime });+ const usage = useUsageExperience();+ const usageRefresh = useRateLimitRefresh(rateLimitMessage, usage.retry);+ function dismissAfterProviderChange() {+ usageRefresh.release();+ dismissRateLimit();+ }return (<>@@ -94,6 +102,10 @@ function ChatHostBody({)}<div className="min-h-0 flex-1 overflow-hidden"><ChatContainer+ isUsageRefused={!!rateLimitMessage || usageRefresh.guarded}+ usageFailure={platformLimitFailure}+ onDismissUsage={dismissAfterProviderChange}+ usageRefresh={usageRefresh}messages={messages}status={status}error={error}@@ -133,6 +145,7 @@ function ChatHostBody({/></div><RateLimitGate+ refreshState={usageRefresh}rateLimitMessage={rateLimitMessage}failure={platformLimitFailure}sessionId={sessionId}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsxindex f43fe8f029..ca0ca71010 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx@@ -1,5 +1,6 @@import {getGetV2ListChatConnectionsMockHandler200,+ getGetV2GetCopilotUsageMockHandler200,getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200,} from "@/app/api/__generated__/endpoints/chat/chat.msw";import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";@@ -10,7 +11,7 @@ import {copilotStreamHandler,streamSseResponse,} from "@/tests/integrations/copilot-sse";-import { screen, waitFor } from "@testing-library/react";+import { screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { UIMessageChunk } from "ai";import { http, HttpResponse } from "msw";@@ -57,7 +58,7 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({}),}));-const flagState = vi.hoisted(() => ({ experts: false }));+const flagState = vi.hoisted(() => ({ experts: false, billing: false }));const streamPath = vi.hoisted(() => ({ runtime: false }));@@ -73,7 +74,9 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({? streamPath.runtime: flag === "HIRE_EXPERTS"? flagState.experts- : false,+ : flag === "ENABLE_PLATFORM_PAYMENT"+ ? flagState.billing+ : false,}));beforeEach(() => {@@ -82,6 +85,7 @@ beforeEach(() => {useCopilotUIStore.setState({ initialPrompt: null });window.localStorage.clear();flagState.experts = false;+ flagState.billing = false;});afterEach(() => {@@ -90,6 +94,7 @@ afterEach(() => {useCopilotUIStore.setState({ initialPrompt: null });window.localStorage.clear();flagState.experts = false;+ flagState.billing = false;});describe.each(STREAM_PATHS)("on the %s path", (path) => {@@ -201,7 +206,7 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {// useCopilotStream's rate-limit branch sets rateLimitMessage, which the// RateLimitGate translates into a Dialog with this title.expect(- await screen.findByText(/daily usage limit reached/i, undefined, {+ await screen.findByText(/We couldn’t check your usage/i, undefined, {timeout: 5000,}),).toBeDefined();@@ -236,7 +241,7 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {});expect(- await screen.findByText(/daily usage limit reached/i, undefined, {+ await screen.findByText(/We couldn’t check your usage/i, undefined, {timeout: 5000,}),).toBeDefined();@@ -389,15 +394,34 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {},};+ function usageLimitAdmission() {+ let refused = false;+ server.use(+ getGetV2GetCopilotUsageMockHandler200(() => ({+ tier: "PRO",+ daily: {+ percent_used: refused ? 100 : 0,+ resets_at: new Date("2099-10-08T00:00:00Z"),+ },+ weekly: {+ percent_used: 40,+ resets_at: new Date("2099-10-12T00:00:00Z"),+ },+ })),+ );+ return http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ () => {+ refused = true;+ return HttpResponse.json(ourCap, { status: 429 });+ },+ );+ }+it("keeps the plan dialog for our cap and offers the linked subscription beside the upgrade", async () => {+ flagState.billing = true;let switchedTo: unknown = null;server.use(- copilotStreamErrorHandler({- baseUrl: TEST_BACKEND_BASE_URL,- sessionId: TEST_SESSION_ID,- status: 429,- body: ourCap,- }),getGetV2ListChatConnectionsMockHandler200({offers: [platformOffer(), chatgptOffer()],}),@@ -410,24 +434,30 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {);renderHost();+ server.use(usageLimitAdmission());await typeAndSend("over the cap");// Our own cap, so our own dialog: the upgrade path survives ...+ const dialog = await screen.findByRole("dialog");expect(- await screen.findByText(/daily usage limit reached/i, undefined, {- timeout: 5000,- }),+ await within(dialog).findByText(+ /You’ve hit today’s limit/i,+ undefined,+ {+ timeout: 5000,+ },+ ),).toBeDefined();expect(screen.queryByText(/hit this connection's limit/i)).toBeNull();expect(- screen.getByRole("button", { name: /upgrade plan|contact us/i }),+ await within(dialog).findByRole("button", { name: /upgrade to max/i }),).toBeDefined();// ... and the linked subscription is offered next to it, because the cap// does not apply to a turn billed to the user's own credential.const user = userEvent.setup();await user.click(- await screen.findByRole(+ await within(dialog).findByRole("button",{ name: /continue on chatgpt/i },{ timeout: 5000 },@@ -440,34 +470,33 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {llm_credential_id: "cred-1",}),);- await waitFor(() =>- expect(screen.queryByText(/daily usage limit reached/i)).toBeNull(),- );+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());});it("offers nothing to continue on when the platform is the only connection", async () => {+ flagState.billing = true;server.use(- copilotStreamErrorHandler({- baseUrl: TEST_BACKEND_BASE_URL,- sessionId: TEST_SESSION_ID,- status: 429,- body: ourCap,- }),getGetV2ListChatConnectionsMockHandler200({offers: [platformOffer()],}),);renderHost();+ server.use(usageLimitAdmission());await typeAndSend("over the cap");+ const dialog = await screen.findByRole("dialog");expect(- await screen.findByText(/daily usage limit reached/i, undefined, {- timeout: 5000,- }),+ await within(dialog).findByText(+ /You’ve hit today’s limit/i,+ undefined,+ {+ timeout: 5000,+ },+ ),).toBeDefined();expect(- screen.getByRole("button", { name: /upgrade plan|contact us/i }),+ await within(dialog).findByRole("button", { name: /upgrade to max/i }),).toBeDefined();// The connection that just refused is never offered back. Were it not// excluded, "Continue on AutoGPT Platform" would appear once the offers@@ -526,7 +555,7 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {timeout: 5000,}),).toBeDefined();- expect(screen.queryByText(/daily usage limit reached/i)).toBeNull();+ expect(screen.queryByText(/You’ve hit today’s limit/i)).toBeNull();});});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsxindex e3de28699b..8b89f4f497 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx@@ -4,6 +4,9 @@ import {getGetV2GetSessionMockHandler200,getPostV2CancelSessionTaskMockHandler200,} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { getGetSubscriptionStatusMockHandler200 } from "@/app/api/__generated__/endpoints/credits/credits.msw";+import { getGetTrialsGetTrialStatusMockHandler200 } from "@/app/api/__generated__/endpoints/trials/trials.msw";+import { ProActivationProvider } from "@/services/pro-activation/ProActivationProvider";import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";@@ -109,7 +112,9 @@ function Wrapper({<NuqsTestingAdapter searchParams={searchParams}><BackendAPIProvider><OnboardingProvider>- <TooltipProvider>{children}</TooltipProvider>+ <TooltipProvider>+ <ProActivationProvider>{children}</ProActivationProvider>+ </TooltipProvider></OnboardingProvider></BackendAPIProvider></NuqsTestingAdapter>@@ -150,6 +155,20 @@ export function renderHost(tier: "PRO",reset_cost: 0,}),+ getGetSubscriptionStatusMockHandler200({+ tier: "PRO",+ monthly_cost: 5000,+ tier_costs: { PRO: 5000, MAX: 32000 },+ proration_credit_cents: 0,+ }),+ getGetTrialsGetTrialStatusMockHandler200({+ active: false,+ converted: true,+ eligible: false,+ offer: null,+ ends_at: null,+ status: "active",+ }),getGetV2GetPendingMessagesMockHandler200({count: opts.pendingMessages?.length ?? 0,messages: opts.pendingMessages ?? [],diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex 7b1e6856f0..6d8df370c1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -1,5 +1,6 @@"use client";import { ChatInput } from "@/app/(platform)/copilot/components/ChatInput/ChatInput";+import { ChatComposerFrame } from "./components/ChatComposerFrame";import {Tooltip,TooltipContent,@@ -7,7 +8,7 @@ import {} from "@/components/atoms/Tooltip/BaseTooltip";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { UIDataTypes, UIMessage, UITools } from "ai";-import { LayoutGroup, motion } from "framer-motion";+import { LayoutGroup } from "framer-motion";import { useCallback, useEffect, useRef, useState } from "react";import type { TurnStatsMap } from "../../helpers/convertChatSessionToUiMessages";import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";@@ -18,6 +19,7 @@ import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/Copiloimport { NewChatOnboarding } from "../ExpertOnboardingCard/NewChatOnboarding";import { EmptySession } from "../EmptySession/EmptySession";import { UsageLimitReachedCard } from "../UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard";+import type { UsageNoticeContext } from "../UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard";import { useIsUsageLimitReached } from "../UsageLimits/useIsUsageLimitReached";import { TaskProgressBar } from "../TaskProgressBar/TaskProgressBar";import { getLatestTaskList } from "../TaskProgressBar/helpers";@@ -56,6 +58,10 @@ import {} from "../../expertKickoff";export interface ChatContainerProps {+ isUsageRefused?: boolean;+ usageFailure?: import("../../providerFailure").ProviderFailure | null;+ onDismissUsage?: () => void;+ usageRefresh?: UsageNoticeContext["refresh"];messages: UIMessage<unknown, UIDataTypes, UITools>[];status: string;error: Error | undefined;@@ -161,6 +167,10 @@ export const ChatContainer = ({onDroppedFilesConsumed,turnStats,expertIdentity,+ isUsageRefused = false,+ usageFailure,+ onDismissUsage,+ usageRefresh,isResolvingExpertIdentity,isAdoptingExpertSession,isKickoffStarting,@@ -188,20 +198,14 @@ export const ChatContainer = ({// state from the backend).const isSessionUnavailable =!!isReconnecting || isLoadingSession || !!isSessionError;- const isLimitReached = useIsUsageLimitReached();- // Only a hover made while the limit is reached may open the usage tooltip.- // Radix reports hovers while `open` holds it shut, and a lifted limit hides- // it without a close event; either would pop it open, unhovered, the next- // time the limit is reached.+ const isUsageExhausted = useIsUsageLimitReached(sessionId);+ const isLimitReached = isUsageExhausted || isUsageRefused;const [isUsageTooltipOpen, setIsUsageTooltipOpen] = useState(false);useEffect(() => {if (!isLimitReached) setIsUsageTooltipOpen(false);}, [isLimitReached]);const isInputDisabled =- isSessionUnavailable ||- isLimitReached ||- !!isResolvingExpertIdentity ||- !!isKickoffStarting;+ isSessionUnavailable || !!isResolvingExpertIdentity || !!isKickoffStarting;// A fired (archived) expert's threads stay as read-only history — the// composer is replaced by a quiet notice so no new turns can be sent.const archivedExpertIdentity = expertIdentity?.isArchived@@ -213,11 +217,16 @@ export const ChatContainer = ({? { id: expertIdentity.id, name: expertIdentity.name }: null;useShareChatExpert(chatExpert);- const isSendLocked = isExpertArchived || !!isResolvingExpertIdentity;+ const isTurnLocked = isExpertArchived || !!isResolvingExpertIdentity;+ const isSendLocked = isTurnLocked || isLimitReached;+ // The usage limit pauses the composer only. A card's answers, a review+ // approval, a retry or a voice turn still go to the server, which refuses+ // them with the limit dialog and keeps the text for the composer; a no-op+ // here dropped what the user had entered.// NO_OP is module-level so a locked composer keeps a stable function identity// across renders — otherwise every consumer of `guardedOnSend` (the actions// provider, ChatInput, EmptySession, handleRetry) re-renders on each pass.- const guardedOnSend = isSendLocked ? NO_OP_SEND : onSend;+ const guardedOnSend = isTurnLocked ? NO_OP_SEND : onSend;const isVoiceModeEnabled = useGetFlag(Flag.COPILOT_VOICE_MODE);const isAutoModeEnabled = useGetFlag(Flag.COPILOT_AUTO_MODE);@@ -375,6 +384,7 @@ export const ChatContainer = ({enabled={messages.length === 0 &&!isInputDisabled &&+ !isLimitReached &&!isStreaming &&!isCreatingSession &&!isExpertArchived@@ -417,33 +427,21 @@ export const ChatContainer = ({/></>) : (- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ duration: 0.3 }}- className={cn(- "relative mx-auto w-full max-w-3xl px-3 pb-6 pt-2",- hasComposerTab && "max-lg:pt-0",- )}+ <ChatComposerFrame+ className={cn(hasComposerTab && "max-lg:pt-0")}+ paused={isLimitReached}+ noticeRef={usageCardRef}+ notice={+ isLimitReached ? (+ <UsageLimitReachedCard+ sessionID={sessionId}+ failure={usageFailure}+ onDismiss={onDismissUsage}+ refresh={usageRefresh}+ />+ ) : null+ }>- {isLimitReached && (- <div- ref={usageCardRef}- className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2"- >- <div- aria-hidden="true"- data-testid="usage-limit-backdrop"- className="absolute -inset-x-14 -top-20 bottom-[-18px] overflow-hidden rounded-[2rem] bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.96)_0%,rgba(255,255,255,0.9)_42%,rgba(255,255,255,0.58)_68%,rgba(255,255,255,0)_100%)] backdrop-blur-lg [mask-image:linear-gradient(to_bottom,transparent_0%,black_26%,black_100%)]"- >- <div className="absolute inset-x-10 bottom-0 h-28 rounded-full bg-white/80 blur-2xl" />- <div className="absolute inset-x-16 bottom-8 h-16 rounded-full bg-white/55 blur-xl" />- </div>- <div className="pointer-events-auto relative px-3">- <UsageLimitReachedCard />- </div>- </div>- )}<SharedChatNotice sessionId={sessionId} />{hasComposerTab && <ComposerPanelTab expert={chatExpert} />}{isTaskBarEnabled && (@@ -464,8 +462,10 @@ export const ChatContainer = ({<div><ChatInputinputId="chat-input-session"+ draftKey={`session:${sessionId}`}onSend={guardedOnSend}disabled={isInputDisabled}+ sendDisabled={isLimitReached}isStreaming={isStreaming}isTurnStarting={status === "submitted"}isUploadingFiles={isUploadingFiles}@@ -514,11 +514,11 @@ export const ChatContainer = ({</div></TooltipTrigger><TooltipContent side="top" className="max-w-sm">- You've reached your usage limit. Wait for it to- refresh or upgrade your plan to continue sending messages.+ Sending is paused. Your draft is saved and you can keep+ editing it.</TooltipContent></Tooltip>- </motion.div>+ </ChatComposerFrame>)}</div>) : (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsxindex 08cb78361f..eb7ddd1625 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx@@ -111,8 +111,18 @@ vi.mock("framer-motion", () => {});vi.mock("@/app/(platform)/copilot/components/ChatInput/ChatInput", () => ({- ChatInput: ({ disabled }: { disabled?: boolean }) => (- <input data-testid="chat-input" disabled={disabled} />+ ChatInput: ({+ disabled,+ sendDisabled,+ }: {+ disabled?: boolean;+ sendDisabled?: boolean;+ }) => (+ <input+ data-testid="chat-input"+ disabled={disabled}+ data-send-disabled={String(!!sendDisabled)}+ />),}));@@ -279,17 +289,46 @@ describe("ChatContainer", () => {expect(screen.queryByRole("tooltip")).toBeNull();});- it("renders the blurred usage-limit backdrop only when the limit is reached", () => {+ it("keeps the draft editable while the usage notice pauses sending", () => {mockIsUsageLimitReached.mockReturnValue(true);-render(<ChatContainer {...baseProps} />);+ expect(screen.getByRole("alert")).toBeDefined();+ const input = screen.getByTestId("chat-input") as HTMLInputElement;+ expect(input.disabled).toBe(false);+ expect(input.getAttribute("data-send-disabled")).toBe("true");+ fireEvent.change(input, { target: { value: "Keep this draft" } });+ expect(input.value).toBe("Keep this draft");+ expect(screen.queryByTestId("usage-limit-backdrop")).toBeNull();+ });++ it("still sends a retry while the limit pauses the composer, so the server can refuse it", () => {+ mockIsUsageLimitReached.mockReturnValue(true);+ const onSend = vi.fn();+ render(+ <ChatContainer+ {...baseProps}+ onSend={onSend}+ messages={[+ {+ id: "question",+ role: "user",+ parts: [{ type: "text", text: "Summarize the launch notes" }],+ },+ ]}+ />,+ );+ expect(+ screen.getByTestId("chat-input").getAttribute("data-send-disabled"),+ ).toBe("true");- const backdrop = screen.getByTestId("usage-limit-backdrop");+ fireEvent.click(screen.getByRole("button", { name: "Retry message" }));- expect(screen.getByRole("alert")).toBeDefined();- expect(backdrop.className).toContain("backdrop-blur-lg");- expect(backdrop.className).toContain("[mask-image:linear-gradient");- expect(backdrop.className).toContain("radial-gradient");+ expect(onSend).toHaveBeenCalledWith(+ "Summarize the launch notes",+ undefined,+ undefined,+ undefined,+ );});it("does not render the usage-limit backdrop while usage is still available", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/ChatComposerFrame.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/ChatComposerFrame.tsxnew file mode 100644index 0000000000..08edd24eac--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/ChatComposerFrame.tsx@@ -0,0 +1,44 @@+import { motion } from "framer-motion";+import type { ReactNode, Ref } from "react";+import { cn } from "@/lib/utils";+import { PausedDraftNote } from "./PausedDraftNote";++interface Props {+ children: ReactNode;+ notice?: ReactNode;+ noticeRef?: Ref<HTMLDivElement>;+ paused?: boolean;+ className?: string;+}++/** Shared composer spacing keeps the floating notice outside the input row. */+export function ChatComposerFrame({+ children,+ notice,+ noticeRef,+ paused = false,+ className,+}: Props) {+ return (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ duration: 0.3 }}+ className={cn(+ "relative mx-auto w-full max-w-3xl px-3 pb-6 pt-2",+ className,+ )}+ >+ {notice && (+ <div+ ref={noticeRef}+ className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2"+ >+ <div className="pointer-events-auto relative px-3">{notice}</div>+ </div>+ )}+ {children}+ {paused && <PausedDraftNote />}+ </motion.div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PausedDraftNote.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PausedDraftNote.tsxnew file mode 100644index 0000000000..bcb0256157--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PausedDraftNote.tsx@@ -0,0 +1,12 @@+import { Text } from "@/components/atoms/Text/Text";++export function PausedDraftNote() {+ return (+ <Text+ variant="small"+ className="mt-2 px-1 text-center !text-xs !text-zinc-500"+ >+ Your draft is saved. You can keep editing while sending is paused.+ </Text>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex b7b985c484..5c080cce91 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -72,6 +72,7 @@ interface Props {workspaceFiles?: WorkspaceAttachment[],) => void | Promise<void>;disabled?: boolean;+ sendDisabled?: boolean;isStreaming?: boolean;/** The sent message's turn has not started: a Stop now would cancel nothing* on the server and drop the message, so the button only shows progress. */@@ -83,6 +84,7 @@ interface Props {placeholder?: string;className?: string;inputId?: string;+ draftKey?: string;/** Files dropped onto the chat window by the parent. */droppedFiles?: File[];/** Called after droppedFiles have been merged into internal state. */@@ -121,6 +123,7 @@ interface Props {export function ChatInput({onSend,disabled = false,+ sendDisabled = false,isStreaming = false,isTurnStarting = false,isUploadingFiles = false,@@ -129,6 +132,7 @@ export function ChatInput({placeholder = "Type your message...",className,inputId = "chat-input",+ draftKey,droppedFiles,onDroppedFilesConsumed,hasSession = false,@@ -210,9 +214,10 @@ export function ChatInput({onEnqueue,isStreaming,hasAttachments,- disabled: isTextareaDisabled,+ disabled: isTextareaDisabled || sendDisabled,canSendEmpty: hasAttachments,inputId,+ draftKey,});const integrations = useConnectedIntegrations(expertId);@@ -286,6 +291,7 @@ export function ChatInput({const devtoolSessionId = isTokenDevtoolEnabled() ? sessionId : null;const canSend =!disabled &&+ !sendDisabled &&(!!value.trim() || hasAttachments) &&!isRecording &&!isTranscribing;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsxindex 80a9bdd0b0..9d5b0ba1b2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx@@ -661,6 +661,22 @@ describe("ChatInput guided prompt prefill", () => {});describe("ChatInput submit behavior", () => {+ it("preserves an editable draft while a usage cap blocks submission", async () => {+ const onSend = vi.fn().mockResolvedValue(undefined);+ const { rerender } = render(<ChatInput onSend={onSend} sendDisabled />);+ const textarea = screen.getByTestId("textarea") as HTMLTextAreaElement;+ expect(textarea.disabled).toBe(false);+ fireEvent.change(textarea, { target: { value: "My next idea" } });+ fireEvent.submit(textarea.closest("form")!);+ expect(onSend).not.toHaveBeenCalled();+ expect(textarea.value).toBe("My next idea");+ rerender(<ChatInput onSend={onSend} sendDisabled={false} />);+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() =>+ expect(onSend).toHaveBeenCalledWith("My next idea", undefined, undefined),+ );+ });+it("does not call onSend when textarea is empty", () => {const onSend = vi.fn().mockResolvedValue(undefined);render(<ChatInput onSend={onSend} />);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsxnew file mode 100644index 0000000000..4003314f8d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/chatDraft.test.tsx@@ -0,0 +1,166 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+const auth = vi.hoisted(() => ({+ user: { id: "user-a" } as { id: string } | null,+}));+const prompts = vi.hoisted(() => ({ initialPrompt: null as string | null }));+vi.mock("@/lib/auth/hooks/useAuthStore", () => ({+ useAuthStore: (selector: (state: typeof auth) => unknown) => selector(auth),+}));+vi.mock("@/app/(platform)/copilot/store", () => ({+ useCopilotUIStore: () => ({+ initialPrompt: prompts.initialPrompt,+ setInitialPrompt: (value: string | null) => {+ prompts.initialPrompt = value;+ },+ notifyMessageSent: vi.fn(),+ }),+}));+import { useChatInput } from "../useChatInput";++beforeEach(() => {+ sessionStorage.clear();+ auth.user = { id: "user-a" };+ prompts.initialPrompt = null;+});+describe("platform chat drafts", () => {+ it("restores the same account and conversation after a billing navigation remount", () => {+ const first = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ );+ act(() => first.result.current.setValue("My unsent next step"));+ first.unmount();+ const returned = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ );+ expect(returned.result.current.value).toBe("My unsent next step");+ });+ it("isolates users and sessions even without unmounting", () => {+ const { result, rerender } = renderHook(+ ({ draftKey }) => useChatInput({ onSend: vi.fn(), draftKey }),+ { initialProps: { draftKey: "session:chat-a" } },+ );+ act(() => result.current.setValue("Private draft"));+ rerender({ draftKey: "session:chat-b" });+ expect(result.current.value).toBe("");+ auth.user = { id: "user-b" };+ rerender({ draftKey: "session:chat-a" });+ expect(result.current.value).toBe("");+ auth.user = { id: "user-a" };+ rerender({ draftKey: "session:chat-a" });+ expect(result.current.value).toBe("Private draft");+ });+ it("clears a successfully sent draft so returning does not resurrect it", async () => {+ const first = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ );+ act(() => first.result.current.setValue("Send this"));+ await act(() => first.result.current.handleSend());+ first.unmount();+ expect(+ renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ ).result.current.value,+ ).toBe("");+ });+ it("persists the restored draft after a failed send", async () => {+ const first = renderHook(() =>+ useChatInput({+ onSend: () => {+ throw new Error("offline");+ },+ draftKey: "session:chat-a",+ }),+ );+ act(() => first.result.current.setValue("Keep this after failure"));+ await act(() => first.result.current.handleSend());+ first.unmount();+ expect(+ renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ ).result.current.value,+ ).toBe("Keep this after failure");+ });+ it("merges a late send failure with the draft written after returning", async () => {+ let rejectSend: ((error: Error) => void) | undefined;+ const sending = new Promise<void>((_, reject) => {+ rejectSend = reject;+ });+ const first = renderHook(() =>+ useChatInput({+ onSend: () => sending,+ draftKey: "session:chat-a",+ }),+ );+ act(() => first.result.current.setValue("Original message"));+ let send: Promise<void> | undefined;+ act(() => {+ send = first.result.current.handleSend();+ });+ first.unmount();+ const returned = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ );+ act(() => returned.result.current.setValue("New draft after returning"));+ await act(async () => {+ rejectSend?.(new Error("offline"));+ await send;+ });+ expect(returned.result.current.value).toBe(+ "Original message\n\nNew draft after returning",+ );+ returned.unmount();+ expect(+ renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "session:chat-a" }),+ ).result.current.value,+ ).toBe("Original message\n\nNew draft after returning");+ });+ it("keeps a late failed send out of another account's current draft", async () => {+ let rejectSend: ((error: Error) => void) | undefined;+ const sending = new Promise<void>((_, reject) => {+ rejectSend = reject;+ });+ const { result, rerender } = renderHook(() =>+ useChatInput({ onSend: () => sending, draftKey: "session:chat-a" }),+ );+ act(() => result.current.setValue("Account A message"));+ let send: Promise<void> | undefined;+ act(() => {+ send = result.current.handleSend();+ });+ auth.user = { id: "user-b" };+ rerender();+ act(() => result.current.setValue("Account B draft"));+ await act(async () => {+ rejectSend?.(new Error("offline"));+ await send;+ });+ expect(result.current.value).toBe("Account B draft");+ auth.user = { id: "user-a" };+ rerender();+ expect(result.current.value).toBe("Account A message");+ });+ it("allows an explicit guided prompt to replace the restored draft", () => {+ const first = renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "new:default" }),+ );+ act(() => first.result.current.setValue("Older draft"));+ first.unmount();+ prompts.initialPrompt = "Build a scheduled task";+ expect(+ renderHook(() =>+ useChatInput({ onSend: vi.fn(), draftKey: "new:default" }),+ ).result.current.value,+ ).toBe("Build a scheduled task");+ });+ it("does not persist inputs that have not opted into a platform draft key", () => {+ const first = renderHook(() => useChatInput({ onSend: vi.fn() }));+ act(() => first.result.current.setValue("Tour text"));+ first.unmount();+ expect(sessionStorage.length).toBe(0);+ expect(+ renderHook(() => useChatInput({ onSend: vi.fn() })).result.current.value,+ ).toBe("");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.tsnew file mode 100644index 0000000000..0fb5125e37--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatDraft.ts@@ -0,0 +1,76 @@+import { useEffect, useRef, useState, type SetStateAction } from "react";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";++const subscribers = new Map<string, Set<(value: string) => void>>();++function readDraft(key: string | null) {+ if (!key || typeof window === "undefined") return "";+ try {+ return sessionStorage.getItem(key) ?? "";+ } catch {+ return "";+ }+}++function writeDraft(key: string | null, value: string) {+ if (!key || typeof window === "undefined") return;+ try {+ if (value) sessionStorage.setItem(key, value);+ else sessionStorage.removeItem(key);+ } catch {+ /* Keep the in-memory draft when browser storage is unavailable. */+ }+ subscribers.get(key)?.forEach((receive) => receive(value));+}++export function useChatDraft(draftKey?: string) {+ const userID = useAuthStore((state) => state.user?.id);+ const key =+ draftKey && userID+ ? `autogpt:chat-draft:${encodeURIComponent(userID)}:${encodeURIComponent(draftKey)}`+ : null;+ const [snapshot, setSnapshot] = useState(() => ({+ key,+ value: readDraft(key),+ }));+ const visible =+ snapshot.key === key ? snapshot : { key, value: readDraft(key) };+ const current = useRef(visible);+ current.current = visible;+ const mounted = useRef(true);+ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);+ useEffect(() => {+ if (!key) return;+ function receive(value: string) {+ const next = { key, value };+ current.current = next;+ setSnapshot(next);+ }+ const listeners = subscribers.get(key) ?? new Set();+ listeners.add(receive);+ subscribers.set(key, listeners);+ return () => {+ listeners.delete(receive);+ if (!listeners.size) subscribers.delete(key);+ };+ }, [key]);+ function setValue(update: SetStateAction<string>) {+ const previous =+ mounted.current && current.current.key === key+ ? current.current.value+ : readDraft(key);+ const value = typeof update === "function" ? update(previous) : update;+ writeDraft(key, value);+ if (mounted.current && current.current.key === key) {+ const next = { key, value };+ current.current = next;+ setSnapshot(next);+ }+ }+ return [visible.value, setValue] as const;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.tsindex 4ef3553a56..aae40d8533 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts@@ -1,5 +1,6 @@import { useCopilotUIStore } from "@/app/(platform)/copilot/store";import { toastSendFailure } from "../../helpers/sendFailureToast";+import { useChatDraft } from "./useChatDraft";import { ChangeEvent, FormEvent, useEffect, useRef, useState } from "react";interface Args {@@ -15,6 +16,7 @@ interface Args {/** Allow sending when text is empty (e.g. when files are attached). */canSendEmpty?: boolean;inputId?: string;+ draftKey?: string;}export function useChatInput({@@ -25,8 +27,9 @@ export function useChatInput({disabled = false,canSendEmpty = false,inputId = "chat-input",+ draftKey,}: Args) {- const [value, setValue] = useState("");+ const [value, setValue] = useChatDraft(draftKey);const [isSending, setIsSending] = useState(false);const [isEnqueueing, setIsEnqueueing] = useState(false);// Synchronous guard against double-submit — refs update immediately,@@ -51,7 +54,7 @@ export function useChatInput({) as HTMLTextAreaElement | null;textarea?.focus();},- [initialPrompt, setInitialPrompt, inputId],+ [initialPrompt, setInitialPrompt, inputId, setValue],);useEffect(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsxindex 25c93b9faa..97cd276061 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx@@ -169,6 +169,7 @@ export function EmptySession({><ChatInputinputId="chat-input-empty"+ draftKey={`new:${selectedExpert?.id ?? expertId ?? "default"}`}stackedvoiceToggle={voiceToggle}modeSelector={modeSelector}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsxindex c205bdda0e..ce9ebbfd35 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx@@ -1,94 +1,62 @@"use client";-import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";-import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";-import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";-import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";-import type { SubscriptionTier } from "@/app/api/__generated__/models/subscriptionTier";-import { toast } from "@/components/molecules/Toast/use-toast";-import { useEffect } from "react";+import { useRateLimitRefresh } from "./useRateLimitRefresh";import type { ProviderFailure } from "../../providerFailure";import { useProviderLimitDialog } from "../ProviderLimitDialog/useProviderLimitDialog";import { RateLimitResetDialog } from "./RateLimitResetDialog";+import { useUsageActions } from "@/services/usageExperience/useUsageActions";interface Props {rateLimitMessage: string | null;- /**- * The typed envelope behind our cap, when the backend sent one. With it- * the dialog can also offer a linked subscription to continue on. Without- * it (an older backend, or a 429 that is not the usage cap) the dialog is- * exactly as it always was.- */failure?: ProviderFailure | null;sessionId?: string | null;onDismiss: () => void;+ onRefreshingChange?: (refreshing: boolean) => void;+ refreshState?: ReturnType<typeof useRateLimitRefresh>;}-/**- * Renders the rate-limit dialog when the user hits their daily limit.- * Falls back to a toast when the usage query fails.- */export function RateLimitGate({rateLimitMessage,failure = null,sessionId = null,onDismiss,+ onRefreshingChange,+ refreshState,}: Props) {- // The switch itself is the provider-limit dialog's: the same offers list,- // the same exclusion of the connection that just refused, the same session- // mutation. Only the framing differs. Here the cap is ours, so the upgrade- // stays on offer and the switch is offered beside it, never instead.+ const state = useUsageActions();+ const localRefresh = useRateLimitRefresh(+ refreshState ? null : rateLimitMessage,+ state.retry,+ onRefreshingChange,+ );+ const refresh = refreshState ?? localRefresh;const { alternative, continueHere, isSwitching } = useProviderLimitDialog({failure,sessionId,- onDismiss,- });-- const {- data: usage,- isSuccess: hasUsage,- isError: usageError,- } = useGetV2GetCopilotUsage({- query: {- select: (res) => res.data as CoPilotUsagePublic,- enabled: !!rateLimitMessage,- refetchInterval: 30_000,- staleTime: 10_000,+ onDismiss: () => {+ refresh.release();+ onDismiss();},});-- // Pulls the user's current tier so the dialog can branch the CTA between- // "Upgrade plan" (route to /settings/billing) and "Contact us" (top-tier- // users have no higher self-serve plan to upgrade to).- const { data: tier } = useGetSubscriptionStatus({- query: {- enabled: !!rateLimitMessage,- select: (res) =>- res.status === 200- ? ((res.data as SubscriptionStatusResponse).tier as SubscriptionTier)- : null,- },- });-- useEffect(() => {- if (!rateLimitMessage) return;- if (!usageError) return;- toast({- title: "Usage limit reached",- description: rateLimitMessage,- variant: "destructive",- });+ const failureWindow = /\b(weekly|daily|trial)\b/i+ .exec(rateLimitMessage ?? "")?.[1]+ ?.toLowerCase();+ function upgrade() {onDismiss();- }, [rateLimitMessage, usageError, onDismiss]);-- const isOpen = !!rateLimitMessage && hasUsage;-+ state.upgrade();+ }return (<RateLimitResetDialog- isOpen={isOpen}+ isOpen={!!rateLimitMessage}onClose={onDismiss}- resetsAt={usage?.daily?.resets_at ?? usage?.weekly?.resets_at ?? null}- tier={tier ?? null}+ experience={state.experience}+ offer={state.offer}+ onUpgrade={upgrade}+ checking={refresh.checking || state.isLoading}+ failureWindow={failureWindow}+ unavailable={state.isError || refresh.failed || !state.experience.blocked}+ onRetry={() => void refresh.refresh()}+ isBillingEnabled={state.isBillingEnabled}alternative={alternative}onContinue={continueHere}isSwitching={isSwitching}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsxindex 48b9107df7..cfc2a7cb90 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx@@ -4,110 +4,196 @@ import type { SubscriptionTier } from "@/app/api/__generated__/models/subscriptiimport { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { PaymentDueAction } from "@/components/organisms/UsageExperience/PaymentDueAction";+import { PlanOffer } from "@/components/organisms/UsageExperience/PlanOffer";+import { ProviderContinuation } from "@/components/organisms/UsageExperience/ProviderContinuation";+import { UsageMeter } from "@/components/organisms/UsageExperience/UsageMeter";+import {+ getUsageExperience,+ getUsageOfferAction,+ type UsageExperience,+} from "@/services/usageExperience/helpers";+import { formatPaymentDue } from "@/services/usageExperience/payment";+import { usagePresentation } from "@/services/usageExperience/presentation";import { useRouter } from "next/navigation";-import { formatResetTime } from "../usageHelpers";+import type { ComponentProps } from "react";interface Props {isOpen: boolean;onClose: () => void;resetsAt?: string | Date | null;tier?: SubscriptionTier | null;- /**- * A linked subscription this chat could continue on instead. The platform- * cap does not apply to a turn billed to the user's own credential, so when- * the account holds one, switching is a way out that costs nothing more.- * Offered beside the upgrade, never instead of it: the cap is still ours.- */+ experience?: UsageExperience;+ offer?: Omit<ComponentProps<typeof PlanOffer>, "onUpgrade">;+ onUpgrade?: () => void;+ unavailable?: boolean;+ checking?: boolean;+ failureWindow?: string;+ onRetry?: () => void;+ isBillingEnabled?: boolean;alternative?: { display_name: string } | null;onContinue?: () => void;isSwitching?: boolean;}-const CONTACT_US_URL = "mailto:[email protected]";-const BILLING_PATH = "/settings/billing";--// Tiers that have no higher self-serve plan to upgrade to — direct these-// users to support instead of the billing page.-const TOP_TIERS: ReadonlySet<SubscriptionTier> = new Set([- "MAX",- "BUSINESS",- "ENTERPRISE",-]);-export function RateLimitResetDialog({isOpen,onClose,resetsAt,tier,- alternative = null,+ experience,+ offer,+ onUpgrade,+ unavailable = false,+ checking = false,+ failureWindow,+ onRetry,+ isBillingEnabled = true,+ alternative,onContinue,- isSwitching = false,+ isSwitching,}: Props) {const router = useRouter();- const resetTimeLabel = resetsAt ? formatResetTime(resetsAt) : null;- const isTopTier = !!tier && TOP_TIERS.has(tier);- const canContinue = alternative !== null && onContinue !== undefined;-- const ctaLabel = isTopTier ? "Contact us" : "Upgrade plan";- const bodyTrailer = isTopTier- ? "or contact us if you need more capacity."- : "or upgrade your plan.";-- function handleCtaClick() {- onClose();- if (isTopTier) {- window.open(CONTACT_US_URL, "_blank", "noopener,noreferrer");- return;+ const model =+ experience ??+ getUsageExperience({+ tier: tier ?? "BASIC",+ daily: {+ percent_used: 100,+ resets_at: resetsAt ? new Date(resetsAt).toISOString() : "",+ },+ });+ const copy = usagePresentation(model, offer?.usageMultiplier);+ const payment = formatPaymentDue(model.payment);+ const fallbackTitle =+ failureWindow === "trial"+ ? "You’ve used your trial allowance"+ : failureWindow === "weekly"+ ? "You’ve hit this week’s limit"+ : failureWindow === "daily"+ ? "You’ve hit today’s limit"+ : "We couldn’t check your usage.";+ function upgrade() {+ if (onUpgrade) onUpgrade();+ else {+ onClose();+ router.push("/settings/billing");}- router.push(BILLING_PATH);}-return (<Dialog- title="Daily usage limit reached"- styling={{ maxWidth: "28rem", minWidth: "auto" }}+ variant="compact"+ title={+ <div className="pr-6">+ <Text variant="small" className="mb-2 !text-xs !text-zinc-500">+ {checking+ ? "Checking your allowance"+ : unavailable+ ? "Usage temporarily unavailable"+ : copy.eyebrow}+ </Text>+ <Text as="span" variant="h3" className="!text-[26px] !leading-8">+ {checking+ ? "One moment. Your work is saved."+ : unavailable+ ? fallbackTitle+ : copy.title}+ </Text>+ </div>+ }+ styling={{ maxWidth: "35rem", minWidth: "auto" }}controlled={{isOpen,- set: async (open) => {+ set: (open) => {if (!open) onClose();},}}><Dialog.Content>- <Text variant="body">- You've reached your daily usage limit.- {resetTimeLabel && resetTimeLabel !== "now"- ? ` Resets ${resetTimeLabel}.`- : ""}{" "}- You can still browse, edit workflows, and view results —{" "}- {bodyTrailer}- </Text>- {canContinue && (- <Text variant="small" className="mt-3 !text-zinc-500">- Or continue on {alternative.display_name}: the rest of this chat- runs there instead, and everything already said stays as it is.- </Text>- )}- <Dialog.Footer className="!justify-center">- <Button variant="secondary" onClick={onClose}>- Wait for reset- </Button>- <Button- variant={canContinue ? "secondary" : "primary"}- onClick={handleCtaClick}+ {checking ? (+ <Text+ variant="body"+ role="status"+ className="!text-sm !text-zinc-500">- {ctaLabel}- </Button>- {canContinue && (- <Button- variant="primary"- onClick={onContinue}- loading={isSwitching}+ Refreshing your plan and usage…+ </Text>+ ) : unavailable ? (+ <div className="space-y-5">+ <Text variant="body" className="!text-sm !leading-6 !text-zinc-500">+ Your work is saved. Try again to check your allowance before+ continuing.+ </Text>+ <Button onClick={onRetry}>Try again</Button>+ </div>+ ) : (+ <>+ <Text+ variant="body"+ unmask={!payment}+ className="mb-5 !text-sm !leading-6 !text-zinc-500">- Continue on {alternative.display_name}- </Button>- )}- </Dialog.Footer>+ {copy.description}+ </Text>+ {copy.trialSpent && (+ <div className="mb-5">+ <UsageMeter+ label="Trial allowance"+ percent={model.trialPercent ?? 100}+ detail="One allowance for your trial. It doesn’t refresh."+ />+ </div>+ )}+ {isBillingEnabled && model.targetTier && (+ <PlanOffer+ tier={model.targetTier}+ {...offer}+ actionLabel={getUsageOfferAction(model, offer ?? {})}+ onUpgrade={upgrade}+ />+ )}+ {isBillingEnabled &&+ model.inactiveTrialStatus === "payment_failed" &&+ (payment ? (+ <PaymentDueAction+ url={payment.url}+ label={payment.actionLabel}+ />+ ) : (+ <Button className="w-full" onClick={upgrade}>+ Review billing details+ </Button>+ ))}+ {isBillingEnabled && model.isTopTier && (+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-zinc-200 p-4">+ <div>+ <Text variant="small-medium">Need more capacity?</Text>+ <Text variant="small" className="mt-1 !text-zinc-500">+ We’ll help find the right fit.+ </Text>+ </div>+ <Button+ as="NextLink"+ href="mailto:[email protected]"+ variant="secondary"+ size="small"+ >+ {copy.supportLabel}+ </Button>+ </div>+ )}+ </>+ )}+ {alternative && onContinue && (+ <ProviderContinuation+ name={alternative.display_name}+ onContinue={onContinue}+ isSwitching={isSwitching}+ />+ )}+ <Button variant="ghost" className="mt-3 w-full" onClick={onClose}>+ {checking || unavailable ? "Back to my work" : copy.secondary}+ </Button></Dialog.Content></Dialog>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsxindex 82115c024d..60c86660d9 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx@@ -1,420 +1,95 @@-import { cleanup, render } from "@/tests/integrations/test-utils";+import {+ cleanup,+ render,+ screen,+ fireEvent,+ act,+} from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {- const actual =- await importOriginal<- typeof import("@/components/molecules/Toast/use-toast")- >();- return {- ...actual,- toast: (...args: unknown[]) => mockToast(...args),- };-});--const mockUseGetV2GetCopilotUsage = vi.fn();-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useGetV2GetCopilotUsage: (...args: unknown[]) =>- mockUseGetV2GetCopilotUsage(...args),-}));--const mockUseGetSubscriptionStatus = vi.fn();-vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({- useGetSubscriptionStatus: (...args: unknown[]) =>- mockUseGetSubscriptionStatus(...args),+import { getUsageExperience } from "@/services/usageExperience/helpers";+const actions = vi.hoisted(() => ({ use: vi.fn() }));+const provider = vi.hoisted(() => ({ use: vi.fn() }));+vi.mock("@/services/usageExperience/useUsageActions", () => ({+ useUsageActions: actions.use,}));--// The switch-connection mechanics are borrowed from the provider-limit-// dialog's hook. Stubbed here so these tests stay about the gate: what it-// asks that hook for, and what it hands the dialog back.-const mockUseProviderLimitDialog = vi.fn();vi.mock("../../ProviderLimitDialog/useProviderLimitDialog", () => ({- useProviderLimitDialog: (...args: unknown[]) =>- mockUseProviderLimitDialog(...args),+ useProviderLimitDialog: provider.use,}));--// Capture props the dialog was rendered with so we can assert on them.-const dialogSpy = vi.fn();-vi.mock("../RateLimitResetDialog", () => ({- RateLimitResetDialog: (props: {- isOpen: boolean;- onClose: () => void;- resetsAt?: string | Date | null;- tier?: string | null;- alternative?: { display_name: string } | null;- onContinue?: () => void;- isSwitching?: boolean;- }) => {- dialogSpy(props);- return <div data-testid="reset-dialog" data-open={String(props.isOpen)} />;- },-}));-import { RateLimitGate } from "../RateLimitGate";--function noAlternative() {- mockUseProviderLimitDialog.mockReturnValue({- alternative: null,- continueHere: vi.fn(),+const retry = vi.fn();+const upgrade = vi.fn();+const continueHere = vi.fn();+beforeEach(() => {+ actions.use.mockReturnValue({+ experience: getUsageExperience({+ tier: "PRO",+ daily: { percent_used: 100, resets_at: "2099-10-07T00:00:00Z" },+ }),+ isLoading: false,+ isError: false,+ retry,+ upgrade,+ isBillingEnabled: true,+ offer: { tier: "MAX" },+ });+ provider.use.mockReturnValue({+ alternative: { display_name: "ChatGPT" },+ continueHere,isSwitching: false,- isLoadingOffers: false,- failedToLoadOffers: false,- retryOffers: vi.fn(),- resetHint: null,});-}--beforeEach(() => {- noAlternative();});-afterEach(() => {cleanup();- mockToast.mockReset();- mockUseGetV2GetCopilotUsage.mockReset();- mockUseGetSubscriptionStatus.mockReset();- mockUseProviderLimitDialog.mockReset();- dialogSpy.mockReset();+ vi.clearAllMocks();});--function setSubscription(tier: string | null = null) {- mockUseGetSubscriptionStatus.mockReturnValue({- data: tier,- isSuccess: tier !== null,- isError: false,- });-}-describe("RateLimitGate", () => {- it("disables the usage query when no rate-limit message is present", () => {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: false,- });- setSubscription();-- render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);-- expect(mockUseGetV2GetCopilotUsage).toHaveBeenCalled();- const [config] = mockUseGetV2GetCopilotUsage.mock.calls[0] as [- { query?: { enabled?: boolean } },- ];- expect(config?.query?.enabled).toBe(false);- });-- it("enables the usage query once a rate-limit message arrives", () => {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: false,- });- setSubscription();-+ it("opens on a backend refusal and preserves the linked-provider action", () => {render(<RateLimitGate- rateLimitMessage="You've hit your usage limit"+ rateLimitMessage="limit"onDismiss={vi.fn()}+ sessionId="chat"/>,);-- const [config] = mockUseGetV2GetCopilotUsage.mock.calls[0] as [- { query?: { enabled?: boolean } },- ];- expect(config?.query?.enabled).toBe(true);- });-- it("disables the subscription query when no rate-limit message is present", () => {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: false,- });- setSubscription();-- render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);-- expect(mockUseGetSubscriptionStatus).toHaveBeenCalled();- const [config] = mockUseGetSubscriptionStatus.mock.calls[0] as [- { query?: { enabled?: boolean } },- ];- expect(config?.query?.enabled).toBe(false);- });-- it("opens the reset dialog when usage data is available", () => {- const future = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { daily: { percent_used: 100, resets_at: future }, weekly: null },- isSuccess: true,- isError: false,- });- setSubscription("PRO");-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,- );-- expect(dialogSpy).toHaveBeenCalled();- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(true);- expect(mockToast).not.toHaveBeenCalled();- });-- it("forwards the user's subscription tier to the dialog", () => {- const future = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { daily: { percent_used: 100, resets_at: future }, weekly: null },- isSuccess: true,- isError: false,- });- setSubscription("MAX");-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,- );-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.tier).toBe("MAX");- });-- it("passes null tier when subscription status is unavailable", () => {- const future = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { daily: { percent_used: 100, resets_at: future }, weekly: null },- isSuccess: true,- isError: false,- });- setSubscription(null);-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,- );-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.tier).toBeNull();- });-- it("falls back to a toast when usage query errors", () => {- const onDismiss = vi.fn();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: true,- });- setSubscription();-- render(- <RateLimitGate- rateLimitMessage="You've hit your usage limit"- onDismiss={onDismiss}- />,- );-- expect(mockToast).toHaveBeenCalledTimes(1);- const toastArg = mockToast.mock.calls[0][0] as {- title: string;- variant: string;- };- expect(toastArg.title).toBe("Usage limit reached");- expect(toastArg.variant).toBe("destructive");- expect(onDismiss).toHaveBeenCalledTimes(1);-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(false);- });-- it("does not fire the fallback toast when no rate-limit message is present", () => {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: true,- });- setSubscription();-- render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);-- expect(mockToast).not.toHaveBeenCalled();- });-- it("keeps the dialog closed while the usage query is still loading", () => {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: false,- });- setSubscription();-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,+ fireEvent.click(+ screen.getByRole("button", { name: "Continue on ChatGPT" }),);-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(false);- expect(mockToast).not.toHaveBeenCalled();- });-- it("forwards daily resets_at timestamp to the dialog", () => {- const future = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { daily: { percent_used: 100, resets_at: future }, weekly: null },- isSuccess: true,- isError: false,- });- setSubscription();-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,+ expect(continueHere).toHaveBeenCalledOnce();+ });+ it("shows a retry state instead of dismissing the refusal on usage API failure", async () => {+ actions.use.mockReturnValue({ ...actions.use(), isError: true });+ const dismiss = vi.fn();+ render(<RateLimitGate rateLimitMessage="limit" onDismiss={dismiss} />);+ fireEvent.click(await screen.findByRole("button", { name: "Try again" }));+ expect(retry.mock.calls.length).toBeGreaterThanOrEqual(2);+ expect(dismiss).not.toHaveBeenCalled();+ });+ it("refreshes a just-refused turn before trusting cached usage", async () => {+ let resolve: (() => void) | undefined;+ retry.mockReturnValueOnce(+ new Promise<void>((done) => {+ resolve = done;+ }),);-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.resetsAt).toBe(future);- });-- it("falls back to weekly resets_at when daily is missing", () => {- const weeklyFuture = new Date(- Date.now() + 3 * 24 * 60 * 60 * 1000,- ).toISOString();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: {- daily: null,- weekly: { percent_used: 100, resets_at: weeklyFuture },- },- isSuccess: true,- isError: false,- });- setSubscription();-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,- );-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(true);- expect(lastProps.resetsAt).toBe(weeklyFuture);- });-- it("passes null resetsAt when neither daily nor weekly data exists", () => {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { daily: null, weekly: null },- isSuccess: true,- isError: false,- });- setSubscription();-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,- );-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(true);- expect(lastProps.resetsAt).toBeNull();- });-- it("prefers daily resets_at over weekly when both are present", () => {- const dailyFuture = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();- const weeklyFuture = new Date(- Date.now() + 3 * 24 * 60 * 60 * 1000,- ).toISOString();- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: {- daily: { percent_used: 100, resets_at: dailyFuture },- weekly: { percent_used: 80, resets_at: weeklyFuture },- },- isSuccess: true,- isError: false,- });- setSubscription();-- render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,- );-- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.resetsAt).toBe(dailyFuture);- });-});--describe("RateLimitGate — continuing on a linked subscription", () => {- const capFailure = {- kind: "usage_limit" as const,- message: "You've reached your daily usage limit. Resets in 1h 0m.",- authProvider: "platform",- credentialId: null,- resetsAt: null,- retryable: false,- reconnectFixesIt: false,- };-- function usageLoaded() {- mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { daily: { percent_used: 100, resets_at: null }, weekly: null },- isSuccess: true,- isError: false,- });- setSubscription("MAX");- }-- it("asks for an alternative only when the cap came with an envelope", () => {- usageLoaded();-+ const onRefreshingChange = vi.fn();render(<RateLimitGate- rateLimitMessage="limit reached"- sessionId="sess-1"+ rateLimitMessage="Weekly limit reached"onDismiss={vi.fn()}+ onRefreshingChange={onRefreshingChange}/>,);-- // A bare-string 429 -- an older backend, or a 429 that is not the usage- // cap -- has no envelope to name the failed connection with, so there is- // nothing to exclude and nothing to offer. The hook is told so.- expect(mockUseProviderLimitDialog).toHaveBeenCalledWith(- expect.objectContaining({ failure: null, sessionId: "sess-1" }),- );- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.alternative).toBeNull();- });-- it("hands the envelope to the switch hook and the offer to the dialog", () => {- usageLoaded();- const continueHere = vi.fn();- mockUseProviderLimitDialog.mockReturnValue({- alternative: {- display_name: "ChatGPT",- auth_provider: "codex",- credential_id: "cred-1",- },- continueHere,- isSwitching: true,- isLoadingOffers: false,- failedToLoadOffers: false,- retryOffers: vi.fn(),- resetHint: null,- });- const onDismiss = vi.fn();-- render(- <RateLimitGate- rateLimitMessage={capFailure.message}- failure={capFailure}- sessionId="sess-1"- onDismiss={onDismiss}- />,- );-- expect(mockUseProviderLimitDialog).toHaveBeenCalledWith({- failure: capFailure,- sessionId: "sess-1",- onDismiss,- });- const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(true);- expect(lastProps.alternative?.display_name).toBe("ChatGPT");- expect(lastProps.onContinue).toBe(continueHere);- expect(lastProps.isSwitching).toBe(true);- // The upgrade path is untouched by the offer: the tier still reaches the- // dialog so it can keep its Upgrade / Contact us CTA beside the switch.- expect(lastProps.tier).toBe("MAX");+ expect(screen.getByText("Refreshing your plan and usage…")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Upgrade to Max" })).toBeNull();+ expect(onRefreshingChange).toHaveBeenCalledWith(true);+ await act(async () => resolve?.());+ expect(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ ).toBeDefined();+ expect(onRefreshingChange).toHaveBeenLastCalledWith(false);+ });+ it("does not show the dialog without a backend refusal", () => {+ render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);+ expect(screen.queryByRole("dialog")).toBeNull();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsxindex 9a58665ac6..439643ca90 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx@@ -4,216 +4,226 @@ import {screen,fireEvent,} from "@/tests/integrations/test-utils";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mockPush = vi.fn();-vi.mock("next/navigation", () => ({- useRouter: () => ({- push: mockPush,- replace: vi.fn(),- prefetch: vi.fn(),- back: vi.fn(),- forward: vi.fn(),- refresh: vi.fn(),- }),- usePathname: () => "/copilot",- useSearchParams: () => new URLSearchParams(),- useParams: () => ({}),-}));-+import { afterEach, describe, expect, it, vi } from "vitest";+import { getUsageExperience } from "@/services/usageExperience/helpers";import { RateLimitResetDialog } from "../RateLimitResetDialog";-const mockWindowOpen = vi.fn();--beforeEach(() => {- // jsdom's window.open returns null and pollutes the test output; spy and- // suppress so we can assert the URL the dialog tries to open.- vi.spyOn(window, "open").mockImplementation(- mockWindowOpen as unknown as typeof window.open,- );-});--afterEach(() => {- cleanup();- mockPush.mockReset();- mockWindowOpen.mockReset();- vi.restoreAllMocks();-});--describe("RateLimitResetDialog", () => {- it("renders the dialog title and body when open", () => {- render(- <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,+afterEach(cleanup);+const usage = {+ tier: "PRO",+ daily: { percent_used: 100, resets_at: "2099-10-07T00:00:00Z" },+ weekly: { percent_used: 100, resets_at: "2099-10-12T00:00:00Z" },+};++describe("Usage limit dialog", () => {+ it("offers fresh Pro usage for an exhausted lifetime trial without a reset countdown or Max", () => {+ const experience = getUsageExperience(+ { ...usage, tier: "TRIAL" },+ {+ active: true,+ converted: false,+ usage_policy: "lifetime",+ allowance_used_percent: 100,+ offer: { tier: "PRO" },+ ends_at: new Date(2026, 9, 12, 12),+ },);-- expect(screen.getByText("Daily usage limit reached")).toBeDefined();- expect(- screen.getByText(/You've reached your daily usage limit/),- ).toBeDefined();- });-- it("shows the reset time when resetsAt is provided", () => {- const future = new Date(Date.now() + 3 * 60 * 60 * 1000).toISOString();+ const onUpgrade = vi.fn();render(<RateLimitResetDialog- isOpen={true}+ isOpenonClose={vi.fn()}- resetsAt={future}+ experience={experience}+ offer={{ tier: "PRO", price: 5000, freshUsage: true }}+ onUpgrade={onUpgrade}/>,);-- expect(screen.getByText(/Resets in/)).toBeDefined();- });-- it("omits the reset time when resetsAt is null", () => {- render(- <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,- );-- const bodyText = screen.getByText(/You've reached your daily usage limit/);- expect(bodyText.textContent).not.toContain("Resets in");- });-- it("renders Wait for reset and Upgrade plan buttons by default", () => {- render(- <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,- );-- expect(screen.getByText("Wait for reset")).toBeDefined();- expect(screen.getByText("Upgrade plan")).toBeDefined();- expect(screen.queryByText("Contact us")).toBeNull();- });-- it("calls onClose when Wait for reset is clicked", () => {- const onClose = vi.fn();- render(- <RateLimitResetDialog isOpen={true} onClose={onClose} resetsAt={null} />,+ expect(screen.getByText("You’ve used your trial allowance")).toBeDefined();+ expect(+ screen.getByText("One allowance for your trial. It doesn’t refresh."),+ ).toBeDefined();+ expect(screen.queryByText(/Wait for reset|Max/)).toBeNull();+ for (const amount of screen.getAllByText(/\$50/)) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ const wait = screen.getByRole("button", { name: "Wait until Oct 12" });+ expect(wait).toBeDefined();+ fireEvent.click(+ screen.getByRole("button", { name: "Start Pro now · $50" }),);-- fireEvent.click(screen.getByText("Wait for reset"));- expect(onClose).toHaveBeenCalledTimes(1);+ expect(onUpgrade).toHaveBeenCalledOnce();});-- it("navigates to /settings/billing when Upgrade plan is clicked (no tier)", () => {- const onClose = vi.fn();+ it("uses the later weekly reset when both paid limits are reached", () => {render(- <RateLimitResetDialog isOpen={true} onClose={onClose} resetsAt={null} />,+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience(usage)}+ />,);-- fireEvent.click(screen.getByText("Upgrade plan"));- expect(onClose).toHaveBeenCalledTimes(1);- expect(mockPush).toHaveBeenCalledWith("/settings/billing");- expect(mockWindowOpen).not.toHaveBeenCalled();+ expect(screen.getByText("Pro · weekly usage reached")).toBeDefined();+ expect(screen.getAllByText(/Oct 12/)[0]).toBeDefined();+ expect(screen.queryByText(/Oct 7,/)).toBeNull();+ expect(+ screen.getByRole("button", { name: "Upgrade to Max" }),+ ).toBeDefined();});-- it.each(["NO_TIER", "BASIC", "PRO"] as const)(- "shows Upgrade plan and routes to /settings/billing for tier=%s",- (tier) => {- const onClose = vi.fn();- render(- <RateLimitResetDialog- isOpen={true}- onClose={onClose}- resetsAt={null}- tier={tier}- />,- );-- expect(screen.getByText("Upgrade plan")).toBeDefined();- fireEvent.click(screen.getByText("Upgrade plan"));- expect(onClose).toHaveBeenCalledTimes(1);- expect(mockPush).toHaveBeenCalledWith("/settings/billing");- expect(mockWindowOpen).not.toHaveBeenCalled();- },- );-it.each(["MAX", "BUSINESS", "ENTERPRISE"] as const)(- "shows Contact us and opens mailto for top-tier plan=%s",+ "offers support instead of a self-service upgrade for %s",(tier) => {- const onClose = vi.fn();render(<RateLimitResetDialog- isOpen={true}- onClose={onClose}- resetsAt={null}- tier={tier}+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience({ ...usage, tier })}/>,);-- expect(screen.getByText("Contact us")).toBeDefined();- expect(screen.queryByText("Upgrade plan")).toBeNull();-- fireEvent.click(screen.getByText("Contact us"));- expect(onClose).toHaveBeenCalledTimes(1);- expect(mockWindowOpen).toHaveBeenCalledWith(- "mailto:[email protected]",- "_blank",- "noopener,noreferrer",- );- expect(mockPush).not.toHaveBeenCalled();+ expect(screen.queryByRole("button", { name: /upgrade/i })).toBeNull();+ expect(+ screen.getByRole("link", { name: /Contact/ }).getAttribute("href"),+ ).toBe("mailto:[email protected]");},);-- it("does not render dialog content when closed", () => {+ it("keeps linked-provider continuation actionable without discarding the blocked draft", () => {+ const onContinue = vi.fn();+ const onClose = vi.fn();render(- <RateLimitResetDialog isOpen={false} onClose={vi.fn()} resetsAt={null} />,+ <RateLimitResetDialog+ isOpen+ onClose={onClose}+ experience={getUsageExperience(usage)}+ alternative={{ display_name: "ChatGPT" }}+ onContinue={onContinue}+ />,);-- expect(screen.queryByText("Daily usage limit reached")).toBeNull();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue on ChatGPT" }),+ );+ expect(onContinue).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();+ expect(+ screen.getByRole("button", { name: "Upgrade to Max" }),+ ).toBeDefined();});-- it("offers nothing to continue on by default", () => {+ it("does not invent an allowance when loading usage fails", () => {+ const retry = vi.fn();render(- <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ unavailable+ onRetry={retry}+ />,);-- expect(screen.queryByText(/Continue on/)).toBeNull();- expect(screen.queryByText(/Or continue on/)).toBeNull();+ expect(screen.queryByRole("progressbar")).toBeNull();+ expect(screen.queryByText(/Upgrade to Pro/)).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));+ expect(retry).toHaveBeenCalledOnce();});-- it("offers a linked subscription beside the upgrade, never instead of it", () => {- const onClose = vi.fn();- const onContinue = vi.fn();+ it("hides billing actions when platform payments are disabled", () => {render(<RateLimitResetDialog- isOpen={true}- onClose={onClose}- resetsAt={null}- tier="MAX"- alternative={{ display_name: "ChatGPT" }}- onContinue={onContinue}+ isOpen+ onClose={vi.fn()}+ isBillingEnabled={false}+ experience={getUsageExperience(usage)}/>,);-- // The cap is still ours, so every answer it always had is still here.- expect(screen.getByText("Wait for reset")).toBeDefined();- expect(screen.getByText("Contact us")).toBeDefined();- expect(screen.getByText(/Or continue on ChatGPT/)).toBeDefined();-- fireEvent.click(screen.getByText("Continue on ChatGPT"));- expect(onContinue).toHaveBeenCalledTimes(1);- // Closing is the switch's job once it lands, not the click's: the- // composer still holds the refused message for the user to resend.- expect(onClose).not.toHaveBeenCalled();- expect(mockPush).not.toHaveBeenCalled();- expect(mockWindowOpen).not.toHaveBeenCalled();+ expect(screen.queryByRole("button", { name: /upgrade/i })).toBeNull();+ expect(+ screen.getByRole("button", { name: "Wait for reset" }),+ ).toBeDefined();});- it("keeps the upgrade path working with a switch on offer", () => {- const onClose = vi.fn();+ it("names the reset time once instead of repeating it in a box", () => {render(<RateLimitResetDialog- isOpen={true}- onClose={onClose}- resetsAt={null}- tier="PRO"- alternative={{ display_name: "ChatGPT" }}- onContinue={vi.fn()}+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience({ ...usage, tier: "MAX" })}/>,);+ expect(screen.getByText(/^You can continue /)).toBeDefined();+ expect(screen.queryByText("You can continue after")).toBeNull();+ });- fireEvent.click(screen.getByText("Upgrade plan"));- expect(onClose).toHaveBeenCalledTimes(1);- expect(mockPush).toHaveBeenCalledWith("/settings/billing");+ it("pays the open trial invoice straight from the dialog", () => {+ const onUpgrade = vi.fn();+ render(+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ experience={getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ {+ active: false,+ converted: false,+ status: "past_due",+ offer: { tier: "PRO" },+ ends_at: new Date(2026, 9, 12, 12),+ payment_due: {+ amount_due: 5000,+ currency: "usd",+ payment_url: "https://invoice.stripe.com/i/acct_1/test_inv_1",+ },+ },+ )}+ onUpgrade={onUpgrade}+ />,+ );+ expect(+ screen.getByText(+ "Pro was due to start on Oct 12, but the $50 charge didn’t go through. Pay now and Pro starts right away. Your chats, agents and results are saved.",+ ),+ ).toBeDefined();+ for (const amount of screen.getAllByText(/\$50/)) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ const pay = screen.getByRole("link", { name: "Pay $50 now" });+ expect(pay.getAttribute("href")).toBe(+ "https://invoice.stripe.com/i/acct_1/test_inv_1",+ );+ expect(pay.getAttribute("target")).toBe("_blank");+ expect(+ screen.queryByRole("button", { name: "Review billing details" }),+ ).toBeNull();+ expect(onUpgrade).not.toHaveBeenCalled();});++ it.each([true, false])(+ "provides failed-payment recovery only when billing is enabled (%s)",+ (isBillingEnabled) => {+ const onUpgrade = vi.fn();+ render(+ <RateLimitResetDialog+ isOpen+ onClose={vi.fn()}+ isBillingEnabled={isBillingEnabled}+ experience={getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ { active: false, converted: false, status: "past_due" },+ )}+ onUpgrade={onUpgrade}+ />,+ );+ expect(screen.getByText("Your payment didn’t go through")).toBeDefined();+ const recovery = screen.queryByRole("button", {+ name: "Review billing details",+ });+ if (isBillingEnabled) {+ expect(recovery).not.toBeNull();+ fireEvent.click(recovery!);+ expect(onUpgrade).toHaveBeenCalledOnce();+ } else {+ expect(recovery).toBeNull();+ expect(onUpgrade).not.toHaveBeenCalled();+ }+ expect(+ screen.queryByRole("button", { name: /^(Start|Upgrade to)/ }),+ ).toBeNull();+ expect(+ screen.getByRole("button", { name: "Back to my work" }),+ ).toBeDefined();+ },+ );});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/useRateLimitRefresh.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/useRateLimitRefresh.test.tsxnew file mode 100644index 0000000000..9c031b9b65--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/useRateLimitRefresh.test.tsx@@ -0,0 +1,69 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useRateLimitRefresh } from "../useRateLimitRefresh";++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("usage refresh recovery", () => {+ it("bounds an offline refresh, preserves the refusal, and recovers by retry", async () => {+ vi.useFakeTimers();+ let finishStaleRequest: (() => void) | undefined;+ const retry = vi.fn().mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finishStaleRequest = resolve;+ }),+ );+ const { result, rerender } = renderHook(+ ({ message }) => useRateLimitRefresh(message, retry),+ { initialProps: { message: "Weekly limit reached" as string | null } },+ );+ expect(result.current.checking).toBe(true);+ expect(retry).toHaveBeenCalledWith(true);+ await act(() => vi.advanceTimersByTimeAsync(25_000));+ expect(result.current.checking).toBe(false);+ expect(result.current.failed).toBe(true);+ expect(result.current.guarded).toBe(true);++ rerender({ message: null });+ expect(result.current.guarded).toBe(true);+ await act(async () => finishStaleRequest?.());+ expect(result.current.failed).toBe(true);+ expect(result.current.guarded).toBe(true);+ retry.mockResolvedValueOnce(undefined);+ await act(() => result.current.refresh());+ expect(result.current.failed).toBe(false);+ expect(result.current.guarded).toBe(false);+ });++ it("releases the guard after an explicit provider switch and ignores old completion", async () => {+ vi.useFakeTimers();+ let finishRequest: (() => void) | undefined;+ const retry = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishRequest = resolve;+ }),+ );+ const { result } = renderHook(() =>+ useRateLimitRefresh("Daily limit reached", retry),+ );+ act(() => result.current.release());+ expect(result.current.guarded).toBe(false);+ await act(async () => finishRequest?.());+ expect(result.current.guarded).toBe(false);+ expect(result.current.failed).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("cleans up a pending deadline on unmount", () => {+ vi.useFakeTimers();+ const { unmount } = renderHook(() =>+ useRateLimitRefresh("Daily limit reached", () => new Promise(() => {})),+ );+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/useRateLimitRefresh.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/useRateLimitRefresh.tsnew file mode 100644index 0000000000..24eae973ce--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/useRateLimitRefresh.ts@@ -0,0 +1,87 @@+import { useEffect, useRef, useState } from "react";++function boundedRefresh(retry: (throwOnError?: boolean) => Promise<unknown>) {+ let cancel = () => {};+ const deadline = new Promise<never>((_, reject) => {+ cancel = () => reject(new Error("Usage refresh did not finish"));+ });+ const timeout = setTimeout(cancel, 25_000);+ return {+ cancel() {+ clearTimeout(timeout);+ cancel();+ },+ result: Promise.race([+ new Promise((resolve) => resolve(retry(true))),+ deadline,+ ]).finally(() => clearTimeout(timeout)),+ };+}++export function useRateLimitRefresh(+ message: string | null,+ retry: (throwOnError?: boolean) => Promise<unknown>,+ onRefreshingChange?: (refreshing: boolean) => void,+) {+ const latest = useRef({ retry, onRefreshingChange });+ latest.current = { retry, onRefreshingChange };+ const requestID = useRef(0);+ const pending = useRef<ReturnType<typeof boundedRefresh> | null>(null);+ const [checkedMessage, setCheckedMessage] = useState<string | null>(null);+ const [checking, setChecking] = useState(false);+ const [failed, setFailed] = useState(false);+ const [guarded, setGuarded] = useState(false);+ async function refresh() {+ const id = ++requestID.current;+ pending.current?.cancel();+ const request = boundedRefresh(latest.current.retry);+ pending.current = request;+ setChecking(true);+ setFailed(false);+ setGuarded(true);+ latest.current.onRefreshingChange?.(true);+ try {+ await request.result;+ if (requestID.current === id) setGuarded(false);+ } catch {+ if (requestID.current === id) setFailed(true);+ } finally {+ if (requestID.current === id) {+ pending.current = null;+ setChecking(false);+ setCheckedMessage(message);+ latest.current.onRefreshingChange?.(false);+ }+ }+ }+ function release() {+ requestID.current += 1;+ pending.current?.cancel();+ pending.current = null;+ setGuarded(false);+ setChecking(false);+ setFailed(false);+ setCheckedMessage(message);+ latest.current.onRefreshingChange?.(false);+ }+ const refreshRef = useRef(refresh);+ refreshRef.current = refresh;+ useEffect(() => {+ if (message) void refreshRef.current();+ else setCheckedMessage(null);+ }, [message]);+ useEffect(+ () => () => {+ requestID.current += 1;+ pending.current?.cancel();+ },+ [],+ );+ return {+ checking: checking || (!!message && checkedMessage !== message),+ failed,+ guarded,+ refresh,+ release,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsxindex 5f0f2f011d..703903c7de 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard.tsx@@ -1,69 +1,131 @@"use client";-import { Badge } from "@/components/atoms/Badge/Badge";+import { ArrowRight02Icon } from "@hugeicons/core-free-icons";import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";-import {- formatTierLabel,- isUsageExhausted,- TIER_BADGE_CLASS_NAME,-} from "../../usageHelpers";-import { StorageBar } from "../StorageBar";-import { UsageBar } from "../UsageBar";+import { getUsageOfferAction } from "@/services/usageExperience/helpers";+import { formatPaymentDue } from "@/services/usageExperience/payment";+import { usagePresentation } from "@/services/usageExperience/presentation";+import { PaymentDueAction } from "@/components/organisms/UsageExperience/PaymentDueAction";+import { ProviderContinuation } from "@/components/organisms/UsageExperience/ProviderContinuation";+import type { UsageNoticeContext } from "./useUsageLimitReachedCard";import { useUsageLimitReachedCard } from "./useUsageLimitReachedCard";-import { Alert01Icon } from "@hugeicons/core-free-icons";-import { Icon } from "@/components/atoms/Icon/Icon";--export function UsageLimitReachedCard() {- const { usage, isSuccess, isBillingEnabled } = useUsageLimitReachedCard();-- if (!isSuccess || !usage) return null;- if (!isUsageExhausted(usage)) return null;-- const tierLabel = formatTierLabel(usage.tier);+export function UsageLimitReachedCard(props: UsageNoticeContext = {}) {+ const state = useUsageLimitReachedCard(props);+ if (state.isLoading || (!state.experience.blocked && !state.isError))+ return null;+ const copy = usagePresentation(state.experience, state.offer.usageMultiplier);+ const isOffer =+ state.isBillingEnabled && state.experience.targetTier && !state.isError;+ const due = formatPaymentDue(state.experience.payment);+ const payment = state.isBillingEnabled && !state.isError ? due : null;return (- <div- role="alert"- className="mx-auto flex w-full max-w-[30rem] flex-col gap-4 rounded-2xl border border-orange-100 bg-white/70 p-4 shadow-[0_8px_32px_rgba(0,0,0,0.04)] backdrop-blur-md"+ <section+ role="status"+ aria-label="Usage notice"+ className="mx-auto w-full rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">- <div className="flex items-center gap-2">- <Icon icon={Alert01Icon} className="size-5 text-orange-500" />- <Text variant="body-medium" className="text-neutral-900">- Usage limit reached+ <div className="mb-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-1">+ <Text variant="small" className="!text-xs !text-zinc-500">+ {state.isRefreshing+ ? "Checking your allowance"+ : state.isError+ ? "Usage temporarily unavailable"+ : copy.eyebrow}</Text>- {tierLabel && (- <Badge variant="info" size="small" className={TIER_BADGE_CLASS_NAME}>- {tierLabel} plan- </Badge>+ {!state.isError && (+ <Button+ as="NextLink"+ href="/settings/billing"+ size="small"+ variant="ghost"+ className="!h-auto !p-0 !text-xs !text-zinc-500"+ >+ {state.experience.inactiveTrialStatus === "payment_failed"+ ? "Review billing"+ : "View usage"}+ </Button>)}</div>- {usage.daily && (- <UsageBar- label="Today"- percentUsed={usage.daily.percent_used}- resetsAt={usage.daily.resets_at}- />+ <Text variant="h4" className="!text-lg !leading-6">+ {state.isRefreshing+ ? "Checking your usage"+ : state.isError+ ? "We couldn’t check your usage."+ : copy.noticeTitle}+ </Text>+ <Text+ variant="small"+ unmask={!due}+ className="mt-2 !leading-5 !text-zinc-500"+ >+ {state.isRefreshing+ ? "Refreshing your plan and usage…"+ : state.isError+ ? "Your work is saved. Try again to check your allowance."+ : copy.description}+ </Text>+ {isOffer && (+ <div className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-2">+ <Button+ size="small"+ onClick={state.upgrade}+ disabled={state.offer.disabled}+ unmask={!state.experience.freshProUsage}+ rightIcon={<Icon icon={ArrowRight02Icon} size={14} />}+ >+ {getUsageOfferAction(state.experience, state.offer)}+ </Button>+ {state.experience.freshProUsage && (+ <Text variant="small" className="!text-xs !text-zinc-500">+ + tax. Review before you pay.+ </Text>+ )}+ </div>)}- {usage.weekly && (- <UsageBar- label="This week"- percentUsed={usage.weekly.percent_used}- resetsAt={usage.weekly.resets_at}- />+ {payment && (+ <div className="mt-4">+ <PaymentDueAction+ url={payment.url}+ label={payment.actionLabel}+ size="small"+ layout="inline"+ />+ </div>)}- <StorageBar />- {isBillingEnabled && (- <Button- as="NextLink"- href="/settings/billing"- variant="primary"- size="small"- className="mt-1 w-full"- >- Go to billing- </Button>+ {state.alternative && (+ <ProviderContinuation+ name={state.alternative.display_name}+ onContinue={state.continueHere}+ isSwitching={state.isSwitching}+ />)}- </div>+ <div className="mt-4 flex flex-wrap items-center justify-between gap-2">+ <Text variant="small" className="!text-xs !text-zinc-400">+ You can keep editing your draft.+ </Text>+ {state.isError ? (+ <Button+ size="small"+ variant="ghost"+ onClick={() => void state.retry()}+ disabled={state.isRefreshing}+ >+ {state.isRefreshing ? "Checking…" : "Try again"}+ </Button>+ ) : state.experience.isTopTier && state.isBillingEnabled ? (+ <Button+ as="NextLink"+ href="mailto:[email protected]"+ size="small"+ variant="ghost"+ >+ {copy.supportLabel}+ </Button>+ ) : null}+ </div>+ </section>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/__tests__/UsageLimitReachedCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/__tests__/UsageLimitReachedCard.test.tsxindex 0c853d7d39..9393bd0e8c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/__tests__/UsageLimitReachedCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/__tests__/UsageLimitReachedCard.test.tsx@@ -1,114 +1,234 @@-import { http, HttpResponse, type JsonBodyType } from "msw";+import { http, HttpResponse } from "msw";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { server } from "@/mocks/mock-server";-import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import {+ cleanup,+ render,+ screen,+ fireEvent,+ waitFor,+} from "@/tests/integrations/test-utils";import { UsageLimitReachedCard } from "../UsageLimitReachedCard";--const mockUseGetFlag = vi.fn();-vi.mock("@/services/feature-flags/use-get-flag", async () => {- const actual = await vi.importActual<+import {+ setTrialUser,+ trialOffer,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+const provider = vi.hoisted(() => ({ use: vi.fn(), continueHere: vi.fn() }));+vi.mock("../../../ProviderLimitDialog/useProviderLimitDialog", () => ({+ useProviderLimitDialog: provider.use,+}));+beforeEach(() =>+ provider.use.mockReturnValue({+ alternative: null,+ continueHere: provider.continueHere,+ isSwitching: false,+ }),+);+vi.mock("@/services/pro-activation/useProActivation", () => ({+ useProActivation: () => ({ start: vi.fn(), isBusy: false, isReady: false }),+}));+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/services/feature-flags/use-get-flag")- >("@/services/feature-flags/use-get-flag");- return {- ...actual,- useGetFlag: (flag: unknown) => mockUseGetFlag(flag),- };-});--vi.mock("../../StorageBar", () => ({- StorageBar: () => null,+ >()),+ useGetFlag: () => true,}));-afterEach(() => {- mockUseGetFlag.mockReset();-});--beforeEach(() => {- mockUseGetFlag.mockReturnValue(true);+ cleanup();+ setTrialUser(null);});--interface UsageOverrides {- dailyPercent?: number | null;- weeklyPercent?: number | null;- tier?: string | null;+function setup(tier = "PRO", daily = 100, weekly = 40) {+ server.use(+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({+ tier,+ daily: { percent_used: daily, resets_at: "2099-10-07T00:00:00Z" },+ weekly: { percent_used: weekly, resets_at: "2099-10-12T00:00:00Z" },+ }),+ ),+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({+ tier,+ tier_costs: { PRO: 5000, MAX: 32000 },+ monthly_cost: 5000,+ proration_credit_cents: 0,+ }),+ ),+ );}--function makeUsage({- dailyPercent = 100,- weeklyPercent = 40,- tier = "BASIC",-}: UsageOverrides = {}) {- const future = new Date(Date.now() + 3600 * 1000).toISOString();- return {- daily:- dailyPercent === null- ? null- : { percent_used: dailyPercent, resets_at: future },- weekly:- weeklyPercent === null- ? null- : { percent_used: weeklyPercent, resets_at: future },- tier,- };-}--function mockUsageResponse(body: JsonBodyType) {- server.use(http.get("*/api/chat/usage", () => HttpResponse.json(body)));-}--describe("UsageLimitReachedCard", () => {- it("renders nothing on the first paint while data is loading", () => {- mockUsageResponse(makeUsage());- const { container } = render(<UsageLimitReachedCard />);- expect(container.innerHTML).toBe("");+describe("Usage notice", () => {+ it("shows the accepted trial price and its automatic Pro start date", async () => {+ setTrialUser();+ setup("TRIAL");+ server.use(+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(+ trialResponse({+ allowance_used_percent: 100,+ usage_policy: "lifetime",+ ends_at: new Date(2026, 9, 12, 12),+ offer: { ...trialOffer, unit_amount: 5013 },+ }),+ ),+ ),+ );+ render(<UsageLimitReachedCard />);+ expect(+ await screen.findByRole("button", { name: "Start Pro now · $50.13" }),+ ).toBeDefined();+ expect(+ screen+ .getByRole("button", { name: "Start Pro now · $50.13" })+ .closest(".sentry-unmask, [data-sentry-unmask]"),+ ).toBeNull();+ expect(screen.getByText("You’ve used your trial allowance")).toBeDefined();+ expect(+ screen.getByText(+ "Pro starts on its own on Oct 12. Start it now to keep working today.",+ ),+ ).toBeDefined();+ expect(screen.getByRole("link", { name: "View usage" })).toBeDefined();});-- it("renders nothing when neither daily nor weekly is exhausted", async () => {- mockUsageResponse(makeUsage({ dailyPercent: 5, weeklyPercent: 4 }));- const { container } = render(<UsageLimitReachedCard />);- await waitFor(() => expect(container.innerHTML).toBe(""));+ it("continues on a linked provider only after an explicit click", async () => {+ setup();+ provider.use.mockReturnValue({+ alternative: { display_name: "ChatGPT" },+ continueHere: provider.continueHere,+ isSwitching: false,+ });+ render(<UsageLimitReachedCard sessionID="chat" />);+ const action = await screen.findByRole("button", {+ name: "Continue on ChatGPT",+ });+ expect(provider.continueHere).not.toHaveBeenCalled();+ fireEvent.click(action);+ expect(provider.continueHere).toHaveBeenCalledOnce();});-- it("renders the alert with daily and weekly bars when the daily limit is reached", async () => {- mockUsageResponse(makeUsage());+ it("prioritizes the blocking window and preserves draft editing", async () => {+ setup("PRO", 100, 100);render(<UsageLimitReachedCard />);-- expect(await screen.findByRole("alert")).toBeDefined();- expect(screen.getByText("Usage limit reached")).toBeDefined();- expect(screen.getByText("Today")).toBeDefined();- expect(screen.getByText("This week")).toBeDefined();+ expect(+ await screen.findByText("You’ve hit this week’s limit"),+ ).toBeDefined();+ expect(screen.getByText(/Oct 12/)).toBeDefined();+ expect(screen.getByText("You can keep editing your draft.")).toBeDefined();+ expect(+ screen.getByRole("button", { name: "Upgrade to Max" }),+ ).toBeDefined();});-- it("always shows the 'Go to billing' button when billing is enabled", async () => {- mockUsageResponse(makeUsage());+ it("does not promote an unavailable self-service tier to Enterprise", async () => {+ setup("ENTERPRISE");render(<UsageLimitReachedCard />);-- const link = (await screen.findByText("Go to billing")).closest("a");- expect(link).not.toBeNull();- expect(link?.getAttribute("href")).toBe("/settings/billing");+ expect(+ await screen.findByRole("link", { name: "Contact your account team" }),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: /upgrade/i })).toBeNull();+ });+ it("hides the limit notice while allowance remains", async () => {+ setup("PRO", 10, 20);+ const { container } = render(<UsageLimitReachedCard />);+ await waitFor(() => expect(container.innerHTML).toBe(""));+ });+ it("offers the bounded refusal retry even when cached usage is below the cap", async () => {+ setup("PRO", 10, 20);+ const refresh = vi.fn().mockResolvedValue(undefined);+ const { rerender } = render(+ <UsageLimitReachedCard+ refresh={{ checking: false, failed: true, refresh }}+ />,+ );+ fireEvent.click(await screen.findByRole("button", { name: "Try again" }));+ expect(refresh).toHaveBeenCalledOnce();+ expect(screen.queryByRole("button", { name: /upgrade/i })).toBeNull();+ rerender(+ <UsageLimitReachedCard+ refresh={{ checking: true, failed: false, refresh }}+ />,+ );+ expect(screen.getByText("Refreshing your plan and usage…")).toBeDefined();+ expect(+ screen+ .getByRole("button", { name: "Checking…" })+ .hasAttribute("disabled"),+ ).toBe(true);+ rerender(+ <UsageLimitReachedCard+ refresh={{ checking: false, failed: false, refresh }}+ />,+ );+ await waitFor(() =>+ expect(screen.queryByRole("status", { name: "Usage notice" })).toBeNull(),+ );});-- it("hides the 'Go to billing' button when billing is disabled at the platform level", async () => {- mockUseGetFlag.mockReturnValue(false);- mockUsageResponse(makeUsage());+ it("lets a failed usage fetch be retried without showing invented remaining usage", async () => {+ setup();+ server.use(+ http.get(+ "*/api/chat/usage",+ () => new HttpResponse(null, { status: 503 }),+ ),+ );render(<UsageLimitReachedCard />);-- expect(await screen.findByRole("alert")).toBeDefined();- expect(screen.queryByText("Go to billing")).toBeNull();+ expect(+ await screen.findByText(+ "We couldn’t check your usage.",+ {},+ { timeout: 5000 },+ ),+ ).toBeDefined();+ setup();+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));+ expect(await screen.findByText("You’ve hit today’s limit")).toBeDefined();});-- it("renders the tier badge when a tier is set", async () => {- mockUsageResponse(makeUsage({ tier: "PRO" }));+ it("pays a failed first trial charge from the notice", async () => {+ setTrialUser();+ setup("NO_TIER");+ server.use(+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(+ trialResponse({+ active: false,+ status: "past_due",+ ends_at: new Date(2026, 9, 12, 12),+ payment_due: {+ amount_due: 5000,+ currency: "usd",+ payment_url: "https://invoice.stripe.com/i/acct_1/test_inv_1",+ },+ }),+ ),+ ),+ );render(<UsageLimitReachedCard />);-- expect(await screen.findByText("Pro plan")).toBeDefined();+ const pay = await screen.findByRole("link", { name: "Pay $50 now" });+ expect(pay.getAttribute("href")).toBe(+ "https://invoice.stripe.com/i/acct_1/test_inv_1",+ );+ expect(screen.getByText("Your payment didn’t go through")).toBeDefined();+ for (const amount of screen.getAllByText(/\$50/)) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ expect(screen.queryByRole("button", { name: /^Start/ })).toBeNull();});-- it("never renders the legacy 'Reset daily limit' control", async () => {- mockUsageResponse(makeUsage());+ it("asks a cancel-pending trial to subscribe instead of starting Pro", async () => {+ setTrialUser();+ setup("TRIAL");+ server.use(+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(+ trialResponse({+ allowance_used_percent: 100,+ usage_policy: "lifetime",+ cancel_at_period_end: true,+ }),+ ),+ ),+ );render(<UsageLimitReachedCard />);-- expect(await screen.findByRole("alert")).toBeDefined();- expect(screen.queryByText(/Reset daily limit/i)).toBeNull();+ expect(+ await screen.findByRole("button", { name: "Subscribe now" }),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: /^Start Pro/ })).toBeNull();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.tsindex d84222b086..6203dbd522 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard/useUsageLimitReachedCard.ts@@ -1,9 +1,50 @@-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";-import { useCopilotUsage } from "../useCopilotUsage";+import { useUsageActions } from "@/services/usageExperience/useUsageActions";+import type { ProviderFailure } from "../../../providerFailure";+import { useProviderLimitDialog } from "../../ProviderLimitDialog/useProviderLimitDialog";+import type { useRateLimitRefresh } from "../../RateLimitResetDialog/useRateLimitRefresh";-export function useUsageLimitReachedCard() {- const { data: usage, isSuccess } = useCopilotUsage();- const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);-- return { usage, isSuccess, isBillingEnabled };+export interface UsageNoticeContext {+ sessionID?: string | null;+ failure?: ProviderFailure | null;+ onDismiss?: () => void;+ refresh?: Pick<+ ReturnType<typeof useRateLimitRefresh>,+ "checking" | "failed" | "refresh"+ >;+}+const dismissNothing = () => undefined;+export function useUsageLimitReachedCard({+ sessionID = null,+ failure = null,+ onDismiss = dismissNothing,+ refresh,+}: UsageNoticeContext = {}) {+ const state = useUsageActions();+ const platformCap: ProviderFailure | null =+ sessionID && state.experience.blocked && !state.isError+ ? {+ kind: "usage_limit",+ message: "Usage limit reached",+ authProvider: "platform",+ credentialId: null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ }+ : null;+ const provider = useProviderLimitDialog({+ failure: failure ?? platformCap,+ sessionId: sessionID,+ onDismiss,+ });+ return {+ ...state,+ isLoading: state.isLoading && !refresh?.checking && !refresh?.failed,+ isError: state.isError || !!refresh?.failed || !!refresh?.checking,+ isRefreshing: !!refresh?.checking,+ retry: refresh?.refresh ?? state.retry,+ alternative: sessionID ? provider.alternative : null,+ continueHere: provider.continueHere,+ isSwitching: provider.isSwitching,+ };}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsxindex a8ea264d50..a389a0bd9a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/UsagePopover.tsx@@ -11,6 +11,8 @@ import {import Link from "next/link";import type { ReactNode } from "react";import { formatTierLabel, TIER_BADGE_CLASS_NAME } from "../../usageHelpers";+import { UsageMeter } from "@/components/organisms/UsageExperience/UsageMeter";+import { formatUsageDate } from "@/services/usageExperience/helpers";import { StorageBar } from "../StorageBar";import { UsageBar } from "../UsageBar";import { useUsagePopover } from "./useUsagePopover";@@ -23,12 +25,14 @@ interface Props {}export function UsagePopover({ trigger, align = "start" }: Props) {- const { usage, isSuccess, isBillingEnabled } = useUsagePopover();+ const { usage, experience, isLoading, isError, retry, isBillingEnabled } =+ useUsagePopover();- if (!isSuccess || !usage) return null;- if (!usage.daily && !usage.weekly) return null;+ if (isLoading) return null;+ if (!isError && !usage?.daily && !usage?.weekly && !experience.isActiveTrial)+ return null;- const tierLabel = formatTierLabel(usage.tier);+ const tierLabel = formatTierLabel(experience.tier);return (<Popover>@@ -54,18 +58,39 @@ export function UsagePopover({ trigger, align = "start" }: Props) {size="small"className={TIER_BADGE_CLASS_NAME}>- {tierLabel} plan+ {tierLabel}</Badge>)}</div>- {usage.daily && (+ {isError && (+ <div>+ <Text variant="small">We couldn’t check your usage.</Text>+ <Button size="small" variant="ghost" onClick={() => void retry()}>+ Try again+ </Button>+ </div>+ )}+ {!isError &&+ experience.isActiveTrial &&+ experience.trialPercent !== null && (+ <UsageMeter+ label="Trial allowance"+ percent={experience.trialPercent}+ detail={+ experience.trialEndsAt+ ? `Trial ends ${formatUsageDate(experience.trialEndsAt)}`+ : "Your allowance for this trial"+ }+ />+ )}+ {!isError && !experience.isLifetimeTrial && usage?.daily && (<UsageBarlabel="Today"percentUsed={usage.daily.percent_used}resetsAt={usage.daily.resets_at}/>)}- {usage.weekly && (+ {!isError && !experience.isLifetimeTrial && usage?.weekly && (<UsageBarlabel="This week"percentUsed={usage.weekly.percent_used}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/__tests__/UsagePopover.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/__tests__/UsagePopover.test.tsxindex 6e2e408727..3009e9dea4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/__tests__/UsagePopover.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/__tests__/UsagePopover.test.tsx@@ -66,7 +66,13 @@ function makeUsage({}function mockUsageResponse(body: JsonBodyType) {- server.use(http.get("*/api/chat/usage", () => HttpResponse.json(body)));+ server.use(+ http.get(+ "*/api/credits/subscription",+ () => new HttpResponse(null, { status: 503 }),+ ),+ http.get("*/api/chat/usage", () => HttpResponse.json(body)),+ );}describe("UsagePopover", () => {@@ -117,7 +123,7 @@ describe("UsagePopover", () => {mockUsageResponse(makeUsage({ tier: "PRO" }));render(<UsagePopover />);- expect(await screen.findByText("Pro plan")).toBeDefined();+ expect(await screen.findByText("Pro")).toBeDefined();});it("never renders the 'Go to billing' button (handled by the card)", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/useUsagePopover.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/useUsagePopover.tsindex d71107c226..5dc114c2a6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/useUsagePopover.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePopover/useUsagePopover.ts@@ -1,8 +1,4 @@-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";-import { useCopilotUsage } from "../useCopilotUsage";-+import { useUsageExperience } from "@/services/usageExperience/useUsageExperience";export function useUsagePopover() {- const { data: usage, isSuccess } = useCopilotUsage();- const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);- return { usage, isSuccess, isBillingEnabled };+ return useUsageExperience();}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsxnew file mode 100644index 0000000000..5b38ee5194--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/useIsUsageLimitReached.test.tsx@@ -0,0 +1,55 @@+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ usage: vi.fn(), session: vi.fn() }));+vi.mock("@/services/usageExperience/useUsageExperience", () => ({+ useUsageExperience: mocks.usage,+}));+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ useGetV2GetSession: mocks.session,+}));+import { useIsUsageLimitReached } from "../useIsUsageLimitReached";+beforeEach(() => {+ mocks.usage.mockReturnValue({+ experience: { blocked: true },+ isError: false,+ });+ mocks.session.mockReturnValue({+ data: {+ status: 200,+ data: { metadata: { llm_auth_provider: "platform" } },+ },+ });+});+describe("chat usage gating", () => {+ it("keeps platform-funded messages blocked after the allowance is exhausted", () => {+ expect(+ renderHook(() => useIsUsageLimitReached("chat")).result.current,+ ).toBe(true);+ });+ it("unblocks the same conversation only after a confirmed provider switch", () => {+ const { result, rerender } = renderHook(() =>+ useIsUsageLimitReached("chat"),+ );+ expect(result.current).toBe(true);+ mocks.session.mockReturnValue({+ data: { status: 200, data: { metadata: { llm_auth_provider: "codex" } } },+ });+ rerender();+ expect(result.current).toBe(false);+ });+ it("does not infer a provider exemption from missing session data", () => {+ mocks.session.mockReturnValue({ data: undefined });+ expect(+ renderHook(() => useIsUsageLimitReached("chat")).result.current,+ ).toBe(true);+ });+ it("pauses platform sending while usage is unavailable", () => {+ mocks.usage.mockReturnValue({+ experience: { blocked: false },+ isError: true,+ });+ expect(+ renderHook(() => useIsUsageLimitReached("chat")).result.current,+ ).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useCopilotUsage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useCopilotUsage.tsindex 6e1f1c2515..a2e32238a8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useCopilotUsage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useCopilotUsage.ts@@ -1,14 +1,12 @@import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";-import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";--const USAGE_QUERY_CONFIG = {- query: {- select: (res: { data: unknown }) => res.data as CoPilotUsagePublic,- refetchInterval: 30000,- staleTime: 10000,- },-} as const;export function useCopilotUsage() {- return useGetV2GetCopilotUsage(USAGE_QUERY_CONFIG);+ return useGetV2GetCopilotUsage({+ query: {+ select: (response) =>+ response.status === 200 ? response.data : undefined,+ refetchInterval: 30_000,+ staleTime: 10_000,+ },+ });}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.tsindex ca75331ea6..9007f93aeb 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached.ts@@ -1,7 +1,15 @@-import { isUsageExhausted } from "../usageHelpers";-import { useCopilotUsage } from "./useCopilotUsage";+import { useGetV2GetSession } from "@/app/api/__generated__/endpoints/chat/chat";+import { useUsageExperience } from "@/services/usageExperience/useUsageExperience";-export function useIsUsageLimitReached() {- const { data: usage } = useCopilotUsage();- return isUsageExhausted(usage);+export function useIsUsageLimitReached(sessionID?: string | null) {+ const state = useUsageExperience();+ const session = useGetV2GetSession(sessionID ?? "", undefined, {+ query: { enabled: !!sessionID },+ });+ const provider =+ session.data?.status === 200+ ? session.data.data.metadata?.llm_auth_provider+ : null;+ if (provider && provider !== "platform") return false;+ return state.experience.blocked || state.isError;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.tsindex f12c81dfa4..510e8c0168 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts@@ -37,6 +37,8 @@ export function formatTierLabel(tier: string | null | undefined,): string | null {if (!tier || tier === "NO_TIER") return null;+ if (tier === "BUSINESS") return "Team";+ if (tier === "TRIAL") return "Free trial";return tier.charAt(0).toUpperCase() + tier.slice(1).toLowerCase();}diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsxindex 336ad5d8ec..2d8a76a36e 100644--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx@@ -3,13 +3,18 @@ import { PushNotificationProvider } from "@/services/push-notifications/PushNotiimport { ReactNode } from "react";import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";import { PlatformChrome } from "./PlatformChrome/PlatformChrome";+import { ProActivationProvider } from "@/services/pro-activation/ProActivationProvider";+import { TrialStatusSync } from "@/services/trials/TrialStatusSync";export default function PlatformLayout({ children }: { children: ReactNode }) {return (<AutoPilotBridgeProvider><NetworkStatusMonitor /><PushNotificationProvider />- <PlatformChrome>{children}</PlatformChrome>+ <TrialStatusSync />+ <ProActivationProvider>+ <PlatformChrome>{children}</PlatformChrome>+ </ProActivationProvider></AutoPilotBridgeProvider>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsxindex 1662586cc0..e86b0b339e 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsx@@ -29,7 +29,9 @@ describe("Settings billing page", () => {it("renders title and billing tabs", () => {render(<SettingsBillingPage />);- expect(screen.getByRole("heading", { name: "Billing" })).toBeDefined();+ expect(+ screen.getByRole("heading", { name: "Billing & usage" }),+ ).toBeDefined();expect(screen.getByRole("tab", { name: "Subscription" })).toBeDefined();expect(screen.getByRole("tab", { name: "Automation Credits" }),diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsxindex 71e3c77028..867cf9003d 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx@@ -1,3 +1,4 @@+import { setTrialUser } from "@/tests/integrations/trial-fixtures";/*** Card-by-card integration tests for the Settings v2 billing page.*@@ -13,7 +14,7 @@import { fireEvent } from "@testing-library/react";import { http, HttpResponse, type JsonBodyType } from "msw";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { server } from "@/mocks/mock-server";import {@@ -32,6 +33,24 @@ import { InvoicesCard } from "../components/SubscriptionTab/InvoicesCard/Invoiceimport { PaymentMethodCard } from "../components/SubscriptionTab/PaymentMethodCard/PaymentMethodCard";import { YourPlanCard } from "../components/SubscriptionTab/YourPlanCard/YourPlanCard";+import { maxUpgradePreview } from "./max-upgrade.fixture";++afterEach(() => setTrialUser(null));++beforeEach(() => {+ setTrialUser("billing-user");+ server.use(+ http.post("*/api/credits/subscription/preview", async ({ request }) => {+ const body = (await request.json()) as {+ billing_cycle: "monthly" | "yearly";+ };+ return HttpResponse.json(+ maxUpgradePreview({ billing_cycle: body.billing_cycle }),+ );+ }),+ );+});+function jsonHandler(method: "get" | "post", path: string, body: JsonBodyType) {return http[method](`*${path}`, () => HttpResponse.json(body));}@@ -156,7 +175,7 @@ describe("YourPlanCard", () => {render(<YourPlanCard />);expect(await screen.findByText("No active subscription")).toBeDefined();- expect(screen.getByRole("button", { name: /get pro/i })).toBeDefined();+ expect(screen.getByRole("button", { name: /start pro/i })).toBeDefined();expect(screen.queryByRole("button", { name: /cancel plan/i })).toBeNull();expect(screen.queryByRole("button", { name: /manage subscription/i }),@@ -471,12 +490,10 @@ describe("YourPlanCard cycle toggle", () => {await screen.findByRole("button", { name: /upgrade to max/i }),);- expect(await screen.findByText(/Upgrade to Max\?/i)).toBeDefined();expect(- screen.getByText(- /charged the prorated difference immediately for the rest of your monthly period/i,- ),+ await screen.findByRole("dialog", { name: /Upgrade to Max/i }),).toBeDefined();+ expect(await screen.findByText("Due today")).toBeDefined();expect(mutationFired).toBe(false);});@@ -507,12 +524,9 @@ describe("YourPlanCard cycle toggle", () => {await screen.findByRole("button", { name: /upgrade to max/i }),);- const confirmInDialog = await screen.findAllByRole("button", {- name: /upgrade to max/i,- });- // Two buttons share the label: the card's trigger + the dialog's confirm.- // The confirm is the second one in DOM order.- fireEvent.click(confirmInDialog[confirmInDialog.length - 1]);+ fireEvent.click(+ await screen.findByRole("button", { name: "Pay $272.78 and upgrade" }),+ );await waitFor(() => {expect(capturedBody).not.toBeNull();@@ -547,11 +561,15 @@ describe("YourPlanCard cycle toggle", () => {fireEvent.click(await screen.findByRole("button", { name: /upgrade to max/i }),);- expect(await screen.findByText(/Upgrade to Max\?/i)).toBeDefined();- fireEvent.click(await screen.findByRole("button", { name: /^cancel$/i }));+ expect(+ await screen.findByRole("dialog", { name: /Upgrade to Max/i }),+ ).toBeDefined();+ fireEvent.click(await screen.findByRole("button", { name: "Keep Pro" }));await waitFor(() =>- expect(screen.queryByText(/Upgrade to Max\?/i)).toBeNull(),+ expect(+ screen.queryByRole("dialog", { name: /Upgrade to Max/i }),+ ).toBeNull(),);expect(mutationFired).toBe(false);});@@ -666,7 +684,7 @@ describe("YourPlanCard cycle toggle", () => {expect(mutationFired).toBe(false);});- it("NO_TIER user clicking Get Pro skips the confirmation dialog (Stripe Checkout flow)", async () => {+ it("NO_TIER user clicking Start Pro skips the confirmation dialog (Stripe Checkout flow)", async () => {let mutationFired = false;server.use(jsonHandler("get", "/api/credits/subscription", {@@ -684,7 +702,7 @@ describe("YourPlanCard cycle toggle", () => {render(<YourPlanCard />);- fireEvent.click(await screen.findByRole("button", { name: /get pro/i }));+ fireEvent.click(await screen.findByRole("button", { name: /start pro/i }));// No SwitchTierDialog rendered for free→paid (Checkout success_url path).await waitFor(() => expect(mutationFired).toBe(true));@@ -991,7 +1009,7 @@ describe("AutopilotUsageCard", () => {render(<AutopilotUsageCard />);expect(await screen.findByText("Today")).toBeDefined();- expect(screen.getByText("This Week")).toBeDefined();+ expect(screen.getByText("This week")).toBeDefined();expect(screen.getByText("12% used")).toBeDefined();expect(screen.getByText("35% used")).toBeDefined();});@@ -1353,7 +1371,7 @@ describe("YourPlanCard begin_checkout", () => {freeAccount("https://checkout.stripe.com/pay/cs_test");render(<YourPlanCard />);- fireEvent.click(await screen.findByRole("button", { name: /get pro/i }));+ fireEvent.click(await screen.findByRole("button", { name: /start pro/i }));await waitFor(() => {expect(gtagCalls).toContainEqual([@@ -1380,7 +1398,7 @@ describe("YourPlanCard begin_checkout", () => {const hits = freeAccount("https://checkout.stripe.com/pay/cs_test");render(<YourPlanCard />);- const upgrade = await screen.findByRole("button", { name: /get pro/i });+ const upgrade = await screen.findByRole("button", { name: /start pro/i });fireEvent.click(upgrade);await waitFor(() =>expect(gtagCalls.some((call) => call[1] === "conversion")).toBe(true),@@ -1403,7 +1421,7 @@ describe("YourPlanCard begin_checkout", () => {render(<YourPlanCard />);await waitFor(() => expect(hits.get).toBe(1));- fireEvent.click(screen.getByRole("button", { name: /get pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /start pro/i }));// The in-place branch refetches the subscription after the POST resolves,// so a second GET is proof the whole path ran — not just that the requestdiff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsxindex 077cdd617f..45bc40c797 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx@@ -1,3 +1,4 @@+import { setTrialUser } from "@/tests/integrations/trial-fixtures";/*** Hook-level coverage for the billing card hooks.*@@ -14,13 +15,26 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { act, renderHook, waitFor } from "@testing-library/react";import { http, HttpResponse, type JsonBodyType } from "msw";import type { ReactNode } from "react";-import { describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useAutoRefillCard } from "../components/AutomationCreditsTab/AutoRefillCard/useAutoRefillCard";import { useBalanceCard } from "../components/AutomationCreditsTab/BalanceCard/useBalanceCard";import { usePaymentMethodCard } from "../components/SubscriptionTab/PaymentMethodCard/usePaymentMethodCard";import { useYourPlanCard } from "../components/SubscriptionTab/YourPlanCard/useYourPlanCard";+import { maxUpgradePreview } from "./max-upgrade.fixture";++afterEach(() => setTrialUser(null));++beforeEach(() => {+ setTrialUser("billing-user");+ server.use(+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(maxUpgradePreview()),+ ),+ );+});+function jsonHandler(method: "get" | "post", path: string, body: JsonBodyType) {return http[method](`*${path}`, () => HttpResponse.json(body));}@@ -666,6 +680,9 @@ describe("useYourPlanCard", () => {result.current.onUpgrade();});await waitFor(() => expect(result.current.pendingTierUpgrade).toBe("MAX"));+ await waitFor(() =>+ expect(result.current.upgradeReview.preview).toBeDefined(),+ );await act(async () => {await result.current.onConfirmTierUpgrade();diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-offer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-offer.test.tsxnew file mode 100644index 0000000000..5937f61b18--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-offer.test.tsx@@ -0,0 +1,110 @@+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, expect, it } from "vitest";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { BillingOffer } from "../components/SubscriptionTab/BillingOffer";+import { YourPlanCard } from "../components/SubscriptionTab/YourPlanCard/YourPlanCard";++beforeEach(() => {+ setTrialUser("billing-user");+ server.use(+ http.get("*/api/credits/manage", () =>+ HttpResponse.json({ url: "https://billing.stripe.com/test" }),+ ),+ );+});+afterEach(() => setTrialUser(null));++function mockTrialAt(percent: number) {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({ tier: "TRIAL", monthly_cost: 0 }),+ ),+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(+ trialResponse({+ usage_policy: "lifetime",+ allowance_used_percent: percent,+ }),+ ),+ ),+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({ tier: "TRIAL", daily: null, weekly: null }),+ ),+ );+}++it.each([0, 64, 79])(+ "keeps the price and start date without pushing an early start at %s%%",+ async (percent) => {+ mockTrialAt(percent);+ render(<BillingOffer />);+ expect(+ await screen.findByRole("heading", { name: "Pro starts on Sep 17" }),+ ).toBeDefined();+ expect(+ screen.getByText(+ "Your trial keeps going until then. You can also start today.",+ ),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: "Start Pro now" })).toBeDefined();+ expect(screen.getByText("$20")).toBeDefined();+ expect(screen.queryByText(/keep working today/)).toBeNull();+ },+);++it.each([80, 100])(+ "offers starting Pro today once the trial is running low at %s%%",+ async (percent) => {+ mockTrialAt(percent);+ render(<BillingOffer />);+ expect(+ await screen.findByRole("button", { name: "Start Pro now · $20" }),+ ).toBeDefined();+ expect(+ screen.getByText(+ "Pro starts on its own on Sep 17. Start it now to keep working today.",+ ),+ ).toBeDefined();+ },+);++it("shows one usage error and keeps the normal plan card when usage fails", async () => {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({+ tier: "PRO",+ monthly_cost: 5000,+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_multipliers: { PRO: 1, MAX: 8.5 },+ billing_cycle: "monthly",+ has_active_stripe_subscription: true,+ }),+ ),+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(trialResponse({ active: false, converted: true })),+ ),+ http.get("*/api/chat/usage", () => HttpResponse.json({}, { status: 500 })),+ );+ render(<YourPlanCard showUsage />);+ expect(await screen.findByText("We couldn’t load your usage")).toBeDefined();+ expect(screen.getAllByText("We couldn’t load your usage")).toHaveLength(1);+ expect(screen.getByRole("button", { name: "Try again" })).toBeDefined();+ expect(screen.getByRole("link", { name: "Contact support" })).toBeDefined();+ expect(screen.queryByText("Something went wrong")).toBeNull();+ expect(+ screen.queryByRole("button", { name: /Report Error|Get Help/ }),+ ).toBeNull();+ expect(+ await screen.findByRole("heading", { name: "Upgrade to Max" }),+ ).toBeDefined();+ expect(+ screen.getByText(+ "What you’ve already used counts toward Max’s higher limit.",+ ),+ ).toBeDefined();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-page.test.tsxindex 33589777b2..dceab156a4 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-page.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-page.test.tsx@@ -82,7 +82,9 @@ describe("Settings billing page (integration)", () => {useDefaultBillingHandlers();render(<SettingsBillingPage />);- expect(screen.getByRole("heading", { name: "Billing" })).toBeDefined();+ expect(+ screen.getByRole("heading", { name: "Billing & usage" }),+ ).toBeDefined();const subscriptionTab = screen.getByRole("tab", { name: "Subscription" });expect(subscriptionTab.getAttribute("data-state")).toBe("active");diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade-session.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade-session.test.tsxnew file mode 100644index 0000000000..2391fa89fc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade-session.test.tsx@@ -0,0 +1,91 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook, waitFor } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { server } from "@/mocks/mock-server";+import {+ deferredTrialResponse,+ setTrialUser,+} from "@/tests/integrations/trial-fixtures";+import { useTierUpgradePreview } from "../components/SubscriptionTab/YourPlanCard/useTierUpgradePreview";+import { maxUpgradePreview } from "./max-upgrade.fixture";++beforeEach(() => setTrialUser("user-a"));+afterEach(() => setTrialUser(null));++function renderReview() {+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ }+ return renderHook(() => useTierUpgradePreview(true, "monthly"), {+ wrapper: Wrapper,+ });+}++it("discards a late quote from the previous account and clears the amount on logout", async () => {+ const pending = deferredTrialResponse<ReturnType<typeof maxUpgradePreview>>();+ const requested = vi.fn();+ server.use(+ http.post("*/api/credits/subscription/preview", async () => {+ requested();+ return HttpResponse.json(+ requested.mock.calls.length === 1+ ? await pending.promise+ : maxUpgradePreview({+ amount_due: 28000,+ preview_id: "b".repeat(32),+ }),+ );+ }),+ );+ const { result } = renderReview();+ await waitFor(() => expect(requested).toHaveBeenCalledOnce());+ act(() => setTrialUser("user-b"));+ expect(result.current.preview).toBeUndefined();+ await waitFor(() => expect(result.current.preview?.amount_due).toBe(28000));+ await act(async () => pending.resolve(maxUpgradePreview()));+ expect(result.current.preview?.preview_id).toBe("b".repeat(32));+ act(() => setTrialUser(null));+ expect(result.current.preview).toBeUndefined();+});++it("withdraws an expired charge and requires another review", async () => {+ let calls = 0;+ server.use(+ http.post("*/api/credits/subscription/preview", () => {+ const expires =+ ++calls === 1+ ? Math.ceil(Date.now() / 1000) + 1+ : Math.floor(Date.now() / 1000) + 900;+ return HttpResponse.json(maxUpgradePreview({ expires_at: expires }));+ }),+ );+ const { result } = renderReview();+ await waitFor(() => expect(result.current.preview).toBeDefined());+ await waitFor(() => expect(result.current.error).toMatch(/expired/), {+ timeout: 2500,+ });+ expect(result.current.preview).toBeUndefined();+ act(() => result.current.retry());+ await waitFor(() => expect(result.current.preview).toBeDefined());+ expect(result.current.error).toBe("");+});++it("never presents an already expired response as payable", async () => {+ server.use(+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(+ maxUpgradePreview({ expires_at: Math.floor(Date.now() / 1000) - 1 }),+ ),+ ),+ );+ const { result } = renderReview();+ await waitFor(() => expect(result.current.error).toMatch(/expired/));+ expect(result.current.preview).toBeUndefined();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade.fixture.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade.fixture.tsnew file mode 100644index 0000000000..65302487dc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade.fixture.ts@@ -0,0 +1,38 @@+import type { SubscriptionUpgradePreview } from "@/app/api/__generated__/models/subscriptionUpgradePreview";++export function maxUpgradePreview(+ overrides: Partial<SubscriptionUpgradePreview> = {},+): SubscriptionUpgradePreview {+ const now = Math.floor(Date.now() / 1000);+ return {+ preview_id: "a".repeat(32),+ amount_due: 27278,+ tax_amount: 2020,+ tax_included: false,+ adjustment_amount: 0,+ currency: "usd",+ proration_date: now,+ period_end: now + 29 * 86400,+ expires_at: now + 900,+ recurring_amount: 32000,+ recurring_tax_included: false,+ billing_cycle: "monthly",+ lines: [+ {+ description: "Remaining Max",+ amount: 29935,+ period_start: now,+ period_end: now + 29 * 86400,+ proration: true,+ },+ {+ description: "Unused Pro",+ amount: -4677,+ period_start: now,+ period_end: now + 29 * 86400,+ proration: true,+ },+ ],+ ...overrides,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade.test.tsxnew file mode 100644index 0000000000..52c7fb7db0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/max-upgrade.test.tsx@@ -0,0 +1,251 @@+import { setTrialUser } from "@/tests/integrations/trial-fixtures";+import { fireEvent, within } from "@testing-library/react";+import { delay, http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import { YourPlanCard } from "../components/SubscriptionTab/YourPlanCard/YourPlanCard";+import { maxUpgradePreview } from "./max-upgrade.fixture";++const subscription = {+ tier: "PRO",+ monthly_cost: 5000,+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ tier_multipliers: { PRO: 2, MAX: 17 },+ billing_cycle: "monthly",+ has_active_stripe_subscription: true,+};++afterEach(() => setTrialUser(null));++beforeEach(() => {+ setTrialUser("billing-user");+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json(subscription),+ ),+ http.get("*/api/credits/manage", () =>+ HttpResponse.json({ url: "https://billing.stripe.com/test" }),+ ),+ );+});++async function openReview() {+ render(<YourPlanCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ );+ return within(await screen.findByRole("dialog", { name: /Upgrade to Max/ }));+}++describe("Max charge review", () => {+ it("discloses the actual debit, credit and tax, then confirms the reviewed timestamp", async () => {+ const preview = maxUpgradePreview();+ const requested = vi.fn();+ const charged = vi.fn();+ server.use(+ http.post("*/api/credits/subscription/preview", async ({ request }) => {+ requested(await request.json());+ return HttpResponse.json(preview);+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ charged(await request.json());+ return HttpResponse.json({ ...subscription, tier: "MAX" });+ }),+ );+ const dialog = await openReview();+ const pay = await dialog.findByRole("button", {+ name: "Pay $272.78 and upgrade",+ });+ expect(dialog.getByText("Due today")).toBeDefined();+ expect(dialog.getByText("$299.35")).toBeDefined();+ expect(dialog.getByText("-$46.77")).toBeDefined();+ expect(dialog.getByText("$20.20")).toBeDefined();+ expect(dialog.getByText(/8.5 times the usage of Pro/)).toBeDefined();+ expect(requested).toHaveBeenCalledWith({+ tier: "MAX",+ billing_cycle: "monthly",+ });+ expect(charged).not.toHaveBeenCalled();+ fireEvent.click(pay);+ await waitFor(() =>+ expect(charged).toHaveBeenCalledWith(+ expect.objectContaining({+ tier: "MAX",+ billing_cycle: "monthly",+ preview_id: preview.preview_id,+ proration_date: preview.proration_date,+ }),+ ),+ );+ });++ it("keeps the plan unchanged when the preview fails and provides an explicit retry", async () => {+ let attempts = 0;+ const charged = vi.fn();+ server.use(+ http.post("*/api/credits/subscription/preview", () =>+ ++attempts === 1+ ? new HttpResponse(null, { status: 502 })+ : HttpResponse.json(maxUpgradePreview()),+ ),+ http.post("*/api/credits/subscription", () => {+ charged();+ return HttpResponse.json(subscription);+ }),+ );+ const dialog = await openReview();+ await dialog.findByText(/We couldn’t load your charge/);+ expect(+ dialog+ .getByRole("button", { name: "Upgrade to Max" })+ .hasAttribute("disabled"),+ ).toBe(true);+ expect(charged).not.toHaveBeenCalled();+ fireEvent.click(dialog.getByRole("button", { name: "Retry review" }));+ await dialog.findByRole("button", { name: "Pay $272.78 and upgrade" });+ fireEvent.click(dialog.getByRole("button", { name: "Keep Pro" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(charged).not.toHaveBeenCalled();+ });++ it.each([+ { status: 409, message: /Your billing details changed/ },+ { status: 402, message: /Payment wasn’t completed/ },+ ])(+ "requires a fresh review after a $status response",+ async ({ status, message }) => {+ let quotes = 0;+ const charged = vi.fn();+ server.use(+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(+ maxUpgradePreview(+ ++quotes === 1+ ? {}+ : {+ preview_id: "b".repeat(32),+ amount_due: 28000,+ adjustment_amount: 722,+ },+ ),+ ),+ ),+ http.post("*/api/credits/subscription", async ({ request }) => {+ charged(await request.json());+ return charged.mock.calls.length === 1+ ? HttpResponse.json({ detail: "Review again" }, { status })+ : HttpResponse.json({ ...subscription, tier: "MAX" });+ }),+ );+ const dialog = await openReview();+ fireEvent.click(+ await dialog.findByRole("button", { name: "Pay $272.78 and upgrade" }),+ );+ await dialog.findByText(message);+ expect(charged).toHaveBeenCalledTimes(1);+ expect(quotes).toBe(1);+ expect(dialog.queryByRole("button", { name: /Pay \$/ })).toBeNull();+ fireEvent.click(dialog.getByRole("button", { name: "Retry review" }));+ fireEvent.click(+ await dialog.findByRole("button", { name: "Pay $280.00 and upgrade" }),+ );+ await waitFor(() => expect(charged).toHaveBeenCalledTimes(2));+ expect(charged.mock.calls[1][0]).toMatchObject({+ preview_id: "b".repeat(32),+ });+ },+ );++ it("retries an uncertain payment with the same reviewed quote", async () => {+ const preview = maxUpgradePreview();+ const requested = vi.fn();+ const charged = vi.fn();+ server.use(+ http.post("*/api/credits/subscription/preview", () => {+ requested();+ return HttpResponse.json(preview);+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ charged(await request.json());+ return charged.mock.calls.length === 1+ ? HttpResponse.json(+ { detail: "Couldn’t confirm the payment result. Please retry." },+ { status: 502 },+ )+ : HttpResponse.json({ ...subscription, tier: "MAX" });+ }),+ );+ const dialog = await openReview();+ const pay = await dialog.findByRole("button", {+ name: "Pay $272.78 and upgrade",+ });+ fireEvent.click(pay);+ await waitFor(() => expect(charged).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(pay.hasAttribute("disabled")).toBe(false));+ expect(dialog.queryByRole("button", { name: "Retry review" })).toBeNull();+ fireEvent.click(pay);+ await waitFor(() => expect(charged).toHaveBeenCalledTimes(2));+ expect(requested).toHaveBeenCalledOnce();+ expect(charged.mock.calls[1][0]).toMatchObject({+ preview_id: preview.preview_id,+ proration_date: preview.proration_date,+ });+ });++ it("lets the user keep Pro while loading and cannot confirm before a quote arrives", async () => {+ server.use(+ http.post("*/api/credits/subscription/preview", async () => {+ await delay(100);+ return HttpResponse.json(maxUpgradePreview());+ }),+ );+ const dialog = await openReview();+ expect(+ dialog+ .getByRole("button", { name: "Upgrade to Max" })+ .hasAttribute("disabled"),+ ).toBe(true);+ fireEvent.click(dialog.getByRole("button", { name: "Keep Pro" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });++ it("uses yearly currency and tax-inclusive terms without adding tax twice", async () => {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({ ...subscription, billing_cycle: "yearly" }),+ ),+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(+ maxUpgradePreview({+ currency: "eur",+ billing_cycle: "yearly",+ recurring_amount: 326400,+ tax_included: true,+ recurring_tax_included: true,+ }),+ ),+ ),+ );+ const dialog = await openReview();+ await dialog.findByRole("button", { name: "Pay €272.78 and upgrade" });+ expect(dialog.getByText("Tax (included)")).toBeDefined();+ expect(+ dialog.getByText(+ /Max’s regular price is €3,264.00 including tax per year/,+ ),+ ).toBeDefined();+ });++ it("displays a zero-decimal currency in Stripe's minor units", async () => {+ server.use(+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(maxUpgradePreview({ currency: "jpy" })),+ ),+ );+ const dialog = await openReview();+ await dialog.findByRole("button", { name: "Pay ¥27,278 and upgrade" });+ expect(dialog.getByText("¥29,935")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/payment-recovery.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/payment-recovery.test.tsxnew file mode 100644index 0000000000..d2e685337a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/payment-recovery.test.tsx@@ -0,0 +1,84 @@+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { getGetTrialsGetTrialStatusMockHandler200 } from "@/app/api/__generated__/endpoints/trials/trials.msw";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import SettingsBillingPage from "../page";++vi.mock("@/hooks/useIsBillingEnabled", () => ({+ useIsBillingEnabled: () => true,+ useBillingStatus: () => ({ isBillingEnabled: true, isResolved: true }),+}));++const PAYMENT_URL = "https://invoice.stripe.com/i/acct_1/test_inv_1";++beforeEach(() => setTrialUser());+afterEach(() => setTrialUser(null));++function mockPastDueTrial(status: string, paymentDue: boolean) {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({+ active: false,+ status,+ payment_due: paymentDue+ ? { amount_due: 5413, currency: "usd", payment_url: PAYMENT_URL }+ : null,+ }),+ ),+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({+ tier: "NO_TIER",+ monthly_cost: 0,+ has_active_stripe_subscription: false,+ }),+ ),+ http.get("*/api/credits/invoices", () => HttpResponse.json([])),+ );+}++it.each(["past_due", "unpaid"])(+ "gives a %s trial one message and one way to pay the open invoice",+ async (status) => {+ mockPastDueTrial(status, true);+ render(<SettingsBillingPage />);+ const pay = await screen.findByRole("link", { name: "Pay $54.13 now" });+ expect(pay.getAttribute("href")).toBe(PAYMENT_URL);+ expect(pay.getAttribute("target")).toBe("_blank");+ expect(pay.closest(".sentry-unmask")).toBeNull();+ expect(screen.getByText("Your payment didn’t go through")).toBeDefined();+ expect(+ screen.getByText(+ "Pro was due to start on Sep 17, but the $54.13 charge didn’t go through. Pay now and Pro starts right away. Your chats, agents and results are saved.",+ ),+ ).toBeDefined();+ for (const amount of screen.getAllByText(/\$54\.13/)) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ expect(screen.queryByText("Your trial has ended")).toBeNull();+ expect(+ screen.queryByText("Pick a plan to continue using AutoGPT."),+ ).toBeNull();+ expect(screen.queryByRole("button", { name: /^Start/ })).toBeNull();+ expect(screen.queryByRole("region", { name: "Usage" })).toBeNull();+ expect(screen.queryByText("Update payment method")).toBeNull();+ expect(screen.getByText("Manage payment method")).toBeDefined();+ },+);++it("points to the payment method row when the open invoice can't be read", async () => {+ mockPastDueTrial("past_due", false);+ render(<SettingsBillingPage />);+ expect(+ await screen.findByText(+ "Update your payment method below to continue. Your chats, agents and results are saved.",+ ),+ ).toBeDefined();+ expect(screen.queryByRole("link", { name: /^Pay / })).toBeNull();+ expect(screen.queryByRole("button", { name: /^Start/ })).toBeNull();+ expect(screen.getByText("Manage payment method")).toBeDefined();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsxindex 82be62ae19..a9ba9782f3 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx@@ -18,7 +18,7 @@ vi.mock("@/hooks/useIsBillingEnabled", () => ({beforeEach(() => setTrialUser());afterEach(() => setTrialUser(null));-it.each(["past_due", "unpaid", "incomplete_expired", "trialing", "canceled"])(+it.each(["incomplete_expired", "trialing", "canceled"])("keeps plan selection available for an inactive %s trial",async (status) => {server.use(@@ -39,7 +39,9 @@ it.each(["past_due", "unpaid", "incomplete_expired", "trialing", "canceled"])(expect(await screen.findByText("Pick a plan to continue using AutoGPT."),).toBeDefined();- expect(screen.getByRole("button", { name: "Get Pro" })).toBeDefined();+ expect(+ screen.getAllByRole("button", { name: "Start Pro" }).length,+ ).toBeGreaterThan(0);},);@@ -57,8 +59,8 @@ it("shows the trial as the current plan during an active trial", async () => {);render(<SettingsBillingPage />);await screen.findByRole("button", { name: "Cancel trial" });- expect(screen.getByText("Your plan")).toBeDefined();- expect(screen.queryByRole("button", { name: "Get Pro" })).toBeNull();+ expect(screen.getAllByText("Your plan").length).toBeGreaterThan(0);+ expect(screen.queryByRole("button", { name: "Start Pro" })).toBeNull();});const trialSubscription = {@@ -87,7 +89,8 @@ it("offers plan choices while a trial cancellation is pending", async () => {await screen.findByRole("button", { name: "Subscribe to Pro" }),).toBeDefined();expect(screen.getByRole("button", { name: "Upgrade to Max" })).toBeDefined();- expect(screen.queryByRole("button", { name: "Get Pro" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Start Pro" })).toBeNull();+ expect(screen.queryByRole("button", { name: /Start Pro now/i })).toBeNull();});it("offers no plan choices during a trial that will convert", async () => {@@ -122,7 +125,9 @@ it("offers no plan choices once a cancel-pending trial has ended", async () => {"NO_TIER",);render(<SettingsBillingPage />);- await screen.findByRole("button", { name: "Get Pro" });+ expect(+ (await screen.findAllByRole("button", { name: "Start Pro" })).length,+ ).toBeGreaterThan(0);expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();expect(screen.queryByRole("button", { name: "Subscribe to Pro" })).toBeNull();});@@ -131,7 +136,7 @@ it("shows a plan bought during a cancel-pending trial the cleanup has not ended"mockBilling(trialResponse({ cancel_at_period_end: true }), "MAX");render(<SettingsBillingPage />);expect(await screen.findByText("Active")).toBeDefined();- expect(screen.getAllByText("Your plan")).toHaveLength(1);+ expect(screen.getByRole("heading", { name: "Max" })).toBeDefined();expect(screen.queryByRole("button", { name: "Resume trial" })).toBeNull();expect(screen.queryByRole("region", { name: "AutoGPT trial" })).toBeNull();expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();@@ -141,7 +146,7 @@ it("keeps a trial that will convert as the plan whatever tier is reported", asynmockBilling(trialResponse({ cancel_at_period_end: false }), "MAX");render(<SettingsBillingPage />);await screen.findByRole("button", { name: "Cancel trial" });- expect(screen.getAllByText("Your plan")).toHaveLength(1);+ expect(screen.getByRole("heading", { name: "Your trial" })).toBeDefined();expect(screen.queryByText("Active")).toBeNull();});@@ -160,6 +165,10 @@ it.each(["PRO", "MAX"])(expect(await screen.findByText("Active")).toBeDefined();expect(screen.queryByText("Your trial has ended")).toBeNull();expect(screen.queryByRole("region", { name: "AutoGPT trial" })).toBeNull();- expect(screen.getAllByText("Your plan")).toHaveLength(1);+ expect(+ screen.getByRole("heading", {+ name: tier === "PRO" ? "Pro" : "Max",+ }),+ ).toBeDefined();},);diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-rejection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-rejection.test.tsxindex 832bf28b7a..9d8587a71c 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-rejection.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-rejection.test.tsx@@ -111,7 +111,9 @@ it("keeps a paid-plan action and support available after rejection", async () =>);render(<SettingsBillingPage />);await screen.findByText("This introductory offer has already been used");- expect(await screen.findByRole("button", { name: "Get Pro" })).toBeDefined();+ expect(+ (await screen.findAllByRole("button", { name: "Start Pro" })).length,+ ).toBeGreaterThan(0);expect(screen.getByRole("link", { name: "Contact support" }).getAttribute("href"),).toBe("https://discord.gg/autogpt");diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/upgrade-replay-privacy.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/upgrade-replay-privacy.test.tsxnew file mode 100644index 0000000000..76e81c6b9a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/upgrade-replay-privacy.test.tsx@@ -0,0 +1,136 @@+import { fireEvent, within } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, expect, it } from "vitest";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+ trialOffer,+} from "@/tests/integrations/trial-fixtures";+import { useProActivation } from "@/services/pro-activation/useProActivation";+import { quote } from "@/services/pro-activation/__tests__/fixtures";+import { BillingOffer } from "../components/SubscriptionTab/BillingOffer";+import { YourPlanCard } from "../components/SubscriptionTab/YourPlanCard/YourPlanCard";+import { maxUpgradePreview } from "./max-upgrade.fixture";++beforeEach(() => {+ setTrialUser("billing-user");+ sessionStorage.clear();+ server.use(+ http.get("*/api/credits/manage", () =>+ HttpResponse.json({ url: "https://billing.stripe.com/test" }),+ ),+ );+});+afterEach(() => setTrialUser(null));++it("keeps every reviewed Max amount out of replay, including the consent button and renewal copy", async () => {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({+ tier: "PRO",+ monthly_cost: 5000,+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ billing_cycle: "monthly",+ has_active_stripe_subscription: true,+ }),+ ),+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(+ maxUpgradePreview({ adjustment_amount: 100, amount_due: 27378 }),+ ),+ ),+ );+ render(<YourPlanCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ );+ const dialog = within(+ await screen.findByRole("dialog", { name: /Upgrade to Max/ }),+ );+ await dialog.findByRole("button", { name: "Pay $273.78 and upgrade" });+ const amounts = dialog.getAllByText(/\$/);+ expect(amounts).toHaveLength(8);+ for (const amount of amounts) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ expect(+ dialog.getByText("Due today").closest(".sentry-unmask"),+ ).not.toBeNull();+ expect(+ dialog.getByRole("button", { name: "Keep Pro" }).closest(".sentry-unmask"),+ ).not.toBeNull();+});++function StartPro() {+ const activation = useProActivation();+ return <button onClick={() => activation.start()}>Start Pro</button>;+}++it("keeps Pro's reviewed charge, discount, tax and full renewal terms masked in the real dialog", async () => {+ server.use(+ http.get(+ "*/api/credits/pro-activation/current",+ () => new HttpResponse(null, { status: 404 }),+ ),+ http.post("*/api/credits/pro-activation/preview", () =>+ HttpResponse.json({+ ...quote,+ terms: {+ ...quote.terms,+ renewal_terms:+ "Renews at £85.00 per year, plus tax. Cancel before renewal.",+ renewal_discounts: [+ { amount_off: 1200, currency: "gbp", duration: "once" },+ ],+ },+ }),+ ),+ );+ render(<StartPro />);+ fireEvent.click(screen.getByRole("button", { name: "Start Pro" }));+ const dialog = within(+ await screen.findByRole("dialog", { name: /Start Pro today/ }),+ );+ await dialog.findByRole("button", { name: "Pay £61.23 and start Pro" });+ const privateValues = dialog.getAllByText(/£|VAT:/);+ expect(privateValues.length).toBeGreaterThanOrEqual(9);+ for (const value of privateValues) {+ expect(value.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ expect(+ dialog.getByRole("button", { name: "Not now" }).closest(".sentry-unmask"),+ ).not.toBeNull();+});++it("masks the accepted trial offer in billing while leaving static plan labels visible", async () => {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({ tier: "TRIAL", monthly_cost: 0 }),+ ),+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(+ trialResponse({+ usage_policy: "lifetime",+ allowance_used_percent: 100,+ offer: { ...trialOffer, unit_amount: 5013 },+ }),+ ),+ ),+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({ tier: "TRIAL", daily: null, weekly: null }),+ ),+ );+ render(<BillingOffer />);+ await screen.findByRole("button", { name: "Start Pro now · $50.13" });+ const amounts = screen.getAllByText(/\$50\.13/);+ expect(amounts).toHaveLength(2);+ for (const amount of amounts) {+ expect(amount.closest(".sentry-unmask, [data-sentry-unmask]")).toBeNull();+ }+ expect(+ screen.getByText("AutoGPT Pro").closest(".sentry-unmask"),+ ).not.toBeNull();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/usage-experience.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/usage-experience.test.tsxnew file mode 100644index 0000000000..7da36168ba--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/usage-experience.test.tsx@@ -0,0 +1,214 @@+import { maxUpgradePreview } from "./max-upgrade.fixture";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, expect, it } from "vitest";+import { server } from "@/mocks/mock-server";+import {+ render,+ screen,+ fireEvent,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { YourPlanCard } from "../components/SubscriptionTab/YourPlanCard/YourPlanCard";+import { AutopilotUsageCard } from "../components/SubscriptionTab/AutopilotUsageCard/AutopilotUsageCard";++beforeEach(() => setTrialUser());+afterEach(() => setTrialUser(null));++function mockUsage(tier: string, trial = {}, daily = 100, weekly = 100) {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({ tier, monthly_cost: 0 }),+ ),+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(trialResponse(trial)),+ ),+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({+ tier,+ daily: { percent_used: daily, resets_at: "2030-09-13T00:00:00Z" },+ weekly: { percent_used: weekly, resets_at: "2030-09-16T00:00:00Z" },+ }),+ ),+ );+}++it("shows one lifetime trial meter and never describes trial end as a reset", async () => {+ mockUsage("TRIAL", { usage_policy: "lifetime", allowance_used_percent: 100 });+ render(<AutopilotUsageCard />);+ expect(await screen.findByText("Trial usage")).toBeDefined();+ expect(screen.getAllByRole("progressbar")).toHaveLength(1);+ expect(+ screen.getByText(/This allowance lasts for your whole trial/),+ ).toBeDefined();+ expect(screen.queryByText(/Resets/)).toBeNull();+});++it("uses the later blocking window when both paid limits are exhausted", async () => {+ mockUsage("PRO", { active: false, converted: true });+ render(<AutopilotUsageCard />);+ const primary = await screen.findByTestId("featured-usage");+ expect(primary.textContent).toContain("This week");+ expect(screen.getAllByRole("progressbar")).toHaveLength(2);+});++it("does not display retained trial consumption after conversion", async () => {+ mockUsage(+ "PRO",+ { active: false, converted: true, allowance_used_percent: 100 },+ 12,+ 35,+ );+ render(<AutopilotUsageCard />);+ expect(await screen.findByText("Today")).toBeDefined();+ expect(screen.queryByText("Trial usage")).toBeNull();+ expect(screen.queryByText("100% used")).toBeNull();+});++it("offers a real retry rather than showing zero after a usage failure", async () => {+ mockUsage("PRO", { active: false, converted: true }, 12, 35);+ let attempts = 0;+ server.use(+ http.get("*/api/chat/usage", () => {+ attempts += 1;+ return attempts === 1+ ? HttpResponse.json({}, { status: 500 })+ : HttpResponse.json({+ tier: "PRO",+ daily: { percent_used: 12, resets_at: null },+ weekly: { percent_used: 35, resets_at: null },+ });+ }),+ );+ render(<AutopilotUsageCard />);+ fireEvent.click(await screen.findByRole("button", { name: /try again/i }));+ await waitFor(() => expect(screen.getByText("Today")).toBeDefined());+ expect(attempts).toBeGreaterThan(1);+});++it("keeps plan recovery visible when an inactive account has no usage permission", async () => {+ mockUsage("NO_TIER", { active: false, converted: true });+ server.use(+ http.get("*/api/chat/usage", () => HttpResponse.json({}, { status: 403 })),+ );+ render(<AutopilotUsageCard />);+ expect(+ await screen.findByText("Choose a plan to keep working"),+ ).toBeDefined();+ expect(screen.queryByRole("progressbar")).toBeNull();+ expect(screen.queryByRole("button", { name: /try again/i })).toBeNull();+});++it("explains an unlimited paid plan without inventing zero usage", async () => {+ mockUsage("ENTERPRISE", { active: false, converted: true });+ server.use(+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({ tier: "ENTERPRISE", daily: null, weekly: null }),+ ),+ );+ render(<AutopilotUsageCard />);+ expect(+ await screen.findByText("Your plan has no daily or weekly usage limits."),+ ).toBeDefined();+ expect(screen.queryByRole("progressbar")).toBeNull();+ expect(screen.queryByText("0% used")).toBeNull();+});++it("features the exhausted total allowance for a legacy trial without suggesting a rolling reset restores access", async () => {+ mockUsage(+ "TRIAL",+ { usage_policy: "rolling", allowance_used_percent: 100 },+ 25,+ 60,+ );+ render(<AutopilotUsageCard />);+ expect(await screen.findByText("Trial usage")).toBeDefined();+ expect(screen.getAllByRole("progressbar")).toHaveLength(1);+ expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBe(+ "100",+ );+ expect(screen.queryByText(/Resets/)).toBeNull();+ expect(screen.queryByText("Today")).toBeNull();+});++it("keeps both recurring meters for a legacy trial whose total allowance remains available", async () => {+ mockUsage(+ "TRIAL",+ { usage_policy: "rolling", allowance_used_percent: 42 },+ 100,+ 60,+ );+ render(<AutopilotUsageCard />);+ expect(await screen.findByText("Today")).toBeDefined();+ expect(screen.getByText("This week")).toBeDefined();+ expect(screen.getAllByRole("progressbar")).toHaveLength(2);+ expect(screen.queryByText("Trial usage")).toBeNull();+});++it("refreshes the rendered usage after a Max upgrade without resetting consumption", async () => {+ mockUsage("PRO", { active: false, converted: true });+ let upgraded = false;+ let usageRequests = 0;+ server.use(+ http.post("*/api/credits/subscription/preview", () =>+ HttpResponse.json(maxUpgradePreview()),+ ),+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({+ tier: upgraded ? "MAX" : "PRO",+ monthly_cost: upgraded ? 32000 : 5000,+ tier_costs: { PRO: 5000, MAX: 32000 },+ billing_cycle: "monthly",+ has_active_stripe_subscription: true,+ }),+ ),+ http.get("*/api/credits/manage", () =>+ HttpResponse.json({ url: "https://billing.stripe.com/p/test" }),+ ),+ http.get("*/api/chat/usage", () => {+ usageRequests += 1;+ return HttpResponse.json({+ tier: upgraded ? "MAX" : "PRO",+ daily: {+ percent_used: upgraded ? 12 : 100,+ resets_at: "2030-09-13T00:00:00Z",+ },+ weekly: {+ percent_used: upgraded ? 10 : 85,+ resets_at: "2030-09-16T00:00:00Z",+ },+ });+ }),+ http.post("*/api/credits/subscription", () => {+ upgraded = true;+ return HttpResponse.json({ url: "" });+ }),+ );+ render(<YourPlanCard showUsage />);+ await waitFor(() =>+ expect(+ screen+ .getByRole("progressbar", { name: "Today usage" })+ .getAttribute("aria-valuenow"),+ ).toBe("100"),+ );+ fireEvent.click(screen.getByRole("button", { name: "Upgrade to Max" }));+ fireEvent.click(+ await within(await screen.findByRole("dialog")).findByRole("button", {+ name: "Pay $272.78 and upgrade",+ }),+ );+ await waitFor(() =>+ expect(+ screen+ .getByRole("progressbar", { name: "Today usage" })+ .getAttribute("aria-valuenow"),+ ).toBe("12"),+ );+ expect(usageRequests).toBeGreaterThanOrEqual(2);+ expect(screen.queryByText("0% used")).toBeNull();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/usage-status.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/usage-status.test.tsxnew file mode 100644index 0000000000..4859f8e65d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/usage-status.test.tsx@@ -0,0 +1,47 @@+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, expect, it } from "vitest";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { AutopilotUsageCard } from "../components/SubscriptionTab/AutopilotUsageCard/AutopilotUsageCard";++beforeEach(() => setTrialUser());+afterEach(() => setTrialUser(null));++it.each([+ [0, "Plenty left"],+ [79, "Plenty left"],+ [80, "Running low"],+ [99, "Running low"],+ [100, "Allowance reached"],+])(+ "reports the featured trial allowance at %s%% as %s",+ async (percent, status) => {+ server.use(+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({ tier: "TRIAL", monthly_cost: 0 }),+ ),+ http.get("*/api/credits/trial", () =>+ HttpResponse.json(+ trialResponse({+ usage_policy: "lifetime",+ allowance_used_percent: percent,+ }),+ ),+ ),+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({+ tier: "TRIAL",+ daily: { percent_used: 5, resets_at: null },+ weekly: { percent_used: 10, resets_at: null },+ }),+ ),+ );+ render(<AutopilotUsageCard />);+ expect(await screen.findByText(status)).toBeDefined();+ expect(screen.queryByText("On track")).toBeNull();+ },+);diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/AutopilotUsageCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/AutopilotUsageCard.tsxindex d4897d4766..25f268a132 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/AutopilotUsageCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/AutopilotUsageCard.tsx@@ -1,88 +1,158 @@"use client";import { motion, useReducedMotion } from "framer-motion";-+import { Clock01Icon } from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";-import { InformationTooltip } from "@/components/molecules/InformationTooltip/InformationTooltip";--import { EASE_OUT, getSectionMotionProps } from "../../../helpers";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { formatUsagePercent } from "@/services/usageExperience/helpers";+import { getSectionMotionProps } from "../../../helpers";import {useAutopilotUsageCard,type UsageWindowView,} from "./useAutopilotUsageCard";+import { UsageUnavailable } from "./UsageUnavailable";interface Props {index?: number;}-const USAGE_EXPLAINER =- "Each expert request consumes a share of your plan's allowance based on the work performed. Simple requests use little; complex workflows use more. No surprise overages.";-export function AutopilotUsageCard({ index = 0 }: Props) {const reduceMotion = useReducedMotion();- const { today, week, hasUsage } = useAutopilotUsageCard();-- if (!hasUsage) return null;-+ const state = useAutopilotUsageCard();+ if (state.isLoading) return <Skeleton className="h-80 rounded-2xl" />;+ if (+ !state.inactive &&+ (state.isError || (!state.hasUsage && !state.unlimited))+ )+ return <UsageUnavailable onRetry={() => void state.retry()} />;return (<motion.section{...getSectionMotionProps(index, Boolean(reduceMotion))}- className="flex w-full flex-col gap-2"+ aria-label="Usage"+ className="flex h-full min-h-80 flex-col rounded-2xl border border-zinc-200 bg-white p-6">- <div className="flex items-center gap-1 px-4">- <Text variant="body-medium" as="span" className="text-textBlack">- Expert usage+ <div className="flex flex-wrap items-center justify-between gap-2">+ <Text variant="large-medium" as="h2">+ Usage</Text>- <InformationTooltip description={USAGE_EXPLAINER} iconSize={22} />- </div>-- <div className="flex flex-col gap-6 rounded-[18px] border border-zinc-200 bg-white px-5 py-5 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">- {today ? <UsageBar window={today} /> : null}- {week ? <UsageBar window={week} /> : null}+ {!state.inactive && (+ <Text variant="small" className={state.status.className}>+ {state.status.label}+ </Text>+ )}</div>+ {state.inactive || state.unlimited ? (+ <div className="my-auto py-8">+ <Text variant="large-medium" className="mb-2">+ {state.unlimited+ ? "No usage limit"+ : "Choose a plan to keep working"}+ </Text>+ <Text variant="small" tone="secondary" className="leading-6">+ {state.unlimited+ ? "Your plan has no daily or weekly usage limits."+ : "Choose a plan to continue working with your saved conversations and agents."}+ </Text>+ </div>+ ) : (+ <>+ {state.featured && <UsageBar window={state.featured} primary />}+ {state.secondary && (+ <div className="mt-6 border-t border-zinc-100 pt-5">+ <UsageBar window={state.secondary} />+ </div>+ )}+ {state.lifetime && (+ <div className="mt-6 border-t border-zinc-100 pt-5">+ <Text variant="small-medium" className="mb-1">+ One allowance for your whole trial+ </Text>+ <Text variant="small" tone="secondary" className="leading-6">+ This allowance lasts for your whole trial. It doesn’t refresh+ each day or week.+ </Text>+ </div>+ )}+ </>+ )}+ <Text+ variant="small"+ tone="secondary"+ className="mt-auto pt-6 text-xs leading-5"+ >+ {state.inactive+ ? "Your work stays saved."+ : "Bigger requests use more of your allowance. Hitting the limit never adds a charge."}+ </Text></motion.section>);}-function UsageBar({ window }: { window: UsageWindowView }) {- const reduceMotion = useReducedMotion();+function UsageBar({+ window,+ primary = false,+}: {+ window: UsageWindowView;+ primary?: boolean;+}) {const percent = Math.min(Math.max(window.percent, 0), 100);- const isHigh = percent >= 80;- const percentLabel =- window.percent > 0 && percent === 0 ? "<1% used" : `${percent}% used`;-+ const label = formatUsagePercent(percent).replace("%", "");return (- <div className="flex flex-col gap-2">- <div className="flex items-baseline justify-between">- <Text variant="body-medium" className="text-neutral-700">+ <div+ className={primary ? "mt-5" : ""}+ data-testid={primary ? "featured-usage" : undefined}+ >+ <div className="mb-3 flex items-end justify-between gap-3">+ <Text variant="body-medium" className={primary ? "pb-1.5" : ""}>{window.label}</Text>- <Text variant="body" className="tabular-nums text-neutral-500">- {percentLabel}- </Text>+ {primary ? (+ <span className="flex items-baseline gap-1 whitespace-nowrap">+ <Text+ variant="h2"+ as="span"+ className="font-sans text-[44px] font-semibold leading-[50px] tracking-[-0.055em]"+ >+ {label}+ </Text>+ <Text as="span" variant="large" tone="secondary">+ %+ </Text>+ <Text as="span" variant="small" tone="secondary" className="ml-1">+ used+ </Text>+ <span className="sr-only">{label}% used</span>+ </span>+ ) : (+ <Text variant="small" tone="secondary">+ {label}% used+ </Text>+ )}</div>- <div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200">- <motion.div- role="progressbar"- aria-label={`${window.label} usage`}- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={percent}- initial={reduceMotion ? { width: `${percent}%` } : { width: 0 }}- animate={{ width: `${percent}%` }}- transition={- reduceMotion- ? undefined- : { duration: 0.9, ease: EASE_OUT, delay: 0.25 }- }- className={`h-full rounded-full ${- isHigh ? "bg-orange-500" : "bg-blue-500"- }`}+ <div+ role="progressbar"+ aria-label={`${window.label} usage`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={percent}+ className="h-2 overflow-hidden rounded-full bg-zinc-100"+ >+ <div+ className={`h-full rounded-full transition-[width] duration-300 motion-reduce:transition-none ${percent >= 100 ? "bg-orange-500" : "bg-purple-500"}`}+ style={{ width: `${percent}%` }}/></div>- <Text variant="small" className="text-neutral-400">- {window.prefix} <span className="text-neutral-700">{window.value}</span>- </Text>+ <div className="mt-3 flex items-start gap-1.5">+ <Icon+ icon={Clock01Icon}+ size={14}+ className="mt-0.5 shrink-0 text-zinc-500"+ />+ <Text variant="small" tone="secondary" className="text-xs leading-5">+ {window.prefix} {window.value}+ </Text>+ </div></div>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/UsageUnavailable.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/UsageUnavailable.tsxnew file mode 100644index 0000000000..f5ffa51354--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/UsageUnavailable.tsx@@ -0,0 +1,51 @@+import { Alert02Icon, RefreshIcon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { ENTERPRISE_CONTACT_URL } from "../YourPlanCard/useYourPlanCard";++interface Props {+ onRetry: () => void;+}++export function UsageUnavailable({ onRetry }: Props) {+ return (+ <section+ aria-label="Usage"+ className="flex h-full min-h-80 flex-col rounded-2xl border border-zinc-200 bg-white p-6"+ >+ <Text variant="large-medium" as="h2">+ Usage+ </Text>+ <div className="my-auto py-8">+ <span className="mb-4 flex size-9 items-center justify-center rounded-xl bg-zinc-100 text-zinc-600">+ <Icon icon={Alert02Icon} size={18} />+ </span>+ <Text variant="large-medium" className="mb-2">+ We couldn’t load your usage+ </Text>+ <Text variant="small" tone="secondary" className="leading-6">+ Your plan and your work aren’t affected. Try again in a moment.+ </Text>+ <div className="mt-5 flex flex-wrap items-center gap-3">+ <Button+ variant="secondary"+ size="small"+ onClick={onRetry}+ leftIcon={<Icon icon={RefreshIcon} size={14} aria-hidden="true" />}+ >+ Try again+ </Button>+ <Button+ as="NextLink"+ href={ENTERPRISE_CONTACT_URL}+ variant="ghost"+ size="small"+ >+ Contact support+ </Button>+ </div>+ </div>+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/useAutopilotUsageCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/useAutopilotUsageCard.tsindex 87262cf243..fb235d0ad4 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/useAutopilotUsageCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/AutopilotUsageCard/useAutopilotUsageCard.ts@@ -1,9 +1,11 @@"use client";-import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";-import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";--import { formatRelativeReset } from "../../../helpers";+import {+ getFeaturedUsagePercent,+ getUsageStatus,+} from "@/services/usageExperience/helpers";+import { useUsageExperience } from "@/services/usageExperience/useUsageExperience";+import { formatRelativeReset, formatShortDate } from "../../../helpers";export interface UsageWindowView {label: string;@@ -13,34 +15,67 @@ export interface UsageWindowView {}export function useAutopilotUsageCard() {- const { data, isLoading } = useGetV2GetCopilotUsage({- query: {- select: (res) => res.data as CoPilotUsagePublic | undefined,- refetchInterval: 30_000,- staleTime: 10_000,- },- });-- const today: UsageWindowView | null = data?.daily+ const { experience, usage, trial, isLoading, isError, retry } =+ useUsageExperience();+ const today: UsageWindowView | null = usage?.daily? {label: "Today",- percent: Math.round(data.daily.percent_used),- ...formatRelativeReset(data.daily.resets_at),+ percent: usage.daily.percent_used,+ ...formatRelativeReset(usage.daily.resets_at),}: null;-- const week: UsageWindowView | null = data?.weekly+ const week: UsageWindowView | null = usage?.weekly? {- label: "This Week",- percent: Math.round(data.weekly.percent_used),- ...formatRelativeReset(data.weekly.resets_at),+ label: "This week",+ percent: usage.weekly.percent_used,+ ...formatRelativeReset(usage.weekly.resets_at),}: null;-+ const showTrialWindow =+ experience.isLifetimeTrial ||+ (experience.isActiveTrial && experience.window === "trial");+ const trialWindow: UsageWindowView | null =+ showTrialWindow && experience.trialPercent != null+ ? {+ label: "Trial usage",+ percent: experience.trialPercent,+ prefix: "Trial ends",+ value: formatShortDate(trial?.ends_at),+ }+ : null;+ const featured = showTrialWindow+ ? trialWindow+ : experience.window === "weekly" || !today+ ? week+ : today;+ const secondary = showTrialWindow ? null : featured === week ? today : week;+ const status =+ USAGE_STATUS[getUsageStatus(getFeaturedUsagePercent(experience, usage))];return {+ status,+ featured,+ secondary,today,week,isLoading,- hasUsage: Boolean(today || week),+ isError,+ retry,+ isTrial: experience.isActiveTrial,+ lifetime: experience.isLifetimeTrial,+ blocked: experience.blocked,+ inactive: experience.tier === "NO_TIER",+ hasUsage: Boolean(featured || secondary),+ unlimited: Boolean(+ usage &&+ !experience.isActiveTrial &&+ usage.daily === null &&+ usage.weekly === null,+ ),};}++const USAGE_STATUS = {+ reached: { label: "Allowance reached", className: "text-orange-700" },+ low: { label: "Running low", className: "text-amber-700" },+ plenty: { label: "Plenty left", className: "text-zinc-500" },+};diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsxnew file mode 100644index 0000000000..76182f2f64--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsx@@ -0,0 +1,140 @@+"use client";++import { BillingPlanOffer } from "./BillingPlanOffer";+import { SupportOffer } from "./SupportOffer";+import { useProActivation } from "@/services/pro-activation/useProActivation";+import { useUsageExperience } from "@/services/usageExperience/useUsageExperience";+import {+ formatOfferPrice,+ formatTrialStartDescription,+ formatTrialStartTitle,+ getFeaturedUsagePercent,+ getUsageStatus,+} from "@/services/usageExperience/helpers";+import { formatCents } from "../../helpers";+import {+ ENTERPRISE_CONTACT_URL,+ TEAM_UPGRADE_URL,+ useYourPlanCard,+} from "./YourPlanCard/useYourPlanCard";++interface Props {+ controller?: ReturnType<typeof useYourPlanCard>;+}++export function BillingOffer({ controller }: Props) {+ const { experience, trial, subscription, usage } = useUsageExperience();+ const activation = useProActivation();+ const isTrial = experience.isActiveTrial;+ const target = isTrial+ ? trial?.offer?.tier === "PRO"+ ? "Pro"+ : null+ : controller?.plan?.nextTierLabel;+ const canUpgrade = isTrial+ ? target === "Pro"+ : controller?.canUpgrade && !controller.plan?.nextTierIsTeamLink;+ if (activation.isReady && experience.tier === "PRO")+ return (+ <SupportOffer+ eyebrow="AutoGPT Pro"+ title="Pro is active"+ description="Pro is active. Pick up where you left off with your conversations and agents."+ label="Back to your work"+ href="/copilot"+ ready+ />+ );+ if (!canUpgrade || !target)+ return (+ <SupportOffer+ eyebrow="Your plan"+ title="Need more capacity?"+ description={+ experience.tier === "ENTERPRISE"+ ? "For additional capacity or changes to your plan, your account team is ready to help."+ : "When your work calls for more capacity, talk with us about what you need."+ }+ label={+ experience.tier === "ENTERPRISE"+ ? "Contact account team"+ : "Contact us"+ }+ href={+ experience.tier === "MAX" ? TEAM_UPGRADE_URL : ENTERPRISE_CONTACT_URL+ }+ />+ );+ const price =+ isTrial && trial?.offer+ ? `${formatOfferPrice(trial.offer.unit_amount, trial.offer.currency)} / ${trial.offer.billing_cycle === "yearly" ? "year" : "month"}`+ : controller?.offerPriceCents !== undefined+ ? `${formatCents(controller.offerPriceCents)} / ${controller.plan?.billingCycle === "yearly" ? "year" : "month"}`+ : null;+ const multipliers = subscription?.tier_multipliers;+ const multiplier =+ multipliers?.MAX && multipliers?.PRO+ ? Math.round((multipliers.MAX / multipliers.PRO) * 10) / 10+ : null;+ const benefits = isTrial+ ? [+ "A full daily and weekly allowance once payment goes through",+ "Your chats, agents and files stay where they are",+ ]+ : target === "Max"+ ? [+ multiplier+ ? `${multiplier}× the usage of Pro`+ : "More room for demanding work",+ "More workspace storage and priority support",+ ]+ : [+ "Experts for content, sales and research, with Otto coordinating",+ "Agents that keep working in the background on a schedule",+ ];+ const quiet =+ isTrial &&+ getUsageStatus(getFeaturedUsagePercent(experience, usage)) === "plenty";+ const title = quiet+ ? formatTrialStartTitle(experience.trialEndsAt)+ : isTrial+ ? "Start Pro now"+ : `${experience.tier === "NO_TIER" ? "Start" : "Upgrade to"} ${target}`;+ return (+ <BillingPlanOffer+ target={target}+ title={title}+ quiet={quiet}+ description={+ isTrial && experience.freshProUsage+ ? quiet+ ? "Your trial keeps going until then. You can also start today."+ : formatTrialStartDescription(experience.trialEndsAt)+ : undefined+ }+ price={price}+ isTrialOffer={isTrial}+ benefits={benefits}+ actionLabel={+ quiet+ ? "Start Pro now"+ : isTrial && price+ ? `${title} · ${price.split(" / ")[0]}`+ : title+ }+ onAction={+ isTrial+ ? () => activation.start("/settings/billing")+ : controller?.onUpgrade+ }+ disabled={isTrial ? activation.isBusy : controller?.isUpdatingTier}+ caption={+ isTrial+ ? "Starting now ends your trial early. You’ll review the charge first."+ : target === "Max"+ ? "What you’ve already used counts toward Max’s higher limit."+ : "Review your options before paying."+ }+ />+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingPlanOffer.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingPlanOffer.tsxnew file mode 100644index 0000000000..b35758a8ac--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingPlanOffer.tsx@@ -0,0 +1,110 @@+import { SparklesIcon, Tick02Icon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";++interface Props {+ target: string;+ title: string;+ quiet?: boolean;+ description?: string;+ price: string | null;+ isTrialOffer?: boolean;+ benefits: string[];+ actionLabel: string;+ caption: string;+ onAction?: () => void;+ disabled?: boolean;+}++export function BillingPlanOffer({+ target,+ title,+ quiet = false,+ description,+ price,+ isTrialOffer = false,+ benefits,+ actionLabel,+ caption,+ onAction,+ disabled,+}: Props) {+ return (+ <section+ aria-label={`AutoGPT ${target}`}+ className={+ quiet+ ? "flex h-full flex-col rounded-2xl border border-zinc-200 bg-white p-6"+ : "flex h-full flex-col rounded-2xl border border-purple-200 bg-gradient-to-br from-purple-50 via-white to-blue-50 p-6"+ }+ >+ <div className="flex items-center gap-2.5">+ <span className="flex size-7 items-center justify-center rounded-lg bg-purple-100 text-purple-700">+ <Icon icon={SparklesIcon} size={17} />+ </span>+ <Text variant="small-medium" className="text-purple-800">+ AutoGPT {target}+ </Text>+ </div>+ <Text+ variant="h4"+ as="h2"+ className="mb-3 mt-4 text-[23px] leading-8 tracking-[-0.04em]"+ >+ {title}+ </Text>+ {description && (+ <Text variant="small" tone="secondary" className="mb-4 leading-6">+ {description}+ </Text>+ )}+ {price && (+ <div className="flex flex-wrap items-baseline gap-1.5">+ <Text+ variant="h2"+ unmask={!isTrialOffer}+ as="span"+ className="font-sans text-[36px] font-semibold leading-10 tracking-[-0.045em]"+ >+ {price.split(" / ")[0]}+ </Text>+ <Text as="span" variant="small" tone="secondary">+ / {price.split(" / ")[1]}+ </Text>+ </div>+ )}+ <ul className="my-5 space-y-2.5">+ {benefits.map((benefit) => (+ <li key={benefit} className="flex items-start gap-2">+ <Icon+ icon={Tick02Icon}+ size={15}+ className="mt-0.5 shrink-0 text-purple-700"+ />+ <Text variant="small" className="text-zinc-700">+ {benefit}+ </Text>+ </li>+ ))}+ </ul>+ <Button+ variant={quiet ? "secondary" : "primary"}+ size="large"+ className="mt-auto w-full"+ onClick={onAction}+ disabled={disabled}+ unmask={!isTrialOffer}+ >+ {actionLabel}+ </Button>+ <Text+ variant="small"+ tone="secondary"+ className="mt-2.5 text-center text-xs leading-5"+ >+ {caption}+ </Text>+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/InvoicesCard/InvoicesCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/InvoicesCard/InvoicesCard.tsxindex 6805ee718e..c9affcf747 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/InvoicesCard/InvoicesCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/InvoicesCard/InvoicesCard.tsx@@ -53,13 +53,13 @@ export function InvoicesCard({ index = 0 }: Props) {return (<motion.section {...sectionMotion} className="flex w-full flex-col gap-2">- <div className="px-4">+ <div className="px-1"><Text variant="body-medium" as="span" className="text-textBlack">Invoices</Text></div>- <div className="overflow-hidden rounded-[18px] border border-zinc-200 bg-white shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="overflow-hidden rounded-2xl border border-zinc-200 bg-white">{invoices.length === 0 ? (<div className="px-4 py-6"><Text variant="small" as="span" className="text-zinc-500">diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/PaymentMethodCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/PaymentMethodCard.tsxindex 935dc68359..8d54ecb98d 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/PaymentMethodCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/PaymentMethodCard.tsx@@ -22,13 +22,13 @@ export function PaymentMethodCard({ index = 0 }: Props) {{...getSectionMotionProps(index, Boolean(reduceMotion))}className="flex w-full flex-col gap-2">- <div className="px-4">+ <div className="sr-only"><Text variant="body-medium" as="span" className="text-textBlack">Payment method</Text></div>- <div className="flex flex-wrap items-center justify-between gap-4 rounded-[18px] border border-zinc-200 bg-white p-5 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-zinc-200 bg-white p-5"><div className="flex min-w-0 items-center gap-3"><div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-[10px] bg-zinc-100 text-zinc-700"><Icon icon={CreditCardIcon} size={20} />diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsxindex 1d3938c5b1..fd9f237b5c 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsx@@ -3,7 +3,9 @@import { Text } from "@/components/atoms/Text/Text";import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";+import { PaymentRecoveryCard } from "@/components/organisms/UsageExperience/PaymentRecoveryCard";+import { BillingOffer } from "./BillingOffer";import { AutopilotUsageCard } from "./AutopilotUsageCard/AutopilotUsageCard";import { InvoicesCard } from "./InvoicesCard/InvoicesCard";import { PaymentMethodCard } from "./PaymentMethodCard/PaymentMethodCard";@@ -16,12 +18,26 @@ interface Props {}export function SubscriptionTab({ isPlanCheckoutReturn = false }: Props) {- const { showPlan, showTrialCard, planChoicesOffer, isConfirmingPlan } =- useSubscriptionTab(isPlanCheckoutReturn);+ const {+ showPlan,+ showTrialCard,+ planChoicesOffer,+ isConfirmingPlan,+ isLoading,+ hasPlanChoices,+ paymentFailed,+ payment,+ } = useSubscriptionTab(isPlanCheckoutReturn);return (- <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-4"><TrialCheckoutConfirmation /><div className="flex flex-col gap-3 empty:hidden">+ {paymentFailed ? (+ <PaymentRecoveryCard+ payment={payment}+ fallback="Update your payment method below to continue. Your chats, agents and results are saved."+ />+ ) : null}{showTrialCard ? <TrialCard /> : null}{isConfirmingPlan ? (<Text variant="small" tone="secondary" role="status" className="px-4">@@ -32,8 +48,19 @@ export function SubscriptionTab({ isPlanCheckoutReturn = false }: Props) {<TrialPlanChoices offer={planChoicesOffer} />) : null}</div>- {showPlan ? <YourPlanCard index={0} /> : null}- <AutopilotUsageCard index={1} />+ {showPlan ? <YourPlanCard index={0} showUsage /> : null}+ {!showPlan && !isLoading && !paymentFailed ? (+ <div+ className={+ hasPlanChoices+ ? "grid gap-4"+ : "grid items-stretch gap-4 md:grid-cols-[1.15fr_1fr]"+ }+ >+ <AutopilotUsageCard index={1} />+ {!hasPlanChoices ? <BillingOffer /> : null}+ </div>+ ) : null}<PaymentMethodCard index={2} /><InvoicesCard index={3} /></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SupportOffer.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SupportOffer.tsxnew file mode 100644index 0000000000..7348b706fb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SupportOffer.tsx@@ -0,0 +1,57 @@+"use client";++import { Message01Icon, SparklesIcon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";++export function SupportOffer({+ eyebrow,+ title,+ description,+ label,+ href,+ ready = false,+}: {+ eyebrow: string;+ title: string;+ description: string;+ label: string;+ href: string;+ ready?: boolean;+}) {+ return (+ <section+ aria-label={ready ? "Your plan is ready" : "Plan support"}+ className="flex h-full flex-col rounded-2xl border border-zinc-200 bg-zinc-50/60 p-6"+ >+ <div className="flex items-center gap-2.5">+ <span className="flex size-7 items-center justify-center rounded-lg bg-white text-zinc-600 ring-1 ring-zinc-200">+ <Icon icon={ready ? SparklesIcon : Message01Icon} size={17} />+ </span>+ <Text variant="small-medium" className="text-zinc-600">+ {eyebrow}+ </Text>+ </div>+ <Text+ variant="h4"+ as="h2"+ className="mb-3 mt-4 text-[23px] leading-8 tracking-[-0.04em]"+ >+ {title}+ </Text>+ <Text variant="small" tone="secondary" className="mb-7 leading-6">+ {description}+ </Text>+ <Button+ variant="secondary"+ size="large"+ className="mt-auto w-full"+ as="NextLink"+ href={href}+ >+ {label}+ </Button>+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/MaxUpgradeReview.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/MaxUpgradeReview.tsxnew file mode 100644index 0000000000..c6f6c287da--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/MaxUpgradeReview.tsx@@ -0,0 +1,38 @@+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { MaxUpgradeSummary } from "./MaxUpgradeSummary";+import type { useTierUpgradePreview } from "./useTierUpgradePreview";++interface Props {+ review: ReturnType<typeof useTierUpgradePreview>;+}++export function MaxUpgradeReview({ review }: Props) {+ return (+ <div aria-live="polite">+ {review.isLoading && (+ <div className="space-y-3">+ <Text variant="small" tone="secondary">+ Reviewing your charge…+ </Text>+ <Skeleton className="h-48 rounded-2xl" />+ </div>+ )}+ {review.error && (+ <div+ role="alert"+ className="rounded-xl border border-orange-200 bg-orange-50 p-4"+ >+ <Text variant="small" className="mb-3 leading-6">+ {review.error}+ </Text>+ <Button variant="secondary" size="small" onClick={review.retry}>+ Retry review+ </Button>+ </div>+ )}+ {review.preview && <MaxUpgradeSummary preview={review.preview} />}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/MaxUpgradeSummary.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/MaxUpgradeSummary.tsxnew file mode 100644index 0000000000..b26088922c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/MaxUpgradeSummary.tsx@@ -0,0 +1,116 @@+import type { SubscriptionUpgradePreview } from "@/app/api/__generated__/models/subscriptionUpgradePreview";+import { Text } from "@/components/atoms/Text/Text";+import { formatAmount } from "@/services/pro-activation/helpers";++interface Props {+ preview: SubscriptionUpgradePreview;+}++export function formatUpgradeAmount(amount: number, currency: string) {+ return formatAmount(amount, currency);+}++function dateLabel(timestamp: number) {+ return new Date(timestamp * 1000).toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ });+}++export function MaxUpgradeSummary({ preview }: Props) {+ const amount = (cents: number) =>+ formatUpgradeAmount(cents, preview.currency);+ const unit = preview.billing_cycle === "yearly" ? "year" : "month";+ const recurringTax = preview.recurring_tax_included+ ? "including tax"+ : "plus applicable tax";+ return (+ <div className="overflow-hidden rounded-2xl border border-zinc-200">+ <div className="flex flex-wrap items-baseline justify-between gap-2 border-b border-zinc-200 bg-zinc-50 px-5 py-4">+ <Text variant="body-medium">+ Max{" "}+ <span className="font-normal text-zinc-500">+ · {preview.billing_cycle === "yearly" ? "Yearly" : "Monthly"}+ </span>+ </Text>+ <Text variant="small" tone="secondary" unmask={false}>+ {amount(preview.recurring_amount)} / {unit}+ </Text>+ </div>+ <div className="space-y-3.5 p-5">+ {preview.lines.map((line, index) => (+ <SummaryRow+ key={index}+ label={+ line.proration+ ? line.amount < 0+ ? "Unused Pro time"+ : `Max, ${dateLabel(line.period_start)} to ${dateLabel(line.period_end)}`+ : line.description+ }+ value={amount(line.amount)}+ />+ ))}+ <SummaryRow+ label={preview.tax_included ? "Tax (included)" : "Tax"}+ value={+ preview.tax_amount == null+ ? "See invoice"+ : amount(preview.tax_amount)+ }+ />+ {preview.adjustment_amount !== 0 && (+ <SummaryRow+ label="Other invoice adjustments"+ value={amount(preview.adjustment_amount)}+ />+ )}+ <div className="border-t border-zinc-200 pt-4">+ <SummaryRow+ label="Due today"+ value={amount(preview.amount_due)}+ emphasized+ />+ </div>+ <Text+ variant="small"+ tone="secondary"+ unmask={false}+ className="pt-2 leading-5"+ >+ Next renewal: {dateLabel(preview.period_end)}. Max’s regular price is{" "}+ {amount(preview.recurring_amount)} {recurringTax} per {unit}, before+ any applicable discounts or account credits.+ </Text>+ </div>+ </div>+ );+}++function SummaryRow({+ label,+ value,+ emphasized = false,+}: {+ label: string;+ value: string;+ emphasized?: boolean;+}) {+ return (+ <div className="flex items-start justify-between gap-4">+ <Text+ variant={emphasized ? "body-medium" : "small"}+ className={emphasized ? "text-zinc-900" : "text-zinc-600"}+ >+ {label}+ </Text>+ <Text+ variant={emphasized ? "body-medium" : "small"}+ unmask={false}+ className={`shrink-0 tabular-nums ${emphasized ? "text-zinc-900" : "text-zinc-600"}`}+ >+ {value}+ </Text>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsxindex 1907bbae87..24884114ff 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsx@@ -2,7 +2,11 @@import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";+import { formatCents } from "../../../helpers";import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { formatUpgradeAmount } from "./MaxUpgradeSummary";+import { MaxUpgradeReview } from "./MaxUpgradeReview";+import type { useTierUpgradePreview } from "./useTierUpgradePreview";interface Props {isOpen: boolean;@@ -13,6 +17,11 @@ interface Props {onConfirm: () => void;title?: string;confirmLabel?: string;+ priceCents?: number;+ billingCycle?: "monthly" | "yearly";+ usageCarriesOver?: boolean;+ usageMultiplier?: number;+ upgradeReview?: ReturnType<typeof useTierUpgradePreview>;}export function SwitchTierDialog({@@ -24,44 +33,160 @@ export function SwitchTierDialog({onConfirm,title,confirmLabel,+ priceCents,+ billingCycle = "monthly",+ usageCarriesOver = false,+ usageMultiplier,+ upgradeReview,}: Props) {+ const preview = upgradeReview?.preview;+ const reviewing = upgradeReview?.required;+ const cannotConfirm = isSaving || (reviewing && !preview);+ const action = preview+ ? `Pay ${formatUpgradeAmount(preview.amount_due, preview.currency)} and upgrade`+ : (confirmLabel ?? `Upgrade to ${targetTierLabel}`);return (<Dialog- title={title ?? `Upgrade to ${targetTierLabel}?`}- styling={{ maxWidth: "440px" }}+ variant="compact"+ title={+ <div className="space-y-2 pr-7">+ <Text variant="small" className="text-zinc-500">+ {title ? "Your subscription" : `Upgrade to ${targetTierLabel}`}+ </Text>+ <Text+ variant="h3"+ as="span"+ className="block text-[26px] leading-8 tracking-tight"+ >+ {title ?? `Upgrade to ${targetTierLabel}`}+ </Text>+ </div>+ }+ styling={{ maxWidth: "520px" }}controlled={{ isOpen, set: onOpenChange }}><Dialog.Content>- <div className="flex flex-col gap-4">- <Text variant="body" as="span" className="text-zinc-700">- {body}+ {usageCarriesOver && (+ <Text variant="body" className="mb-5 leading-6 text-zinc-600">+ {usageMultiplier+ ? `${usageMultiplier} times the usage of Pro and priority support.`+ : "More room for demanding work and priority support."}</Text>- </div>-- <Dialog.Footer>- <Button- type="button"- variant="ghost"- size="small"- onClick={() => onOpenChange(false)}- disabled={isSaving}- >- Cancel- </Button>- <Button- type="button"- variant="primary"- size="small"- onClick={onConfirm}- disabled={isSaving}- loading={isSaving}- data-fast-goal="subscription_change_confirm"- data-fast-goal-surface="settings_billing"+ )}+ {reviewing ? (+ <MaxUpgradeReview review={upgradeReview} />+ ) : (+ <>+ {priceCents !== undefined && (+ <div className="mb-5 flex flex-wrap items-baseline justify-between gap-3 rounded-2xl border border-zinc-200 bg-zinc-50 p-5">+ <Text variant="large-medium">AutoGPT {targetTierLabel}</Text>+ <div>+ <Text variant="h3" as="span">+ {formatCents(priceCents)}+ </Text>+ <Text variant="small" as="span" tone="secondary">+ {" "}+ / {billingCycle === "yearly" ? "year" : "month"}+ </Text>+ </div>+ </div>+ )}+ <Text variant="body" as="span" className="text-zinc-700">+ {body}+ </Text>+ </>+ )}+ {usageCarriesOver && (+ <Text+ variant="small"+ tone="secondary"+ className="mt-4 rounded-xl bg-zinc-50 p-4 leading-6">- {confirmLabel ?? `Upgrade to ${targetTierLabel}`}- </Button>+ You can keep going once payment goes through. What you’ve already+ used counts toward Max’s limit+ {usageMultiplier+ ? `, which is ${usageMultiplier} times as high as Pro’s.`+ : "."}+ </Text>+ )}+ <Dialog.Footer+ className={+ usageCarriesOver ? "flex-col items-stretch gap-2" : undefined+ }+ >+ {usageCarriesOver ? (+ <>+ <ConfirmButton+ label={action}+ unmask={!preview}+ disabled={cannotConfirm}+ isSaving={isSaving}+ onConfirm={onConfirm}+ />+ <Button+ type="button"+ variant="ghost"+ size="large"+ className="w-full"+ onClick={() => onOpenChange(false)}+ disabled={isSaving}+ >+ Keep Pro+ </Button>+ </>+ ) : (+ <>+ <Button+ type="button"+ variant="ghost"+ size="large"+ onClick={() => onOpenChange(false)}+ disabled={isSaving}+ >+ Cancel+ </Button>+ <ConfirmButton+ label={action}+ unmask={!preview}+ disabled={cannotConfirm}+ isSaving={isSaving}+ onConfirm={onConfirm}+ />+ </>+ )}</Dialog.Footer></Dialog.Content></Dialog>);}++function ConfirmButton({+ label,+ unmask,+ disabled,+ isSaving,+ onConfirm,+}: {+ label: string;+ unmask: boolean;+ disabled?: boolean;+ isSaving: boolean;+ onConfirm: () => void;+}) {+ return (+ <Button+ type="button"+ variant="primary"+ size="large"+ className="w-full"+ onClick={onConfirm}+ disabled={disabled}+ loading={isSaving}+ unmask={unmask}+ data-fast-goal="subscription_change_confirm"+ data-fast-goal-surface="settings_billing"+ >+ {label}+ </Button>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsxindex df12e14ec5..4ce1ecdd77 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx@@ -3,6 +3,9 @@import { motion, useReducedMotion } from "framer-motion";import { Badge } from "@/components/atoms/Badge/Badge";import { Button } from "@/components/atoms/Button/Button";+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { BillingOffer } from "../BillingOffer";+import { AutopilotUsageCard } from "../AutopilotUsageCard/AutopilotUsageCard";import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { Text } from "@/components/atoms/Text/Text";@@ -20,12 +23,16 @@ import { Icon } from "@/components/atoms/Icon/Icon";interface Props {index?: number;+ showUsage?: boolean;}-export function YourPlanCard({ index = 0 }: Props) {+export function YourPlanCard({ index = 0, showUsage = false }: Props) {const reduceMotion = useReducedMotion();+ const controller = useYourPlanCard();const {plan,+ isError,+ retry,isLoading,isUpdatingTier,canManagePortal,@@ -54,11 +61,12 @@ export function YourPlanCard({ index = 0 }: Props) {onDowngrade,onResume,onManage,- } = useYourPlanCard();+ } = controller;const sectionMotion = getSectionMotionProps(index, Boolean(reduceMotion));if (plan?.tierKey === "TRIAL") return null;+ if (isError) return <ErrorCard context="your subscription" onRetry={retry} />;if (isLoading || !plan) {return (@@ -69,17 +77,17 @@ export function YourPlanCard({ index = 0 }: Props) {}return (- <motion.section {...sectionMotion} className="flex w-full flex-col gap-2">- <div className="flex items-center gap-2 px-4">+ <motion.section {...sectionMotion} className="flex w-full flex-col gap-4">+ <div className="sr-only"><Text variant="body-medium" as="span" className="text-textBlack">Your plan</Text></div>- <div className="flex flex-wrap items-center justify-between gap-4 rounded-[18px] border border-zinc-200 bg-white p-5 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex flex-wrap items-center justify-between gap-x-5 gap-y-3 py-4"><div className="flex min-w-0 flex-col gap-2"><div className="flex flex-wrap items-center gap-2">- <Text variant="large-medium" as="span" className="text-textBlack">+ <Text variant="large-semibold" as="h2" className="text-textBlack">{plan.label}</Text><Badge@@ -191,7 +199,9 @@ export function YourPlanCard({ index = 0 }: Props) {Manage subscription</Button>) : null}- {canUpgrade && plan.nextTierLabel ? (+ {canUpgrade &&+ plan.nextTierLabel &&+ (!showUsage || !plan.isPaidPlan) ? (<Buttonvariant="primary"size="small"@@ -209,7 +219,7 @@ export function YourPlanCard({ index = 0 }: Props) {}>{!plan.isPaidPlan- ? `Get ${plan.nextTierLabel}`+ ? `Start ${plan.nextTierLabel}`: plan.nextTierIsTeamLink? `Talk to sales — ${plan.nextTierLabel}`: `Upgrade to ${plan.nextTierLabel}`}@@ -218,6 +228,13 @@ export function YourPlanCard({ index = 0 }: Props) {</div></div>+ {showUsage ? (+ <div className="grid items-stretch gap-4 md:grid-cols-[1.15fr_1fr]">+ <AutopilotUsageCard index={1} />+ <BillingOffer controller={controller} />+ </div>+ ) : null}+{pendingCycle ? (<SwitchCycleDialogisOpen={pendingCycle !== null}@@ -240,6 +257,13 @@ export function YourPlanCard({ index = 0 }: Props) {}}targetTierLabel={pendingTierUpgradeLabel}body={tierUpgradeDialogBody}+ priceCents={controller.offerPriceCents}+ billingCycle={plan.billingCycle}+ usageCarriesOver={+ plan.tierKey === "PRO" && pendingTierUpgrade === "MAX"+ }+ usageMultiplier={controller.upgradeUsageMultiplier}+ upgradeReview={controller.upgradeReview}isSaving={isUpdatingTier}onConfirm={onConfirmTierUpgrade}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useTierUpgradePreview.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useTierUpgradePreview.tsnew file mode 100644index 0000000000..7d58342601--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useTierUpgradePreview.ts@@ -0,0 +1,97 @@+import { useEffect, useState } from "react";+import { usePreviewSubscriptionUpgrade } from "@/app/api/__generated__/endpoints/credits/credits";+import type { SubscriptionUpgradePreview } from "@/app/api/__generated__/models/subscriptionUpgradePreview";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";++interface ReviewState {+ userID: string;+ billingCycle: "monthly" | "yearly";+ preview?: SubscriptionUpgradePreview;+ error?: string;+}++export function useTierUpgradePreview(+ enabled: boolean,+ billingCycle: "monthly" | "yearly",+) {+ const { mutateAsync } = usePreviewSubscriptionUpgrade();+ const userID = useAuthStore((state) => state.user?.id);+ const [state, setState] = useState<ReviewState>();+ const [attempt, setAttempt] = useState(0);+ const current =+ enabled && state?.userID === userID && state?.billingCycle === billingCycle;+ const preview = current ? state?.preview : undefined;+ const error = current ? (state?.error ?? "") : "";++ useEffect(() => {+ setState(undefined);+ if (!enabled || !userID) return;+ let current = true;+ const owner = { userID, billingCycle };+ void mutateAsync({ data: { tier: "MAX", billing_cycle: billingCycle } })+ .then((response) => {+ if (!current || useAuthStore.getState().user?.id !== userID) return;+ if (response.status !== 200) throw new Error("Review unavailable");+ if (response.data.expires_at * 1000 <= Date.now()) {+ setState({+ ...owner,+ error:+ "This review expired. Review the charge again before paying.",+ });+ return;+ }+ setState({ ...owner, preview: response.data });+ })+ .catch(() => {+ if (current && useAuthStore.getState().user?.id === userID)+ setState({+ ...owner,+ error: "We couldn’t load your charge. Try again before upgrading.",+ });+ });+ return () => {+ current = false;+ };+ }, [enabled, userID, billingCycle, attempt, mutateAsync]);++ useEffect(() => {+ if (!preview) return;+ const timer = setTimeout(+ () => {+ setState((value) =>+ value+ ? {+ ...value,+ preview: undefined,+ error:+ "This review expired. Review the charge again before paying.",+ }+ : value,+ );+ },+ Math.max(0, preview.expires_at * 1000 - Date.now()),+ );+ return () => clearTimeout(timer);+ }, [preview]);++ return {+ required: enabled,+ preview,+ error,+ isLoading: enabled && !preview && !error,+ retry: () => setAttempt((value) => value + 1),+ invalidate: (+ message = "Your billing details changed. Review the updated charge before paying.",+ ) => {+ setState((value) =>+ value+ ? {+ ...value,+ preview: undefined,+ error: message,+ }+ : value,+ );+ },+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.tsindex f0c29bb51e..af162effce 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts@@ -1,6 +1,9 @@"use client";import { useEffect, useState } from "react";+import { useSearchParams } from "next/navigation";+import { useQueryClient } from "@tanstack/react-query";+import { getGetV2GetCopilotUsageQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";import {useGetSubscriptionStatus,@@ -11,6 +14,7 @@ import type { GetV1ManagePaymentMethods200 } from "@/app/api/__generated__/modelimport type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";import type { SubscriptionTierRequestBillingCycle } from "@/app/api/__generated__/models/subscriptionTierRequestBillingCycle";import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";+import type { SubscriptionUpgradePreview } from "@/app/api/__generated__/models/subscriptionUpgradePreview";import { ApiError } from "@/lib/autogpt-server-api/helpers";import { toast } from "@/components/molecules/Toast/use-toast";import {@@ -26,6 +30,7 @@ import {import { formatCents, formatShortDate } from "../../../helpers";import { getCheckoutReturnURLs } from "../helpers";+import { useTierUpgradePreview } from "./useTierUpgradePreview";const PLAN_LABEL: Record<string, string> = {NO_TIER: "No active subscription",@@ -68,6 +73,9 @@ function getPreviousTier(current: string): SubscriptionTierRequestTier | null {}export function useYourPlanCard() {+ const queryClient = useQueryClient();+ const searchParams = useSearchParams();+ const [handledUpgrade, setHandledUpgrade] = useState(false);const subscription = useGetSubscriptionStatus({query: {select: (res) =>@@ -115,6 +123,12 @@ export function useYourPlanCard() {// explicit feedback that the action took effect.const [pendingTierDowngrade, setPendingTierDowngrade] =useState<SubscriptionTierRequestTier | null>(null);+ const upgradeReview = useTierUpgradePreview(+ pendingTierUpgrade === "MAX" &&+ effectiveTier === "PRO" &&+ subscription.data?.has_active_stripe_subscription === true,+ serverCycle,+ );// Re-sync local toggle when the server response updates (e.g. after refetch// post-mutation). Avoids stale "yearly" pill after a successful switch.@@ -224,11 +238,12 @@ export function useYourPlanCard() {async function changeTier(tier: SubscriptionTierRequestTier,billingCycle?: SubscriptionTierRequestBillingCycle,+ preview?: SubscriptionUpgradePreview,) {if (isUpdatingTier) return false;setIsChangingTier(true);try {- return await requestTierChange(tier, billingCycle);+ return await requestTierChange(tier, billingCycle, preview);} finally {setIsChangingTier(false);}@@ -237,6 +252,7 @@ export function useYourPlanCard() {async function requestTierChange(tier: SubscriptionTierRequestTier,billingCycle?: SubscriptionTierRequestBillingCycle,+ preview?: SubscriptionUpgradePreview,) {const cycle = billingCycle ?? "monthly";const { successURL, cancelURL } = getCheckoutReturnURLs({ tier, cycle });@@ -247,6 +263,12 @@ export function useYourPlanCard() {success_url: successURL,cancel_url: cancelURL,...(billingCycle ? { billing_cycle: billingCycle } : {}),+ ...(preview+ ? {+ preview_id: preview.preview_id,+ proration_date: preview.proration_date,+ }+ : {}),surface: "billing",},});@@ -267,9 +289,26 @@ export function useYourPlanCard() {window.location.href = url;return;}- await subscription.refetch();+ await Promise.all([+ subscription.refetch(),+ queryClient.invalidateQueries({+ queryKey: getGetV2GetCopilotUsageQueryKey(),+ }),+ ]);return true;} catch (error) {+ if (+ preview &&+ error instanceof ApiError &&+ (error.status === 409 || error.status === 402)+ ) {+ upgradeReview.invalidate(+ error.status === 402+ ? "Payment wasn’t completed. Check your payment method, then review the charge again."+ : undefined,+ );+ return false;+ }// 422 fail-closed on a YEARLY request = LD missing the *_YEARLY price for// this tier. Match billingCycle === "yearly" specifically — a 422 on a// monthly request is a different failure (e.g. tier unconfigured) and@@ -497,6 +536,24 @@ export function useYourPlanCard() {].filter((line): line is { label?: string; text: string } => line !== null);}+ useEffect(() => {+ if (handledUpgrade || !subscription.data) return;+ if (+ searchParams.get("upgrade") === "MAX" &&+ effectiveTier === "PRO" &&+ !pendingTier+ ) {+ setPendingTierUpgrade("MAX");+ setHandledUpgrade(true);+ }+ }, [+ searchParams,+ handledUpgrade,+ subscription.data,+ effectiveTier,+ pendingTier,+ ]);+function getTierUpgradeDialogBody(): string {if (!pendingTierUpgrade) return "";const targetCents =@@ -513,6 +570,7 @@ export function useYourPlanCard() {return [`You'll be charged the prorated difference immediately for the rest of your ${cycleNoun} period.`,renewLine,+ "Your current usage carries over into the higher allowance.",].filter(Boolean).join(" ");@@ -520,10 +578,10 @@ export function useYourPlanCard() {async function confirmTierUpgrade() {if (!pendingTierUpgrade) return;+ if (upgradeReview.required && !upgradeReview.preview) return;const target = pendingTierUpgrade;- const ok = await changeTier(target, serverCycle);- setPendingTierUpgrade(null);- if (!ok) return;+ const ok = await changeTier(target, serverCycle, upgradeReview.preview);+ if (ok) setPendingTierUpgrade(null);}function cancelTierUpgrade() {@@ -563,7 +621,24 @@ export function useYourPlanCard() {return {plan,isLoading: subscription.isLoading,+ isError: subscription.isError,+ retry: () => void subscription.refetch(),+ offerPriceCents: nextTierKey+ ? serverCycle === "yearly"+ ? tierCostsYearly[nextTierKey]+ : tierCosts[nextTierKey]+ : undefined,isUpdatingTier,+ upgradeReview,+ upgradeUsageMultiplier:+ subscription.data?.tier_multipliers?.MAX &&+ subscription.data.tier_multipliers.PRO+ ? Math.round(+ (subscription.data.tier_multipliers.MAX /+ subscription.data.tier_multipliers.PRO) *+ 10,+ ) / 10+ : undefined,// ENTERPRISE has no Stripe subscription to manage; the Payment method// card still exposes the portal for cards and invoices.canManagePortal: Boolean(paymentPortal.data) && !isAdminManaged,@@ -634,7 +709,10 @@ export function useYourPlanCard() {// success_url redirect — there's no immediate proration risk, so go// straight to changeTier without a confirm step. Only paid→paid// upgrades hit the always_invoice immediate-billing path.- if (!plan.isPaidPlan) {+ if (+ !plan.isPaidPlan &&+ !subscription.data?.has_active_stripe_subscription+ ) {void changeTier(plan.nextTier, selectedCycle);return;}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.tsindex ed9b167090..8bb6ba199b 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.ts@@ -2,6 +2,7 @@import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";import { useTrialStatus } from "@/services/trials/useTrialStatus";+import { usePaymentRecovery } from "@/services/usageExperience/usePaymentRecovery";import { isPaidTier, readTier } from "./helpers";import { getCancelPendingOffer } from "./TrialPlanChoices/helpers";@@ -11,6 +12,7 @@ export function useSubscriptionTab(isPlanCheckoutReturn: boolean) {const { data: trial, isLoading } = useTrialStatus();const tier = useGetSubscriptionStatus({ query: { select: readTier } });const { isConfirmingPlan } = usePlanCheckoutReturn(isPlanCheckoutReturn);+ const { paymentFailed, payment } = usePaymentRecovery(tier.data);// An ended trial that a paid plan replaced is history, not the plan; it// waits for the tier so it never flashes above the plan card.const isEndedTrial = Boolean(trial && !trial.eligible && !trial.active);@@ -27,9 +29,16 @@ export function useSubscriptionTab(isPlanCheckoutReturn: boolean) {const cancelPendingOffer = getCancelPendingOffer(trial);return {+ isLoading,+ paymentFailed,+ payment,+ hasPlanChoices: Boolean(cancelPendingOffer),showPlan:- !isLoading && (!trial?.active || trial.converted || isSupersededTrial),- showTrialCard: !(isEndedTrial && isReplaced) && !isSupersededTrial,+ !paymentFailed &&+ !isLoading &&+ (!trial?.active || trial.converted || isSupersededTrial),+ showTrialCard:+ !paymentFailed && !(isEndedTrial && isReplaced) && !isSupersededTrial,planChoicesOffer: isConfirmingPlan ? null : cancelPendingOffer,isConfirmingPlan: Boolean(cancelPendingOffer) && isConfirmingPlan,};diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsxindex ae8275d50d..073d5de4dc 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx@@ -116,7 +116,7 @@ function SettingsBillingPage() {if (subscriptionStatus === "success") {toast({- title: "Subscription updated",+ title: "Confirming your subscription",description:"Your new plan is being applied. It may take a moment to reflect.",});@@ -151,13 +151,18 @@ function SettingsBillingPage() {);return (- <div className="flex flex-col gap-4 pb-8 sm:gap-6">- <Text variant="h4" as="h1" className="pl-4 leading-[28px] text-textBlack">- Billing- </Text>+ <div className="mx-auto flex w-full max-w-[900px] flex-col gap-5 px-4 pb-8 sm:px-6">+ <header className="space-y-1">+ <Text variant="h3" as="h1" className="tracking-[-0.035em]">+ Billing & usage+ </Text>+ <Text variant="body" tone="secondary">+ Everything you need to manage your plan.+ </Text>+ </header><TabsLine value={activeTab} onValueChange={handleTabChange}>- <TabsLineList flush className="ml-4 overflow-x-auto">+ <TabsLineList flush className="overflow-x-auto"><TabsLineTrigger value="subscription">Subscription</TabsLineTrigger><TabsLineTrigger value="automation-credits">Automation Creditsdiff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsxindex 069e57366d..e501549bb5 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/integrations.test.tsx@@ -3,6 +3,10 @@ import {getListExpertCredentialsMockHandler,getListExpertRunsMockHandler,} from "@/app/api/__generated__/endpoints/experts/experts.msw";+import {+ getGetHomeDashboardMockHandler,+ getGetHomeDashboardResponseMock200,+} from "@/app/api/__generated__/endpoints/home/home.msw";import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";import type { Expert } from "@/app/api/__generated__/models/expert";import type { ExpertCredentialRef } from "@/app/api/__generated__/models/expertCredentialRef";@@ -113,6 +117,9 @@ const linkedin: ExpertCredentialRef = {beforeEach(() => {server.use(+ getGetHomeDashboardMockHandler(+ getGetHomeDashboardResponseMock200({ attention: [] }),+ ),getGetExpertMockHandler(maria),getGetV1ListExecutionSchedulesForAUserMockHandler([]),getListExpertRunsMockHandler([]),diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 02a7971f08..d56e69bf88 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -6108,6 +6108,47 @@"security": [{ "HTTPBearerJWT": [] }]}},+ "/api/credits/subscription/preview": {+ "post": {+ "tags": ["v1", "credits"],+ "summary": "Review the prorated charge for a paid Pro-to-Max upgrade",+ "operationId": "previewSubscriptionUpgrade",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubscriptionUpgradePreviewRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubscriptionUpgradePreview"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },"/api/credits/transactions": {"get": {"tags": ["v1", "credits"],@@ -18635,6 +18676,31 @@"type": "string","format": "date-time","title": "Expires At"+ },+ "trial_ends_at": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "title": "Trial Ends At"+ },+ "period_starts_at": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "title": "Period Starts At"+ },+ "next_payment_at": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "title": "Next Payment At"+ },+ "tax_amount": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Tax Amount"}},"type": "object",@@ -32994,6 +33060,20 @@"title": "Billing Cycle","default": "monthly"},+ "proration_date": {+ "anyOf": [+ { "type": "integer", "exclusiveMinimum": 0.0 },+ { "type": "null" }+ ],+ "title": "Proration Date"+ },+ "preview_id": {+ "anyOf": [+ { "type": "string", "pattern": "^[a-f0-9]{32}$" },+ { "type": "null" }+ ],+ "title": "Preview Id"+ },"surface": {"anyOf": [{@@ -33010,6 +33090,74 @@"required": ["tier"],"title": "SubscriptionTierRequest"},+ "SubscriptionUpgradePreview": {+ "properties": {+ "preview_id": { "type": "string", "title": "Preview Id" },+ "amount_due": { "type": "integer", "title": "Amount Due" },+ "tax_amount": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Tax Amount"+ },+ "tax_included": { "type": "boolean", "title": "Tax Included" },+ "adjustment_amount": {+ "type": "integer",+ "title": "Adjustment Amount"+ },+ "currency": { "type": "string", "title": "Currency" },+ "proration_date": { "type": "integer", "title": "Proration Date" },+ "period_end": { "type": "integer", "title": "Period End" },+ "expires_at": { "type": "integer", "title": "Expires At" },+ "recurring_amount": {+ "type": "integer",+ "title": "Recurring Amount"+ },+ "recurring_tax_included": {+ "type": "boolean",+ "title": "Recurring Tax Included"+ },+ "billing_cycle": {+ "type": "string",+ "enum": ["monthly", "yearly"],+ "title": "Billing Cycle"+ },+ "lines": {+ "items": { "$ref": "#/components/schemas/UpgradeProrationLine" },+ "type": "array",+ "title": "Lines"+ }+ },+ "type": "object",+ "required": [+ "preview_id",+ "amount_due",+ "tax_amount",+ "tax_included",+ "adjustment_amount",+ "currency",+ "proration_date",+ "period_end",+ "expires_at",+ "recurring_amount",+ "recurring_tax_included",+ "billing_cycle",+ "lines"+ ],+ "title": "SubscriptionUpgradePreview"+ },+ "SubscriptionUpgradePreviewRequest": {+ "properties": {+ "tier": { "type": "string", "const": "MAX", "title": "Tier" },+ "billing_cycle": {+ "type": "string",+ "enum": ["monthly", "yearly"],+ "title": "Billing Cycle",+ "default": "monthly"+ }+ },+ "type": "object",+ "required": ["tier"],+ "title": "SubscriptionUpgradePreviewRequest"+ },"SuggestedGoalResponse": {"properties": {"type": {@@ -34194,6 +34342,16 @@],"title": "TrialOfferResponse"},+ "TrialPaymentDue": {+ "properties": {+ "amount_due": { "type": "integer", "title": "Amount Due" },+ "currency": { "type": "string", "title": "Currency" },+ "payment_url": { "type": "string", "title": "Payment Url" }+ },+ "type": "object",+ "required": ["amount_due", "currency", "payment_url"],+ "title": "TrialPaymentDue"+ },"TrialRejectionReason": {"type": "string","enum": ["intro_offer_already_used", "card_verification_failed"],@@ -34238,6 +34396,13 @@"anyOf": [{ "type": "number" }, { "type": "null" }],"title": "Allowance Used Percent"},+ "usage_policy": {+ "anyOf": [+ { "type": "string", "enum": ["lifetime", "rolling"] },+ { "type": "null" }+ ],+ "title": "Usage Policy"+ },"active": { "type": "boolean", "title": "Active", "default": false },"converted": {"type": "boolean",@@ -34248,6 +34413,12 @@"type": "boolean","title": "Onboarding Credits Previously Received","default": false+ },+ "payment_due": {+ "anyOf": [+ { "$ref": "#/components/schemas/TrialPaymentDue" },+ { "type": "null" }+ ]}},"type": "object",@@ -35105,6 +35276,24 @@"required": ["timezone"],"title": "UpdateTimezoneRequest"},+ "UpgradeProrationLine": {+ "properties": {+ "description": { "type": "string", "title": "Description" },+ "amount": { "type": "integer", "title": "Amount" },+ "period_start": { "type": "integer", "title": "Period Start" },+ "period_end": { "type": "integer", "title": "Period End" },+ "proration": { "type": "boolean", "title": "Proration" }+ },+ "type": "object",+ "required": [+ "description",+ "amount",+ "period_start",+ "period_end",+ "proration"+ ],+ "title": "UpgradeProrationLine"+ },"UploadCopilotSkillRequest": {"properties": { "content": { "type": "string", "title": "Content" } },"type": "object",diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCopilotUsage.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCopilotUsage.test.tsxindex ea46035e04..220c53ace5 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCopilotUsage.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCopilotUsage.test.tsx@@ -13,6 +13,7 @@ import {setTrialUser,trialResponse,} from "@/tests/integrations/trial-fixtures";+import { TrialStatusSync } from "@/services/trials/TrialStatusSync";import { WalletCopilotUsage } from "../components/WalletCopilotUsage";const future = new Date("2030-09-17T15:00:00Z");@@ -145,7 +146,7 @@ describe("WalletCopilotUsage", () => {expect(screen.queryByText("100% used")).toBeNull();});- it("refreshes trial allowance while the wallet stays open", async () => {+ it("reads allowance refreshed by the shared platform observer while the wallet stays open", async () => {vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });setTrialUser();mockUsage(0, 0, "TRIAL");@@ -155,7 +156,12 @@ describe("WalletCopilotUsage", () => {trialResponse({ allowance_used_percent: allowanceUsed }),),);- render(<WalletCopilotUsage />);+ render(+ <>+ <TrialStatusSync />+ <WalletCopilotUsage />+ </>,+ );expect(await screen.findByText("12% used")).toBeDefined();allowanceUsed = 54;diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCopilotUsage.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCopilotUsage.tsxindex 677cb1e699..e6d1ad55bc 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCopilotUsage.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCopilotUsage.tsx@@ -83,13 +83,7 @@ function UsageWindows({ usage }: { usage: CoPilotUsagePublic }) {}function TrialUsage() {- const {- data: trial,- isPending,- refetch,- } = useTrialStatus({- refetchInterval: 30_000,- });+ const { data: trial, isPending, refetch } = useTrialStatus();if (isPending) return <UsageLoading />;if (trial?.allowance_used_percent == null) {return <UsageUnavailable onRetry={() => void refetch()} />;diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationPaymentMethod.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationPaymentMethod.tsxnew file mode 100644index 0000000000..426543f678--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationPaymentMethod.tsx@@ -0,0 +1,37 @@+import { useGetV1ManagePaymentMethods } from "@/app/api/__generated__/endpoints/credits/credits";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { CreditCardIcon, LinkSquare01Icon } from "@hugeicons/core-free-icons";++export function ActivationPaymentMethod() {+ const { data } = useGetV1ManagePaymentMethods({ query: { retry: false } });+ const raw = data?.data;+ const portal =+ raw && typeof raw === "object" && "url" in raw ? raw.url : null;+ const url =+ typeof portal === "string" &&+ /^https:\/\/billing\.stripe\.com\//.test(portal)+ ? portal+ : null;+ return (+ <div className="flex items-center justify-between gap-3 rounded-large border border-zinc-200 px-4 py-3">+ <div className="flex items-center gap-2 text-sm text-zinc-600">+ <Icon icon={CreditCardIcon} size={18} />+ Payment method+ </div>+ <Button+ as="NextLink"+ href={url ?? "/settings/billing"}+ target="_blank"+ rel="noopener noreferrer"+ variant="ghost"+ size="small"+ className="h-auto min-w-0 p-0 text-sm underline underline-offset-4"+ aria-label="Manage payment method in a new tab"+ >+ Manage+ <Icon icon={LinkSquare01Icon} size={14} />+ </Button>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationStatus.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationStatus.tsxnew file mode 100644index 0000000000..c5e7f225fb--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationStatus.tsx@@ -0,0 +1,124 @@+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { Icon } from "@/components/atoms/Icon/Icon";+import {+ CheckmarkCircle02Icon,+ Loading03Icon,+ Shield01Icon,+} from "@hugeicons/core-free-icons";+import { invoiceURL } from "@/services/pro-activation/helpers";++interface Props {+ attempt: ActivationResponse | null;+ isReady: boolean;+ hasFreshUsage: boolean;+ plan: "Pro" | "Max";+ isBusy: boolean;+ check: () => Promise<void>;+ close: () => void;+}++export function ActivationStatus({+ attempt,+ isReady,+ hasFreshUsage,+ plan,+ isBusy,+ check,+ close,+}: Props) {+ const url = invoiceURL(attempt?.hosted_invoice_url);+ const payment =+ attempt?.status === "payment_required" ||+ attempt?.status === "action_required";+ const failed = attempt?.status === "failed";+ const notApplicable = attempt?.status === "not_applicable";+ const needsSupport = ["recovery_required", "terms_changed"].includes(+ attempt?.error_code ?? "",+ );+ return (+ <div className="space-y-6">+ <div className="rounded-xlarge border border-zinc-200 bg-zinc-50 p-5">+ <Icon+ icon={+ isReady+ ? CheckmarkCircle02Icon+ : payment+ ? Shield01Icon+ : Loading03Icon+ }+ size={24}+ className={+ !isReady && !payment && !failed && !notApplicable+ ? "mb-4 animate-spin text-violet-600"+ : "mb-4 text-violet-600"+ }+ />+ <Text variant="body" className="text-zinc-700">+ {isReady+ ? hasFreshUsage+ ? `Your ${plan} plan is active with fresh daily and weekly allowances. Your conversations and work are right where you left them.`+ : `Your ${plan} plan is active. Your existing usage still counts toward your plan’s limits.`+ : notApplicable+ ? "This activation no longer applies to your current plan. Check Billing for your current plan and payment details."+ : payment+ ? "Complete payment securely with Stripe using your existing invoice. It opens in a new tab, keeping your draft here while we check your activation."+ : failed+ ? "This payment was canceled or could not be completed. Your usage has not been reset."+ : needsSupport+ ? "We need to verify your existing payment before you can continue. Contact support; please don’t start another purchase."+ : `We’re confirming your payment and preparing your ${plan} allowance. You can close this window; we’ll keep checking.`}+ </Text>+ </div>+ {notApplicable && (+ <Button+ as="NextLink"+ href="/settings/billing"+ variant="primary"+ className="w-full"+ onClick={close}+ >+ View my plan+ </Button>+ )}+ {url && payment && (+ <Button+ as="NextLink"+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ variant="primary"+ className="w-full"+ >+ {attempt?.status === "action_required"+ ? "Verify payment securely"+ : "Complete payment securely"}+ </Button>+ )}+ {needsSupport && (+ <Button+ as="NextLink"+ href="mailto:[email protected]"+ variant="primary"+ className="w-full"+ >+ Contact support+ </Button>+ )}+ <Button+ onClick={() => (isReady || failed || notApplicable ? close() : check())}+ disabled={isBusy}+ loading={isBusy}+ variant={isReady ? "primary" : "secondary"}+ className="w-full"+ >+ {isReady+ ? "Continue where you left off"+ : failed || notApplicable+ ? "Back to your work"+ : "Check activation status"}+ </Button>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationSummary.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationSummary.tsxnew file mode 100644index 0000000000..17625a598d--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationSummary.tsx@@ -0,0 +1,75 @@+import type { ActivationTerms } from "@/app/api/__generated__/models/activationTerms";+import { formatAmount, intervalLabel } from "@/services/pro-activation/helpers";+import {+ billingCadence,+ invoiceAdjustment,+ shortDate,+} from "@/services/pro-activation/reviewDetails";++interface Props {+ terms: ActivationTerms;+}++export function ActivationSummary({ terms }: Props) {+ const plan = terms.plan === "MAX" ? "Max" : "Pro";+ const cadence = billingCadence(terms);+ const adjustment = invoiceAdjustment(terms);+ const period =+ terms.period_starts_at && terms.next_payment_at+ ? `${plan}, ${shortDate(terms.period_starts_at)} to ${shortDate(terms.next_payment_at)}`+ : `${plan} subscription`;+ return (+ <div className="overflow-hidden rounded-xlarge border border-zinc-200">+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1 border-b border-zinc-200 bg-zinc-50 px-4 py-3.5">+ <p className="text-sm text-zinc-500">+ <span className="text-base font-semibold text-zinc-900">{plan}</span>{" "}+ ·{" "}+ <span className="capitalize">+ {cadence.charAt(0).toUpperCase() + cadence.slice(1)}+ </span>+ </p>+ <p className="text-sm tabular-nums text-zinc-600">+ {formatAmount(terms.renewal_unit_amount, terms.currency)} /{" "}+ {intervalLabel(+ terms.billing_interval,+ terms.billing_interval_count ?? 1,+ )}+ </p>+ </div>+ <dl className="space-y-3.5 p-4 text-sm text-zinc-600">+ <div className="flex items-start justify-between gap-4">+ <dt>{period}</dt>+ <dd className="shrink-0 tabular-nums">+ {formatAmount(terms.renewal_unit_amount, terms.currency)}+ </dd>+ </div>+ {!!adjustment && (+ <div className="flex items-start justify-between gap-4">+ <dt>Discounts, credits & adjustments</dt>+ <dd className="shrink-0 tabular-nums">+ {formatAmount(adjustment, terms.currency)}+ </dd>+ </div>+ )}+ <div className="flex items-start justify-between gap-4">+ <dt>+ {terms.renewal_tax?.price_tax_behavior === "inclusive"+ ? "Tax (included)"+ : "Tax"}+ </dt>+ <dd className="shrink-0 tabular-nums">+ {terms.tax_amount == null+ ? "Included in total"+ : formatAmount(terms.tax_amount, terms.currency)}+ </dd>+ </div>+ <div className="flex items-baseline justify-between gap-4 border-t border-zinc-200 pt-3.5 text-base font-semibold text-zinc-900">+ <dt>Due today</dt>+ <dd className="tabular-nums">+ {formatAmount(terms.amount_due, terms.currency)}+ </dd>+ </div>+ </dl>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationTerms.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationTerms.tsxnew file mode 100644index 0000000000..ee4fcb7e7c--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationTerms.tsx@@ -0,0 +1,23 @@+import type { ActivationTerms as Terms } from "@/app/api/__generated__/models/activationTerms";+import { Text } from "@/components/atoms/Text/Text";+import { trialEndNotice } from "@/services/pro-activation/reviewDetails";+import { ActivationSummary } from "./ActivationSummary";+import { ActivationTimeline } from "./ActivationTimeline";+import { RenewalDetails } from "./RenewalDetails";++interface Props {+ terms: Terms;+}++export function ActivationTerms({ terms }: Props) {+ return (+ <div className="space-y-5">+ <Text variant="body" className="leading-relaxed text-zinc-600">+ {trialEndNotice(terms)}+ </Text>+ <ActivationSummary terms={terms} />+ <ActivationTimeline terms={terms} />+ <RenewalDetails terms={terms} />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationTimeline.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationTimeline.tsxnew file mode 100644index 0000000000..c9d93ecfe1--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/ActivationTimeline.tsx@@ -0,0 +1,40 @@+import type { ActivationTerms } from "@/app/api/__generated__/models/activationTerms";+import {+ nextPaymentDescription,+ shortDate,+} from "@/services/pro-activation/reviewDetails";++interface Props {+ terms: ActivationTerms;+}++export function ActivationTimeline({ terms }: Props) {+ const plan = terms.plan === "MAX" ? "Max" : "Pro";+ return (+ <ol className="space-y-4 text-sm">+ <li className="relative grid grid-cols-[0.75rem_4.5rem_1fr] gap-x-3 before:absolute before:bottom-[-1rem] before:left-[5px] before:top-4 before:w-px before:bg-zinc-200">+ <span+ aria-hidden="true"+ className="mt-1.5 h-2.5 w-2.5 rounded-full bg-zinc-900"+ />+ <span className="font-medium text-zinc-900">Today</span>+ <span className="leading-relaxed text-zinc-600">+ After payment succeeds, {plan} starts and your daily and weekly+ allowances reset.+ </span>+ </li>+ <li className="grid grid-cols-[0.75rem_4.5rem_1fr] gap-x-3">+ <span+ aria-hidden="true"+ className="mt-1.5 h-2.5 w-2.5 rounded-full border border-zinc-400 bg-white"+ />+ <span className="font-medium text-zinc-900">+ {terms.next_payment_at ? shortDate(terms.next_payment_at) : "Renewal"}+ </span>+ <span className="leading-relaxed text-zinc-600">+ {nextPaymentDescription(terms)}+ </span>+ </li>+ </ol>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/ProActivationDialog.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/ProActivationDialog.tsxnew file mode 100644index 0000000000..1f8c1734f0--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/ProActivationDialog.tsx@@ -0,0 +1,157 @@+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { Text } from "@/components/atoms/Text/Text";+import { Button } from "@/components/atoms/Button/Button";+import type { useActivationController } from "@/services/pro-activation/useActivationController";+import { formatAmount } from "@/services/pro-activation/helpers";+import { ActivationTerms } from "./ActivationTerms";+import { ActivationStatus } from "./ActivationStatus";+import { ActivationPaymentMethod } from "./ActivationPaymentMethod";+import { billingCadence } from "@/services/pro-activation/reviewDetails";+import { useQuoteExpiry } from "@/services/pro-activation/useQuoteExpiry";++interface Props {+ activation: ReturnType<typeof useActivationController>;+}++export function ProActivationDialog({ activation }: Props) {+ const {+ attempt,+ isOpen,+ setOpen,+ isBusy,+ isReady,+ hasFreshUsage,+ readyPlan,+ error,+ needsNewTerms,+ retryConsent,+ confirm,+ check,+ start,+ } = activation;+ const review = attempt?.status === "confirmation_required" && attempt.terms;+ const expiry = useQuoteExpiry(review ? review.expires_at : undefined);+ const refreshTerms = needsNewTerms || (expiry.expired && !retryConsent);+ const plan = (attempt?.terms?.plan ?? readyPlan) === "MAX" ? "Max" : "Pro";+ const title = isReady+ ? `${plan} is active`+ : review+ ? `Start ${plan} today`+ : attempt?.status === "not_applicable"+ ? "Your plan has changed"+ : attempt?.status === "failed"+ ? "Your payment wasn’t completed."+ : attempt?.status === "action_required" ||+ attempt?.status === "payment_required"+ ? `One more step to start ${plan}.`+ : `Getting ${plan} ready.`;+ return (+ <Dialog+ variant="compact"+ controlled={{ isOpen, set: setOpen }}+ styling={{ maxWidth: "560px" }}+ title={+ <div className="space-y-2 pr-7">+ <Text variant="small" className="font-medium text-zinc-500">+ {review ? "Payment review" : `AutoGPT ${plan}`}+ </Text>+ <span className="block text-[26px] font-semibold leading-[1.2] tracking-[-0.6px] text-zinc-900">+ {title}+ </span>+ </div>+ }+ >+ <Dialog.Content>+ <div className="space-y-5">+ {error && (+ <div+ role="alert"+ className="rounded-large border border-amber-200 bg-amber-50 p-4 text-sm text-zinc-700"+ >+ {error}+ </div>+ )}+ {review ? (+ <>+ <ActivationTerms terms={review} />+ <ActivationPaymentMethod />+ {expiry.expiringSoon && !retryConsent && (+ <Text variant="small" className="text-amber-700">+ This price is held for a few more minutes.+ </Text>+ )}+ {expiry.expired && !retryConsent && (+ <Text variant="small" className="text-amber-700" role="status">+ This quote has expired. Review the current terms before+ paying.+ </Text>+ )}+ <Button+ variant="primary"+ className="w-full"+ disabled={isBusy || refreshTerms}+ loading={isBusy}+ onClick={confirm}+ unmask={retryConsent}+ >+ {retryConsent+ ? "Retry same confirmation"+ : `Pay ${formatAmount(review.amount_due, review.currency)} and start ${plan}`}+ </Button>+ <Text variant="small" className="text-center text-zinc-500">+ Renews {billingCadence(review)} until you cancel. Cancel anytime+ in Billing.+ </Text>+ {error && !needsNewTerms && retryConsent && (+ <Button+ variant="secondary"+ className="w-full"+ onClick={() => check()}+ disabled={isBusy}+ >+ Check existing payment+ </Button>+ )}+ {refreshTerms && (+ <Button+ variant="secondary"+ className="w-full"+ onClick={() => start(attempt.return_to)}+ disabled={isBusy}+ >+ Review current terms+ </Button>+ )}+ <Button+ variant="link"+ className="w-full text-zinc-600"+ onClick={() => setOpen(false)}+ >+ Not now+ </Button>+ </>+ ) : attempt ? (+ <ActivationStatus+ attempt={attempt}+ isBusy={isBusy}+ isReady={isReady}+ hasFreshUsage={hasFreshUsage}+ plan={plan}+ check={check}+ close={() => setOpen(false)}+ />+ ) : (+ <Button+ variant="secondary"+ className="w-full"+ loading={isBusy}+ onClick={() => start()}+ >+ {isBusy ? "Loading your upgrade details…" : "Try again"}+ </Button>+ )}+ </div>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ProActivation/RenewalDetails.tsx b/autogpt_platform/frontend/src/components/organisms/ProActivation/RenewalDetails.tsxnew file mode 100644index 0000000000..2b22eb22c7--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ProActivation/RenewalDetails.tsx@@ -0,0 +1,69 @@+import type { ActivationTerms } from "@/app/api/__generated__/models/activationTerms";+import type { RenewalDiscount } from "@/app/api/__generated__/models/renewalDiscount";+import { Text } from "@/components/atoms/Text/Text";+import { formatAmount } from "@/services/pro-activation/helpers";++function discountText(discount: RenewalDiscount, currency: string) {+ const amount =+ discount.percent_off != null+ ? `${discount.percent_off}% off`+ : discount.amount_off != null+ ? `${formatAmount(discount.amount_off, discount.currency ?? currency)} off`+ : "Offer discount";+ const duration =+ discount.duration === "once"+ ? "the first invoice only"+ : discount.duration === "forever"+ ? "every renewal"+ : discount.duration_in_months+ ? `for ${discount.duration_in_months} months`+ : "for the offer period";+ return `${amount} ${duration}${discount.ends_at ? ` · ends ${new Date(discount.ends_at * 1000).toLocaleDateString()}` : ""}`;+}++interface Props {+ terms: ActivationTerms;+}++export function RenewalDetails({ terms }: Props) {+ return (+ <div className="space-y-2">+ {terms.renewal_discounts?.map((discount, index) => (+ <Text+ key={index}+ unmask={false}+ variant="small"+ className="text-zinc-600"+ >+ {discountText(discount, terms.currency)}+ </Text>+ ))}+ <details className="group text-sm text-zinc-500">+ <summary className="w-fit cursor-pointer rounded-small underline decoration-zinc-300 underline-offset-4 focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-500">+ Full renewal terms+ </summary>+ <Text+ variant="small"+ unmask={false}+ className="mt-3 leading-relaxed text-zinc-600"+ >+ {terms.renewal_terms}+ </Text>+ {terms.renewal_tax?.rates?.map((rate, index) => (+ <Text+ key={index}+ unmask={false}+ variant="small"+ className="mt-2 text-zinc-600"+ >+ {rate.display_name}: {rate.percentage}%{" "}+ {rate.inclusive ? "included" : "additional"}+ {[rate.country, rate.state].filter(Boolean).length+ ? ` · ${[rate.country, rate.state].filter(Boolean).join(", ")}`+ : ""}+ </Text>+ ))}+ </details>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsxindex 5388ac2949..86a4ac41fd 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx@@ -94,16 +94,14 @@ export function TrialCardContent({return (<sectionaria-label="AutoGPT trial"- className="flex w-full flex-col gap-2"+ className="flex w-full flex-col gap-2 py-4">- <div className="flex items-center gap-2 px-4">+ <div className="sr-only"><Text variant="body-medium" as="span" className="text-textBlack">{trial.eligible ? "Free trial" : "Your plan"}</Text></div>- <div className="rounded-[18px] border border-zinc-200 bg-white p-5 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">- {body}- </div>+ <div className="w-full">{body}</div></section>);return (diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsxindex 65ede83fdf..f6081bd6a5 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx@@ -1,10 +1,10 @@import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { Badge } from "@/components/atoms/Badge/Badge";import { Text } from "@/components/atoms/Text/Text";import { CancelTrialDialog } from "./CancelTrialDialog";import { formatTrialEnd, formatTrialPrice } from "./helpers";import { TrialCancelPending } from "./TrialCancelPending";import { TrialRejection } from "./TrialRejection";-import { TrialTitle } from "./TrialTitle/TrialTitle";interface Props {trial: TrialStatusResponse;@@ -35,28 +35,47 @@ export function TrialStatus({);const end = formatTrialEnd(trial.ends_at);return (- <div className="flex flex-col gap-3">- <TrialTitle>- {trial.active ? "Your trial" : "Your trial has ended"}- </TrialTitle>- <Text variant="body" unmask={false} className="!text-zinc-800">- {trial.status === "canceled"- ? "Cancellation confirmed. Trial access has ended and your trial will not convert to a paid plan."- : trial.cancel_at_period_end- ? `Cancellation confirmed. Your trial will not convert to a paid plan. Trial access ends ${end}.`- : trial.active- ? `Your trial ends ${end}. Your saved card will then be charged ${formatTrialPrice(trial.offer)}, plus applicable tax.`- : "Paid access requires a successful payment. Review your payment method and plan below."}- </Text>- {trial.active && !trial.cancel_at_period_end ? (- <div className="mt-1">- <CancelTrialDialog- trial={trial}- isCanceling={isCanceling}- onCancel={onCancel}- />+ <div className="flex flex-wrap items-center justify-between gap-x-5 gap-y-3">+ <div className="min-w-0 basis-full space-y-2 sm:flex-1 sm:basis-auto">+ <div className="flex flex-wrap items-center gap-2.5">+ <Text variant="large-semibold" as="h2">+ {trial.active ? "Your trial" : "Your trial has ended"}+ </Text>+ <Badge variant="info" size="small">+ {trial.status === "canceled"+ ? "Canceled"+ : trial.active+ ? "Free trial"+ : "Ended"}+ </Badge></div>- ) : null}+ <Text+ variant="small"+ unmask={false}+ tone="secondary"+ className="max-w-[560px] leading-5"+ >+ {trial.status === "canceled"+ ? "Cancellation confirmed. Trial access has ended and your trial will not convert to a paid plan."+ : trial.cancel_at_period_end+ ? `Cancellation confirmed. Your trial will not convert to a paid plan. Trial access ends ${end}.`+ : trial.active+ ? `Your trial ends ${end}. Your saved card will then be charged ${formatTrialPrice(trial.offer)}, plus applicable tax.`+ : "Paid access requires a successful payment. Review your payment method and plan below."}+ </Text>+ {trial.active && (+ <Text variant="small" tone="secondary" className="text-xs">+ Cancel before your trial ends to avoid a charge.+ </Text>+ )}+ </div>+ {trial.active && !trial.cancel_at_period_end && (+ <CancelTrialDialog+ trial={trial}+ isCanceling={isCanceling}+ onCancel={onCancel}+ />+ )}</div>);}diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/PaymentDueAction.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PaymentDueAction.tsxnew file mode 100644index 0000000000..1005147b7b--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PaymentDueAction.tsx@@ -0,0 +1,53 @@+import { LinkSquare01Icon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { cn } from "@/lib/utils";++interface Props {+ url: string;+ label: string;+ size?: "small" | "large";+ layout?: "stacked" | "inline";+}++export function PaymentDueAction({+ url,+ label,+ size = "large",+ layout = "stacked",+}: Props) {+ const stacked = layout === "stacked";+ return (+ <div+ className={cn(+ stacked ? "space-y-2.5" : "flex flex-wrap items-center gap-x-4 gap-y-2",+ )}+ >+ <Button+ as="NextLink"+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ size={size}+ unmask={false}+ className={stacked ? "w-full" : undefined}+ rightIcon={+ <Icon+ icon={LinkSquare01Icon}+ size={size === "small" ? 14 : 16}+ aria-hidden="true"+ />+ }+ >+ {label}+ </Button>+ <Text+ variant="small"+ className={cn("!text-xs !text-zinc-500", stacked && "text-center")}+ >+ Opens a secure Stripe page. You can use a different card there.+ </Text>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/PaymentRecoveryCard.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PaymentRecoveryCard.tsxnew file mode 100644index 0000000000..447993e18d--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PaymentRecoveryCard.tsx@@ -0,0 +1,52 @@+import { CreditCardIcon } from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import type { formatPaymentDue } from "@/services/usageExperience/payment";+import { PaymentDueAction } from "./PaymentDueAction";++interface Props {+ payment: ReturnType<typeof formatPaymentDue>;+ fallback: string;+}++export function PaymentRecoveryCard({ payment, fallback }: Props) {+ return (+ <section+ aria-label="Payment"+ className="w-full rounded-2xl border border-zinc-200 bg-white p-6 text-left"+ >+ <div className="flex items-center gap-2.5">+ <span className="flex size-7 items-center justify-center rounded-lg bg-white text-zinc-600 ring-1 ring-zinc-200">+ <Icon icon={CreditCardIcon} size={17} />+ </span>+ <Text variant="small-medium" className="text-zinc-600">+ Payment+ </Text>+ </div>+ <Text+ variant="h4"+ as="h2"+ className="mb-3 mt-4 text-[23px] leading-8 tracking-[-0.04em]"+ >+ Your payment didn’t go through+ </Text>+ <Text+ variant="small"+ tone="secondary"+ unmask={!payment}+ className="max-w-[38rem] leading-6"+ >+ {payment?.description ?? fallback}+ </Text>+ {payment ? (+ <div className="mt-5">+ <PaymentDueAction+ url={payment.url}+ label={payment.actionLabel}+ layout="inline"+ />+ </div>+ ) : null}+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/PlanOffer.stories.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PlanOffer.stories.tsxnew file mode 100644index 0000000000..717980e86e--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PlanOffer.stories.tsx@@ -0,0 +1,27 @@+import type { Meta, StoryObj } from "@storybook/nextjs";+import { fn } from "storybook/test";+import { PlanOffer } from "./PlanOffer";+const meta = {+ title: "Organisms/UsageExperience/PlanOffer",+ component: PlanOffer,+ parameters: { layout: "centered" },+ args: { onUpgrade: fn() },+ decorators: [+ (Story) => (+ <div className="w-full max-w-md">+ <Story />+ </div>+ ),+ ],+} satisfies Meta<typeof PlanOffer>;+export default meta;+type Story = StoryObj<typeof meta>;+export const TrialToPro: Story = {+ args: { tier: "PRO", price: 5000, freshUsage: true },+};+export const ProToMax: Story = {+ args: { tier: "MAX", price: 32000, usageMultiplier: 8.5 },+};+export const AcceptedYearlyOffer: Story = {+ args: { tier: "PRO", price: 51000, cycle: "yearly", freshUsage: true },+};diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/PlanOffer.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PlanOffer.tsxnew file mode 100644index 0000000000..491d65d4a1--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/PlanOffer.tsx@@ -0,0 +1,130 @@+"use client";++import {+ ArrowRight02Icon,+ SparklesIcon,+ Tick02Icon,+} from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { formatOfferPrice } from "@/services/usageExperience/helpers";++interface Props {+ tier: "PRO" | "MAX";+ price?: number;+ currency?: string;+ cycle?: "monthly" | "yearly";+ usageMultiplier?: number;+ storageMultiplier?: number;+ freshUsage?: boolean;+ actionLabel?: string;+ onUpgrade: () => void;+ disabled?: boolean;+}++export function PlanOffer({+ tier,+ price,+ currency = "USD",+ cycle = "monthly",+ usageMultiplier,+ storageMultiplier,+ freshUsage = false,+ actionLabel,+ onUpgrade,+ disabled = false,+}: Props) {+ const name = tier === "PRO" ? "Pro" : "Max";+ const amount = formatOfferPrice(price, currency);+ const features =+ tier === "PRO"+ ? [+ freshUsage+ ? "A full daily and weekly allowance once payment goes through"+ : "Experts for content, sales and research, with Otto coordinating",+ freshUsage+ ? "Your chats, agents and files stay where they are"+ : "Agents that keep working in the background on a schedule",+ ]+ : [+ usageMultiplier+ ? `${usageMultiplier}× the usage of Pro`+ : "More room for your daily and weekly work",+ storageMultiplier+ ? `${storageMultiplier}× the workspace storage`+ : "More workspace storage",+ "Priority support",+ ];+ return (+ <section+ aria-label={`${name} plan`}+ className="rounded-2xl border border-purple-200 bg-gradient-to-br from-purple-50 via-white to-blue-50 p-5 sm:p-6"+ >+ <div className="mb-5 flex items-start justify-between gap-3">+ <div className="flex min-w-0 items-center gap-3">+ <span className="hidden size-10 shrink-0 items-center justify-center rounded-xl border border-purple-200 bg-white text-purple-600 min-[360px]:flex">+ <Icon icon={SparklesIcon} size={20} />+ </span>+ <div>+ <Text variant="h4" className="!text-xl">+ {name}+ </Text>+ <Text variant="small" className="!text-zinc-500">+ Billed {cycle}+ </Text>+ </div>+ </div>+ {amount && (+ <div className="shrink-0 text-right">+ <Text variant="h4" className="!text-2xl" unmask={!freshUsage}>+ {amount}+ </Text>+ <Text variant="small" className="!text-zinc-500">+ per {cycle === "yearly" ? "year" : "month"} + tax+ </Text>+ </div>+ )}+ </div>+ <ul className="mb-5 space-y-2.5">+ {features.map((feature) => (+ <li+ key={feature}+ className="flex gap-2.5 text-sm leading-5 text-zinc-700"+ >+ <Icon+ icon={Tick02Icon}+ size={16}+ className="mt-0.5 shrink-0 text-purple-600"+ />+ {feature}+ </li>+ ))}+ </ul>+ <Button+ className="w-full"+ onClick={onUpgrade}+ disabled={disabled}+ unmask={!freshUsage}+ rightIcon={<Icon icon={ArrowRight02Icon} size={16} />}+ >+ {actionLabel ??+ (tier === "MAX"+ ? "Upgrade to Max"+ : freshUsage+ ? `Start Pro now${amount ? ` · ${amount}` : ""}`+ : "Start Pro")}+ </Button>+ <Text+ variant="small"+ className="mt-3 text-center !text-xs !text-zinc-500"+ >+ {freshUsage+ ? "You’ll see the full charge before you pay."+ : tier === "MAX"+ ? "What you’ve already used counts toward Max’s higher limit."+ : "Review your plan and payment before confirming."}+ </Text>+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/ProviderContinuation.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/ProviderContinuation.tsxnew file mode 100644index 0000000000..5e4a03a5e1--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/ProviderContinuation.tsx@@ -0,0 +1,28 @@+import { ArrowRight02Icon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+interface Props {+ name: string;+ onContinue: () => void;+ isSwitching?: boolean;+}+export function ProviderContinuation({ name, onContinue, isSwitching }: Props) {+ return (+ <div className="mt-4 flex flex-wrap items-center justify-between gap-2 border-t border-zinc-200 pt-4">+ <Text variant="small" className="!text-zinc-500">+ Or keep going with your connected {name} account. The rest of this chat+ runs there.+ </Text>+ <Button+ size="small"+ variant="ghost"+ onClick={onContinue}+ loading={isSwitching}+ rightIcon={<Icon icon={ArrowRight02Icon} size={14} />}+ >+ Continue on {name}+ </Button>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/UsageExperience/UsageMeter.tsx b/autogpt_platform/frontend/src/components/organisms/UsageExperience/UsageMeter.tsxnew file mode 100644index 0000000000..19cb5bfb5f--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/UsageExperience/UsageMeter.tsx@@ -0,0 +1,46 @@+import { Text } from "@/components/atoms/Text/Text";+import { formatUsagePercent } from "@/services/usageExperience/helpers";+import { cn } from "@/lib/utils";++interface Props {+ label: string;+ percent: number;+ detail?: string | null;+}++export function UsageMeter({ label, percent, detail }: Props) {+ const value = Math.min(100, Math.max(0, percent));+ return (+ <div className="space-y-2">+ <div className="flex justify-between gap-2">+ <Text variant="small-medium" className="!text-zinc-700">+ {label}+ </Text>+ <Text variant="small" className="tabular-nums !text-zinc-500">+ {formatUsagePercent(value)} used+ </Text>+ </div>+ <div+ role="progressbar"+ aria-label={label}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={value}+ className="h-1.5 overflow-hidden rounded-full bg-zinc-100"+ >+ <div+ className={cn(+ "h-full rounded-full transition-[width]",+ value >= 100 ? "bg-orange-500" : "bg-purple-500",+ )}+ style={{ width: `${value}%` }}+ />+ </div>+ {detail && (+ <Text variant="small" className="!text-xs !text-zinc-500">+ {detail}+ </Text>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/mocks/mock-handlers.ts b/autogpt_platform/frontend/src/mocks/mock-handlers.tsindex ffa4a35a65..f1bd224aec 100644--- a/autogpt_platform/frontend/src/mocks/mock-handlers.ts+++ b/autogpt_platform/frontend/src/mocks/mock-handlers.ts@@ -30,9 +30,14 @@ import { getSearchMock } from "@/app/api/__generated__/endpoints/search/search.mimport { getSkillsMock } from "@/app/api/__generated__/endpoints/skills/skills.msw";import { getStoreMock } from "@/app/api/__generated__/endpoints/store/store.msw";import { getWorkspaceMock } from "@/app/api/__generated__/endpoints/workspace/workspace.msw";+import { http, HttpResponse } from "msw";// Pass hard-coded data to individual handler functions to override faker-generated data.export const mockHandlers = [+ // No activation in progress unless a test explicitly provides one.+ http.get("/api/proxy/api/credits/pro-activation/current", () =>+ HttpResponse.json({ detail: "No activation in progress" }, { status: 404 }),+ ),...getAdminMock(),...getAnalyticsMock(),...getApiKeysMock(),diff --git a/autogpt_platform/frontend/src/playwright/journeys/__tests__/guard.test.ts b/autogpt_platform/frontend/src/playwright/journeys/__tests__/guard.test.tsnew file mode 100644index 0000000000..686e72d6a5--- /dev/null+++ b/autogpt_platform/frontend/src/playwright/journeys/__tests__/guard.test.ts@@ -0,0 +1,65 @@+import type { BrowserContext, Response } from "@playwright/test";+import { describe, expect, it } from "vitest";+import { watchForUnexpectedErrors } from "../guard";++const activationURL =+ "http://localhost:3000/api/proxy/api/credits/pro-activation/current";++async function collect(+ status: number,+ url: string,+ method: string,+ body: unknown,+) {+ let listener: ((response: Response) => void) | undefined;+ const context = {+ on(event: string, handler: (response: Response) => void) {+ if (event === "response") listener = handler;+ },+ } as unknown as BrowserContext;+ const guard = watchForUnexpectedErrors(context, []);+ listener?.({+ url: () => url,+ status: () => status,+ request: () => ({ method: () => method }),+ json: async () => body,+ text: async () => JSON.stringify(body),+ } as unknown as Response);+ return guard.collect();+}++describe("journey activation lookup contract", () => {+ it("accepts the exact absence response from the optional current lookup", async () => {+ expect(+ await collect(404, activationURL, "GET", {+ detail: "No activation is available",+ }),+ ).toEqual([]);+ });++ it.each([+ [500, activationURL, "GET", { detail: "No activation is available" }],+ [404, activationURL, "POST", { detail: "No activation is available" }],+ [+ 404,+ `${activationURL}/other`,+ "GET",+ { detail: "No activation is available" },+ ],+ [404, activationURL, "GET", { detail: "User not found" }],+ [+ 404,+ activationURL,+ "GET",+ { detail: "No activation is available", error: "unexpected" },+ ],+ [404, activationURL, "GET", "invalid body"],+ ] as const)(+ "keeps unexpected response %s %s %s visible",+ async (status, url, method, body) => {+ const errors = await collect(status, url, method, body);+ expect(errors).toHaveLength(1);+ expect(errors[0]).toContain(`${status} ${method} ${url}`);+ },+ );+});diff --git a/autogpt_platform/frontend/src/playwright/journeys/guard.ts b/autogpt_platform/frontend/src/playwright/journeys/guard.tsindex 15b6267162..7e802d3fed 100644--- a/autogpt_platform/frontend/src/playwright/journeys/guard.ts+++ b/autogpt_platform/frontend/src/playwright/journeys/guard.ts@@ -46,13 +46,17 @@ export function watchForUnexpectedErrors(context: BrowserContext,expected: ExpectedResponse[],) {- const pending: Promise<string>[] = [];+ const pending: Promise<string | null>[] = [];context.on("response", (response) => {if (!isApiResponse(response) || response.status() < 400) return;if (isExpected(response, expected)) return;if (isKnownNoise({ kind: "response", response })) return;- pending.push(describeResponse(response));+ pending.push(+ isMissingActivation(response).then((missing) =>+ missing ? null : describeResponse(response),+ ),+ );});context.on("console", (message) => {@@ -74,7 +78,9 @@ export function watchForUnexpectedErrors(return {async collect() {- return Promise.all(pending);+ return (await Promise.all(pending)).filter(+ (problem): problem is string => problem !== null,+ );},};}@@ -114,6 +120,26 @@ function isKnownNoise(candidate: NoiseCandidate) {});}+// The optional recovery lookup returns this exact 404 when no activation exists.+// Different errors, methods, endpoints and response bodies remain findings.+async function isMissingActivation(response: Response) {+ if (+ response.status() !== 404 ||+ response.request().method() !== "GET" ||+ new URL(response.url()).pathname !==+ "/api/proxy/api/credits/pro-activation/current"+ )+ return false;+ const body: unknown = await response.json().catch(() => null);+ return (+ body !== null &&+ typeof body === "object" &&+ Object.keys(body).length === 1 &&+ "detail" in body &&+ body.detail === "No activation is available"+ );+}+async function describeResponse(response: Response) {const body = await response.text()diff --git a/autogpt_platform/frontend/src/services/pro-activation/ProActivationProvider.tsx b/autogpt_platform/frontend/src/services/pro-activation/ProActivationProvider.tsxnew file mode 100644index 0000000000..83d66223ef--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/ProActivationProvider.tsx@@ -0,0 +1,78 @@+"use client";+import {+ PropsWithChildren,+ RefObject,+ useImperativeHandle,+ useLayoutEffect,+ useRef,+ useState,+} from "react";+import { ProActivationDialog } from "@/components/organisms/ProActivation/ProActivationDialog";+import { ProActivationContext } from "./context";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { useActivationController } from "./useActivationController";++interface SessionStatus {+ userID: string | undefined;+ isBusy: boolean;+ isReady: boolean;+}++interface SessionHandle {+ userID: string | undefined;+ start: (returnTo?: string) => Promise<void>;+}++export function ProActivationProvider({ children }: PropsWithChildren) {+ const userID = useAuthStore((state) => state.user?.id);+ const controller = useRef<SessionHandle | null>(null);+ const [status, setStatus] = useState<SessionStatus>();++ async function start(returnTo?: string) {+ if (controller.current?.userID !== userID) return;+ await controller.current?.start(returnTo);+ }++ return (+ <ProActivationContext.Provider+ value={{+ start,+ isBusy: status?.userID === userID && !!status?.isBusy,+ isReady: status?.userID === userID && !!status?.isReady,+ }}+ >+ {children}+ <ActivationSession+ key={userID ?? "signed-out"}+ userID={userID}+ controller={controller}+ onStatus={setStatus}+ />+ </ProActivationContext.Provider>+ );+}++interface SessionProps {+ userID: string | undefined;+ controller: RefObject<SessionHandle | null>;+ onStatus: (status: SessionStatus) => void;+}++function ActivationSession({ userID, controller, onStatus }: SessionProps) {+ const activation = useActivationController();+ useImperativeHandle(controller, () => ({ userID, start: activation.start }));+ useLayoutEffect(() => {+ onStatus({+ userID,+ isBusy: activation.isBusy,+ isReady: activation.isReady && activation.hasFreshUsage,+ });+ }, [+ userID,+ activation.isBusy,+ activation.isReady,+ activation.hasFreshUsage,+ onStatus,+ ]);+ return <ProActivationDialog activation={activation} />;+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/activation-terms.test.tsx b/autogpt_platform/frontend/src/services/pro-activation/__tests__/activation-terms.test.tsxnew file mode 100644index 0000000000..4e60d31e98--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/activation-terms.test.tsx@@ -0,0 +1,100 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { ActivationTerms } from "@/components/organisms/ProActivation/ActivationTerms";+import { quote } from "./fixtures";++const terms = {+ ...quote.terms!,+ currency: "usd",+ amount_due: 6000,+ renewal_unit_amount: 5000,+ billing_interval: "month" as const,+ renewal_discounts: [],+ trial_ends_at: new Date("2026-10-12T12:00:00Z"),+ period_starts_at: new Date("2026-10-07T12:00:00Z"),+ next_payment_at: new Date("2026-11-07T12:00:00Z"),+ tax_amount: 1000,+};++describe("Pro payment review", () => {+ it("shows the early trial end, paid period, actual tax and next payment", () => {+ render(<ActivationTerms terms={terms} />);+ expect(screen.getByText(/instead of Oct 12/)).toBeDefined();+ expect(screen.getByText(/billing date moves to the 7th/)).toBeDefined();+ expect(screen.getByText("Pro, Oct 7 to Nov 7")).toBeDefined();+ expect(screen.getByText("Tax")).toBeDefined();+ expect(screen.getByText("$10.00")).toBeDefined();+ expect(screen.getByText("Due today")).toBeDefined();+ expect(screen.getByText("$60.00")).toBeDefined();+ expect(screen.getByText(/Next payment of \$50.00 plus tax/)).toBeDefined();+ expect(screen.getByText(/After payment succeeds/)).toBeDefined();+ expect(screen.queryByText(/Quote valid until/)).toBeNull();+ const disclosure = screen+ .getByText("Full renewal terms")+ .closest("details");+ expect(disclosure?.open).toBe(false);+ fireEvent.click(screen.getByText("Full renewal terms"));+ });++ it("distinguishes unavailable tax from a quoted zero and included tax", () => {+ const result = render(+ <ActivationTerms terms={{ ...terms, tax_amount: null }} />,+ );+ expect(screen.queryByText("$0.00")).toBeNull();+ expect(screen.getByText("Included in total")).toBeDefined();+ result.rerender(+ <ActivationTerms terms={{ ...terms, tax_amount: 0, amount_due: 5000 }} />,+ );+ expect(screen.getByText("$0.00")).toBeDefined();+ result.rerender(+ <ActivationTerms+ terms={{+ ...terms,+ amount_due: 5000,+ renewal_tax: { price_tax_behavior: "inclusive" },+ }}+ />,+ );+ expect(screen.getByText("Tax (included)")).toBeDefined();+ expect(screen.queryByText(/plus tax/)).toBeNull();+ });++ it("names discounts and credits when the quote differs from the recurring price", () => {+ render(<ActivationTerms terms={{ ...terms, amount_due: 5400 }} />);+ expect(screen.getByText("Discounts, credits & adjustments")).toBeDefined();+ expect(screen.getByText("-$6.00")).toBeDefined();+ expect(screen.getByText("$54.00")).toBeDefined();+ });++ it("uses yearly terms without promising a monthly renewal", () => {+ render(+ <ActivationTerms+ terms={{+ ...terms,+ billing_interval: "year",+ next_payment_at: new Date("2027-10-07T12:00:00Z"),+ }}+ />,+ );+ expect(screen.getByText("Yearly")).toBeDefined();+ expect(screen.getByText(/then every year/)).toBeDefined();+ expect(screen.queryByText(/then every month/)).toBeNull();+ });++ it("keeps legacy saved attempts readable without invented dates", () => {+ render(+ <ActivationTerms+ terms={{+ ...terms,+ trial_ends_at: null,+ period_starts_at: null,+ next_payment_at: null,+ }}+ />,+ );+ expect(screen.queryByText(/instead of/)).toBeNull();+ expect(+ screen.getByText(/Your paid billing period begins when you confirm/),+ ).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/activation.test.tsx b/autogpt_platform/frontend/src/services/pro-activation/__tests__/activation.test.tsxnew file mode 100644index 0000000000..dc2a700fc7--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/activation.test.tsx@@ -0,0 +1,627 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen, waitFor, fireEvent } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { http, HttpResponse } from "msw";+import { server } from "@/mocks/mock-server";+import { ProActivationProvider } from "../ProActivationProvider";+import { useProActivation } from "../useProActivation";+import { quote } from "./fixtures";++vi.mock("@/lib/auth/hooks/useAuthStore", () => ({+ useAuthStore: Object.assign(+ (select: (state: { user: { id: string } }) => unknown) =>+ select({ user: { id: "user-1" } }),+ { getState: () => ({ user: { id: "user-1" } }) },+ ),+}));+vi.mock("@/components/molecules/Dialog/Dialog", () => ({+ Dialog: Object.assign(+ function Dialog({+ controlled,+ children,+ title,+ }: {+ controlled: { isOpen: boolean };+ children: React.ReactNode;+ title: React.ReactNode;+ }) {+ return controlled.isOpen ? (+ <div role="dialog">+ {title}+ {children}+ </div>+ ) : null;+ },+ {+ Content: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ },+ ),+}));++function Subject() {+ const activation = useProActivation();+ return (+ <>+ <button+ onClick={() => activation.start("/copilot/thread?resume=1#draft")}+ >+ Upgrade+ </button>+ <span>+ {activation.isReady ? "allowance ready" : "allowance waiting"}+ </span>+ </>+ );+}+function mount() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <ProActivationProvider>+ <Subject />+ </ProActivationProvider>+ </QueryClientProvider>,+ );+}+const base = "*/api/proxy/api/credits/pro-activation";+const confirm = vi.fn();+const preview = vi.fn();++beforeEach(() => {+ sessionStorage.clear();+ window.history.replaceState({}, "", "/");+ confirm.mockReset();+ preview.mockReset();+ server.use(+ http.get("*/api/proxy/api/credits/manage", () =>+ HttpResponse.json({ url: "https://billing.stripe.com/p/session/test" }),+ ),+ http.get(`${base}/current`, () => new HttpResponse(null, { status: 404 })),+ http.post(`${base}/preview`, async ({ request }) => {+ preview(await request.json());+ return HttpResponse.json(quote);+ }),+ http.post(`${base}/attempt-1/confirm`, async ({ request }) => {+ confirm(await request.json());+ return HttpResponse.json({+ ...quote,+ status: "processing",+ retry_after_seconds: 30,+ });+ }),+ http.get(`${base}/attempt-1`, () =>+ HttpResponse.json({+ ...quote,+ status: "processing",+ retry_after_seconds: 30,+ }),+ ),+ );+});++describe("Pro activation", () => {+ it("reads a lookup that couldn't check as an error, not a payment in flight", async () => {+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({ status: "processing", retry_after_seconds: 3 }),+ ),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText(+ "We couldn’t load your upgrade details. Please try again before confirming payment.",+ );+ expect(screen.queryByText(/We’re confirming your payment/)).toBeNull();+ expect(screen.getByRole("button", { name: "Try again" })).toBeDefined();+ expect(preview).not.toHaveBeenCalled();+ });++ it.each([+ { usage_reset: false },+ { usage_reset: true },+ { usage_reset: false, activation_id: "generation-1" },+ ])(+ "does not promise fresh usage without a reset receipt (%j)",+ async (receipt) => {+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({ ...quote, status: "ready", ...receipt }),+ ),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: false, converted: true }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ http.get("*/api/proxy/api/chat/usage", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText("Pro is active");+ expect(screen.getByText("allowance waiting")).toBeDefined();+ expect(screen.queryByText("allowance ready")).toBeNull();+ expect(+ screen.getByText(+ "Your Pro plan is active. Your existing usage still counts toward your plan’s limits.",+ ),+ ).toBeDefined();+ },+ );++ it("recovers a paid Max activation without relabeling it Pro or promising a reset", async () => {+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({+ ...quote,+ terms: { ...quote.terms, plan: "MAX" },+ status: "ready",+ usage_reset: false,+ }),+ ),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: false, converted: true }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "MAX" }),+ ),+ http.get("*/api/proxy/api/chat/usage", () =>+ HttpResponse.json({ tier: "MAX" }),+ ),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText("Max is active");+ expect(+ screen.getByText(+ "Your Max plan is active. Your existing usage still counts toward your plan’s limits.",+ ),+ ).toBeDefined();+ expect(screen.queryByText("allowance ready")).toBeNull();+ expect(preview).not.toHaveBeenCalled();+ expect(confirm).not.toHaveBeenCalled();+ });++ it("clears prior readiness when the current plan no longer matches", async () => {+ let changed = false;+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({+ ...quote,+ status: changed ? "not_applicable" : "ready",+ usage_reset: true,+ activation_id: "generation-1",+ }),+ ),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: false, converted: true }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ http.get("*/api/proxy/api/chat/usage", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText("allowance ready");+ fireEvent.click(+ screen.getByRole("button", { name: "Continue where you left off" }),+ );+ changed = true;+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText("Your plan has changed");+ expect(screen.queryByText("Pro is active")).toBeNull();+ expect(screen.getByText("allowance waiting")).toBeDefined();+ });++ it("handles a different current plan without polling or starting another payment", async () => {+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({ ...quote, status: "not_applicable" }),+ ),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText("Your plan has changed");+ expect(screen.getByRole("link", { name: "View my plan" })).toBeDefined();+ expect(+ screen.queryByRole("button", { name: "Check activation status" }),+ ).toBeNull();+ expect(preview).not.toHaveBeenCalled();+ expect(confirm).not.toHaveBeenCalled();+ });++ it("requires a fresh quote when the displayed price has expired", async () => {+ server.use(+ http.post(`${base}/preview`, () =>+ HttpResponse.json({+ ...quote,+ terms: { ...quote.terms, expires_at: new Date(Date.now() - 1000) },+ }),+ ),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByText(/This quote has expired/);+ expect(+ screen+ .getByRole("button", { name: "Pay £61.23 and start Pro" })+ .hasAttribute("disabled"),+ ).toBe(true);+ expect(+ screen.getByRole("button", { name: "Review current terms" }),+ ).toBeDefined();+ expect(confirm).not.toHaveBeenCalled();+ });++ it("offers payment management in another tab without discarding the current review", async () => {+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ const manage = await screen.findByRole("link", {+ name: "Manage payment method in a new tab",+ });+ await waitFor(() =>+ expect(manage.getAttribute("href")).toBe(+ "https://billing.stripe.com/p/session/test",+ ),+ );+ expect(manage.getAttribute("target")).toBe("_blank");+ expect(manage.getAttribute("rel")).toBe("noopener noreferrer");+ expect(screen.getByText("Start Pro today")).toBeDefined();+ expect(confirm).not.toHaveBeenCalled();+ });++ it.each(["processing", "payment_required", "action_required", "failed"])(+ "makes no recovery lookup for an unsolicited %s outside an activation flow",+ async (status) => {+ const current = vi.fn();+ server.use(+ http.get(`${base}/current`, () => {+ current();+ return HttpResponse.json({ ...quote, status });+ }),+ );+ mount();+ await new Promise((resolve) => setTimeout(resolve, 50));+ // Only a payment being resumed can use the answer, so a plain page+ // load doesn't ask.+ expect(current).not.toHaveBeenCalled();+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(screen.getByText("allowance waiting")).toBeDefined();+ expect(confirm).not.toHaveBeenCalled();+ expect(preview).not.toHaveBeenCalled();+ },+ );++ it("retains the checkout-return signal while the billing page cleans up its URL", async () => {+ window.history.replaceState(+ {},+ "",+ "/settings/billing?subscription=success",+ );+ let releaseCurrent: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ releaseCurrent = resolve;+ });+ const currentStarted = vi.fn();+ server.use(+ http.get(`${base}/current`, async () => {+ currentStarted();+ await pending;+ return HttpResponse.json({+ ...quote,+ status: "ready",+ usage_reset: true,+ activation_id: "generation-1",+ });+ }),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: false, converted: true }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ http.get("*/api/proxy/api/chat/usage", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ );+ mount();+ await waitFor(() => expect(currentStarted).toHaveBeenCalledTimes(1));+ window.history.replaceState({}, "", "/settings/billing");+ releaseCurrent();+ await screen.findByText("allowance ready");+ expect(screen.getByText("Pro is active")).toBeDefined();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue where you left off" }),+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ // Closing success must not immediately replace fresh-Pro billing with a Max upsell.+ expect(screen.getByText("allowance ready")).toBeDefined();+ });++ it("does not announce readiness when refreshed data still describes the trial", async () => {+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({+ ...quote,+ status: "ready",+ usage_reset: true,+ activation_id: "generation-1",+ }),+ ),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: true, converted: false }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "TRIAL" }),+ ),+ http.get("*/api/proxy/api/chat/usage", () =>+ HttpResponse.json({ tier: "TRIAL" }),+ ),+ );+ sessionStorage.setItem(+ "pro-activation:user-1",+ JSON.stringify({ id: quote.id, token: quote.terms_token }),+ );+ mount();+ await screen.findByText(+ /Your payment is confirmed. We’re refreshing your plan/,+ );+ expect(screen.queryByText("allowance ready")).toBeNull();+ expect(screen.getByText("allowance waiting")).toBeDefined();+ });++ it.each(["PRO", "MAX", "NO_TIER"])(+ "makes no recovery lookup for a historical activation of current %s customers",+ async (tier) => {+ const readUsage = vi.fn();+ const current = vi.fn();+ server.use(+ http.get(`${base}/current`, () => {+ current();+ return HttpResponse.json({+ ...quote,+ status: "ready",+ usage_reset: true,+ activation_id: "generation-1",+ });+ }),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: false, converted: true }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier }),+ ),+ http.get("*/api/proxy/api/chat/usage", () => {+ readUsage();+ return HttpResponse.json({ tier });+ }),+ );+ mount();+ await new Promise((resolve) => setTimeout(resolve, 50));+ // Only a payment being resumed can use the answer, so a plain page+ // load doesn't ask.+ expect(current).not.toHaveBeenCalled();+ expect(readUsage).not.toHaveBeenCalled();+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(screen.queryByText("allowance ready")).toBeNull();+ },+ );++ it("ignores a stale mount recovery response after an explicit newer upgrade", async () => {+ window.history.replaceState(+ {},+ "",+ "/settings/billing?subscription=success",+ );+ let releaseOld: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ releaseOld = resolve;+ });+ let calls = 0;+ server.use(+ http.get(`${base}/current`, async () => {+ calls++;+ if (calls === 1) {+ await pending;+ return HttpResponse.json({ ...quote, status: "failed" });+ }+ return new HttpResponse(null, { status: 404 });+ }),+ );+ mount();+ await waitFor(() => expect(calls).toBe(1));+ fireEvent.click(screen.getByText("Upgrade"));+ await screen.findByRole("button", { name: "Pay £61.23 and start Pro" });+ releaseOld();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(+ screen.getByRole("button", { name: "Pay £61.23 and start Pro" }),+ ).toBeDefined();+ expect(screen.queryByText("Your payment wasn’t completed.")).toBeNull();+ });++ it("retains explicit consent across refresh and retries the same attempt and token", async () => {+ sessionStorage.setItem(+ "pro-activation:user-1",+ JSON.stringify({ id: quote.id, token: quote.terms_token }),+ );+ server.use(http.get(`${base}/current`, () => HttpResponse.json(quote)));+ mount();+ fireEvent.click(+ await screen.findByRole("button", { name: "Retry same confirmation" }),+ );+ await screen.findByRole("button", { name: "Check activation status" });+ expect(confirm).toHaveBeenCalledExactlyOnceWith({+ confirmed: true,+ terms_token: quote.terms_token,+ });+ expect(preview).not.toHaveBeenCalled();+ });++ it("requires refreshed terms after a conflict and never automatically retries confirmation", async () => {+ server.use(+ http.post(`${base}/attempt-1/confirm`, async ({ request }) => {+ confirm(await request.json());+ return HttpResponse.json({ detail: "Terms expired" }, { status: 409 });+ }),+ http.get(`${base}/attempt-1`, () => HttpResponse.json(quote)),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ fireEvent.click(+ await screen.findByRole("button", { name: "Pay £61.23 and start Pro" }),+ );+ const refresh = await screen.findByRole("button", {+ name: "Review current terms",+ });+ expect(+ screen+ .getByRole("button", { name: "Pay £61.23 and start Pro" })+ .hasAttribute("disabled"),+ ).toBe(true);+ expect(confirm).toHaveBeenCalledTimes(1);+ fireEvent.click(refresh);+ await waitFor(() => expect(preview).toHaveBeenCalledTimes(2));+ expect(confirm).toHaveBeenCalledTimes(1);+ });++ it("shows the actual quote and modifiers before explicit consent", async () => {+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ const pay = await screen.findByRole("button", {+ name: "Pay £61.23 and start Pro",+ });+ expect(screen.getByText("£85.00 / year")).toBeDefined();+ expect(screen.getByText(/20% off the first invoice only/)).toBeDefined();+ expect(screen.getByText(/VAT: 20% additional · GB/)).toBeDefined();+ expect(confirm).not.toHaveBeenCalled();+ expect(preview).toHaveBeenCalledWith({+ return_to: "/copilot/thread?resume=1#draft",+ });+ fireEvent.click(pay);+ await screen.findByRole("button", { name: "Check activation status" });+ expect(confirm).toHaveBeenCalledExactlyOnceWith({+ confirmed: true,+ terms_token: quote.terms_token,+ });+ expect(screen.getByText("allowance waiting")).toBeDefined();+ });++ it("waits for all authoritative data before declaring readiness", async () => {+ let releaseUsage: () => void = () => {};+ const usageWait = new Promise<void>((resolve) => {+ releaseUsage = resolve;+ });+ server.use(+ http.get(`${base}/attempt-1`, () =>+ HttpResponse.json({+ ...quote,+ status: "ready",+ usage_reset: true,+ activation_id: "generation-1",+ }),+ ),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ status: "converted" }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ http.get("*/api/proxy/api/chat/usage", async () => {+ await usageWait;+ return HttpResponse.json({ tier: "PRO", daily: { used: 0 } });+ }),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ fireEvent.click(+ await screen.findByRole("button", { name: "Pay £61.23 and start Pro" }),+ );+ fireEvent.click(+ await screen.findByRole("button", { name: "Check activation status" }),+ );+ expect(screen.getByText("allowance waiting")).toBeDefined();+ expect(screen.queryByText("Pro is active")).toBeNull();+ releaseUsage();+ await screen.findByText("allowance ready");+ expect(await screen.findByText("Pro is active")).toBeDefined();+ });++ it("recovers existing authentication using its invoice without another charge", async () => {+ sessionStorage.setItem(+ "pro-activation:user-1",+ JSON.stringify({ id: quote.id, token: quote.terms_token }),+ );+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({+ ...quote,+ status: "action_required",+ hosted_invoice_url: "https://invoice.stripe.com/i/existing",+ }),+ ),+ );+ mount();+ const link = await screen.findByRole("link", {+ name: "Verify payment securely",+ });+ expect(link.getAttribute("href")).toBe(+ "https://invoice.stripe.com/i/existing",+ );+ expect(link.getAttribute("target")).toBe("_blank");+ expect(link.getAttribute("rel")).toBe("noopener noreferrer");+ expect(screen.getByText(/keeping your draft here/)).toBeDefined();+ expect(confirm).not.toHaveBeenCalled();+ expect(preview).not.toHaveBeenCalled();+ expect(screen.getByText("allowance waiting")).toBeDefined();+ });++ it("recovers processing after navigation using GET only", async () => {+ sessionStorage.setItem(+ "pro-activation:user-1",+ JSON.stringify({ id: quote.id, token: quote.terms_token }),+ );+ server.use(+ http.get(`${base}/current`, () =>+ HttpResponse.json({+ ...quote,+ status: "processing",+ retry_after_seconds: 30,+ }),+ ),+ );+ mount();+ fireEvent.click(+ await screen.findByRole("button", { name: "Check activation status" }),+ );+ await waitFor(() => expect(confirm).not.toHaveBeenCalled());+ expect(preview).not.toHaveBeenCalled();+ expect(screen.getByText("allowance waiting")).toBeDefined();+ });++ it("resolves a lost confirmation response using the same attempt's status", async () => {+ server.use(+ http.post(`${base}/attempt-1/confirm`, async ({ request }) => {+ confirm(await request.json());+ return HttpResponse.error();+ }),+ );+ mount();+ fireEvent.click(screen.getByText("Upgrade"));+ fireEvent.click(+ await screen.findByRole("button", { name: "Pay £61.23 and start Pro" }),+ );+ await screen.findByRole("button", { name: "Check activation status" });+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(preview).toHaveBeenCalledTimes(1);+ expect(screen.getByText("allowance waiting")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/fixtures.ts b/autogpt_platform/frontend/src/services/pro-activation/__tests__/fixtures.tsnew file mode 100644index 0000000000..58d29e9790--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/fixtures.ts@@ -0,0 +1,37 @@+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";++export const quote: ActivationResponse = {+ id: "attempt-1",+ status: "confirmation_required",+ terms_token: "a".repeat(64),+ return_to: "/copilot/thread?resume=1#draft",+ terms: {+ plan: "PRO",+ price_id: "accepted-price",+ accepted_offer_token: "accepted-offer",+ amount_due: 6123,+ currency: "gbp",+ billing_interval: "year",+ billing_interval_count: 1,+ renewal_unit_amount: 8500,+ renewal_terms: "Renews annually. Cancel before renewal.",+ renewal_discounts: [{ percent_off: 20, duration: "once" }],+ renewal_tax: {+ automatic: true,+ price_tax_behavior: "exclusive",+ rates: [+ {+ display_name: "VAT",+ percentage: 20,+ inclusive: false,+ country: "GB",+ },+ ],+ },+ expires_at: new Date("2099-01-01T00:00:00Z"),+ trial_ends_at: new Date("2026-10-12T12:00:00Z"),+ period_starts_at: new Date("2026-10-07T12:00:00Z"),+ next_payment_at: new Date("2027-10-07T12:00:00Z"),+ tax_amount: 1021,+ },+};diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/services/pro-activation/__tests__/helpers.test.tsnew file mode 100644index 0000000000..d7bf153f32--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/helpers.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import {+ formatAmount,+ safeReturnTo,+ invoiceURL,+ intervalLabel,+} from "../helpers";++describe("activation payment terms", () => {+ it("uses the currency's minor unit, including zero and three digit currencies", () => {+ expect(formatAmount(1234, "usd")).toBe("$12.34");+ expect(formatAmount(1234, "jpy")).toBe("¥1,234");+ expect(formatAmount(1234, "kwd")).toContain("1.234");+ });+ it("preserves local return context but rejects external destinations", () => {+ expect(safeReturnTo("/copilot/thread?resume=1#draft")).toBe(+ "/copilot/thread?resume=1#draft",+ );+ for (const path of [+ "//evil.example",+ "/\\evil.example",+ "https://evil.example",+ "/\nfoo",+ ]) {+ expect(safeReturnTo(path)).toBe("/settings/billing");+ }+ });+ it("allows only Stripe hosted invoice payment recovery", () => {+ expect(invoiceURL("https://invoice.stripe.com/i/123")).toBe(+ "https://invoice.stripe.com/i/123",+ );+ expect(invoiceURL("javascript:alert(1)")).toBeNull();+ expect(+ invoiceURL("https://invoice.stripe.com.evil.example/i/123"),+ ).toBeNull();+ });+ it("does not assume all quotes are monthly", () => {+ expect(intervalLabel("year", 1)).toBe("year");+ expect(intervalLabel("month", 3)).toBe("3 months");+ });+});diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/provider-session.test.tsx b/autogpt_platform/frontend/src/services/pro-activation/__tests__/provider-session.test.tsxnew file mode 100644index 0000000000..b0750b1490--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/provider-session.test.tsx@@ -0,0 +1,116 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { http, HttpResponse } from "msw";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { server } from "@/mocks/mock-server";+import { ProActivationProvider } from "../ProActivationProvider";+import { useProActivation } from "../useProActivation";+import { quote } from "./fixtures";++vi.mock("@/lib/auth/hooks/useAuthStore", async () => {+ const { create } = await import("zustand");+ return {+ useAuthStore: create<{ user: { id: string } | null }>(() => ({+ user: null,+ })),+ };+});++const userA = { id: "user-A", email: "[email protected]", user_metadata: {} };+const userB = { id: "user-B", email: "[email protected]", user_metadata: {} };++function Subject() {+ const activation = useProActivation();+ return (+ <>+ <input aria-label="Search agents" />+ <span>+ {activation.isReady ? "allowance ready" : "allowance waiting"}+ </span>+ </>+ );+}++function mount() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <ProActivationProvider>+ <Subject />+ </ProActivationProvider>+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ useAuthStore.setState({ user: null });+ sessionStorage.clear();+ window.history.replaceState({}, "", "/");+ server.use(+ http.get(+ "*/api/proxy/api/credits/pro-activation/current",+ () => new HttpResponse(null, { status: 404 }),+ ),+ );+});++describe("Pro activation account lifecycle", () => {+ it("preserves page input and focus when the authenticated user hydrates", () => {+ mount();+ const input = screen.getByRole<HTMLInputElement>("textbox", {+ name: "Search agents",+ });+ input.focus();+ fireEvent.change(input, { target: { value: "My agent" } });++ act(() => useAuthStore.setState({ user: userA }));++ expect(screen.getByRole("textbox", { name: "Search agents" })).toBe(input);+ expect(input.value).toBe("My agent");+ expect(document.activeElement).toBe(input);+ });++ it("clears the previous account's activation readiness on account changes", async () => {+ useAuthStore.setState({ user: userA });+ sessionStorage.setItem(+ "pro-activation:user-A",+ JSON.stringify({ id: quote.id, token: quote.terms_token }),+ );+ server.use(+ http.get("*/api/proxy/api/credits/pro-activation/current", () =>+ HttpResponse.json({+ ...quote,+ status: "ready",+ usage_reset: true,+ activation_id: "generation-1",+ }),+ ),+ http.get("*/api/proxy/api/credits/trial", () =>+ HttpResponse.json({ active: false, converted: true }),+ ),+ http.get("*/api/proxy/api/credits/subscription", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ http.get("*/api/proxy/api/chat/usage", () =>+ HttpResponse.json({ tier: "PRO" }),+ ),+ );+ mount();+ await screen.findByText("allowance ready");++ act(() => useAuthStore.setState({ user: userB }));++ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(screen.getByText("allowance waiting")).toBeDefined();+ expect(screen.queryByText("allowance ready")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/quote-expiry.test.ts b/autogpt_platform/frontend/src/services/pro-activation/__tests__/quote-expiry.test.tsnew file mode 100644index 0000000000..0984860064--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/quote-expiry.test.ts@@ -0,0 +1,23 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useQuoteExpiry } from "../useQuoteExpiry";++afterEach(() => vi.useRealTimers());++describe("quoted price expiry", () => {+ it("stays quiet until two minutes remain and then requires a refreshed quote", () => {+ vi.useFakeTimers();+ const now = new Date("2026-10-07T12:00:00Z");+ vi.setSystemTime(now);+ const { result, unmount } = renderHook(() =>+ useQuoteExpiry(new Date(now.getTime() + 180000)),+ );+ expect(result.current).toEqual({ expired: false, expiringSoon: false });+ act(() => vi.advanceTimersByTime(61000));+ expect(result.current).toEqual({ expired: false, expiringSoon: true });+ act(() => vi.advanceTimersByTime(119000));+ expect(result.current).toEqual({ expired: true, expiringSoon: false });+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/autogpt_platform/frontend/src/services/pro-activation/__tests__/recovery-polling.test.tsx b/autogpt_platform/frontend/src/services/pro-activation/__tests__/recovery-polling.test.tsxnew file mode 100644index 0000000000..c5a107039e--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/__tests__/recovery-polling.test.tsx@@ -0,0 +1,180 @@+import { focusManager, onlineManager } from "@tanstack/react-query";+import { act, cleanup, render, screen } from "@testing-library/react";+import { useState } from "react";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";+import { server } from "@/mocks/mock-server";+import { useActivationRecovery } from "../useActivationRecovery";+import { quote } from "./fixtures";++const requests = vi.fn();+let response: ActivationResponse;++function Subject({ onMissing = vi.fn() }: { onMissing?: () => void }) {+ const [attempt, setAttempt] = useState<ActivationResponse | null>({+ ...quote,+ status: "processing",+ retry_after_seconds: 3,+ });+ useActivationRecovery({+ userID: "user-1",+ attempt,+ checkoutReturn: false,+ accept: setAttempt,+ onError: vi.fn(),+ onMissing: () => {+ onMissing();+ setAttempt(null);+ },+ });+ return <span>{attempt?.status ?? "none"}</span>;+}++function PageLoad({ checkoutReturn }: { checkoutReturn: boolean }) {+ useActivationRecovery({+ userID: "user-1",+ attempt: null,+ checkoutReturn,+ accept: vi.fn(),+ onError: vi.fn(),+ onMissing: vi.fn(),+ });+ return null;+}++async function advance(milliseconds: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(milliseconds);+ });+}++async function expectReady() {+ await vi.waitFor(async () => {+ await advance(1);+ expect(screen.getByText("ready")).toBeDefined();+ });+}++beforeEach(() => {+ vi.useFakeTimers();+ focusManager.setFocused(true);+ onlineManager.setOnline(true);+ requests.mockReset();+ response = { ...quote, status: "processing", retry_after_seconds: 3 };+ server.use(+ http.get(+ "*/api/proxy/api/credits/pro-activation/current",+ () => new HttpResponse(null, { status: 404 }),+ ),+ http.get("*/api/proxy/api/credits/pro-activation/attempt-1", () => {+ requests();+ return HttpResponse.json(response);+ }),+ );+});++afterEach(() => {+ cleanup();+ sessionStorage.clear();+ focusManager.setFocused(undefined);+ onlineManager.setOnline(true);+ vi.useRealTimers();+});++describe("pending activation synchronization", () => {+ it("pauses while hidden or offline, checks immediately on return, and stops at ready", async () => {+ render(<Subject />);+ act(() => focusManager.setFocused(false));+ await advance(30_000);+ expect(requests).not.toHaveBeenCalled();+ act(() => onlineManager.setOnline(false));+ act(() => focusManager.setFocused(true));+ await advance(30_000);+ expect(requests).not.toHaveBeenCalled();+ response = { ...quote, status: "ready" };+ act(() => onlineManager.setOnline(true));+ await expectReady();+ expect(requests).toHaveBeenCalledTimes(1);+ await advance(30_000);+ act(() => focusManager.setFocused(false));+ act(() => focusManager.setFocused(true));+ await advance(3_000);+ expect(requests).toHaveBeenCalledTimes(1);+ });++ it("stops checking once the server has no such activation", async () => {+ const onMissing = vi.fn();+ server.use(+ http.get("*/api/proxy/api/credits/pro-activation/attempt-1", () => {+ requests();+ return new HttpResponse(null, { status: 404 });+ }),+ );+ render(<Subject onMissing={onMissing} />);+ await vi.waitFor(async () => {+ await advance(1_000);+ expect(onMissing).toHaveBeenCalledTimes(1);+ });+ expect(screen.getByText("none")).toBeDefined();+ await advance(30_000);+ expect(requests).toHaveBeenCalledTimes(1);+ });++ it("looks up an activation on load only when a payment is being resumed", async () => {+ const lookups = vi.fn();+ server.use(+ http.get("*/api/proxy/api/credits/pro-activation/current", () => {+ lookups();+ return new HttpResponse(null, { status: 404 });+ }),+ );+ render(<PageLoad checkoutReturn={false} />);+ await advance(5_000);+ expect(lookups).not.toHaveBeenCalled();+ cleanup();++ sessionStorage.setItem(+ "pro-activation:user-1",+ JSON.stringify({ id: "attempt-1", token: "a".repeat(64) }),+ );+ render(<PageLoad checkoutReturn={false} />);+ await vi.waitFor(async () => {+ await advance(1);+ expect(lookups).toHaveBeenCalledTimes(1);+ });+ cleanup();+ sessionStorage.clear();++ render(<PageLoad checkoutReturn />);+ await vi.waitFor(async () => {+ await advance(1);+ expect(lookups).toHaveBeenCalledTimes(2);+ });+ });++ it("keeps one in-flight status check when visibility changes during the request", async () => {+ let release!: () => void;+ const pending = new Promise<void>((resolve) => {+ release = resolve;+ });+ server.use(+ http.get("*/api/proxy/api/credits/pro-activation/attempt-1", async () => {+ requests();+ await pending;+ return HttpResponse.json({ ...quote, status: "ready" });+ }),+ );+ render(<Subject />);+ await advance(3_000);+ await vi.waitFor(() => expect(requests).toHaveBeenCalledTimes(1));+ act(() => focusManager.setFocused(false));+ act(() => focusManager.setFocused(true));+ await advance(9_000);+ expect(requests).toHaveBeenCalledTimes(1);+ release();+ await expectReady();+ await advance(30_000);+ expect(requests).toHaveBeenCalledTimes(1);+ });+});diff --git a/autogpt_platform/frontend/src/services/pro-activation/api.ts b/autogpt_platform/frontend/src/services/pro-activation/api.tsnew file mode 100644index 0000000000..51759f118c--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/api.ts@@ -0,0 +1,42 @@+import {+ getSubscriptionsGetCurrentProActivation,+ getSubscriptionsGetProActivation,+ postSubscriptionsConfirmProActivation,+ postSubscriptionsPreviewProActivation,+} from "@/app/api/__generated__/endpoints/subscriptions/subscriptions";+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";++function response<T extends { status: number; data: unknown }>(result: T) {+ if (result.status !== 200)+ throw new Error("Activation request could not be completed");+ return result.data as ActivationResponse;+}++export async function previewActivation(returnTo: string) {+ return response(+ await postSubscriptionsPreviewProActivation({ return_to: returnTo }),+ );+}++export async function confirmActivation(id: string, token: string) {+ return response(+ await postSubscriptionsConfirmProActivation(id, {+ confirmed: true,+ terms_token: token,+ }),+ );+}++export async function retrieveActivation(id?: string | null) {+ return response(+ await (id+ ? getSubscriptionsGetProActivation(id)+ : getSubscriptionsGetCurrentProActivation()),+ );+}++export function statusCode(error: unknown) {+ return error && typeof error === "object" && "status" in error+ ? error.status+ : undefined;+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/context.ts b/autogpt_platform/frontend/src/services/pro-activation/context.tsnew file mode 100644index 0000000000..f23bd79858--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/context.ts@@ -0,0 +1,7 @@+import { createContext } from "react";++export const ProActivationContext = createContext<{+ start: (returnTo?: string) => Promise<void>;+ isBusy: boolean;+ isReady: boolean;+} | null>(null);diff --git a/autogpt_platform/frontend/src/services/pro-activation/helpers.ts b/autogpt_platform/frontend/src/services/pro-activation/helpers.tsnew file mode 100644index 0000000000..0ca21195c8--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/helpers.ts@@ -0,0 +1,33 @@+export function formatAmount(amount: number, currency: string) {+ const formatter = new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: currency.toUpperCase(),+ });+ const digits = formatter.resolvedOptions().maximumFractionDigits ?? 2;+ return formatter.format(amount / 10 ** digits);+}++export function intervalLabel(interval: string, count: number) {+ return count === 1 ? interval : `${count} ${interval}s`;+}++export function safeReturnTo(path: string) {+ return path.startsWith("/") &&+ !path.startsWith("//") &&+ !path.includes("\\") &&+ !/[\u0000-\u001f]/.test(path)+ ? path+ : "/settings/billing";+}++export function invoiceURL(value?: string | null) {+ if (!value) return null;+ try {+ const url = new URL(value);+ return url.protocol === "https:" && url.hostname === "invoice.stripe.com"+ ? url.href+ : null;+ } catch {+ return null;+ }+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/refreshActivation.ts b/autogpt_platform/frontend/src/services/pro-activation/refreshActivation.tsnew file mode 100644index 0000000000..779ade6271--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/refreshActivation.ts@@ -0,0 +1,77 @@+import { QueryClient } from "@tanstack/react-query";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";++import {+ getGetTrialsGetTrialStatusQueryKey,+ getTrialsGetTrialStatus,+} from "@/app/api/__generated__/endpoints/trials/trials";+import {+ getGetSubscriptionStatusQueryKey,+ getSubscriptionStatus,+} from "@/app/api/__generated__/endpoints/credits/credits";+import {+ getGetV2GetCopilotUsageQueryKey,+ getV2GetCopilotUsage,+} from "@/app/api/__generated__/endpoints/chat/chat";++export async function refreshActivation(+ client: QueryClient,+ userID: string,+ expectedPlan?: "PRO" | "MAX",+) {+ const keys = [+ getGetTrialsGetTrialStatusQueryKey(),+ getGetSubscriptionStatusQueryKey(),+ getGetV2GetCopilotUsageQueryKey(),+ ];+ await Promise.all(keys.map((queryKey) => client.cancelQueries({ queryKey })));+ await Promise.all(+ keys.map((queryKey) =>+ client.invalidateQueries({ queryKey, refetchType: "none" }),+ ),+ );+ const [trial, subscription, usage] = await Promise.all([+ client.fetchQuery({+ queryKey: [...keys[0], userID],+ queryFn: ({ signal }) =>+ ownedResponse(() => getTrialsGetTrialStatus({ signal }), userID),+ staleTime: 0,+ }),+ client.fetchQuery({+ queryKey: keys[1],+ queryFn: ({ signal }) =>+ ownedResponse(() => getSubscriptionStatus({ signal })),+ staleTime: 0,+ }),+ client.fetchQuery({+ queryKey: keys[2],+ queryFn: ({ signal }) =>+ ownedResponse(() => getV2GetCopilotUsage({ signal })),+ staleTime: 0,+ }),+ ]);+ if (+ trial.status !== 200 ||+ subscription.status !== 200 ||+ usage.status !== 200 ||+ trial.data.active ||+ !["PRO", "MAX"].includes(subscription.data.tier ?? "") ||+ usage.data.tier !== subscription.data.tier ||+ (expectedPlan != null && subscription.data.tier !== expectedPlan)+ )+ throw new Error("Your plan and allowance are still being refreshed");+ return subscription.data.tier === "MAX" ? "MAX" : "PRO";+}++async function ownedResponse<T>(+ request: () => Promise<T>,+ expectedUserID?: string,+) {+ const userID = expectedUserID ?? useAuthStore.getState().user?.id;+ if (!userID || useAuthStore.getState().user?.id !== userID)+ throw new Error("Account changed during activation");+ const result = await request();+ if (useAuthStore.getState().user?.id !== userID)+ throw new Error("Account changed during activation");+ return result;+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/reviewDetails.ts b/autogpt_platform/frontend/src/services/pro-activation/reviewDetails.tsnew file mode 100644index 0000000000..691bb33239--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/reviewDetails.ts@@ -0,0 +1,66 @@+import type { ActivationTerms } from "@/app/api/__generated__/models/activationTerms";+import { formatAmount, intervalLabel } from "./helpers";++export function shortDate(value: Date | string) {+ return new Date(value).toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ });+}++function ordinal(day: number) {+ const suffix =+ day % 100 >= 11 && day % 100 <= 13+ ? "th"+ : ({ 1: "st", 2: "nd", 3: "rd" }[day % 10] ?? "th");+ return `${day}${suffix}`;+}++export function billingCadence(terms: ActivationTerms) {+ return (terms.billing_interval_count ?? 1) === 1+ ? terms.billing_interval === "year"+ ? "yearly"+ : "monthly"+ : `every ${intervalLabel(terms.billing_interval, terms.billing_interval_count ?? 1)}`;+}++export function trialEndNotice(terms: ActivationTerms) {+ const plan = terms.plan === "MAX" ? "Max" : "Pro";+ const trialEnd = terms.trial_ends_at;+ const start = terms.period_starts_at;+ if (!trialEnd || !start)+ return `Starting ${plan} ends your free trial early. Your paid billing period begins when you confirm.`;+ const billingDay =+ terms.billing_interval === "year"+ ? shortDate(start)+ : `the ${ordinal(new Date(start).getDate())}`;+ return `Your free trial ends now instead of ${shortDate(trialEnd)}, and your billing date moves to ${billingDay}.`;+}++export function nextPaymentDescription(terms: ActivationTerms) {+ const amount = formatAmount(terms.renewal_unit_amount, terms.currency);+ const discountedRenewal = terms.renewal_discounts?.some(+ (discount) => discount.duration !== "once",+ );+ const price = discountedRenewal+ ? `Next payment based on ${amount} before renewal discounts`+ : `Next payment of ${amount}`;+ const tax =+ terms.renewal_tax?.price_tax_behavior === "inclusive"+ ? " including tax"+ : " plus tax";+ return `${price}${tax}, then every ${intervalLabel(terms.billing_interval, terms.billing_interval_count ?? 1)}.`;+}++export function invoiceAdjustment(terms: ActivationTerms) {+ if (+ terms.tax_amount == null ||+ terms.renewal_tax?.price_tax_behavior === "unspecified"+ )+ return null;+ const additionalTax =+ terms.renewal_tax?.price_tax_behavior === "inclusive"+ ? 0+ : terms.tax_amount;+ return terms.amount_due - terms.renewal_unit_amount - additionalTax;+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/storage.ts b/autogpt_platform/frontend/src/services/pro-activation/storage.tsnew file mode 100644index 0000000000..3d818912aa--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/storage.ts@@ -0,0 +1,33 @@+export interface PendingConsent {+ id: string;+ token: string;+}++export function pendingConsent(userID?: string): PendingConsent | null {+ if (!userID || typeof window === "undefined") return null;+ try {+ const value = JSON.parse(+ sessionStorage.getItem(`pro-activation:${userID}`) ?? "null",+ );+ return value &&+ typeof value.id === "string" &&+ /^[a-f0-9]{64}$/.test(value.token)+ ? value+ : null;+ } catch {+ return null;+ }+}++export function storeConsent(userID: string, consent: PendingConsent | null) {+ try {+ if (consent)+ sessionStorage.setItem(+ `pro-activation:${userID}`,+ JSON.stringify(consent),+ );+ else sessionStorage.removeItem(`pro-activation:${userID}`);+ } catch {+ /* The server remains the source of recovery if browser storage is unavailable. */+ }+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/useActivationController.ts b/autogpt_platform/frontend/src/services/pro-activation/useActivationController.tsnew file mode 100644index 0000000000..9655799421--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/useActivationController.ts@@ -0,0 +1,242 @@+import { useRef, useState } from "react";+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import {+ confirmActivation,+ previewActivation,+ retrieveActivation,+ statusCode,+} from "./api";+import { useActivationReadiness } from "./useActivationReadiness";+import { pendingConsent, storeConsent } from "./storage";+import { safeReturnTo } from "./helpers";+import { useActivationRecovery } from "./useActivationRecovery";++export function useActivationController() {+ const userID = useAuthStore((state) => state.user?.id);+ const [attempt, setAttempt] = useState<ActivationResponse | null>(null);+ const [isOpen, setOpen] = useState(false);+ const [isBusy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const [needsNewTerms, setNeedsNewTerms] = useState(false);+ const inFlight = useRef(false);+ const checkoutReturn = useRef(+ typeof window !== "undefined" &&+ new URLSearchParams(window.location.search).get("subscription") ===+ "success",+ );+ const interacted = useRef(false);+ const latestAttempt = useRef<ActivationResponse | null>(null);+ const consent = useRef<{ id: string; token: string } | null>(null);+ const destination = useRef("/settings/billing");+ const returnFocus = useRef<HTMLElement | null>(null);+ const [retryConsent, setRetryConsent] = useState(false);+ const {+ isReady,+ readyPlan,+ hasFreshUsage,+ isRefreshing,+ finish,+ clearReadiness,+ } = useActivationReadiness(userID, setOpen, setError);++ function isCurrentUser() {+ return !!userID && useAuthStore.getState().user?.id === userID;+ }+ function remember() {+ if (userID && consent.current) storeConsent(userID, consent.current);+ setRetryConsent(true);+ }+ function accept(+ response: ActivationResponse,+ recovered = false,+ background = false,+ ) {+ if (!userID || !isCurrentUser() || (recovered && interacted.current))+ return;+ if (background && latestAttempt.current?.status === "ready") return;+ const resumed = !!pendingConsent(userID) || checkoutReturn.current;+ if (recovered && !resumed) return;+ latestAttempt.current = response;+ setAttempt(response);+ setError("");+ if (response.status === "not_applicable") {+ clearReadiness();+ consent.current = null;+ storeConsent(userID, null);+ setRetryConsent(false);+ if (recovered) setOpen(false);+ return;+ }+ if (response.status === "ready") {+ void finish(response, !recovered || resumed);+ } else if (+ response.status !== "confirmation_required" ||+ !recovered ||+ resumed+ ) {+ consent.current ??= pendingConsent(userID);+ setRetryConsent(!!consent.current);+ if (!background) setOpen(true);+ }+ }++ function changeOpen(open: boolean) {+ setOpen(open);+ if (!open)+ requestAnimationFrame(() => {+ if (returnFocus.current?.isConnected) returnFocus.current.focus();+ });+ }++ async function start(+ returnTo = `${window.location.pathname}${window.location.search}${window.location.hash}`,+ ) {+ if (inFlight.current || !userID) return;+ interacted.current = true;+ if (!isOpen && document.activeElement instanceof HTMLElement)+ returnFocus.current = document.activeElement;+ setOpen(true);+ setError("");+ if (+ attempt &&+ ["processing", "payment_required", "action_required"].includes(+ attempt.status,+ )+ )+ return;+ const saved = consent.current ?? pendingConsent(userID);+ if (saved) {+ consent.current = saved;+ await check(saved.id);+ return;+ }+ destination.current = safeReturnTo(returnTo);+ inFlight.current = true;+ setBusy(true);+ try {+ let existing: ActivationResponse | null = null;+ try {+ existing = await retrieveActivation();+ } catch (error) {+ if (statusCode(error) !== 404) throw error;+ }+ // Without an attempt id this is the lookup saying it couldn't check,+ // not a payment in flight to wait on.+ if (existing?.status === "processing" && !existing.id)+ throw new Error("Activation status is unavailable");+ if (+ existing &&+ existing.status !== "confirmation_required" &&+ existing.status !== "failed"+ )+ accept(existing);+ else {+ const quote = await previewActivation(destination.current);+ consent.current = null;+ setRetryConsent(false);+ setNeedsNewTerms(false);+ accept(quote);+ }+ } catch {+ setError(+ "We couldn’t load your upgrade details. Please try again before confirming payment.",+ );+ } finally {+ inFlight.current = false;+ setBusy(false);+ }+ }++ async function confirm() {+ if (+ inFlight.current ||+ !attempt?.id ||+ !attempt.terms_token ||+ !attempt.terms+ )+ return;+ interacted.current = true;+ inFlight.current = true;+ setBusy(true);+ setError("");+ consent.current ??= { id: attempt.id, token: attempt.terms_token };+ remember();+ try {+ accept(+ await confirmActivation(consent.current.id, consent.current.token),+ );+ } catch (error) {+ try {+ const current = await retrieveActivation(consent.current.id);+ accept(current);+ if (+ current.status === "confirmation_required" &&+ statusCode(error) === 409+ ) {+ consent.current = null;+ if (userID) storeConsent(userID, null);+ setRetryConsent(false);+ setNeedsNewTerms(true);+ setError("Review the current terms before confirming this upgrade.");+ }+ } catch {+ setError(+ "We couldn’t confirm the payment status. Check the existing payment before trying again.",+ );+ }+ } finally {+ inFlight.current = false;+ setBusy(false);+ }+ }++ async function check(id = attempt?.id) {+ if (inFlight.current) return;+ inFlight.current = true;+ setBusy(true);+ try {+ accept(await retrieveActivation(id));+ } catch {+ setError("We couldn’t check your payment yet. Please try again.");+ } finally {+ inFlight.current = false;+ setBusy(false);+ }+ }++ // The server has nothing for the attempt being checked: stop waiting on it+ // so Start Pro can quote again.+ function forget() {+ latestAttempt.current = null;+ setAttempt(null);+ consent.current = null;+ if (userID) storeConsent(userID, null);+ setRetryConsent(false);+ setError("We couldn’t find a payment in progress. You can start again.");+ }++ useActivationRecovery({+ userID,+ attempt,+ checkoutReturn: checkoutReturn.current,+ accept,+ onError: setError,+ onMissing: forget,+ });+ return {+ attempt,+ isOpen,+ setOpen: changeOpen,+ isBusy: isBusy || isRefreshing,+ isReady,+ hasFreshUsage,+ readyPlan,+ error,+ needsNewTerms,+ retryConsent,+ start,+ confirm,+ check,+ };+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/useActivationReadiness.ts b/autogpt_platform/frontend/src/services/pro-activation/useActivationReadiness.tsnew file mode 100644index 0000000000..cb0c455bea--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/useActivationReadiness.ts@@ -0,0 +1,78 @@+import { useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { useRouter } from "next/navigation";+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { refreshActivation } from "./refreshActivation";+import { safeReturnTo } from "./helpers";+import { storeConsent } from "./storage";++export function useActivationReadiness(+ userID: string | undefined,+ setOpen: (open: boolean) => void,+ setError: (error: string) => void,+) {+ const client = useQueryClient();+ const router = useRouter();+ const [readyPlan, setReadyPlan] = useState<"PRO" | "MAX" | null>(null);+ const [isReady, setReady] = useState(false);+ const [hasFreshUsage, setFreshUsage] = useState(false);+ const [isRefreshing, setRefreshing] = useState(false);+ const finishing = useRef(false);+ async function finish(response: ActivationResponse, notify: boolean) {+ if (!userID || finishing.current) return;+ finishing.current = true;+ setRefreshing(true);+ try {+ const plan = await refreshActivation(+ client,+ userID,+ response.terms?.plan,+ );+ if (useAuthStore.getState().user?.id !== userID) return;+ if (notify) {+ setReady(true);+ setReadyPlan(plan);+ setFreshUsage(+ response.usage_reset === true && !!response.activation_id,+ );+ }+ storeConsent(userID, null);+ if (notify) {+ setOpen(true);+ const returnTo = safeReturnTo(+ response.return_to ?? "/settings/billing",+ );+ if (+ returnTo !==+ `${window.location.pathname}${window.location.search}${window.location.hash}`+ )+ router.replace(returnTo);+ }+ } catch {+ finishing.current = false;+ if (useAuthStore.getState().user?.id === userID) {+ setOpen(true);+ setError(+ "Your payment is confirmed. We’re refreshing your plan and usage before you continue.",+ );+ }+ } finally {+ finishing.current = false;+ setRefreshing(false);+ }+ }+ function clearReadiness() {+ setReady(false);+ setReadyPlan(null);+ setFreshUsage(false);+ }+ return {+ isReady,+ readyPlan,+ hasFreshUsage,+ isRefreshing,+ finish,+ clearReadiness,+ };+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/useActivationRecovery.ts b/autogpt_platform/frontend/src/services/pro-activation/useActivationRecovery.tsnew file mode 100644index 0000000000..d684408046--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/useActivationRecovery.ts@@ -0,0 +1,102 @@+import { useEffect, useRef } from "react";+import { focusManager, onlineManager } from "@tanstack/react-query";+import type { ActivationResponse } from "@/app/api/__generated__/models/activationResponse";+import { retrieveActivation, statusCode } from "./api";+import { pendingConsent } from "./storage";++interface Options {+ userID?: string;+ attempt: ActivationResponse | null;+ /** The page loaded on the way back from Stripe's checkout. */+ checkoutReturn: boolean;+ accept: (+ response: ActivationResponse,+ recovered?: boolean,+ background?: boolean,+ ) => void;+ onError: (message: string) => void;+ /** The server has no activation for the attempt being checked. */+ onMissing: () => void;+}++export function useActivationRecovery(options: Options) {+ const latest = useRef(options);+ latest.current = options;+ const { userID, attempt, checkoutReturn } = options;+ useEffect(() => {+ // Only a payment being resumed can use the answer, and for a paying user+ // the lookup reconciles with Stripe, so an ordinary page load skips it.+ if (!userID || (!checkoutReturn && !pendingConsent(userID))) return;+ let alive = true;+ retrieveActivation()+ .then((result) => {+ if (alive) latest.current.accept(result, true);+ })+ .catch((error) => {+ if (alive && statusCode(error) !== 404) {+ latest.current.onError(+ "We couldn’t check your payment yet. Your activation can be recovered without starting another purchase.",+ );+ }+ });+ return () => {+ alive = false;+ };+ }, [userID, checkoutReturn]);++ useEffect(() => {+ if (+ !userID ||+ !attempt ||+ !["processing", "payment_required", "action_required"].includes(+ attempt.status,+ )+ )+ return;+ let alive = true;+ let timer: ReturnType<typeof setTimeout>;+ let inFlight = false;+ function canPoll() {+ return alive && focusManager.isFocused() && onlineManager.isOnline();+ }+ function schedule() {+ clearTimeout(timer);+ if (canPoll())+ timer = setTimeout(+ poll,+ Math.max(3, attempt?.retry_after_seconds ?? 3) * 1000,+ );+ }+ async function poll() {+ if (!canPoll() || inFlight) return;+ inFlight = true;+ try {+ const response = await retrieveActivation(attempt?.id);+ if (alive) latest.current.accept(response, false, true);+ } catch (error) {+ // An attempt the server no longer has is nothing to wait for.+ if (alive && statusCode(error) === 404) latest.current.onMissing();+ else if (alive)+ latest.current.onError(+ "We’re still checking your payment. You won’t be charged again by this status check.",+ );+ } finally {+ inFlight = false;+ schedule();+ }+ }+ function resume() {+ clearTimeout(timer);+ void poll();+ }+ const unsubscribeFocus = focusManager.subscribe(resume);+ const unsubscribeOnline = onlineManager.subscribe(resume);+ schedule();+ return () => {+ alive = false;+ clearTimeout(timer);+ unsubscribeFocus();+ unsubscribeOnline();+ };+ }, [userID, attempt?.id, attempt?.status, attempt?.retry_after_seconds]);+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/useProActivation.ts b/autogpt_platform/frontend/src/services/pro-activation/useProActivation.tsnew file mode 100644index 0000000000..257fc2be67--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/useProActivation.ts@@ -0,0 +1,10 @@+"use client";+import { useContext } from "react";+import { ProActivationContext } from "./context";++export function useProActivation() {+ const context = useContext(ProActivationContext);+ if (!context)+ throw new Error("useProActivation requires ProActivationProvider");+ return context;+}diff --git a/autogpt_platform/frontend/src/services/pro-activation/useQuoteExpiry.ts b/autogpt_platform/frontend/src/services/pro-activation/useQuoteExpiry.tsnew file mode 100644index 0000000000..99aceed6cf--- /dev/null+++ b/autogpt_platform/frontend/src/services/pro-activation/useQuoteExpiry.ts@@ -0,0 +1,17 @@+import { useEffect, useState } from "react";++export function useQuoteExpiry(expiresAt?: Date | string) {+ const [now, setNow] = useState(Date.now);+ const expiration = expiresAt ? new Date(expiresAt).getTime() : null;+ useEffect(() => {+ if (expiration == null) return;+ setNow(Date.now());+ const timer = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(timer);+ }, [expiration]);+ const remaining = expiration == null ? null : expiration - now;+ return {+ expired: remaining != null && remaining <= 0,+ expiringSoon: remaining != null && remaining > 0 && remaining < 120000,+ };+}diff --git a/autogpt_platform/frontend/src/services/trials/TrialStatusSync.tsx b/autogpt_platform/frontend/src/services/trials/TrialStatusSync.tsxnew file mode 100644index 0000000000..26facbfe00--- /dev/null+++ b/autogpt_platform/frontend/src/services/trials/TrialStatusSync.tsx@@ -0,0 +1,8 @@+"use client";++import { useTrialStatus } from "./useTrialStatus";++export function TrialStatusSync() {+ useTrialStatus({ poll: true });+ return null;+}diff --git a/autogpt_platform/frontend/src/services/trials/__tests__/trial-status-polling.test.tsx b/autogpt_platform/frontend/src/services/trials/__tests__/trial-status-polling.test.tsxnew file mode 100644index 0000000000..54d2629444--- /dev/null+++ b/autogpt_platform/frontend/src/services/trials/__tests__/trial-status-polling.test.tsx@@ -0,0 +1,206 @@+import {+ QueryClient,+ QueryClientProvider,+ focusManager,+} from "@tanstack/react-query";+import { act, cleanup, render } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { server } from "@/mocks/mock-server";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { TrialStatusSync } from "../TrialStatusSync";+import { useTrialStatus } from "../useTrialStatus";++vi.mock("@/lib/auth/hooks/useAuthStore", async () => {+ const { create } = await import("zustand");+ return {+ useAuthStore: create<{ user: { id: string } | null }>(() => ({+ user: null,+ })),+ };+});++let trial: TrialStatusResponse;+let client: QueryClient;+const requests = vi.fn();++function Consumer() {+ const status = useTrialStatus();+ return <span>{status.data?.status}</span>;+}++function CheckoutReturnConsumer() {+ useTrialStatus({+ refetchInterval: (status) =>+ status?.active && status.cancel_at_period_end ? 2_000 : false,+ });+ return null;+}++function tree(consumers = 1) {+ return (+ <QueryClientProvider client={client}>+ <TrialStatusSync />+ {Array.from({ length: consumers }, (_, index) => (+ <Consumer key={index} />+ ))}+ </QueryClientProvider>+ );+}++async function advance(milliseconds: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(milliseconds);+ });+}++async function settled() {+ await act(async () => {+ await vi.waitFor(() => expect(client.isFetching()).toBe(0));+ await vi.advanceTimersByTimeAsync(1);+ });+}++beforeEach(() => {+ vi.useFakeTimers();+ focusManager.setFocused(true);+ useAuthStore.setState({+ user: { id: "user-A", email: "[email protected]", user_metadata: {} },+ });+ trial = { active: false, eligible: true, status: null };+ requests.mockReset();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ server.use(+ http.get("*/api/proxy/api/credits/trial", () => {+ requests(useAuthStore.getState().user?.id);+ return HttpResponse.json(trial);+ }),+ );+});++afterEach(() => {+ cleanup();+ client.clear();+ focusManager.setFocused(undefined);+ vi.useRealTimers();+});++describe("trial status synchronization", () => {+ it("does not give individual consumers their own polling timers", async () => {+ trial = { active: true, status: "trialing" };+ render(+ <QueryClientProvider client={client}>+ <Consumer />+ <Consumer />+ </QueryClientProvider>,+ );+ await settled();+ await advance(90_000);+ expect(requests).toHaveBeenCalledTimes(1);+ });++ it.each([+ { active: false, eligible: true, status: null },+ { active: false, converted: true, status: "converted" },+ { active: false, status: "canceled" },+ { active: false, eligible: true, status: "checkout_pending" },+ ])("does not poll a stable state %j", async (state) => {+ trial = state;+ render(tree(3));+ await settled();+ expect(requests).toHaveBeenCalledTimes(1);+ await advance(120_000);+ expect(requests).toHaveBeenCalledTimes(1);+ });++ it("has one polling owner even when consumers mount at different times", async () => {+ trial = { active: true, status: "trialing" };+ const view = render(tree());+ await settled();+ await advance(5_000);+ view.rerender(tree(3));+ await advance(25_000);+ await settled();+ expect(requests).toHaveBeenCalledTimes(2);+ await advance(5_000);+ expect(requests).toHaveBeenCalledTimes(2);+ await advance(25_000);+ await settled();+ expect(requests).toHaveBeenCalledTimes(3);+ });++ it("starts polling after a focus refresh activates a trial and stops after conversion", async () => {+ render(tree());+ await settled();+ act(() => focusManager.setFocused(false));+ await advance(11_000);+ trial = { active: true, status: "trialing" };+ act(() => focusManager.setFocused(true));+ await settled();+ expect(requests).toHaveBeenCalledTimes(2);+ trial = { active: false, converted: true, status: "converted" };+ await advance(30_000);+ await settled();+ expect(requests).toHaveBeenCalledTimes(3);+ await advance(90_000);+ expect(requests).toHaveBeenCalledTimes(3);+ });++ it("pauses hidden-tab polling and refreshes once when the user returns", async () => {+ trial = { active: true, status: "trialing" };+ render(tree(3));+ await settled();+ act(() => focusManager.setFocused(false));+ await advance(90_000);+ expect(requests).toHaveBeenCalledTimes(1);+ act(() => focusManager.setFocused(true));+ await settled();+ expect(requests).toHaveBeenCalledTimes(2);+ });++ it("switches cache ownership with the account and stops all requests on sign-out", async () => {+ trial = { active: true, status: "trialing" };+ render(tree(2));+ await settled();+ trial = { active: false, converted: true, status: "converted" };+ act(() =>+ useAuthStore.setState({+ user: { id: "user-B", email: "[email protected]", user_metadata: {} },+ }),+ );+ await settled();+ expect(requests.mock.calls).toEqual([["user-A"], ["user-B"]]);+ await advance(60_000);+ expect(requests).toHaveBeenCalledTimes(2);+ act(() => useAuthStore.setState({ user: null }));+ await advance(60_000);+ act(() => focusManager.setFocused(false));+ act(() => focusManager.setFocused(true));+ await settled();+ expect(requests).toHaveBeenCalledTimes(2);+ });++ it("keeps checkout reconciliation fast, pauses hidden requests, and stops when the plan lands", async () => {+ trial = { active: true, cancel_at_period_end: true, status: "trialing" };+ render(+ <QueryClientProvider client={client}>+ <CheckoutReturnConsumer />+ <Consumer />+ </QueryClientProvider>,+ );+ await settled();+ await advance(2_000);+ await settled();+ expect(requests).toHaveBeenCalledTimes(2);+ act(() => focusManager.setFocused(false));+ await advance(20_000);+ expect(requests).toHaveBeenCalledTimes(2);+ trial = { active: false, converted: true, status: "converted" };+ act(() => focusManager.setFocused(true));+ await settled();+ expect(requests).toHaveBeenCalledTimes(3);+ await advance(60_000);+ expect(requests).toHaveBeenCalledTimes(3);+ });+});diff --git a/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts b/autogpt_platform/frontend/src/services/trials/useTrialStatus.tsindex 089546fb0a..2ab37edba6 100644--- a/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts+++ b/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts@@ -6,25 +6,32 @@ import {import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";-type TrialRefetchInterval =- | number- | ((trial: TrialStatusResponse | undefined) => number | false);-interface Options {- refetchInterval?: TrialRefetchInterval;+ poll?: boolean;+ refetchInterval?: (trial: TrialStatusResponse | undefined) => number | false;}-export function useTrialStatus({ refetchInterval }: Options = {}) {+export function useTrialStatus({+ poll = false,+ refetchInterval,+}: Options = {}) {const userID = useAuthStore((state) => state.user?.id);return useGetTrialsGetTrialStatus({query: {queryKey: [...getGetTrialsGetTrialStatusQueryKey(), userID],enabled: Boolean(userID),retry: false,- refetchInterval:- typeof refetchInterval === "function"- ? (query) => refetchInterval(readTrial(query.state.data))- : refetchInterval,+ refetchInterval: (query) => {+ if (refetchInterval)+ return refetchInterval(readTrial(query.state.data));+ const response = query.state.data;+ return poll && response?.status === 200 && response.data.active+ ? 30_000+ : false;+ },+ refetchIntervalInBackground: false,+ refetchOnWindowFocus: true,+ staleTime: 10_000,select: readTrial,},});diff --git a/autogpt_platform/frontend/src/services/usageExperience/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/services/usageExperience/__tests__/helpers.test.tsnew file mode 100644index 0000000000..e7be2da880--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/__tests__/helpers.test.ts@@ -0,0 +1,214 @@+import { describe, expect, it } from "vitest";+import {+ getFeaturedUsagePercent,+ getUsageExperience,+ getUsageOfferAction,+ getUsageStatus,+ formatUsageDate,+} from "../helpers";++const usage = {+ tier: "PRO",+ daily: { percent_used: 100, resets_at: "2026-10-08T00:00:00Z" },+ weekly: { percent_used: 100, resets_at: "2026-10-12T00:00:00Z" },+};+const trial = {+ active: true,+ converted: false,+ allowance_used_percent: 100,+ ends_at: "2026-10-12T12:00:00Z",+ usage_policy: "lifetime",+};++describe("usage experience", () => {+ it("waits for the later blocking window when both limits are exhausted", () => {+ expect(getUsageExperience(usage)).toMatchObject({+ blocked: true,+ window: "weekly",+ resetsAt: usage.weekly.resets_at,+ targetTier: "MAX",+ });+ });+ it("uses the durable lifetime percentage for an active trial without promising a reset", () => {+ expect(+ getUsageExperience({ ...usage, tier: "TRIAL" }, trial),+ ).toMatchObject({+ isLifetimeTrial: true,+ blocked: true,+ window: "trial",+ resetsAt: null,+ trialPercent: 100,+ targetTier: "PRO",+ });+ });+ it("does not apply historical trial consumption after paid activation", () => {+ expect(+ getUsageExperience(+ { ...usage, daily: null, weekly: null },+ { ...trial, converted: true },+ ),+ ).toMatchObject({+ isActiveTrial: false,+ blocked: false,+ trialPercent: null,+ });+ });+ it("retains recurring windows for accepted legacy trial offers", () => {+ expect(+ getUsageExperience(+ { ...usage, tier: "TRIAL" },+ { ...trial, usage_policy: "rolling", allowance_used_percent: 20 },+ ),+ ).toMatchObject({+ isLifetimeTrial: false,+ window: "weekly",+ resetsAt: usage.weekly.resets_at,+ });+ });+ it("does not show a stale trial lifetime meter after expiry", () => {+ expect(+ getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ { ...trial, active: false },+ ),+ ).toMatchObject({ isActiveTrial: false, trialPercent: null });+ });+ it("handles generated Date timestamps alongside serialized API timestamps", () => {+ const daily = new Date(usage.daily.resets_at);+ const weekly = new Date(usage.weekly.resets_at);+ expect(+ getUsageExperience({+ ...usage,+ daily: { ...usage.daily, resets_at: daily },+ weekly: { ...usage.weekly, resets_at: weekly },+ }),+ ).toMatchObject({ window: "weekly", resetsAt: weekly });+ expect(formatUsageDate(weekly)).toBe(+ formatUsageDate(usage.weekly.resets_at),+ );+ expect(+ getUsageExperience(+ { tier: "NO_TIER" },+ {+ active: false,+ converted: false,+ status: "trialing",+ ends_at: new Date("2000-01-01T00:00:00Z"),+ },+ ),+ ).toMatchObject({ inactiveTrialStatus: "expired", resetsAt: null });+ });+ it.each(["canceled", "expired"])(+ "never suggests a reset for an inactive %s trial",+ (status) => {+ expect(+ getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ { ...trial, active: false, status },+ ),+ ).toMatchObject({+ blocked: true,+ inactiveTrialStatus: status,+ resetsAt: null,+ trialPercent: null,+ freshProUsage: false,+ });+ },+ );+ it("does not describe automatic Pro activation for a cancel-pending trial", () => {+ expect(+ getUsageExperience(+ { ...usage, tier: "TRIAL" },+ { ...trial, offer: { tier: "PRO" }, cancel_at_period_end: true },+ ),+ ).toMatchObject({ isActiveTrial: true, freshProUsage: false });+ });+ it("does not promise the Pro activation reset for a legacy non-Pro trial", () => {+ expect(+ getUsageExperience(+ { ...usage, tier: "TRIAL" },+ { ...trial, offer: { tier: "MAX" } },+ ),+ ).toMatchObject({ freshProUsage: false });+ });+ it.each(["MAX", "BUSINESS", "ENTERPRISE"])(+ "does not offer a self-service upgrade to %s",+ (tier) => {+ expect(getUsageExperience({ ...usage, tier })).toMatchObject({+ isTopTier: true,+ targetTier: null,+ });+ },+ );+ it("asks a cancel-pending trial to subscribe rather than start Pro", () => {+ const experience = getUsageExperience(+ { ...usage, tier: "TRIAL" },+ { ...trial, offer: { tier: "PRO" }, cancel_at_period_end: true },+ );+ expect(experience.isCancelPending).toBe(true);+ expect(getUsageOfferAction(experience, {})).toBe("Subscribe now");+ });+ it("keeps Start Pro for a trial that ended without a pending cancellation", () => {+ const experience = getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ { ...trial, active: false, status: "expired" },+ );+ expect(experience.isCancelPending).toBe(false);+ expect(getUsageOfferAction(experience, {})).toBe("Start Pro");+ });+ it("carries the open invoice only for a failed first charge", () => {+ const payment_due = {+ amount_due: 5000,+ currency: "usd",+ payment_url: "https://invoice.stripe.com/i/acct_1/test_inv_1",+ };+ expect(+ getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ {+ ...trial,+ active: false,+ status: "past_due",+ offer: { tier: "PRO" },+ payment_due,+ },+ ).payment,+ ).toEqual({ ...payment_due, plan: "PRO", startsOn: trial.ends_at });+ expect(+ getUsageExperience(+ { ...usage, tier: "NO_TIER" },+ { ...trial, active: false, status: "expired", payment_due },+ ).payment,+ ).toBeNull();+ });+ it.each([+ [0, "plenty"],+ [79.9, "plenty"],+ [80, "low"],+ [99.9, "low"],+ [100, "reached"],+ ] as const)("reports %s%% as %s", (percent, status) => {+ expect(getUsageStatus(percent)).toBe(status);+ });+ it("features the same window the usage card shows", () => {+ const lifetime = getUsageExperience(+ { ...usage, tier: "TRIAL" },+ { ...trial, allowance_used_percent: 64 },+ );+ expect(getFeaturedUsagePercent(lifetime, usage)).toBe(64);+ const weekly = {+ ...usage,+ daily: { ...usage.daily, percent_used: 40 },+ weekly: { ...usage.weekly, percent_used: 100 },+ };+ expect(getFeaturedUsagePercent(getUsageExperience(weekly), weekly)).toBe(+ 100,+ );+ const daily = {+ ...usage,+ daily: { ...usage.daily, percent_used: 30 },+ weekly: { ...usage.weekly, percent_used: 70 },+ };+ expect(getFeaturedUsagePercent(getUsageExperience(daily), daily)).toBe(30);+ });+});diff --git a/autogpt_platform/frontend/src/services/usageExperience/__tests__/offer-price.test.ts b/autogpt_platform/frontend/src/services/usageExperience/__tests__/offer-price.test.tsnew file mode 100644index 0000000000..9271426ddb--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/__tests__/offer-price.test.ts@@ -0,0 +1,16 @@+import { expect, it } from "vitest";+import { formatOfferPrice } from "../helpers";++it.each([+ [5000, "USD", "$50"],+ [5050, "USD", "$50.50"],+ [5000, "JPY", "¥5,000"],+ [50123, "BHD", "BHD 50.123"],+] as const)(+ "keeps accepted %s %s offers consistent with their currency's minor units",+ (amount, currency, expected) => {+ expect(formatOfferPrice(amount, currency)?.replace(/\s+/g, " ")).toBe(+ expected,+ );+ },+);diff --git a/autogpt_platform/frontend/src/services/usageExperience/__tests__/presentation.test.ts b/autogpt_platform/frontend/src/services/usageExperience/__tests__/presentation.test.tsnew file mode 100644index 0000000000..cabb9c377b--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/__tests__/presentation.test.ts@@ -0,0 +1,125 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ formatOfferPrice,+ formatResumeTime,+ getUsageExperience,+ getUsageOfferAction,+} from "../helpers";+import { usagePresentation } from "../presentation";++afterEach(() => vi.useRealTimers());++describe("usage messages", () => {+ it("anchors an exhausted Pro trial to its automatic start date", () => {+ const experience = getUsageExperience(+ { tier: "TRIAL" },+ {+ active: true,+ converted: false,+ usage_policy: "lifetime",+ allowance_used_percent: 100,+ offer: { tier: "PRO" },+ ends_at: new Date(2026, 9, 12, 12),+ },+ );+ expect(usagePresentation(experience)).toMatchObject({+ title: "You’ve used your trial allowance",+ noticeTitle: "You’ve used your trial allowance",+ description:+ "Pro starts on its own on Oct 12. Start it now to keep working today.",+ secondary: "Wait until Oct 12",+ });+ });++ it("does not invent an automatic Pro start for a non-Pro trial", () => {+ const experience = getUsageExperience(+ { tier: "TRIAL" },+ {+ active: true,+ allowance_used_percent: 100,+ offer: { tier: "MAX" },+ ends_at: new Date(2026, 9, 12, 12),+ },+ );+ expect(usagePresentation(experience).description).not.toContain(+ "Pro starts on its own",+ );+ });++ it("keeps the trial start honest when its end date is unavailable", () => {+ const experience = getUsageExperience(+ { tier: "TRIAL" },+ { active: true, allowance_used_percent: 100, offer: { tier: "PRO" } },+ );+ expect(usagePresentation(experience)).toMatchObject({+ description:+ "Pro starts on its own when your trial ends. Start it now to keep working today.",+ secondary: "Back to my work",+ });+ expect(getUsageOfferAction(experience, { price: 5013 })).toBe(+ "Start Pro now · $50.13",+ );+ expect(formatOfferPrice(undefined)).toBeNull();+ expect(formatOfferPrice(51000, "GBP")).toBe("£510");+ });++ it("uses local calendar days at midnight and does not invent missing times", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 9, 7, 23, 55));+ expect(formatResumeTime(new Date(2026, 9, 8, 0, 5))).toBe(+ "tomorrow at 12:05 AM",+ );+ expect(formatResumeTime(new Date(2026, 9, 11, 17))).toBe(+ "Sunday at 5:00 PM",+ );+ expect(formatResumeTime("invalid")).toBeNull();+ expect(formatResumeTime(null)).toBeNull();+ });++ it("leads with the user's local resume time for the highest plans", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 9, 7, 10));+ const experience = getUsageExperience({+ tier: "MAX",+ daily: { percent_used: 100, resets_at: new Date(2026, 9, 7, 17) },+ });+ expect(usagePresentation(experience)).toMatchObject({+ title: "You can continue today at 5:00 PM",+ noticeTitle: "You can continue today at 5:00 PM",+ description: "Your chats, agents and results are saved.",+ });+ });+ it("states the amount and start date of a failed first trial charge", () => {+ const experience = getUsageExperience(+ { tier: "NO_TIER" },+ {+ active: false,+ converted: false,+ status: "past_due",+ offer: { tier: "PRO" },+ ends_at: new Date(2026, 9, 12, 12),+ payment_due: {+ amount_due: 5413,+ currency: "usd",+ payment_url: "https://invoice.stripe.com/i/acct_1/test_inv_1",+ },+ },+ "NO_TIER",+ );+ expect(usagePresentation(experience)).toMatchObject({+ title: "Your payment didn’t go through",+ description:+ "Pro was due to start on Oct 12, but the $54.13 charge didn’t go through. Pay now and Pro starts right away. Your chats, agents and results are saved.",+ });+ });+ it("keeps the billing route when the open invoice is unavailable", () => {+ const experience = getUsageExperience(+ { tier: "NO_TIER" },+ { active: false, converted: false, status: "past_due" },+ "NO_TIER",+ );+ expect(usagePresentation(experience).description).toBe(+ "Review your billing details to continue. Your chats, agents and results are saved.",+ );+ });+});diff --git a/autogpt_platform/frontend/src/services/usageExperience/helpers.ts b/autogpt_platform/frontend/src/services/usageExperience/helpers.tsnew file mode 100644index 0000000000..1840805606--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/helpers.ts@@ -0,0 +1,225 @@+interface UsageWindow {+ percent_used: number;+ resets_at: string | Date;+}+interface Usage {+ tier?: string | null;+ daily?: UsageWindow | null;+ weekly?: UsageWindow | null;+}+interface Trial {+ status?: string | null;+ offer?: { tier?: string } | null;+ active?: boolean;+ cancel_at_period_end?: boolean;+ converted?: boolean;+ allowance_used_percent?: number | null;+ ends_at?: string | Date | null;+ usage_policy?: string | null;+ payment_due?: {+ amount_due: number;+ currency: string;+ payment_url: string;+ } | null;+}++function getTrialPayment(trial?: Trial | null) {+ const due = trial?.payment_due;+ if (!due) return null;+ return {+ ...due,+ plan: trial.offer?.tier ?? null,+ startsOn: trial.ends_at ?? null,+ };+}++export function getUsageExperience(+ usage?: Usage | null,+ trial?: Trial | null,+ subscriptionTier?: string | null,+) {+ const tier = subscriptionTier ?? usage?.tier ?? null;+ const isActiveTrial =+ tier === "TRIAL" && trial?.active === true && !trial.converted;+ const isLifetimeTrial = isActiveTrial && trial?.usage_policy === "lifetime";+ const trialPercent = isActiveTrial+ ? (trial?.allowance_used_percent ?? null)+ : null;+ const trialEnded =+ tier === "NO_TIER" && trial && !trial.active && !trial.converted;+ const inactiveTrialStatus = trialEnded+ ? ["canceled", "cancelled"].includes(trial.status ?? "")+ ? "canceled"+ : ["past_due", "unpaid", "payment_failed"].includes(trial.status ?? "")+ ? "payment_failed"+ : ["expired", "incomplete_expired"].includes(trial.status ?? "") ||+ (trial.status === "trialing" &&+ !!trial.ends_at &&+ new Date(trial.ends_at).getTime() <= Date.now())+ ? "expired"+ : null+ : null;+ const exhausted = (trialPercent ?? 0) >= 100;+ const recurring =+ isLifetimeTrial || inactiveTrialStatus+ ? []+ : (["daily", "weekly"] as const).filter(+ (key) => (usage?.[key]?.percent_used ?? 0) >= 100,+ );+ const window = exhausted+ ? "trial"+ : (recurring.sort(+ (a, b) =>+ new Date(usage?.[b]?.resets_at ?? "").getTime() -+ new Date(usage?.[a]?.resets_at ?? "").getTime(),+ )[0] ?? null);+ const isTopTier =+ tier === "MAX" || tier === "BUSINESS" || tier === "ENTERPRISE";+ return {+ tier,+ isActiveTrial,+ isLifetimeTrial,+ freshProUsage:+ isActiveTrial &&+ !trial?.cancel_at_period_end &&+ trial?.offer?.tier === "PRO",+ isCancelPending: isActiveTrial && trial?.cancel_at_period_end === true,+ trialPercent,+ inactiveTrialStatus,+ payment:+ inactiveTrialStatus === "payment_failed" ? getTrialPayment(trial) : null,+ trialEndsAt: isActiveTrial ? (trial?.ends_at ?? null) : null,+ blocked: window !== null || !!inactiveTrialStatus,+ window,+ resetsAt:+ window && window !== "trial"+ ? (usage?.[window]?.resets_at ?? null)+ : null,+ targetTier:+ isTopTier || !tier || inactiveTrialStatus === "payment_failed"+ ? null+ : tier === "PRO"+ ? ("MAX" as const)+ : ("PRO" as const),+ isTopTier,+ };+}++export type UsageExperience = ReturnType<typeof getUsageExperience>;++export function getUsageStatus(percent: number) {+ if (percent >= 100) return "reached" as const;+ return percent >= 80 ? ("low" as const) : ("plenty" as const);+}++export function getFeaturedUsagePercent(+ experience: UsageExperience,+ usage?: Usage | null,+) {+ if (+ experience.isLifetimeTrial ||+ (experience.isActiveTrial && experience.window === "trial")+ )+ return experience.trialPercent ?? 0;+ const featured =+ experience.window === "weekly" || !usage?.daily+ ? usage?.weekly+ : usage.daily;+ return featured?.percent_used ?? 0;+}++export function formatUsagePercent(value: number) {+ if (value > 0 && value < 1) return "<1%";+ if (value < 100 && value > 99) return "99%";+ return `${Math.min(100, Math.max(0, Math.round(value)))}%`;+}++export function formatUsageDate(value: string | Date) {+ const date = new Date(value);+ if (!Number.isFinite(date.getTime())) return "";+ return date.toLocaleString(undefined, {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ timeZoneName: "short",+ });+}++export function formatTrialDate(value: string | Date | null) {+ if (!value) return null;+ const date = new Date(value);+ if (!Number.isFinite(date.getTime())) return null;+ return date.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ });+}++export function formatTrialStartDescription(value: string | Date | null) {+ const date = formatTrialDate(value);+ return `Pro starts on its own ${date ? `on ${date}` : "when your trial ends"}. Start it now to keep working today.`;+}++export function formatTrialStartTitle(value: string | Date | null) {+ const date = formatTrialDate(value);+ return date ? `Pro starts on ${date}` : "Pro starts when your trial ends";+}++export function formatResumeTime(value: string | Date | null) {+ if (!value) return null;+ const date = new Date(value);+ if (!Number.isFinite(date.getTime())) return null;+ const today = new Date();+ const tomorrow = new Date(today);+ tomorrow.setDate(tomorrow.getDate() + 1);+ const nextWeek = new Date(today);+ nextWeek.setDate(nextWeek.getDate() + 7);+ const day =+ date.toDateString() === today.toDateString()+ ? "today"+ : date.toDateString() === tomorrow.toDateString()+ ? "tomorrow"+ : date > today && date < nextWeek+ ? date.toLocaleDateString(undefined, { weekday: "long" })+ : date.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ ...(date.getFullYear() !== today.getFullYear()+ ? { year: "numeric" as const }+ : {}),+ });+ return `${day} at ${date.toLocaleTimeString(undefined, {+ hour: "numeric",+ minute: "2-digit",+ })}`;+}++export function formatOfferPrice(price?: number, currency = "USD") {+ if (price === undefined || !Number.isFinite(price)) return null;+ const digits =+ new Intl.NumberFormat(undefined, {+ style: "currency",+ currency,+ }).resolvedOptions().maximumFractionDigits ?? 2;+ const amount = price / 10 ** digits;+ return new Intl.NumberFormat(undefined, {+ style: "currency",+ currency,+ minimumFractionDigits: Number.isInteger(amount) ? 0 : digits,+ maximumFractionDigits: digits,+ }).format(amount);+}++export function getUsageOfferAction(+ experience: UsageExperience,+ offer: { price?: number; currency?: string },+) {+ if (experience.targetTier === "MAX") return "Upgrade to Max";+ if (experience.freshProUsage) {+ const amount = formatOfferPrice(offer.price, offer.currency);+ return `Start Pro now${amount ? ` · ${amount}` : ""}`;+ }+ if (experience.isCancelPending) return "Subscribe now";+ return experience.tier === "BASIC" ? "Upgrade to Pro" : "Start Pro";+}diff --git a/autogpt_platform/frontend/src/services/usageExperience/payment.ts b/autogpt_platform/frontend/src/services/usageExperience/payment.tsnew file mode 100644index 0000000000..da568eae50--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/payment.ts@@ -0,0 +1,19 @@+import { formatTierLabel } from "@/app/(platform)/copilot/components/usageHelpers";+import {+ formatOfferPrice,+ formatTrialDate,+ type UsageExperience,+} from "./helpers";++export function formatPaymentDue(payment: UsageExperience["payment"]) {+ if (!payment) return null;+ const amount = formatOfferPrice(payment.amount_due, payment.currency);+ if (!amount) return null;+ const plan = formatTierLabel(payment.plan) ?? "Your plan";+ const date = formatTrialDate(payment.startsOn);+ return {+ url: payment.payment_url,+ actionLabel: `Pay ${amount} now`,+ description: `${plan} was due to start${date ? ` on ${date}` : ""}, but the ${amount} charge didn’t go through. Pay now and ${plan === "Your plan" ? "your plan" : plan} starts right away. Your chats, agents and results are saved.`,+ };+}diff --git a/autogpt_platform/frontend/src/services/usageExperience/presentation.ts b/autogpt_platform/frontend/src/services/usageExperience/presentation.tsnew file mode 100644index 0000000000..038894aa51--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/presentation.ts@@ -0,0 +1,82 @@+import { formatTierLabel } from "@/app/(platform)/copilot/components/usageHelpers";+import {+ formatResumeTime,+ formatTrialDate,+ formatTrialStartDescription,+ type UsageExperience,+} from "./helpers";+import { formatPaymentDue } from "./payment";++export function usagePresentation(+ experience: UsageExperience,+ usageMultiplier?: number,+) {+ const { tier, window, isTopTier, isActiveTrial } = experience;+ if (experience.inactiveTrialStatus) {+ const canceled = experience.inactiveTrialStatus === "canceled";+ const payment = experience.inactiveTrialStatus === "payment_failed";+ const title = payment+ ? "Your payment didn’t go through"+ : canceled+ ? "Your trial was canceled"+ : "Your trial has ended";+ return {+ eyebrow: payment+ ? "Payment needs attention"+ : canceled+ ? "Free trial · Canceled"+ : "Free trial · Ended",+ title,+ noticeTitle: title,+ description: payment+ ? (formatPaymentDue(experience.payment)?.description ??+ "Review your billing details to continue. Your chats, agents and results are saved.")+ : canceled+ ? "Your trial won’t turn into a paid subscription. Your chats, agents and results are saved whenever you’re ready to choose a plan."+ : "Your chats, agents and results are saved. Choose a plan to keep going.",+ supportLabel: "Contact support",+ secondary: "Back to my work",+ trialSpent: false,+ };+ }+ const trialSpent = isActiveTrial && window === "trial";+ const windowLabel = window === "weekly" ? "Weekly" : "Daily";+ const trialDate = formatTrialDate(experience.trialEndsAt);+ const resumeTime = formatResumeTime(experience.resetsAt);+ const resume = resumeTime+ ? `You can continue ${resumeTime}`+ : "You can continue when your allowance refreshes";+ const title = trialSpent+ ? "You’ve used your trial allowance"+ : isTopTier+ ? resume+ : window === "weekly"+ ? "You’ve hit this week’s limit"+ : "You’ve hit today’s limit";+ return {+ eyebrow: `${formatTierLabel(tier) ?? "Your plan"} · ${trialSpent ? "Trial allowance used" : `${windowLabel.toLowerCase()} usage reached`}`,+ title,+ noticeTitle: title,+ description: trialSpent+ ? experience.freshProUsage+ ? formatTrialStartDescription(experience.trialEndsAt)+ : "Choose your next plan to continue. Your chats, agents and results are saved."+ : isTopTier+ ? "Your chats, agents and results are saved."+ : tier === "PRO"+ ? `${resume}, or upgrade to Max for ${usageMultiplier ? `${usageMultiplier} times the usage` : "more usage"}.`+ : `${resume}, or ${tier === "BASIC" ? "upgrade to Pro" : "start Pro"}.`,+ supportLabel:+ tier === "ENTERPRISE"+ ? "Contact your account team"+ : tier === "BUSINESS"+ ? "Contact support"+ : "Contact us",+ secondary: trialSpent+ ? experience.freshProUsage && trialDate+ ? `Wait until ${trialDate}`+ : "Back to my work"+ : "Wait for reset",+ trialSpent,+ };+}diff --git a/autogpt_platform/frontend/src/services/usageExperience/usePaymentRecovery.ts b/autogpt_platform/frontend/src/services/usageExperience/usePaymentRecovery.tsnew file mode 100644index 0000000000..53baa7cd2c--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/usePaymentRecovery.ts@@ -0,0 +1,49 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef } from "react";+import { getGetV2GetCopilotUsageQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";+import { getGetSubscriptionStatusQueryKey } from "@/app/api/__generated__/endpoints/credits/credits";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { useTrialStatus } from "@/services/trials/useTrialStatus";+import { getUsageExperience } from "./helpers";+import { formatPaymentDue } from "./payment";++// The open invoice is paid in another tab, so keep checking until the+// conversion lands; the trial query already pauses while this tab is hidden.+const PAYMENT_CHECK_MS = 15_000;++export function usePaymentRecovery(tier: string | null | undefined) {+ const queryClient = useQueryClient();+ const trial = useTrialStatus({+ refetchInterval: (current) =>+ isAwaitingPayment(current) ? PAYMENT_CHECK_MS : false,+ });+ const experience = getUsageExperience(null, trial.data, tier);+ const paymentFailed = experience.inactiveTrialStatus === "payment_failed";+ const wasFailed = useRef(paymentFailed);+ useEffect(() => {+ if (wasFailed.current && !paymentFailed) {+ void queryClient.invalidateQueries({+ queryKey: getGetSubscriptionStatusQueryKey(),+ });+ void queryClient.invalidateQueries({+ queryKey: getGetV2GetCopilotUsageQueryKey(),+ });+ }+ wasFailed.current = paymentFailed;+ }, [paymentFailed, queryClient]);+ return {+ paymentFailed,+ payment: paymentFailed ? formatPaymentDue(experience.payment) : null,+ };+}++function isAwaitingPayment(trial: TrialStatusResponse | undefined) {+ return Boolean(+ trial &&+ !trial.active &&+ !trial.converted &&+ ["past_due", "unpaid"].includes(trial.status ?? ""),+ );+}diff --git a/autogpt_platform/frontend/src/services/usageExperience/useUsageActions.ts b/autogpt_platform/frontend/src/services/usageExperience/useUsageActions.tsnew file mode 100644index 0000000000..9fbd16bc21--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/useUsageActions.ts@@ -0,0 +1,61 @@+"use client";+import { useRouter } from "next/navigation";+import { useProActivation } from "@/services/pro-activation/useProActivation";+import { useUsageExperience } from "./useUsageExperience";++export function useUsageActions() {+ const state = useUsageExperience();+ const router = useRouter();+ const activation = useProActivation();+ const acceptedProTrial = state.experience.freshProUsage;+ const target = state.experience.targetTier;+ const cycle: "monthly" | "yearly" = acceptedProTrial+ ? (state.trial?.offer?.billing_cycle ?? "monthly")+ : state.subscription?.billing_cycle === "yearly"+ ? "yearly"+ : "monthly";+ const prices =+ cycle === "yearly"+ ? state.subscription?.tier_costs_yearly+ : state.subscription?.tier_costs;+ const offer = {+ tier: target ?? ("PRO" as const),+ price:+ state.experience.isActiveTrial && state.trial?.cancel_at_period_end+ ? undefined+ : acceptedProTrial+ ? state.trial?.offer?.unit_amount+ : target+ ? prices?.[target]+ : undefined,+ currency: acceptedProTrial ? state.trial?.offer?.currency : "USD",+ cycle,+ freshUsage: acceptedProTrial,+ usageMultiplier:+ state.subscription?.tier_multipliers?.MAX &&+ state.subscription?.tier_multipliers?.PRO+ ? Math.round(+ (state.subscription.tier_multipliers.MAX /+ state.subscription.tier_multipliers.PRO) *+ 10,+ ) / 10+ : undefined,+ disabled: activation.isBusy,+ };+ function upgrade() {+ if (acceptedProTrial) {+ void activation.start(+ window.location.pathname ++ window.location.search ++ window.location.hash,+ );+ } else {+ router.push(+ target === "MAX"+ ? "/settings/billing?upgrade=MAX"+ : "/settings/billing",+ );+ }+ }+ return { ...state, offer, upgrade };+}diff --git a/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.ts b/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.tsnew file mode 100644index 0000000000..8ac46504c0--- /dev/null+++ b/autogpt_platform/frontend/src/services/usageExperience/useUsageExperience.ts@@ -0,0 +1,43 @@+"use client";++import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";+import { useCopilotUsage } from "@/app/(platform)/copilot/components/UsageLimits/useCopilotUsage";+import { useTrialStatus } from "@/services/trials/useTrialStatus";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { getUsageExperience } from "./helpers";++export function useUsageExperience() {+ const usage = useCopilotUsage();+ const trial = useTrialStatus();+ const subscription = useGetSubscriptionStatus({+ query: {+ select: (response) =>+ response.status === 200 ? response.data : undefined,+ },+ });+ const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);+ const experience = getUsageExperience(+ usage.data,+ trial.data,+ subscription.data?.tier,+ );+ const trialUnavailable =+ experience.tier === "TRIAL" && (trial.isError || !trial.data);+ return {+ experience,+ usage: usage.data,+ trial: trial.data,+ subscription: subscription.data,+ isBillingEnabled,+ isLoading:+ usage.isLoading || (experience.tier === "TRIAL" && trial.isLoading),+ isError:+ usage.isError || (!usage.isLoading && !usage.data) || trialUnavailable,+ retry: (throwOnError = false) =>+ Promise.all([+ usage.refetch({ throwOnError }),+ trial.refetch({ throwOnError }),+ subscription.refetch({ throwOnError }),+ ]),+ };+}diff --git a/autogpt_platform/frontend/src/tests/integrations/test-utils.tsx b/autogpt_platform/frontend/src/tests/integrations/test-utils.tsxindex 4438b0546f..6aaeb8f8a7 100644--- a/autogpt_platform/frontend/src/tests/integrations/test-utils.tsx+++ b/autogpt_platform/frontend/src/tests/integrations/test-utils.tsx@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { render, RenderOptions } from "@testing-library/react";import { NuqsTestingAdapter } from "nuqs/adapters/testing";import { ReactElement, ReactNode } from "react";+import { ProActivationProvider } from "@/services/pro-activation/ProActivationProvider";function createTestQueryClient() {return new QueryClient({@@ -23,7 +24,9 @@ function TestProviders({ children }: { children: ReactNode }) {<NuqsTestingAdapter><BackendAPIProvider><OnboardingProvider>- <TooltipProvider>{children}</TooltipProvider>+ <TooltipProvider>+ <ProActivationProvider>{children}</ProActivationProvider>+ </TooltipProvider></OnboardingProvider></BackendAPIProvider></NuqsTestingAdapter>diff --git a/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.ts b/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.tsindex d9f2457864..e3cd668d82 100644--- a/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.ts+++ b/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.ts@@ -26,6 +26,7 @@ export function trialResponse(overrides: Partial<TrialStatusResponse> = {}) {active: true,converted: false,onboarding_credits_previously_received: false,+ payment_due: null,...overrides,});}