Skip to content

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

feat(platform): add configurable card-required trials (#14353)

Nicholas Tindlef8682a62d706
diff --git a/.github/workflows/platform-backend-ci.yml b/.github/workflows/platform-backend-ci.yml
index a53a5c613f..8c6386b53c 100644
--- a/.github/workflows/platform-backend-ci.yml
+++ b/.github/workflows/platform-backend-ci.yml
@@ -465,6 +465,7 @@ jobs:
# ``docker restart <shard>`` mid-stream. Off locally so a
# contributor's ``poetry run test`` doesn't pay the ~15s cost.
E2E_RESTART_ISOLATED: "1"
+ TRIAL_TEST_DATABASE: "1"
- name: Upload coverage reports to Codecov
if: ${{ !cancelled() }}
diff --git a/.secrets.baseline b/.secrets.baseline
index 1c4ecd9fc7..a25d4c071f 100644
--- a/.secrets.baseline
+++ b/.secrets.baseline
@@ -165,7 +165,7 @@
"filename": "autogpt_platform/backend/backend/blocks/dataforseo/_config.py",
"hashed_secret": "32ce93887331fa5d192f2876ea15ec000c7d58b8",
"is_verified": false,
- "line_number": 12
+ "line_number": 13
}
],
"autogpt_platform/backend/backend/blocks/github/checks.py": [
@@ -578,5 +578,5 @@
}
]
},
- "generated_at": "2026-08-18T14:15:25Z"
+ "generated_at": "2026-09-04T21:56:43Z"
}
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
index 18b7c5dab8..d4ed449808 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
@@ -584,7 +584,7 @@ class TestEnsurePlatformUser:
import types
db_mod = types.ModuleType("backend.data.db")
- db_mod.prisma = Mock()
+ mocker.patch.object(db_mod, "prisma", Mock(), create=True)
# A list means "successive calls" -- used to model the row appearing
# between the initial probe and the post-failure re-check.
db_mod.prisma.user.find_unique = (
@@ -594,7 +594,9 @@ class TestEnsurePlatformUser:
)
user_mod = types.ModuleType("backend.data.user")
- user_mod.get_or_create_user_with_status = provisioner
+ mocker.patch.object(
+ user_mod, "get_or_create_user_with_status", provisioner, create=True
+ )
mocker.patch.dict(
sys.modules,
@@ -698,7 +700,7 @@ class TestRequestContextProvisioning:
org_member.Org = Mock(deletedAt=None)
db_mod = types.ModuleType("backend.data.db")
- db_mod.prisma = Mock()
+ mocker.patch.object(db_mod, "prisma", Mock(), create=True)
# No personal org -> the self-heal branch.
db_mod.prisma.orgmember.find_first = AsyncMock(return_value=None)
db_mod.prisma.orgmember.find_unique = AsyncMock(return_value=org_member)
@@ -708,7 +710,9 @@ class TestRequestContextProvisioning:
return "org-1", "team-1"
orgs_mod = types.ModuleType("backend.api.features.orgs.db")
- orgs_mod.get_user_default_team = _default_team
+ mocker.patch.object(
+ orgs_mod, "get_user_default_team", _default_team, create=True
+ )
mocker.patch.dict(
sys.modules,
diff --git a/autogpt_platform/autogpt_libs/pyproject.toml b/autogpt_platform/autogpt_libs/pyproject.toml
index ed30dd6d8e..d500794633 100644
--- a/autogpt_platform/autogpt_libs/pyproject.toml
+++ b/autogpt_platform/autogpt_libs/pyproject.toml
@@ -40,3 +40,6 @@ extend-select = ["I"] # sort dependencies
[tool.pytest.ini_options]
# Run bare `async def` tests without a per-test marker, matching the backend.
asyncio_mode = "auto"
+
+[tool.pyright]
+extraPaths = ["../backend"]
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 80d37c0565..77f2f9c116 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -1236,6 +1236,8 @@ async def reset_copilot_usage(
config.weekly_cost_limit_microdollars,
)
+ if tier.value == "TRIAL":
+ raise HTTPException(409, "Trial allowances cannot be reset with credits.")
if daily_limit <= 0:
raise HTTPException(
status_code=400,
diff --git a/autogpt_platform/backend/backend/api/features/credits_rate_limit.py b/autogpt_platform/backend/backend/api/features/credits_rate_limit.py
index 686ef6b8d2..19dfef87d9 100644
--- a/autogpt_platform/backend/backend/api/features/credits_rate_limit.py
+++ b/autogpt_platform/backend/backend/api/features/credits_rate_limit.py
@@ -1,16 +1,18 @@
-"""Per-user rate limit for ``GET /api/credits/subscription``.
+"""Shared per-user rate limit for subscription status and the trial router.
The subscription-status endpoint fans out to uncached Stripe reads per request
and is fetched on every load of the billing page, so a scripted client can
drive a lot of upstream traffic from one account. A per-user cap puts a hard
-ceiling on that without affecting normal use: the frontend shares one React
-Query entry with a 60s ``staleTime``, so a real user stays well under the cap.
+ceiling on that without affecting normal use. Trial status and checkout,
+confirmation, and cancellation share this budget because they also call Stripe.
+Subscription status shares a React Query entry with a 60s ``staleTime``;
+trial mutations additionally retain their own ownership and idempotency checks.
Atomic fixed-window counter in Redis (Lua ``INCR`` + first-hit ``EXPIRE``),
keyed per ``user_id``. A single key per check keeps it correct on the Redis
cluster.
-Availability: this puts Redis in front of a billing read, so the check is
+Availability: this puts Redis in front of billing, so the check is
strictly best-effort. It is bounded by a short deadline and **fails open** on
any Redis trouble — being unable to prove a user is under their cap must never
cost every user their billing status.
@@ -92,10 +94,9 @@ async def enforce_subscription_status_rate_limit(
) -> None:
"""Raise HTTP 429 when ``user_id`` exceeds the per-window cap.
- Wired as a route dependency on ``GET /credits/subscription`` only, so the
- internal callers of ``get_subscription_status`` (e.g. the POST update flow
- returning fresh state) never trip it — FastAPI dependencies run for HTTP
- requests, not for direct function calls.
+ Wired on ``GET /credits/subscription`` and all ``/credits/trial`` routes.
+ Internal callers returning fresh subscription/trial status never trip it:
+ FastAPI dependencies run for HTTP requests, not direct function calls.
On any Redis trouble this fails *open* (logs and lets the call through): a
Redis blip must never block the billing status read for every user, which
diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py
new file mode 100644
index 0000000000..775026be16
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py
@@ -0,0 +1,223 @@
+from datetime import datetime
+from typing import Annotated, Literal
+
+import stripe
+from autogpt_libs.auth import get_user_id
+from fastapi import APIRouter, Depends, Header, HTTPException, Security
+from pydantic import BaseModel, Field
+
+from backend.api.features.credits_rate_limit import (
+ enforce_subscription_status_rate_limit,
+)
+from backend.data.credit import _datafast_metadata, sync_subscription_from_stripe
+from backend.data.stripe_client import stripe_call
+from backend.data.subscription_trial import (
+ get_subscription_trial,
+ has_received_onboarding_credit,
+)
+from backend.data.subscription_trial_checkout import (
+ TrialUnavailable,
+ confirm_trial_checkout,
+ create_trial_checkout,
+ resolve_trial_price,
+)
+from backend.data.subscription_trial_config import AcceptedTrialOffer, get_trial_offer
+from backend.data.subscription_trial_rejection import TrialRejectionReason
+from backend.data.user import get_user_by_id
+from backend.util.settings import Settings
+
+router = APIRouter(
+ prefix="/credits/trial",
+ tags=["trials"],
+ dependencies=[Depends(enforce_subscription_status_rate_limit)],
+)
+CurrentUser = Annotated[str, Security(get_user_id)]
+
+
+class TrialOfferResponse(BaseModel):
+ token: str
+ version: str
+ duration_days: int
+ tier: Literal["BASIC", "PRO", "MAX", "BUSINESS"]
+ billing_cycle: Literal["monthly", "yearly"]
+ unit_amount: int
+ currency: str
+ onboarding_credit_amount: int
+
+ @classmethod
+ def from_offer(cls, offer: AcceptedTrialOffer) -> "TrialOfferResponse":
+ return cls(**offer.model_dump(), token=offer.token)
+
+
+class TrialStatusResponse(BaseModel):
+ eligible: bool = False
+ offer: TrialOfferResponse | None = None
+ status: str | None = None
+ rejection_reason: TrialRejectionReason | None = None
+ ends_at: datetime | None = None
+ cancel_at_period_end: bool = False
+ allowance_used_percent: float | None = None
+ active: bool = False
+ converted: bool = False
+ onboarding_credits_previously_received: bool = False
+
+
+class TrialCheckoutRequest(BaseModel):
+ offer_token: str = Field(pattern=r"^[a-f0-9]{64}$")
+ return_to: Literal["onboarding", "billing"] = "billing"
+
+
+class TrialCheckoutResponse(BaseModel):
+ url: str
+
+
+async def get_trial_status(user_id: CurrentUser) -> TrialStatusResponse:
+ trial = await get_subscription_trial(user_id)
+ if trial:
+ return TrialStatusResponse(
+ eligible=(
+ trial.status == "checkout_pending"
+ and trial.consumed_at is None
+ and await get_trial_offer(user_id) is not None
+ ),
+ offer=TrialOfferResponse.from_offer(trial.offer),
+ status=trial.status,
+ rejection_reason=trial.rejection_reason,
+ ends_at=trial.ends_at,
+ cancel_at_period_end=trial.cancel_at_period_end,
+ active=trial.active,
+ converted=trial.converted_at is not None,
+ onboarding_credits_previously_received=await has_received_onboarding_credit(
+ user_id
+ ),
+ allowance_used_percent=min(
+ 100, 100 * trial.cost_microdollars / trial.offer.total_cost_limit
+ ),
+ )
+ offer = await get_trial_offer(user_id)
+ if offer is None:
+ return TrialStatusResponse()
+ user = await get_user_by_id(user_id)
+ has_history = False
+ if user.stripe_customer_id:
+ subscriptions = await stripe_call(
+ stripe.Subscription.list_async,
+ customer=user.stripe_customer_id,
+ status="all",
+ limit=1,
+ )
+ has_history = bool(subscriptions.data)
+ if not offer.is_eligible(
+ created_at=user.created_at,
+ current_tier=user.subscription_tier.value,
+ has_subscription_history=has_history,
+ ):
+ return TrialStatusResponse()
+ try:
+ accepted = await resolve_trial_price(offer)
+ except TrialUnavailable:
+ return TrialStatusResponse()
+ return TrialStatusResponse(
+ eligible=True,
+ offer=TrialOfferResponse.from_offer(accepted),
+ onboarding_credits_previously_received=await has_received_onboarding_credit(
+ user_id
+ ),
+ )
+
+
+ "",
+ responses={
+ 409: {"description": "Trial offer unavailable"},
+ 502: {"description": "Stripe checkout unavailable"},
+ 503: {"description": "Billing return URL not configured"},
+ },
+)
+async def start_trial_checkout(
+ body: TrialCheckoutRequest,
+ user_id: CurrentUser,
+ x_datafast_visitor_id: Annotated[str | None, Header()] = None,
+ x_datafast_session_id: Annotated[str | None, Header()] = None,
+) -> TrialCheckoutResponse:
+ config = Settings().config
+ base = config.frontend_base_url or config.platform_base_url
+ if not base:
+ raise HTTPException(503, "The billing return URL is not configured")
+ billing = f"{base.rstrip('/')}/settings/billing"
+ destination = (
+ f"{base.rstrip('/')}/onboarding" if body.return_to == "onboarding" else billing
+ )
+ try:
+ url = await create_trial_checkout(
+ user_id=user_id,
+ offer_token=body.offer_token,
+ success_url=f"{destination}?trial=success",
+ cancel_url=f"{destination}?trial=cancelled",
+ metadata=_datafast_metadata(x_datafast_visitor_id, x_datafast_session_id),
+ )
+ except TrialUnavailable as exc:
+ raise HTTPException(409, str(exc)) from exc
+ except stripe.StripeError as exc:
+ raise HTTPException(502, "Unable to start checkout. Please try again.") from exc
+ return TrialCheckoutResponse(url=url)
+
+
+ "/cancel",
+ responses={
+ 409: {"description": "No cancelable trial subscription"},
+ 502: {"description": "Stripe cancellation temporarily unavailable"},
+ },
+)
+async def cancel_trial(user_id: CurrentUser) -> TrialStatusResponse:
+ trial = await get_subscription_trial(user_id)
+ if (
+ trial is None
+ or trial.subscription_id is None
+ or trial.consumed_at is None
+ or trial.converted_at is not None
+ ):
+ raise HTTPException(409, "No trial subscription is available to cancel")
+ try:
+ subscription = await stripe_call(
+ stripe.Subscription.retrieve_async, trial.subscription_id
+ )
+ if subscription.customer != trial.customer_id or subscription.status not in (
+ "trialing",
+ "canceled",
+ ):
+ raise HTTPException(
+ 409, "This trial has ended. Manage the plan in billing."
+ )
+ if subscription.status == "trialing":
+ subscription = await stripe_call(
+ stripe.Subscription.cancel_async,
+ trial.subscription_id,
+ invoice_now=False,
+ prorate=False,
+ )
+ except stripe.StripeError as exc:
+ raise HTTPException(502, "Unable to cancel your trial. Please retry.") from exc
+ await sync_subscription_from_stripe(dict(subscription))
+ return await get_trial_status(user_id)
+
+
+ "/confirm",
+ responses={
+ 409: {"description": "Trial checkout is unavailable or no longer current"},
+ 502: {"description": "Stripe confirmation temporarily unavailable"},
+ },
+)
+async def confirm_trial(user_id: CurrentUser) -> TrialStatusResponse:
+ try:
+ await confirm_trial_checkout(user_id)
+ except TrialUnavailable as exc:
+ raise HTTPException(409, str(exc)) from exc
+ except stripe.StripeError as exc:
+ raise HTTPException(
+ 502, "Unable to confirm the trial yet. Please retry."
+ ) from exc
+ return await get_trial_status(user_id)
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.py
new file mode 100644
index 0000000000..42a3bc4ab8
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py
@@ -0,0 +1,243 @@
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from fastapi import FastAPI
+from httpx import ASGITransport, AsyncClient
+
+from backend.api.features import subscription_trial_routes as routes
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+
+
[email protected](autouse=True)
+def billing_return_origin(monkeypatch):
+ settings = routes.Settings()
+ settings.config.frontend_base_url = "https://platform.example.com"
+ monkeypatch.setattr(routes, "Settings", lambda: settings)
+
+
+def trial() -> TrialState:
+ now = datetime.now(UTC)
+ return TrialState(
+ id="trial-1",
+ user_id="user-1",
+ customer_id="cus_1",
+ offer=AcceptedTrialOffer(
+ version="api-v1",
+ new_users_from=now - timedelta(days=1),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_pro",
+ unit_amount=2000,
+ currency="usd",
+ ),
+ checkout_session_id="cs_1",
+ subscription_id=None,
+ checkout_attempt=0,
+ success_url="https://example.com/ok",
+ cancel_url="https://example.com/no",
+ checkout_metadata={},
+ status="checkout_pending",
+ card_verified_at=None,
+ started_at=None,
+ ends_at=None,
+ consumed_at=None,
+ converted_at=None,
+ cancel_at_period_end=False,
+ cost_microdollars=0,
+ )
+
+
+async def test_disabled_flag_hides_pending_enrollment(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 not status.eligible
+ assert status.status == "checkout_pending"
+
+
+async def test_status_never_exposes_internal_spend_or_stripe_identifiers(trial):
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=trial.offer)),
+ patch.object(
+ routes, "has_received_onboarding_credit", AsyncMock(return_value=True)
+ ),
+ ):
+ status = await routes.get_trial_status(trial.user_id)
+ public = status.model_dump_json()
+ for private in (
+ "customer_id",
+ "price_id",
+ "daily_cost_limit",
+ "total_cost_limit",
+ "user_id",
+ ):
+ assert private not in public
+ assert status.onboarding_credits_previously_received
+
+
+async def test_status_exposes_safe_rejection_reason(trial):
+ trial = trial.model_copy(
+ update={"status": "canceled", "rejection_reason": "intro_offer_already_used"}
+ )
+ 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("rejection_reason") == "intro_offer_already_used"
+
+
+async def test_checkout_uses_authenticated_identity_and_server_return_urls(trial):
+ app = FastAPI()
+ app.include_router(routes.router)
+ app.dependency_overrides[routes.get_user_id] = lambda: trial.user_id
+ app.dependency_overrides[routes.enforce_subscription_status_rate_limit] = (
+ lambda: None
+ )
+ with patch.object(
+ routes,
+ "create_trial_checkout",
+ AsyncMock(return_value="https://checkout.stripe.com/test"),
+ ) as checkout:
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="https://example.com"
+ ) as client:
+ response = await client.post(
+ "/credits/trial",
+ json={"offer_token": trial.offer.token, "return_to": "onboarding"},
+ headers={"X-Datafast-Visitor-Id": "visitor-1"},
+ )
+ assert response.status_code == 200
+ params = checkout.await_args.kwargs
+ assert params["user_id"] == trial.user_id
+ assert (
+ params["success_url"] == "https://platform.example.com/onboarding?trial=success"
+ )
+ assert (
+ params["cancel_url"]
+ == "https://platform.example.com/onboarding?trial=cancelled"
+ )
+ assert params["metadata"]["datafast_visitor_id"] == "visitor-1"
+
+
+async def test_unavailable_offer_is_conflict_not_success(trial):
+ with patch.object(
+ routes,
+ "create_trial_checkout",
+ AsyncMock(side_effect=routes.TrialUnavailable("Offer changed")),
+ ):
+ with pytest.raises(routes.HTTPException) as error:
+ await routes.start_trial_checkout(
+ routes.TrialCheckoutRequest(offer_token=trial.offer.token),
+ trial.user_id,
+ )
+ assert error.value.status_code == 409
+
+
+async def test_cancellation_ends_trial_immediately(trial):
+ trial = trial.model_copy(
+ update={"subscription_id": "sub_1", "consumed_at": datetime.now(UTC)}
+ )
+ canceled = {"id": "sub_1", "customer": trial.customer_id, "status": "canceled"}
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(
+ routes.stripe.Subscription,
+ "retrieve_async",
+ AsyncMock(
+ return_value=MagicMock(customer=trial.customer_id, status="trialing")
+ ),
+ ),
+ patch.object(
+ routes.stripe.Subscription, "cancel_async", AsyncMock(return_value=canceled)
+ ) as cancel,
+ patch.object(
+ routes.stripe.Subscription, "modify_async", AsyncMock(return_value=canceled)
+ ) as modify,
+ patch.object(routes, "sync_subscription_from_stripe", AsyncMock()) as sync,
+ patch.object(
+ routes,
+ "get_trial_status",
+ AsyncMock(return_value=routes.TrialStatusResponse(status="canceled")),
+ ),
+ ):
+ result = await routes.cancel_trial(trial.user_id)
+ cancel.assert_awaited_once_with("sub_1", invoice_now=False, prorate=False)
+ modify.assert_not_awaited()
+ sync.assert_awaited_once_with(canceled)
+ assert not result.active
+
+
+async def test_cancellation_retry_reconciles_an_already_canceled_trial(trial):
+ trial = trial.model_copy(
+ update={"subscription_id": "sub_1", "consumed_at": datetime.now(UTC)}
+ )
+ canceled = routes.stripe.Subscription.construct_from(
+ {"id": "sub_1", "customer": trial.customer_id, "status": "canceled"}, "test-key"
+ )
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(
+ routes.stripe.Subscription,
+ "retrieve_async",
+ AsyncMock(return_value=canceled),
+ ),
+ patch.object(routes.stripe.Subscription, "cancel_async", AsyncMock()) as cancel,
+ patch.object(routes, "sync_subscription_from_stripe", AsyncMock()) as sync,
+ patch.object(
+ routes,
+ "get_trial_status",
+ AsyncMock(return_value=routes.TrialStatusResponse(status="canceled")),
+ ),
+ ):
+ assert not (await routes.cancel_trial(trial.user_id)).active
+ cancel.assert_not_awaited()
+ sync.assert_awaited_once_with(dict(canceled))
+
+
+ "customer,status", [("cus_other", "trialing"), ("cus_1", "active")]
+)
+async def test_cancellation_cannot_cancel_another_customer_or_paid_plan(
+ trial, customer, status
+):
+ trial = trial.model_copy(
+ update={"subscription_id": "sub_1", "consumed_at": datetime.now(UTC)}
+ )
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(
+ routes.stripe.Subscription,
+ "retrieve_async",
+ AsyncMock(return_value=MagicMock(customer=customer, status=status)),
+ ),
+ patch.object(routes.stripe.Subscription, "cancel_async", AsyncMock()) as cancel,
+ ):
+ with pytest.raises(routes.HTTPException) as error:
+ await routes.cancel_trial(trial.user_id)
+ assert error.value.status_code == 409
+ cancel.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.py
new file mode 100644
index 0000000000..8930ac0077
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.py
@@ -0,0 +1,12 @@
+import pytest
+from fastapi import FastAPI
+
+from backend.api.features.subscription_trial_routes import router
+
+
[email protected]("path", ["/cancel", "/confirm"])
+def test_trial_mutation_errors_are_documented(path):
+ app = FastAPI()
+ app.include_router(router)
+ responses = app.openapi()["paths"][f"/credits/trial{path}"]["post"]["responses"]
+ assert {"200", "409", "502"} <= responses.keys()
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 1a0ee98bd6..300fa2ea33 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -129,6 +129,10 @@ from backend.data.onboarding import (
from backend.data.redis_client import get_redis_async
from backend.data.sharing.tokens import SHARE_TOKEN_PATTERN, generate_share_token
from backend.data.stripe_client import stripe_call
+from backend.data.subscription_trial_billing import (
+ TRIAL_BILLING_EVENTS,
+ sync_trials_for_billing_event,
+)
from backend.data.tally import extract_business_understanding
from backend.data.tenancy import get_user_team_ids
from backend.data.understanding import (
@@ -158,6 +162,7 @@ from backend.monitoring.instrumentation import (
)
from backend.notifications import lifecycle
from backend.notifications.queue import queue_pass_work
+from backend.notifications.trial import notify_trial, on_trial_invoice
from backend.util.cache import cached
from backend.util.clients import get_scheduler_client
from backend.util.cloud_storage import get_cloud_storage_handler
@@ -874,7 +879,7 @@ class SubscriptionTierRequest(BaseModel):
class SubscriptionStatusResponse(BaseModel):
- tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]
+ tier: Literal["NO_TIER", "TRIAL", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]
monthly_cost: int # amount in cents (Stripe convention)
tier_costs: dict[str, int] # tier name -> monthly amount in cents
tier_costs_yearly: dict[str, int] = Field(
@@ -1174,6 +1179,11 @@ async def update_subscription_tier(
# admin-granted tiers (DB tier set, no Stripe sub) must fall through to the
# Checkout flow so "start paying for my current tier" is not a no-op.
current_tier = user.subscription_tier or SubscriptionTier.NO_TIER
+ if current_tier == SubscriptionTier.TRIAL and tier != SubscriptionTier.NO_TIER:
+ raise HTTPException(
+ 409,
+ "Your accepted plan starts after your trial. Manage the trial in billing.",
+ )
current_cycle = await get_user_billing_cycle(user_id) or "monthly"
has_active_stripe_subscription = (
await get_active_subscription_period_end(user_id) is not None
@@ -1501,6 +1511,8 @@ async def _notify_checkout_completed(session: dict) -> None:
).model_dump_json(),
)
if not result.success:
+ if (session.get("metadata") or {}).get("trial_enrollment_id"):
+ raise RuntimeError("Could not queue the trial welcome notice")
logger.warning(
"stripe_webhook: could not queue the welcome email for session %s: %s",
session_id,
@@ -1559,6 +1571,12 @@ async def stripe_webhook(request: Request):
event_id = event.get("id", "")
event_type = event.get("type", "")
+ if event_type in TRIAL_BILLING_EVENTS:
+ # This idempotent path only reconciles current Stripe state. Do not let
+ # a claim left by a crashed delivery suppress card removal/restoration.
+ await sync_trials_for_billing_event(event_type, event.get("data"))
+ return Response(status_code=200)
+
# Event-level dedup: short-circuit identical re-deliveries before any
# handler runs. Stripe retries the same event.id on non-2xx responses, and
# not every downstream handler is independently idempotent.
@@ -1629,10 +1647,16 @@ async def stripe_webhook(request: Request):
if event_type == "invoice.payment_succeeded":
await handle_subscription_payment_success(data_object)
+ await on_trial_invoice(data_object, paid=True)
+
+ if event_type == "customer.subscription.trial_will_end":
+ await sync_subscription_from_stripe(data_object)
+ await notify_trial(data_object, "ending")
if event_type == "invoice.payment_failed":
await handle_subscription_payment_failure(data_object)
- await lifecycle.on_payment_failed(data_object)
+ if not await on_trial_invoice(data_object, paid=False):
+ await lifecycle.on_payment_failed(data_object)
# New Stripe API (≥2025-04-01) split the per-payment events off the
# Invoice resource. data.object is an InvoicePayment, not an Invoice,
@@ -1648,9 +1672,11 @@ async def stripe_webhook(request: Request):
invoice_payload = cast(dict, invoice)
if event_type == "invoice_payment.paid":
await handle_subscription_payment_success(invoice_payload)
+ await on_trial_invoice(invoice_payload, paid=True)
else:
await handle_subscription_payment_failure(invoice_payload)
- await lifecycle.on_payment_failed(invoice_payload)
+ if not await on_trial_invoice(invoice_payload, paid=False):
+ await lifecycle.on_payment_failed(invoice_payload)
# `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects
# (Dispute/Refund). The Stripe webhook payload's `data.object` is a
diff --git a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
index 9323736590..b616959e17 100644
--- a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
@@ -499,11 +499,12 @@ async def test_expire_open_subscription_sessions_paginates(
page2 = MagicMock()
page2.data = [MagicMock(id="cs_page2", mode="subscription")]
page2.has_more = False
+ page1.next_page_async = AsyncMock(return_value=page2)
mock_list = mocker.patch(
"stripe.checkout.Session.list_async",
new_callable=AsyncMock,
- side_effect=[page1, page2],
+ return_value=page1,
)
mock_expire = mocker.patch(
"stripe.checkout.Session.expire_async", new_callable=AsyncMock
@@ -511,12 +512,11 @@ async def test_expire_open_subscription_sessions_paginates(
await _expire_open_subscription_sessions("cus_test")
- assert mock_list.call_count == 2
- mock_list.assert_any_call(customer="cus_test", status="open", limit=100)
- mock_list.assert_any_call(
- customer="cus_test", status="open", limit=100, starting_after="cs_page1"
- )
+ mock_list.assert_awaited_once_with(customer="cus_test", status="open", limit=100)
+ page1.next_page_async.assert_awaited_once_with()
assert mock_expire.call_count == 2
+ mock_expire.assert_any_await("cs_page1")
+ mock_expire.assert_any_await("cs_page2")
# ---------------------------------------------------------------------------
@@ -837,16 +837,29 @@ def test_payment_failure_triggers_the_payment_email(
stub_lifecycle_emails["payment_failed"].assert_awaited_once()
-def test_a_trial_ending_event_is_not_listened_for(
+def test_trial_ending_event_reconciles_and_queues_trial_reminder(
mocker: pytest_mock.MockFixture, stub_lifecycle_emails
) -> None:
- """The platform does not offer a trial, so this event does nothing."""
+ sync = mocker.patch(
+ "backend.api.features.v1.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
+ )
+ notify = mocker.patch(
+ "backend.api.features.v1.notify_trial", new_callable=AsyncMock
+ )
+ subscription = {
+ "id": "sub_1",
+ "customer": "cus_1",
+ "metadata": {"trial_enrollment_id": "trial-1"},
+ }
_post_event(
mocker,
{
"type": "customer.subscription.trial_will_end",
- "data": {"object": {"id": "sub_1", "customer": "cus_1"}},
+ "data": {"object": subscription},
},
)
+ sync.assert_awaited_once_with(subscription)
+ notify.assert_awaited_once_with(subscription, "ending")
for mock in stub_lifecycle_emails.values():
mock.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py
new file mode 100644
index 0000000000..0c489b33d6
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py
@@ -0,0 +1,110 @@
+"""Signed billing-card events must refresh trials, including repeated delivery."""
+
+import hashlib
+import hmac
+import json
+import time
+from unittest.mock import AsyncMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+
+from backend.api.features import v1
+
+app = fastapi.FastAPI()
+app.include_router(v1.v1_router)
+client = fastapi.testclient.TestClient(app, raise_server_exceptions=False)
+TEST_SECRET = "whsec_trial_billing_test_only"
+
+
+def billing_refresh(mocker):
+ mocker.patch.object(v1.settings.secrets, "stripe_webhook_secret", TEST_SECRET)
+ mocker.patch.object(v1, "_claim_stripe_event", AsyncMock(return_value=True))
+ return mocker.patch.object(v1, "sync_trials_for_billing_event", AsyncMock())
+
+
+def signed_request(event_type, data=None, secret=TEST_SECRET):
+ event = {
+ "id": "evt_billing_test",
+ "object": "event",
+ "api_version": "2023-10-16",
+ "type": event_type,
+ "data": data or {"object": {"id": "cus_trial"}},
+ }
+ payload = json.dumps(event)
+ timestamp = int(time.time())
+ signature = hmac.new(
+ secret.encode(), f"{timestamp}.{payload}".encode(), hashlib.sha256
+ ).hexdigest()
+ return client.post(
+ "/credits/stripe_webhook",
+ content=payload,
+ headers={"stripe-signature": f"t={timestamp},v1={signature}"},
+ )
+
+
+ "event_type",
+ [
+ "customer.updated",
+ "customer.deleted",
+ "payment_method.attached",
+ "payment_method.updated",
+ "payment_method.automatically_updated",
+ "payment_method.detached",
+ "setup_intent.succeeded",
+ "setup_intent.requires_action",
+ "setup_intent.setup_failed",
+ "setup_intent.canceled",
+ ],
+)
+def test_signed_card_event_refreshes_trial(event_type, billing_refresh):
+ if event_type.startswith("customer."):
+ data = {"object": {"id": "cus_trial"}}
+ elif event_type.startswith("setup_intent."):
+ data = {"object": {"id": "seti_trial", "customer": "cus_trial"}}
+ else:
+ data = {
+ "object": {"id": "pm_trial", "customer": None},
+ "previous_attributes": {"customer": "cus_trial"},
+ }
+ response = signed_request(event_type, data)
+ assert response.status_code == 200
+ billing_refresh.assert_awaited_once_with(event_type, data)
+
+
+def test_invalid_signature_cannot_refresh_trial(billing_refresh):
+ response = signed_request("customer.updated", secret="wrong_secret")
+ assert response.status_code == 400
+ billing_refresh.assert_not_awaited()
+
+
+def test_unconfigured_webhook_cannot_refresh_trial(billing_refresh, mocker):
+ mocker.patch.object(v1.settings.secrets, "stripe_webhook_secret", "")
+ response = signed_request("customer.updated")
+ assert response.status_code == 503
+ billing_refresh.assert_not_awaited()
+
+
+def test_unrelated_event_does_not_refresh_trial(billing_refresh):
+ assert signed_request("customer.tax_id.created").status_code == 200
+ billing_refresh.assert_not_awaited()
+
+
+def test_repeated_billing_event_always_refreshes_current_state(billing_refresh, mocker):
+ claim = mocker.patch.object(
+ v1, "_claim_stripe_event", AsyncMock(return_value=False)
+ )
+ assert signed_request("customer.updated").status_code == 200
+ assert signed_request("customer.updated").status_code == 200
+ assert billing_refresh.await_count == 2
+ claim.assert_not_awaited()
+
+
+def test_failed_billing_refresh_is_retryable(billing_refresh):
+ billing_refresh.side_effect = [RuntimeError("temporary Stripe outage"), None]
+ assert signed_request("customer.updated").status_code == 500
+ assert signed_request("customer.updated").status_code == 200
+ assert billing_refresh.await_count == 2
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 8f130e818e..8b6ae95340 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -55,6 +55,7 @@ import backend.api.features.push.routes as push_routes
import backend.api.features.search.routes as search_routes
import backend.api.features.store.model
import backend.api.features.store.routes
+import backend.api.features.subscription_trial_routes as subscription_trial_routes
import backend.api.features.transfers.routes as transfer_routes
import backend.api.features.v1
import backend.api.features.workspace.folder_routes as workspace_folder_routes
@@ -379,6 +380,7 @@ app.add_exception_handler(PreconditionFailed, handle_internal_http_error(428))
app.add_exception_handler(Exception, handle_internal_http_error(500))
app.include_router(backend.api.features.v1.v1_router, tags=["v1"], prefix="/api")
+app.include_router(subscription_trial_routes.router, prefix="/api")
app.include_router(
auth_email_routes.auth_email_router,
prefix="/api/auth/email",
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.py
index 9eaabd3182..10b4056a9e 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py
@@ -11,6 +11,7 @@ import os
import subprocess
import threading
import time
+from contextlib import AsyncExitStack
from typing import TYPE_CHECKING, Callable, cast
from backend.copilot import stream_registry
@@ -26,6 +27,7 @@ from backend.copilot.response_model import StreamError, StreamStatus
from backend.copilot.sdk import service as sdk_service
from backend.copilot.sdk.dummy import stream_chat_completion_dummy
from backend.copilot.stream_heartbeat import wrap_stream_with_heartbeat
+from backend.copilot.trial_cost_context import trial_cost_context
from backend.executor.cluster_lock import ClusterLock
from backend.integrations.codex.transport import CodexCredentialIntegrityError
from backend.util.decorator import error_logged
@@ -496,6 +498,7 @@ class CoPilotProcessor:
refresh_interval = 30.0 # Refresh lock every 30 seconds
error_msg = None
credential_lease = None
+ cost_context_stack = AsyncExitStack()
try:
from backend.copilot.model import get_chat_session
@@ -613,6 +616,10 @@ class CoPilotProcessor:
)
log.info(f"Using {'SDK' if use_sdk else 'baseline'} service")
+ await cost_context_stack.enter_async_context(
+ trial_cost_context(entry.user_id)
+ )
+
# Stream chat completion and publish chunks to Redis.
# stream_and_publish wraps the raw stream with registry
# publishing so subscribers on the session Redis stream
@@ -708,3 +715,5 @@ class CoPilotProcessor:
)
except Exception as mark_err:
log.error(f"Failed to mark session completed: {mark_err}")
+ finally:
+ await cost_context_stack.aclose()
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor_test.py b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
index 076fcf2f37..ed766933c7 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor_test.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
@@ -43,6 +43,15 @@ from backend.util.exceptions import (
)
[email protected](autouse=True)
+def no_trial_attribution(mocker):
+ store = MagicMock()
+ store.get_subscription_trial = AsyncMock(return_value=None)
+ mocker.patch(
+ "backend.copilot.trial_cost_context.db_accessors.credit_db", return_value=store
+ )
+
+
class TestResolveUseSdk:
"""Which engine runs a turn — entirely the server's call."""
diff --git a/autogpt_platform/backend/backend/copilot/executor/trial_cost_test.py b/autogpt_platform/backend/backend/copilot/executor/trial_cost_test.py
new file mode 100644
index 0000000000..aab21216aa
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/executor/trial_cost_test.py
@@ -0,0 +1,118 @@
+"""Exercise delayed usage through the real turn execution boundary."""
+
+import asyncio
+import logging
+import threading
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.executor.processor import CoPilotProcessor
+from backend.copilot.executor.utils import CoPilotExecutionEntry, CoPilotLogMetadata
+from backend.copilot.model import ChatSession
+from backend.copilot.rate_limit import SubscriptionTier
+from backend.copilot.response_model import StreamStatus
+from backend.copilot.token_tracking import persist_and_record_usage
+from backend.copilot.trial_cost_context import get_trial_cost_context
+
+
[email protected]("use_sdk", [True, False])
+async def test_delayed_trial_cost_and_later_paid_turn_are_separate(use_sdk):
+ trial = SimpleNamespace(id="trial-1", active=True, consumed_at=True)
+ store = MagicMock()
+ store.get_subscription_trial = AsyncMock(return_value=trial)
+ store.record_subscription_trial_cost = AsyncMock()
+ tier = AsyncMock(return_value=SubscriptionTier.TRIAL)
+ release = asyncio.Event()
+ pending: list[asyncio.Task] = []
+
+ async def settle():
+ await release.wait()
+ await persist_and_record_usage(
+ session=None,
+ user_id="user-1",
+ prompt_tokens=10,
+ completion_tokens=5,
+ cost_usd=0.01,
+ )
+
+ async def stream(**_kwargs):
+ pending.append(asyncio.create_task(settle()))
+ yield StreamStatus(message="Done")
+
+ entry = CoPilotExecutionEntry(
+ session_id="session-1", turn_id="turn-1", user_id="user-1", message="Hi"
+ )
+ with (
+ patch("backend.data.db_accessors.credit_db", return_value=store),
+ patch("backend.copilot.rate_limit.credit_db", return_value=store),
+ patch("backend.copilot.rate_limit._fetch_user_tier", tier),
+ patch("backend.copilot.rate_limit.get_redis_async", AsyncMock()),
+ patch("backend.copilot.rate_limit._incr_counter_atomic", AsyncMock()),
+ patch("backend.copilot.token_tracking._schedule_cost_log") as cost_log,
+ patch(
+ "backend.copilot.model.get_chat_session",
+ AsyncMock(return_value=ChatSession.new("user-1", dry_run=False)),
+ ),
+ patch(
+ "backend.copilot.executor.processor.ChatConfig",
+ return_value=MagicMock(test_mode=False),
+ ),
+ patch(
+ "backend.copilot.executor.processor.resolve_use_sdk",
+ AsyncMock(return_value=use_sdk),
+ ),
+ patch(
+ "backend.copilot.executor.processor._building_mode_forces_sdk",
+ AsyncMock(return_value=False),
+ ),
+ patch(
+ "backend.copilot.executor.processor.sdk_service.stream_chat_completion_sdk",
+ stream,
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_chat_completion_baseline", stream
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.stream_and_publish",
+ lambda **kw: kw["stream"],
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.publish_chunk",
+ AsyncMock(),
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.mark_session_completed",
+ AsyncMock(),
+ ),
+ ):
+ processor = CoPilotProcessor()
+ log = CoPilotLogMetadata(logger=logging.getLogger("trial-cost-test"))
+ try:
+ await processor._execute_async(entry, threading.Event(), MagicMock(), log)
+ trial.active = False
+ tier.return_value = SubscriptionTier.PRO
+ release.set()
+ await asyncio.gather(*pending)
+ await processor._execute_async(
+ entry.model_copy(update={"turn_id": "turn-2"}),
+ threading.Event(),
+ MagicMock(),
+ log,
+ )
+ await asyncio.gather(*pending)
+ finally:
+ release.set()
+ await asyncio.gather(*pending)
+
+ store.record_subscription_trial_cost.assert_awaited_once_with(
+ "user-1", 10_000, trial_id="trial-1"
+ )
+ assert [
+ call.args[0].metadata["subscription_trial_id"]
+ for call in cost_log.call_args_list
+ ] == ["trial-1", None]
+ tier.assert_not_awaited()
+ assert get_trial_cost_context("user-1") is None
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.py
index 39f2e6f920..2f2cc1b2b5 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py
@@ -62,6 +62,7 @@ from prisma.models import User as PrismaUser
from pydantic import BaseModel, Field
from redis.exceptions import RedisClusterException, RedisError
+from backend.copilot.trial_cost_context import record_attributed_trial_cost
from backend.data.db_accessors import credit_db, user_db
from backend.data.redis_client import AsyncRedisClient, get_redis_async
from backend.data.user import get_user_by_id
@@ -91,6 +92,7 @@ class SubscriptionTier(str, Enum):
"""
NO_TIER = "NO_TIER"
+ TRIAL = "TRIAL"
BASIC = "BASIC"
PRO = "PRO"
MAX = "MAX"
@@ -114,6 +116,7 @@ _DEFAULT_TIER_MULTIPLIERS: dict[SubscriptionTier, float] = {
# server-side regardless of client). BASIC is not sold today and stays on
# the base limits.
SubscriptionTier.NO_TIER: 0.0,
+ SubscriptionTier.TRIAL: 0.0,
SubscriptionTier.BASIC: 1.0,
SubscriptionTier.PRO: 1.25,
SubscriptionTier.MAX: 10.6667,
@@ -134,6 +137,7 @@ DEFAULT_TIER = SubscriptionTier.NO_TIER
# while LaunchDarkly can still tune tiers without a deploy.
_DEFAULT_TIER_WORKSPACE_STORAGE_MB: dict[SubscriptionTier, int] = {
SubscriptionTier.NO_TIER: 250, # 250 MB
+ SubscriptionTier.TRIAL: 250,
SubscriptionTier.BASIC: 250, # 250 MB
SubscriptionTier.PRO: 1024, # 1 GB
SubscriptionTier.MAX: 5 * 1024, # 5 GB
@@ -517,7 +521,7 @@ async def get_usage_status(
resets_at=_weekly_reset_time(now=now),
),
tier=tier,
- reset_cost=rate_limit_reset_cost,
+ reset_cost=0 if tier == SubscriptionTier.TRIAL else rate_limit_reset_cost,
)
@@ -556,6 +560,11 @@ async def get_remaining_usd_budget(
to start a turn. Set to ``0.0`` when the caller wants a
faithful "no remaining budget" signal instead of a floor.
"""
+ trial = None
+ if await _fetch_user_tier(user_id) == SubscriptionTier.TRIAL:
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None or not trial.active:
+ return 0.0
now = datetime.now(UTC)
try:
redis = await get_redis_async()
@@ -567,7 +576,7 @@ async def get_remaining_usd_budget(
weekly_used = int(weekly_raw or 0)
except (RedisError, RedisClusterException, ConnectionError, OSError, ValueError):
logger.warning("Redis unavailable for remaining-budget lookup, returning floor")
- return floor_usd
+ return 0.0 if trial else floor_usd
# ``>= 0`` (not ``> 0``): a limit of 0 is "no spend allowed", so the
# remaining is 0 on that window. Mirrors check_rate_limit's semantics
@@ -586,6 +595,11 @@ async def get_remaining_usd_budget(
if remaining_microdollars != float("inf")
else float("inf")
)
+ if trial:
+ return min(
+ remaining_usd,
+ max(0, trial.offer.total_cost_limit - trial.cost_microdollars) / 1_000_000,
+ )
return max(floor_usd, remaining_usd)
@@ -668,6 +682,12 @@ async def check_rate_limit(
(the exact cost is unknown until after generation).
"""
now = datetime.now(UTC)
+ if await _fetch_user_tier(user_id) == SubscriptionTier.TRIAL:
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None or not trial.active:
+ raise RateLimitExceeded("trial", now)
+ if trial.cost_microdollars >= trial.offer.total_cost_limit:
+ raise RateLimitExceeded("trial", trial.ends_at or now)
try:
redis = await get_redis_async()
daily_raw, weekly_raw = await asyncio.gather(
@@ -830,6 +850,11 @@ async def record_cost_usage(
cost_microdollars = max(0, cost_microdollars)
if cost_microdollars <= 0:
return
+ if (
+ not await record_attributed_trial_cost(user_id, cost_microdollars)
+ and await _fetch_user_tier(user_id) == SubscriptionTier.TRIAL
+ ):
+ await credit_db().record_subscription_trial_cost(user_id, cost_microdollars)
logger.info(
"Recording copilot spend: %d microdollars (skip_daily=%s)",
@@ -995,6 +1020,9 @@ async def get_user_tier(user_id: str) -> SubscriptionTier:
tier = DEFAULT_TIER
tier_from_db = False
+ if tier == SubscriptionTier.TRIAL:
+ trial = await credit_db().get_subscription_trial(user_id)
+ return tier if trial and trial.active else SubscriptionTier.NO_TIER
if tier != SubscriptionTier.NO_TIER:
return tier
@@ -1173,6 +1201,11 @@ async def get_global_rate_limits(
# only NO_TIER path that gets here is the beta cohort (flag off), which
# falls back to BASIC limits so testers retain access.
tier = await get_user_tier(user_id)
+ if tier == SubscriptionTier.TRIAL:
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None or not trial.active:
+ return 0, 0, SubscriptionTier.NO_TIER
+ return trial.offer.daily_cost_limit, trial.offer.weekly_cost_limit, tier
multipliers = await get_tier_multipliers()
multiplier = multipliers.get(tier.value, 1.0)
if tier == SubscriptionTier.NO_TIER and not await is_feature_enabled(
@@ -1297,6 +1330,9 @@ async def is_user_paywalled(user_id: str) -> bool:
user_id[:8],
)
tier = SubscriptionTier.NO_TIER
+ if tier == SubscriptionTier.TRIAL:
+ trial = await credit_db().get_subscription_trial(user_id)
+ return trial is None or not trial.active
if tier != SubscriptionTier.NO_TIER:
return False
return await is_feature_enabled(Flag.ENABLE_PLATFORM_PAYMENT, user_id)
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
index b182e86119..c0aa697f16 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
@@ -177,6 +177,13 @@ class TestGetUsageStatus:
class TestCheckRateLimit:
+ @pytest.fixture(autouse=True)
+ def paid_user_tier(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.PRO),
+ )
+
@pytest.mark.asyncio
async def test_allows_when_under_limit(self):
mock_redis = AsyncMock()
@@ -741,6 +748,13 @@ class TestEnforcePaymentPaywallContinued:
class TestRecordCostUsage:
+ @pytest.fixture(autouse=True)
+ def paid_user_tier(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.PRO),
+ )
+
@staticmethod
def _make_pipeline_mock() -> MagicMock:
"""Create a pipeline mock with sync methods and async execute."""
@@ -1278,6 +1292,13 @@ class TestGetGlobalRateLimitsCostLimitsFlag:
class TestGetUserTier:
+ @pytest.fixture(autouse=True)
+ def no_stripe_reconciliation(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._maybe_reconcile_stripe_tier",
+ new=AsyncMock(return_value=False),
+ )
+
@pytest.fixture(autouse=True)
def _clear_tier_cache(self):
"""Clear the get_user_tier cache before each test."""
@@ -1853,6 +1874,13 @@ class TestGetGlobalRateLimitsWithTiers:
class TestTierLimitsRespected:
+ @pytest.fixture(autouse=True)
+ def paid_user_tier(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.PRO),
+ )
+
"""Verify that tier-adjusted limits from get_global_rate_limits flow
correctly into check_rate_limit, so higher tiers allow more usage and
lower tiers are blocked when they would exceed their allocation."""
@@ -2065,6 +2093,13 @@ class TestResetDailyUsage:
class TestTierLimitsEnforced:
+ @pytest.fixture(autouse=True)
+ def paid_user_tier(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.PRO),
+ )
+
"""Verify that tier-multiplied limits are actually respected by
``check_rate_limit`` — i.e. that usage within the tier allowance passes
and usage at/above the tier allowance is rejected."""
@@ -2552,7 +2587,7 @@ class TestWorkspaceStorageLimits:
f"SubscriptionTier.{tier.name} has no entry in "
f"_DEFAULT_TIER_MULTIPLIERS — add one"
)
- if tier == SubscriptionTier.NO_TIER:
+ if tier in (SubscriptionTier.NO_TIER, SubscriptionTier.TRIAL):
assert _DEFAULT_TIER_MULTIPLIERS[tier] == 0.0
else:
assert _DEFAULT_TIER_MULTIPLIERS[tier] > 0
@@ -2709,6 +2744,13 @@ class TestWarnIfStripeSubscriptionDriftsYearly:
class TestGetRemainingUsdBudget:
+ @pytest.fixture(autouse=True)
+ def paid_user_tier(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.PRO),
+ )
+
@pytest.mark.asyncio
async def test_zero_limits_return_floor_not_unlimited(self):
"""With no real-world unlimited tier, both limits at 0 means
@@ -2797,6 +2839,13 @@ class TestGetRemainingUsdBudget:
class TestBuildBudgetCtx:
+ @pytest.fixture(autouse=True)
+ def paid_user_tier(self, mocker):
+ mocker.patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.PRO),
+ )
+
"""The helper combines ``get_global_rate_limits`` + ``get_remaining_usd_budget``
into a single call so callers don't have to compose them by hand on
every turn, and returns the *inner* text only — ``inject_user_context``
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index db6c3912d9..13d9bede16 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -53,6 +53,7 @@ from backend.copilot.provider_failure import ProviderFailure
from backend.copilot.segments import Segment, stamp_segment
from backend.copilot.graphiti.ingest import enqueue_conversation_turn
from backend.copilot.sdk.codex_compat_gateway import CodexAnthropicGateway
+from backend.copilot.sdk.trial_budget import resolve_trial_sdk_budget
from backend.copilot.tool_display import tool_calls_for_provider
from backend.data.db_accessors import chat_db
from backend.data.redis_client import get_redis_async
@@ -273,7 +274,7 @@ async def _resolve_dynamic_max_budget_usd(user_id: str | None) -> float:
static_cap = config.claude_agent_max_budget_usd
if not user_id:
return static_cap
- daily_limit, weekly_limit, _ = await get_global_rate_limits(
+ daily_limit, weekly_limit, tier = await get_global_rate_limits(
user_id,
config.daily_cost_limit_microdollars,
config.weekly_cost_limit_microdollars,
@@ -291,6 +292,8 @@ async def _resolve_dynamic_max_budget_usd(user_id: str | None) -> float:
weekly_cost_limit=weekly_limit,
floor_usd=-1.0,
)
+ if tier == "TRIAL":
+ return resolve_trial_sdk_budget(static_cap, remaining)
if remaining < 0 or remaining == float("inf"):
return static_cap
return max(_MAX_BUDGET_USD_FLOOR, min(static_cap, remaining))
diff --git a/autogpt_platform/backend/backend/copilot/sdk/trial_budget.py b/autogpt_platform/backend/backend/copilot/sdk/trial_budget.py
new file mode 100644
index 0000000000..e0e8a169c1
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/sdk/trial_budget.py
@@ -0,0 +1,11 @@
+from math import isfinite
+
+
+def resolve_trial_sdk_budget(static_cap: float, remaining: float) -> float:
+ if (
+ not isfinite(static_cap)
+ or not isfinite(remaining)
+ or min(static_cap, remaining) <= 0
+ ):
+ raise ValueError("Trial budget is unavailable or exhausted; no turn can start")
+ return min(static_cap, remaining)
diff --git a/autogpt_platform/backend/backend/copilot/sdk/trial_budget_test.py b/autogpt_platform/backend/backend/copilot/sdk/trial_budget_test.py
new file mode 100644
index 0000000000..6a2a6c1d4f
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/sdk/trial_budget_test.py
@@ -0,0 +1,40 @@
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from backend.copilot.sdk.service import _resolve_dynamic_max_budget_usd
+
+
+def trial_budget():
+ with (
+ patch(
+ "backend.copilot.sdk.service.get_global_rate_limits",
+ AsyncMock(return_value=(250_000, 1_000_000, "TRIAL")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.get_remaining_usd_budget", AsyncMock()
+ ) as remaining,
+ patch("backend.copilot.sdk.service.config.claude_agent_max_budget_usd", 10.0),
+ ):
+ yield remaining
+
+
+async def test_trial_budget_is_never_rounded_up_to_paid_floor(trial_budget):
+ trial_budget.return_value = 0.05
+ assert await _resolve_dynamic_max_budget_usd("trial-user") == 0.05
+
+
[email protected]("remaining", [0.0, -1.0, float("inf"), float("nan")])
+async def test_unavailable_trial_budget_refuses_sdk_dispatch(trial_budget, remaining):
+ trial_budget.return_value = remaining
+ with pytest.raises(ValueError, match="Trial budget"):
+ await _resolve_dynamic_max_budget_usd("trial-user")
+
+
+async def test_trial_still_respects_static_per_turn_cap(trial_budget):
+ trial_budget.return_value = 20.0
+ assert await _resolve_dynamic_max_budget_usd("trial-user") == 10.0
diff --git a/autogpt_platform/backend/backend/copilot/token_tracking.py b/autogpt_platform/backend/backend/copilot/token_tracking.py
index 3d67776ecf..872db7d4c9 100644
--- a/autogpt_platform/backend/backend/copilot/token_tracking.py
+++ b/autogpt_platform/backend/backend/copilot/token_tracking.py
@@ -17,6 +17,7 @@ import threading
from openai.types.completion_usage import PromptTokensDetails
+from backend.copilot.trial_cost_context import get_trial_cost_context
from backend.data.db_accessors import platform_cost_db
from backend.data.platform_cost import PlatformCostEntry, usd_to_microdollars
@@ -268,6 +269,10 @@ async def persist_and_record_usage(
# to mark source="dream_pass"); base keys it doesn't touch stay.
metadata.update(extra_metadata)
+ trial_context = get_trial_cost_context(user_id)
+ if trial_context is not None:
+ metadata["subscription_trial_id"] = trial_context.trial_id
+
_schedule_cost_log(
PlatformCostEntry(
user_id=user_id,
diff --git a/autogpt_platform/backend/backend/copilot/trial_cost_context.py b/autogpt_platform/backend/backend/copilot/trial_cost_context.py
new file mode 100644
index 0000000000..330367faa6
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/trial_cost_context.py
@@ -0,0 +1,66 @@
+"""Keep delayed foreground usage attached to the trial that started the turn.
+
+This is attribution, not a spend reservation or a durable settlement queue.
+Async child tasks inherit the snapshot even after their parent turn exits.
+"""
+
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from contextvars import ContextVar
+
+from pydantic import BaseModel, ConfigDict
+
+from backend.data import db_accessors
+
+
+class TrialCostContext(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ user_id: str | None
+ trial_id: str | None
+
+
+_trial_cost_context: ContextVar[TrialCostContext | None] = ContextVar(
+ "trial_cost_context", default=None
+)
+
+
+@asynccontextmanager
+async def trial_cost_context(user_id: str | None) -> AsyncIterator[None]:
+ trial = (
+ await db_accessors.credit_db().get_subscription_trial(user_id)
+ if user_id is not None
+ else None
+ )
+ context = TrialCostContext(
+ user_id=user_id,
+ trial_id=(
+ trial.id
+ if trial is not None and trial.active and trial.consumed_at is not None
+ else None
+ ),
+ )
+ token = _trial_cost_context.set(context)
+ try:
+ yield
+ finally:
+ _trial_cost_context.reset(token)
+
+
+def get_trial_cost_context(user_id: str | None) -> TrialCostContext | None:
+ context = _trial_cost_context.get()
+ if context is not None and context.user_id != user_id:
+ raise ValueError("Trial cost attribution belongs to a different user")
+ return context
+
+
+async def record_attributed_trial_cost(user_id: str, cost_microdollars: int) -> bool:
+ """Return whether the turn has a snapshot, including explicitly non-trial work."""
+ context = get_trial_cost_context(user_id)
+ if context is None:
+ return False
+ if context.trial_id is not None:
+ await db_accessors.credit_db().record_subscription_trial_cost(
+ user_id, cost_microdollars, trial_id=context.trial_id
+ )
+ return True
diff --git a/autogpt_platform/backend/backend/copilot/trial_cost_context_test.py b/autogpt_platform/backend/backend/copilot/trial_cost_context_test.py
new file mode 100644
index 0000000000..d7498a4249
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/trial_cost_context_test.py
@@ -0,0 +1,117 @@
+import asyncio
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from backend.copilot.trial_cost_context import (
+ get_trial_cost_context,
+ record_attributed_trial_cost,
+ trial_cost_context,
+)
+from backend.data.subscription_trial import TrialState
+
+
+def store(mocker):
+ trial = MagicMock(spec=TrialState)
+ trial.id = "trial-1"
+ trial.active = True
+ trial.consumed_at = datetime.now(UTC)
+ store = MagicMock()
+ store.get_subscription_trial = AsyncMock(return_value=trial)
+ store.record_subscription_trial_cost = AsyncMock()
+ mocker.patch(
+ "backend.copilot.trial_cost_context.db_accessors.credit_db", return_value=store
+ )
+ return store
+
+
[email protected]("exit_error", [RuntimeError, asyncio.CancelledError])
+async def test_scope_restores_parent_even_on_failure(store, exit_error):
+ assert get_trial_cost_context("user-1") is None
+ async with trial_cost_context("user-1"):
+ parent = get_trial_cost_context("user-1")
+ with pytest.raises(exit_error):
+ async with trial_cost_context(None):
+ anonymous = get_trial_cost_context(None)
+ assert anonymous is not None and anonymous.trial_id is None
+ raise exit_error()
+ assert get_trial_cost_context("user-1") is parent
+ assert get_trial_cost_context("user-1") is None
+ store.get_subscription_trial.assert_awaited_once_with("user-1")
+
+
+async def test_cross_user_cost_is_rejected_before_writes(store):
+ async with trial_cost_context("user-1"):
+ with pytest.raises(ValueError, match="different user"):
+ await record_attributed_trial_cost("user-2", 100)
+ store.record_subscription_trial_cost.assert_not_awaited()
+
+
[email protected]("initial_state", ["absent", "inactive", "unconsumed"])
+async def test_non_trial_snapshot_never_picks_up_later_enrollment(store, initial_state):
+ trial = store.get_subscription_trial.return_value
+ if initial_state == "absent":
+ store.get_subscription_trial.return_value = None
+ elif initial_state == "inactive":
+ trial.active = False
+ else:
+ trial.consumed_at = None
+ async with trial_cost_context("user-1"):
+ store.get_subscription_trial.return_value = trial
+ trial.active = True
+ trial.consumed_at = datetime.now(UTC)
+ assert await record_attributed_trial_cost("user-1", 100) is True
+ store.record_subscription_trial_cost.assert_not_awaited()
+
+
+async def test_unscoped_call_preserves_legacy_recording(store):
+ assert await record_attributed_trial_cost("user-1", 100) is False
+ store.get_subscription_trial.assert_not_awaited()
+ store.record_subscription_trial_cost.assert_not_awaited()
+
+
+async def test_lookup_failure_prevents_work_and_does_not_leak_context(store):
+ store.get_subscription_trial.side_effect = ConnectionError("Database unavailable")
+ with pytest.raises(ConnectionError):
+ async with trial_cost_context("user-1"):
+ pytest.fail("Work must not start without an attribution snapshot")
+ assert get_trial_cost_context("user-1") is None
+
+
+async def test_accounting_failure_is_not_silently_discarded(store):
+ store.record_subscription_trial_cost.side_effect = ConnectionError("Database down")
+ async with trial_cost_context("user-1"):
+ with pytest.raises(ConnectionError):
+ await record_attributed_trial_cost("user-1", 100)
+
+
+async def test_parallel_users_do_not_share_attribution(store):
+ async def lookup(user_id):
+ trial = MagicMock(spec=TrialState)
+ trial.id = f"trial-{user_id}"
+ trial.active = True
+ trial.consumed_at = datetime.now(UTC)
+ return trial
+
+ store.get_subscription_trial.side_effect = lookup
+ barrier = asyncio.Barrier(2)
+
+ async def turn(user_id):
+ async with trial_cost_context(user_id):
+ await barrier.wait()
+ assert await record_attributed_trial_cost(user_id, 100) is True
+
+ await asyncio.gather(turn("a"), turn("b"))
+ assert store.record_subscription_trial_cost.await_count == 2
+ store.record_subscription_trial_cost.assert_any_await("a", 100, trial_id="trial-a")
+ store.record_subscription_trial_cost.assert_any_await("b", 100, trial_id="trial-b")
+ assert get_trial_cost_context("a") is None
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 0dc8ae6936..c3b34cf307 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -36,7 +36,13 @@ from backend.data.model import (
from backend.data.model import User as AppUser
from backend.data.model import UserTransaction
from backend.data.notifications import NotificationEventModel, OpsData
-from backend.data.stripe_client import stripe_call
+from backend.data.stripe_client import stripe_call, stripe_list_items
+from backend.data.subscription_checkout import (
+ ensure_no_unconverted_trial,
+ expire_other_subscription_checkouts,
+ subscription_checkout_lock,
+)
+from backend.data.subscription_trial_stripe import reconcile_trial_subscription
from backend.data.user import get_user_by_id, get_user_email_by_id
from backend.notifications.queue import queue_notification_async
from backend.util.cache import cached
@@ -1522,6 +1528,10 @@ async def set_subscription_tier(
"subscriptionTier": tier,
}
await User.prisma().update(where={"id": user_id}, data=data)
+ invalidate_subscription_caches(user_id)
+
+
+def invalidate_subscription_caches(user_id: str) -> None:
get_user_by_id.cache_delete(user_id)
# Also invalidate the rate-limit tier cache so CoPilot picks up the new
# tier immediately rather than waiting up to 5 minutes for the TTL to expire.
@@ -1547,13 +1557,10 @@ async def _cancel_customer_subscriptions(
start billing once the trial ends and must be cleaned up on downgrade/upgrade to
avoid double-charging or charging users who intended to cancel.
- When ``at_period_end=True``, schedules cancellation at the end of the current
- billing period instead of cancelling immediately — the user keeps their tier
- until the period ends, then ``customer.subscription.deleted`` fires and the
- webhook downgrades them to BASIC.
+ When ``at_period_end=True``, paid subscriptions retain access through their
+ paid period. Trials always end immediately without invoicing or proration.
- Wraps every synchronous Stripe SDK call with run_in_threadpool so the async event
- loop is never blocked. Raises stripe.StripeError on list/cancel failure so callers
+ Uses the async Stripe client. Raises stripe.StripeError on list/cancel failure so callers
that need strict consistency can react; cleanup callers can catch and log instead.
Returns the number of subscriptions cancelled/scheduled for cancellation.
@@ -1569,24 +1576,14 @@ async def _cancel_customer_subscriptions(
status=status,
limit=10,
)
- # Iterate only the first page (up to 10); avoid auto_paging_iter which would
- # trigger additional sync HTTP calls inside the event loop.
- if subscriptions.has_more:
- logger.error(
- "_cancel_customer_subscriptions: customer %s has more than 10 %s"
- " subscriptions — only the first page was processed; remaining"
- " subscriptions were NOT cancelled",
- customer_id,
- status,
- )
- for sub in subscriptions.data:
+ async for sub in stripe_list_items(subscriptions):
sub_id = sub["id"]
if exclude_sub_id and sub_id == exclude_sub_id:
continue
if sub_id in seen_ids:
continue
seen_ids.add(sub_id)
- if at_period_end:
+ if at_period_end and status != "trialing":
# Stripe rejects modify(cancel_at_period_end=True) with 400 when a
# Subscription Schedule is attached (e.g. the user previously
# queued a paid→paid downgrade and is now clicking "Cancel").
@@ -1605,15 +1602,24 @@ async def _cancel_customer_subscriptions(
await stripe_call(
stripe.Subscription.modify_async, sub_id, cancel_at_period_end=True
)
+ elif status == "trialing":
+ canceled = await stripe_call(
+ stripe.Subscription.cancel_async,
+ sub_id,
+ invoice_now=False,
+ prorate=False,
+ )
+ if (sub.get("metadata") or {}).get("trial_enrollment_id"):
+ await sync_subscription_from_stripe(dict(canceled))
else:
await stripe_call(stripe.Subscription.cancel_async, sub_id)
return len(seen_ids)
async def cancel_stripe_subscription(user_id: str) -> bool:
- """Schedule cancellation of all active/trialing Stripe subscriptions at period end.
+ """Cancel trials immediately and paid subscriptions at period end.
- The subscription stays active until the end of the billing period so the user
+ A paid subscription stays active until the end of the billing period so the user
keeps their tier for the time they already paid for. The ``customer.subscription.deleted``
webhook fires at period end and downgrades the DB tier to BASIC.
@@ -1699,6 +1705,7 @@ async def get_proration_credit_cents(user_id: str, monthly_cost_cents: int) -> i
# never reached via self-service flows.
_TIER_ORDER: tuple[SubscriptionTier, ...] = (
SubscriptionTier.NO_TIER,
+ SubscriptionTier.TRIAL,
SubscriptionTier.BASIC,
SubscriptionTier.PRO,
SubscriptionTier.MAX,
@@ -2037,6 +2044,10 @@ async def modify_stripe_subscription_for_tier(
sub = await _get_active_subscription(user.stripe_customer_id)
if sub is None:
return False
+ if (sub.get("metadata") or {}).get("trial_enrollment_id"):
+ if sub.get("status") == "trialing":
+ raise ValueError("Manage your accepted trial plan in billing")
+ await ensure_no_unconverted_trial(user_id, user.stripe_customer_id)
items = sub["items"].data
if not items:
return False
@@ -2463,42 +2474,7 @@ async def build_price_to_tier_map() -> dict[str, SubscriptionTier]:
async def _expire_open_subscription_sessions(customer_id: str) -> None:
- """Expire open subscription checkout sessions for the customer.
-
- An abandoned subscription session leaves an incomplete subscription + open invoice
- in Stripe. Expiring it triggers Stripe to cancel that subscription and void the
- invoice, so the user is not shown phantom charges on their billing page.
- """
- try:
- starting_after: str | None = None
- while True:
- list_kwargs: dict = {
- "customer": customer_id,
- "status": "open",
- "limit": 100,
- }
- if starting_after:
- list_kwargs["starting_after"] = starting_after
- sessions = await stripe_call(
- stripe.checkout.Session.list_async, **list_kwargs
- )
- for s in sessions.data:
- if s.mode == "subscription":
- try:
- await stripe_call(stripe.checkout.Session.expire_async, s.id)
- except stripe.StripeError:
- logger.warning(
- "create_subscription_checkout: could not expire session %s",
- s.id,
- )
- if not sessions.has_more or not sessions.data:
- break
- starting_after = sessions.data[-1].id
- except Exception:
- logger.warning(
- "create_subscription_checkout: could not list open sessions for %s",
- customer_id,
- )
+ await expire_other_subscription_checkouts(customer_id)
def _is_stripe_reconcilable(user: AppUser) -> bool:
@@ -2597,11 +2573,33 @@ async def create_subscription_checkout(
datafast_session_id: str | None = None,
) -> str:
"""Create a Stripe Checkout Session for a subscription. Returns the redirect URL."""
+ async with subscription_checkout_lock(user_id):
+ return await _create_subscription_checkout(
+ user_id,
+ tier,
+ success_url,
+ cancel_url,
+ billing_cycle,
+ datafast_visitor_id,
+ datafast_session_id,
+ )
+
+
+async def _create_subscription_checkout(
+ user_id: str,
+ tier: SubscriptionTier,
+ success_url: str,
+ cancel_url: str,
+ billing_cycle: BillingCycle,
+ datafast_visitor_id: str | None,
+ datafast_session_id: str | None,
+) -> str:
price_id = await get_subscription_price_id(tier, billing_cycle)
if not price_id:
raise ValueError(f"Subscription not available for tier {tier.value}")
customer_id = await get_stripe_customer_id(user_id)
await _expire_open_subscription_sessions(customer_id)
+ await ensure_no_unconverted_trial(user_id, customer_id)
datafast = _datafast_metadata(datafast_visitor_id, datafast_session_id)
session = await stripe_call(
stripe.checkout.Session.create_async,
@@ -2729,6 +2727,15 @@ async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:
return
status = stripe_subscription.get("status", "")
new_sub_id = stripe_subscription.get("id", "")
+ if metadata.get("trial_enrollment_id") and new_sub_id:
+ trial_result = await reconcile_trial_subscription(user.id, new_sub_id)
+ if trial_result is None:
+ raise ValueError("Stripe trial is missing its matching enrollment")
+ stripe_subscription, trial_tier = trial_result
+ status = stripe_subscription.get("status", "")
+ if trial_tier is not None:
+ invalidate_subscription_caches(user.id)
+ return
if status in ("active", "trialing"):
price_id = ""
items = stripe_subscription.get("items", {}).get("data", [])
diff --git a/autogpt_platform/backend/backend/data/credit_metadata_test.py b/autogpt_platform/backend/backend/data/credit_metadata_test.py
index c291975db9..1727267b50 100644
--- a/autogpt_platform/backend/backend/data/credit_metadata_test.py
+++ b/autogpt_platform/backend/backend/data/credit_metadata_test.py
@@ -216,6 +216,14 @@ async def test_create_subscription_checkout_attaches_datafast_metadata():
mock_session.url = "https://checkout.stripe.com/pay/cs_test_sub"
create_mock = AsyncMock(return_value=mock_session)
with (
+ patch(
+ "backend.data.credit.subscription_checkout_lock",
+ return_value=AsyncMock(),
+ ),
+ patch(
+ "backend.data.credit.ensure_no_unconverted_trial",
+ new_callable=AsyncMock,
+ ),
patch(
"backend.data.credit.get_subscription_price_id",
new_callable=AsyncMock,
diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.py
index a00b0ac5af..cd95ede498 100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@ -681,7 +681,10 @@ async def test_cancel_stripe_subscription_no_active():
"backend.data.credit.stripe.Subscription.list_async",
return_value=mock_subscriptions,
),
- patch("backend.data.credit.stripe.Subscription.cancel_async") as mock_cancel,
+ patch(
+ "backend.data.credit.stripe.Subscription.cancel_async",
+ new_callable=AsyncMock,
+ ) as mock_cancel,
):
await cancel_stripe_subscription("user-1")
mock_cancel.assert_not_called()
@@ -707,7 +710,7 @@ async def test_cancel_stripe_subscription_raises_on_list_failure():
@pytest.mark.asyncio
async def test_cancel_stripe_subscription_cancels_trialing():
- """Trialing subs must also be scheduled for cancellation, else users get billed after trial end."""
+ """Trial cancellation ends access without invoicing or prorating."""
active_subs = MagicMock()
active_subs.data = []
active_subs.has_more = False
@@ -733,14 +736,21 @@ async def test_cancel_stripe_subscription_cancels_trialing():
side_effect=list_side_effect,
),
patch("backend.data.credit.stripe.Subscription.modify_async") as mock_modify,
+ patch(
+ "backend.data.credit.stripe.Subscription.cancel_async",
+ new_callable=AsyncMock,
+ ) as mock_cancel,
):
await cancel_stripe_subscription("user-1")
- mock_modify.assert_called_once_with("sub_trial_123", cancel_at_period_end=True)
+ mock_cancel.assert_called_once_with(
+ "sub_trial_123", invoice_now=False, prorate=False
+ )
+ mock_modify.assert_not_called()
@pytest.mark.asyncio
async def test_cancel_stripe_subscription_cancels_active_and_trialing():
- """Both active AND trialing subs present → both get scheduled for cancellation, no duplicates."""
+ """Paid access lasts through the paid period; trial access ends now."""
active_subs = MagicMock()
active_subs.data = [
stripe.Subscription.construct_from(
@@ -770,10 +780,17 @@ async def test_cancel_stripe_subscription_cancels_active_and_trialing():
side_effect=list_side_effect,
),
patch("backend.data.credit.stripe.Subscription.modify_async") as mock_modify,
+ patch(
+ "backend.data.credit.stripe.Subscription.cancel_async",
+ new_callable=AsyncMock,
+ ) as mock_cancel,
):
await cancel_stripe_subscription("user-1")
modified_ids = {call.args[0] for call in mock_modify.call_args_list}
- assert modified_ids == {"sub_active_1", "sub_trial_2"}
+ assert modified_ids == {"sub_active_1"}
+ mock_cancel.assert_called_once_with(
+ "sub_trial_2", invoice_now=False, prorate=False
+ )
@pytest.mark.asyncio
@@ -930,7 +947,7 @@ async def test_active_subscription_lookup_is_cached_within_window():
@pytest.mark.asyncio
-async def test_create_subscription_checkout_returns_url():
+async def test_create_subscription_checkout_returns_url(checkout_guard):
mock_session = MagicMock()
mock_session.url = "https://checkout.stripe.com/pay/cs_test_abc123"
with (
@@ -959,7 +976,9 @@ async def test_create_subscription_checkout_returns_url():
@pytest.mark.asyncio
-async def test_create_subscription_checkout_offers_saved_payment_methods():
+async def test_create_subscription_checkout_offers_saved_payment_methods(
+ checkout_guard,
+):
"""Returning subscribers must see their saved cards in Checkout.
Cards attached by a previous subscription-mode Checkout get
@@ -1002,7 +1021,7 @@ async def test_create_subscription_checkout_offers_saved_payment_methods():
@pytest.mark.asyncio
-async def test_create_subscription_checkout_no_price_raises():
+async def test_create_subscription_checkout_no_price_raises(checkout_guard):
with patch(
"backend.data.credit.get_subscription_price_id",
new_callable=AsyncMock,
@@ -1017,6 +1036,23 @@ async def test_create_subscription_checkout_no_price_raises():
)
+def checkout_guard():
+ with (
+ patch(
+ "backend.data.credit.subscription_checkout_lock", return_value=AsyncMock()
+ ),
+ patch(
+ "backend.data.credit.ensure_no_unconverted_trial", new_callable=AsyncMock
+ ),
+ patch(
+ "backend.data.credit._expire_open_subscription_sessions",
+ new_callable=AsyncMock,
+ ),
+ ):
+ yield
+
+
@pytest.mark.asyncio
async def test_sync_subscription_from_stripe_missing_customer_key_returns_early():
"""A webhook payload missing 'customer' must not raise KeyError — returns early with a warning."""
diff --git a/autogpt_platform/backend/backend/data/db.py b/autogpt_platform/backend/backend/data/db.py
index d3084af487..562688baf3 100644
--- a/autogpt_platform/backend/backend/data/db.py
+++ b/autogpt_platform/backend/backend/data/db.py
@@ -171,7 +171,9 @@ async def _raw_with_schema(
@overload
-async def query_raw_with_schema(query_template: str, *args) -> list[dict]: ...
+async def query_raw_with_schema(
+ query_template: str, *args, client: Prisma | None = None
+) -> list[dict]: ...
@overload
@@ -179,6 +181,7 @@ async def query_raw_with_schema(
query_template: str,
*args,
model: type[RawQueryModelT],
+ client: Prisma | None = None,
) -> list[RawQueryModelT]: ...
@@ -186,6 +189,7 @@ async def query_raw_with_schema(
query_template: str,
*args,
model: type[RawQueryModelT] | None = None,
+ client: Prisma | None = None,
) -> list[dict] | list[RawQueryModelT]:
"""Execute raw SQL SELECT query with proper schema handling.
@@ -207,6 +211,7 @@ async def query_raw_with_schema(
*args,
execute=False,
model=model,
+ client=client,
) # type: ignore
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 701393e9a8..9e38dabad2 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -93,6 +93,7 @@ from backend.data.credit import (
get_recent_daily_spend,
get_user_credit_model,
reconcile_stripe_tier_for_user,
+ sync_subscription_from_stripe,
)
from backend.data.execution import (
create_graph_execution,
@@ -148,6 +149,10 @@ from backend.data.push_subscription import (
increment_fail_count,
)
from backend.data.stripe_reconciliation import reconcile_all_stripe_tiers
+from backend.data.subscription_trial import (
+ get_subscription_trial,
+ record_subscription_trial_cost,
+)
from backend.data.understanding import (
get_business_understanding,
upsert_business_understanding,
@@ -338,6 +343,9 @@ class DatabaseManager(AppService):
# ============ User + Integrations ============ #
get_user_by_id = _(get_user_by_id)
get_user_subscription_tier = _(get_user_subscription_tier)
+ get_subscription_trial = _(get_subscription_trial)
+ sync_subscription_from_stripe = _(sync_subscription_from_stripe)
+ record_subscription_trial_cost = _(record_subscription_trial_cost)
# Exposed so Prisma-less workers (scheduler, copilot-executor) can build a
# full LaunchDarkly context — see backend/util/feature_flag.py.
get_auth_user_flag_fields = _(get_auth_user_flag_fields)
@@ -719,6 +727,9 @@ class DatabaseManagerAsyncClient(AppServiceClient):
# ============ User + Integrations ============ #
get_user_by_id = d.get_user_by_id
get_user_subscription_tier = d.get_user_subscription_tier
+ get_subscription_trial = d.get_subscription_trial
+ sync_subscription_from_stripe = d.sync_subscription_from_stripe
+ record_subscription_trial_cost = d.record_subscription_trial_cost
get_auth_user_flag_fields = d.get_auth_user_flag_fields
get_user_integrations = d.get_user_integrations
update_user_integrations = d.update_user_integrations
diff --git a/autogpt_platform/backend/backend/data/notifications.py b/autogpt_platform/backend/backend/data/notifications.py
index d0769b0621..40382d894c 100644
--- a/autogpt_platform/backend/backend/data/notifications.py
+++ b/autogpt_platform/backend/backend/data/notifications.py
@@ -239,6 +239,22 @@ class SubscriptionEndedData(LifecycleData):
due_to_payment: bool
+class TrialUpdateData(LifecycleData):
+ notice_key: str | None = None
+ kind: Literal[
+ "started",
+ "ending",
+ "canceled",
+ "resumed",
+ "ended",
+ "converted",
+ "payment_failed",
+ ]
+ ends_label: str
+ onboarding_credit_amount: int
+ offer_version: str
+
+
NotificationData = Union[
BriefingData,
AlertData,
@@ -250,6 +266,7 @@ NotificationData = Union[
SubscriptionCancelledData,
SubscriptionResumedData,
SubscriptionEndedData,
+ TrialUpdateData,
]
_DATA_TYPES: dict[NotificationType, type[BaseNotificationData]] = {
@@ -263,6 +280,7 @@ _DATA_TYPES: dict[NotificationType, type[BaseNotificationData]] = {
NotificationType.SUBSCRIPTION_CANCELLED: SubscriptionCancelledData,
NotificationType.SUBSCRIPTION_RESUMED: SubscriptionResumedData,
NotificationType.SUBSCRIPTION_ENDED: SubscriptionEndedData,
+ NotificationType.TRIAL_UPDATE: TrialUpdateData,
}
# Which Jinja template family renders each type. The billing messages all share
@@ -278,6 +296,7 @@ _TEMPLATES: dict[NotificationType, str] = {
NotificationType.SUBSCRIPTION_CANCELLED: "lifecycle",
NotificationType.SUBSCRIPTION_RESUMED: "lifecycle",
NotificationType.SUBSCRIPTION_ENDED: "lifecycle",
+ NotificationType.TRIAL_UPDATE: "trial",
}
# The `kind` slot the lifecycle template branches on.
@@ -328,6 +347,7 @@ _STREAMS: dict[NotificationType, DeliveryStream] = {
NotificationType.SUBSCRIPTION_CANCELLED: DeliveryStream.BILLING,
NotificationType.SUBSCRIPTION_RESUMED: DeliveryStream.BILLING,
NotificationType.SUBSCRIPTION_ENDED: DeliveryStream.BILLING,
+ NotificationType.TRIAL_UPDATE: DeliveryStream.BILLING,
}
diff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.py
index 9ebbfd105a..94b48e7e4d 100644
--- a/autogpt_platform/backend/backend/data/onboarding.py
+++ b/autogpt_platform/backend/backend/data/onboarding.py
@@ -19,6 +19,7 @@ from backend.data.onboarding_steps import (
FrontendOnboardingStep as FrontendOnboardingStep,
)
from backend.data.onboarding_steps import OnboardingStep
+from backend.data.subscription_trial import get_subscription_trial
from backend.data.user import get_user_by_id
from backend.util.cache import cached
from backend.util.json import SafeJson
@@ -123,12 +124,17 @@ async def update_user_onboarding(user_id: str, data: UserOnboardingUpdate):
async def _reward_user(user_id: str, onboarding: UserOnboarding, step: OnboardingStep):
+ """Internal grant: callers must derive user_id from authenticated identity
+ or a verified webhook's stored owner, never an untrusted request field."""
reward = 0
match step:
# The wizard fires ONBOARDING_COMPLETE on completion; this is the grant
# backing the wallet's "Complete onboarding" task ($3).
case OnboardingStep.ONBOARDING_COMPLETE:
reward = 300
+ trial = await get_subscription_trial(user_id)
+ if trial and trial.consumed_at:
+ reward = trial.offer.onboarding_credit_amount
case OnboardingStep.AGENT_NEW_RUN:
reward = 300
case OnboardingStep.MARKETPLACE_ADD_AGENT:
diff --git a/autogpt_platform/backend/backend/data/onboarding_test.py b/autogpt_platform/backend/backend/data/onboarding_test.py
index 814e860d58..197b1224d1 100644
--- a/autogpt_platform/backend/backend/data/onboarding_test.py
+++ b/autogpt_platform/backend/backend/data/onboarding_test.py
@@ -11,6 +11,14 @@ from backend.data.onboarding import (
)
[email protected](autouse=True)
+def no_trial_enrollment(mocker: pytest_mock.MockFixture):
+ mocker.patch(
+ "backend.data.onboarding.get_subscription_trial",
+ AsyncMock(return_value=None),
+ )
+
+
def test_format_onboarding_for_extraction_basic():
result = format_onboarding_for_extraction(
user_name="John",
diff --git a/autogpt_platform/backend/backend/data/platform_cost.py b/autogpt_platform/backend/backend/data/platform_cost.py
index 83fe89bfa5..f8b25e338c 100644
--- a/autogpt_platform/backend/backend/data/platform_cost.py
+++ b/autogpt_platform/backend/backend/data/platform_cost.py
@@ -905,8 +905,8 @@ async def get_copilot_weekly_usage_for_export(
"""Aggregate copilot:* PlatformCostLog rows by (user, ISO week) for export.
Joins User to surface the email and subscription tier in a single query,
- then computes the per-tier weekly limit from `get_tier_multipliers()` so
- `percent_used` reflects what's actually enforced (LD overrides included).
+ then computes paid-tier limits from `get_tier_multipliers()`. TRIAL uses
+ its accepted offer's frozen weekly limit, not the zero tier multiplier.
Caveats:
- Tier is the user's **current** tier — `PlatformCostLog` has no historical
@@ -943,9 +943,11 @@ async def get_copilot_weekly_usage_for_export(
' u."subscriptionTier" AS tier,'
" (date_trunc('week', log.\"createdAt\" AT TIME ZONE 'UTC') AT TIME ZONE 'UTC')"
" AS week_start,"
- ' SUM(COALESCE(log."costMicrodollars", 0))::bigint AS cost_microdollars'
+ ' SUM(COALESCE(log."costMicrodollars", 0))::bigint AS cost_microdollars,'
+ " MAX((trial.\"offer\"->>'weekly_cost_limit')::bigint) AS trial_weekly_limit"
' FROM {schema_prefix}"PlatformCostLog" log'
' LEFT JOIN {schema_prefix}"User" u ON u."id" = log."userId"'
+ ' LEFT JOIN {schema_prefix}"SubscriptionTrial" trial ON trial."userId" = log."userId"'
' WHERE log."createdAt" >= $1::timestamptz'
' AND log."createdAt" <= $2::timestamptz'
" AND log.\"blockName\" ILIKE 'copilot:%'"
@@ -1001,6 +1003,11 @@ async def get_copilot_weekly_usage_for_export(
# Clamp to >= 0 so a misconfigured/negative multiplier never emits
# negative limits in the CSV.
weekly_limit = max(0, int(base_weekly * multiplier))
+ if tier_enum == SubscriptionTier.TRIAL:
+ accepted_limit = r.get("trial_weekly_limit")
+ if accepted_limit is None or int(accepted_limit) <= 0:
+ raise ValueError("Trial export requires an accepted weekly limit")
+ weekly_limit = int(accepted_limit)
if weekly_limit > 0:
percent_used = round(100.0 * cost / weekly_limit, 2)
else:
diff --git a/autogpt_platform/backend/backend/data/stripe_client.py b/autogpt_platform/backend/backend/data/stripe_client.py
index 93273d829a..8b6c446e02 100644
--- a/autogpt_platform/backend/backend/data/stripe_client.py
+++ b/autogpt_platform/backend/backend/data/stripe_client.py
@@ -22,7 +22,7 @@ recorded as ``timeout`` and logged at error level so it is never silent.
import asyncio
import logging
import time
-from collections.abc import Awaitable, Callable
+from collections.abc import AsyncIterator, Awaitable, Callable
from typing import ParamSpec, TypeVar
import stripe
@@ -33,6 +33,7 @@ logger = logging.getLogger(__name__)
P = ParamSpec("P")
T = TypeVar("T")
+StripeResource = TypeVar("StripeResource", bound=stripe.StripeObject)
# Stripe's own p99 is low single-digit seconds; 80s (the SDK default) only
# ever means a stalled socket, and holding a request that long serves nobody.
@@ -61,6 +62,20 @@ async def stripe_call_timeout(
return await _call(timeout_seconds, fn, *args, **kwargs)
+async def stripe_list_items(
+ page: stripe.ListObject[StripeResource],
+) -> AsyncIterator[StripeResource]:
+ """Keep subsequent SDK list requests inside the same timeout/metrics boundary."""
+ while True:
+ for item in page.data:
+ yield item
+ if not page.has_more:
+ return
+ if not page.data:
+ raise ValueError("Stripe returned an empty page with more results")
+ page = await stripe_call(page.next_page_async)
+
+
async def _call(
timeout_seconds: float,
fn: Callable[P, Awaitable[T]],
diff --git a/autogpt_platform/backend/backend/data/stripe_client_test.py b/autogpt_platform/backend/backend/data/stripe_client_test.py
index 8be5e620cf..e3f74791b0 100644
--- a/autogpt_platform/backend/backend/data/stripe_client_test.py
+++ b/autogpt_platform/backend/backend/data/stripe_client_test.py
@@ -1,12 +1,17 @@
"""Tests for the single-door Stripe helper."""
import asyncio
+from unittest.mock import AsyncMock, patch
import pytest
import stripe
from prometheus_client import REGISTRY
-from backend.data.stripe_client import stripe_call, stripe_call_timeout
+from backend.data.stripe_client import (
+ stripe_call,
+ stripe_call_timeout,
+ stripe_list_items,
+)
def _n(resource: str, method: str, outcome: str) -> float:
@@ -83,3 +88,28 @@ async def test_timeout_is_bounded_and_counted():
assert "exceeded 0.05s" in str(info.value)
assert info.value.should_retry is False
assert _n("Subscription", "retrieve", "timeout") == before + 1
+
+
+async def test_pagination_preserves_all_items():
+ first = stripe.ListObject.construct_from(
+ {"data": [{"id": "first"}], "has_more": True}, "test-key"
+ )
+ second = stripe.ListObject.construct_from(
+ {"data": [{"id": "second"}], "has_more": False}, "test-key"
+ )
+ with patch.object(
+ stripe.ListObject, "next_page_async", AsyncMock(return_value=second)
+ ) as next_page:
+ assert [item.id async for item in stripe_list_items(first)] == [
+ "first",
+ "second",
+ ]
+ next_page.assert_awaited_once()
+
+
+async def test_incomplete_empty_page_is_not_treated_as_exhaustive_history():
+ page = stripe.ListObject.construct_from({"data": [], "has_more": True}, "test-key")
+ with pytest.raises(ValueError, match="empty page"):
+ _ = [item async for item in stripe_list_items(page)]
diff --git a/autogpt_platform/backend/backend/data/stripe_reconciliation.py b/autogpt_platform/backend/backend/data/stripe_reconciliation.py
index ac9c1edf80..2c36a7f5b5 100644
--- a/autogpt_platform/backend/backend/data/stripe_reconciliation.py
+++ b/autogpt_platform/backend/backend/data/stripe_reconciliation.py
@@ -24,6 +24,7 @@ from backend.data.credit import (
build_price_to_tier_map,
log_tier_reconciliation_discrepancy,
set_subscription_tier,
+ sync_subscription_from_stripe,
)
from backend.data.stripe_client import stripe_call
@@ -213,8 +214,9 @@ async def _collect_status_page(
tiers: dict[str, SubscriptionTier],
) -> bool:
"""Accumulate one Stripe status's subscriptions into ``tiers``. Returns
- True if pagination was capped before exhausting the dataset."""
+ True if a list or trial sync failed, or pagination was capped."""
starting_after: str | None = None
+ incomplete = False
for _ in range(_MAX_SUBSCRIPTION_PAGES):
list_kwargs: dict = {"status": status, "limit": _PAGE_SIZE}
if starting_after:
@@ -232,9 +234,28 @@ async def _collect_status_page(
)
return True
for sub in subs.data:
+ if (sub.get("metadata") or {}).get("trial_enrollment_id"):
+ try:
+ await sync_subscription_from_stripe(dict(sub))
+ except (ValueError, stripe.StripeError):
+ logger.exception(
+ "Trial reconciliation failed for subscription %s; snapshot is incomplete",
+ sub.id,
+ )
+ incomplete = True
+ continue
+ user = await User.prisma().find_first(
+ where={"stripeCustomerId": str(sub.customer)}
+ )
+ if user:
+ tier = SubscriptionTier(user.subscriptionTier)
+ existing = tiers.get(str(sub.customer))
+ if existing is None or _TIER_RANK[tier] > _TIER_RANK[existing]:
+ tiers[str(sub.customer)] = tier
+ continue
_record_subscription(sub, price_to_tier, tiers)
if not subs.has_more or not subs.data:
- return False
+ return incomplete
starting_after = subs.data[-1].id
logger.warning(
"reconcile_all_stripe_tiers: hit %d-page cap for status=%s; remaining"
@@ -268,6 +289,7 @@ def _record_subscription(
_TIER_RANK: dict[SubscriptionTier, int] = {
SubscriptionTier.NO_TIER: 0,
+ SubscriptionTier.TRIAL: 0,
SubscriptionTier.BASIC: 1,
SubscriptionTier.PRO: 2,
SubscriptionTier.MAX: 3,
diff --git a/autogpt_platform/backend/backend/data/subscription_checkout.py b/autogpt_platform/backend/backend/data/subscription_checkout.py
new file mode 100644
index 0000000000..5ac0942555
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_checkout.py
@@ -0,0 +1,66 @@
+"""Coordinate paid and trial Checkout creation for the same account."""
+
+from contextlib import asynccontextmanager
+from datetime import timedelta
+
+import stripe
+from pydantic import BaseModel
+
+from backend.data.db import query_raw_with_schema, transaction
+from backend.data.stripe_client import stripe_call, stripe_list_items
+from backend.data.subscription_trial import get_subscription_trial
+
+
+class SubscriptionCheckoutUnavailable(ValueError):
+ pass
+
+
+class CheckoutLock(BaseModel):
+ acquired: bool
+
+
+@asynccontextmanager
+async def subscription_checkout_lock(user_id: str):
+ async with transaction(timeout=timedelta(seconds=120)) as tx:
+ locks = await query_raw_with_schema(
+ "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS acquired",
+ f"subscription-checkout:{user_id}",
+ client=tx,
+ model=CheckoutLock,
+ )
+ if not locks or not locks[0].acquired:
+ raise SubscriptionCheckoutUnavailable(
+ "Another checkout is already starting. Please retry."
+ )
+ yield
+
+
+async def expire_other_subscription_checkouts(
+ customer_id: str, keep_session_id: str | None = None
+) -> None:
+ sessions = await stripe_call(
+ stripe.checkout.Session.list_async,
+ customer=customer_id,
+ status="open",
+ limit=100,
+ )
+ async for session in stripe_list_items(sessions):
+ if session.mode == "subscription" and session.id != keep_session_id:
+ await stripe_call(stripe.checkout.Session.expire_async, session.id)
+
+
+async def ensure_no_unconverted_trial(user_id: str, customer_id: str) -> None:
+ trial = await get_subscription_trial(user_id)
+ if trial is None or trial.converted_at:
+ return
+ subscriptions = await stripe_call(
+ stripe.Subscription.list_async, customer=customer_id, status="all", limit=100
+ )
+ async for subscription in stripe_list_items(subscriptions):
+ if (subscription.metadata or {}).get(
+ "trial_enrollment_id"
+ ) == trial.id and subscription.status not in ("canceled", "incomplete_expired"):
+ raise SubscriptionCheckoutUnavailable(
+ "This account already has a trial subscription. "
+ "Manage it in billing before starting another plan."
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_checkout_test.py b/autogpt_platform/backend/backend/data/subscription_checkout_test.py
new file mode 100644
index 0000000000..64e087930c
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_checkout_test.py
@@ -0,0 +1,121 @@
+import asyncio
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import stripe
+from prisma.enums import SubscriptionTier
+
+from backend.data import credit, stripe_client, subscription_checkout
+from backend.data.credit import _expire_open_subscription_sessions
+
+
+async def test_expiration_list_failure_stops_new_checkout():
+ with patch(
+ "backend.data.credit.stripe.checkout.Session.list_async",
+ AsyncMock(side_effect=stripe.APIConnectionError("unavailable")),
+ ):
+ with pytest.raises(stripe.APIConnectionError):
+ await _expire_open_subscription_sessions("cus_test")
+
+
+async def test_in_place_change_cannot_bypass_trial_with_stale_local_tier():
+ subscription = stripe.Subscription.construct_from(
+ {
+ "id": "sub_trial",
+ "status": "trialing",
+ "schedule": None,
+ "cancel_at_period_end": False,
+ "items": {"data": [{"id": "si_trial"}]},
+ "metadata": {"trial_enrollment_id": "trial-1"},
+ },
+ "test-key",
+ )
+ user = MagicMock(
+ stripe_customer_id="cus_test", subscription_tier=SubscriptionTier.NO_TIER
+ )
+ with (
+ patch.object(
+ credit, "get_subscription_price_id", AsyncMock(return_value="price_max")
+ ),
+ patch.object(credit, "get_user_by_id", AsyncMock(return_value=user)),
+ patch.object(
+ credit, "_get_active_subscription", AsyncMock(return_value=subscription)
+ ),
+ patch.object(credit.stripe.Subscription, "modify_async", AsyncMock()) as modify,
+ patch.object(credit, "set_subscription_tier", AsyncMock()) as promote,
+ patch.object(credit, "_track_billing_event"),
+ ):
+ with pytest.raises(ValueError, match="trial"):
+ await credit.modify_stripe_subscription_for_tier(
+ "user-1", SubscriptionTier.MAX
+ )
+ modify.assert_not_awaited()
+ promote.assert_not_awaited()
+
+
+async def test_session_completed_during_expiration_stops_new_checkout():
+ sessions = stripe.ListObject.construct_from(
+ {"data": [{"id": "cs_old", "mode": "subscription"}], "has_more": False},
+ "test-key",
+ )
+ with (
+ patch(
+ "backend.data.credit.stripe.checkout.Session.list_async",
+ AsyncMock(return_value=sessions),
+ ),
+ patch(
+ "backend.data.credit.stripe.checkout.Session.expire_async",
+ AsyncMock(side_effect=stripe.InvalidRequestError("already complete", "id")),
+ ),
+ ):
+ with pytest.raises(stripe.InvalidRequestError):
+ await _expire_open_subscription_sessions("cus_test")
+
+
+async def test_checkout_history_pagination_has_a_bounded_timeout():
+ first = stripe.ListObject.construct_from(
+ {
+ "data": [{"id": "sub_old", "status": "canceled", "metadata": {}}],
+ "has_more": True,
+ },
+ "test-key",
+ )
+ second = stripe.ListObject.construct_from(
+ {
+ "data": [
+ {
+ "id": "sub_trial",
+ "status": "trialing",
+ "metadata": {"trial_enrollment_id": "trial-1"},
+ }
+ ],
+ "has_more": False,
+ },
+ "test-key",
+ )
+
+ async def delayed_page():
+ await asyncio.sleep(0.05)
+ return second
+
+ with (
+ patch.object(stripe_client, "DEFAULT_TIMEOUT_SECONDS", 0.01),
+ patch.object(
+ subscription_checkout,
+ "get_subscription_trial",
+ AsyncMock(return_value=MagicMock(id="trial-1", converted_at=None)),
+ ),
+ patch.object(stripe.Subscription, "list_async", AsyncMock(return_value=first)),
+ patch.object(
+ stripe.ListObject, "next_page_async", AsyncMock(side_effect=delayed_page)
+ ) as next_page,
+ ):
+ with pytest.raises(stripe.APIConnectionError):
+ await subscription_checkout.ensure_no_unconverted_trial(
+ "user-1", "cus_test"
+ )
+ next_page.assert_awaited_once()
diff --git a/autogpt_platform/backend/backend/data/subscription_trial.py b/autogpt_platform/backend/backend/data/subscription_trial.py
new file mode 100644
index 0000000000..a9aff8d82f
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial.py
@@ -0,0 +1,137 @@
+"""Durable enrollment and usage state, scoped to the authenticated user."""
+
+from datetime import datetime
+
+from prisma.errors import UniqueViolationError
+from prisma.models import CreditTransaction, SubscriptionTrial
+from prisma.types import SubscriptionTrialWhereInput
+from pydantic import BaseModel, TypeAdapter
+
+from backend.data.subscription_trial_config import AcceptedTrialOffer, trial_is_active
+from backend.data.subscription_trial_rejection import TrialRejectionReason
+from backend.util.json import SafeJson
+
+
+class TrialState(BaseModel):
+ id: str
+ user_id: str
+ offer: AcceptedTrialOffer
+ customer_id: str
+ checkout_session_id: str | None
+ subscription_id: str | None
+ checkout_attempt: int
+ success_url: str
+ cancel_url: str
+ checkout_metadata: dict[str, str]
+ status: str
+ rejection_reason: TrialRejectionReason | None = None
+ card_verified_at: datetime | None
+ started_at: datetime | None
+ ends_at: datetime | None
+ consumed_at: datetime | None
+ converted_at: datetime | None
+ conversion_invoice_id: str | None = None
+ notification_revision: int = 0
+ cancel_at_period_end: bool
+ cost_microdollars: int
+
+ @property
+ def active(self) -> bool:
+ return trial_is_active(
+ status=self.status,
+ trial_end=self.ends_at,
+ card_verified=self.card_verified_at is not None,
+ )
+
+ @classmethod
+ def from_db(cls, row: SubscriptionTrial) -> "TrialState":
+ return cls(
+ id=row.id,
+ user_id=row.userId,
+ offer=AcceptedTrialOffer.model_validate(row.offer),
+ customer_id=row.stripeCustomerId,
+ checkout_session_id=row.stripeCheckoutSessionId,
+ subscription_id=row.stripeSubscriptionId,
+ checkout_attempt=row.checkoutAttempt,
+ success_url=row.checkoutSuccessUrl,
+ cancel_url=row.checkoutCancelUrl,
+ checkout_metadata=TypeAdapter(dict[str, str]).validate_python(
+ row.checkoutMetadata
+ ),
+ status=row.status,
+ rejection_reason=(
+ TrialRejectionReason(row.rejectionReason)
+ if row.rejectionReason
+ else None
+ ),
+ card_verified_at=row.cardVerifiedAt,
+ started_at=row.startedAt,
+ ends_at=row.endsAt,
+ consumed_at=row.consumedAt,
+ converted_at=row.convertedAt,
+ conversion_invoice_id=row.stripeConversionInvoiceId,
+ notification_revision=row.notificationRevision,
+ cancel_at_period_end=row.cancelAtPeriodEnd,
+ cost_microdollars=row.costMicrodollars,
+ )
+
+
+async def get_subscription_trial(user_id: str) -> TrialState | None:
+ row = await SubscriptionTrial.prisma().find_unique(where={"userId": user_id})
+ return TrialState.from_db(row) if row else None
+
+
+async def has_received_onboarding_credit(user_id: str) -> bool:
+ return (
+ await CreditTransaction.prisma().find_unique(
+ where={
+ "creditTransactionIdentifier": {
+ "userId": user_id,
+ "transactionKey": f"REWARD-{user_id}-ONBOARDING_COMPLETE",
+ }
+ }
+ )
+ is not None
+ )
+
+
+async def reserve_subscription_trial(
+ user_id: str,
+ offer: AcceptedTrialOffer,
+ customer_id: str,
+ success_url: str,
+ cancel_url: str,
+ metadata: dict[str, str],
+) -> TrialState:
+ try:
+ row = await SubscriptionTrial.prisma().create(
+ data={
+ "userId": user_id,
+ "offer": SafeJson(offer.model_dump(mode="json")),
+ "stripeCustomerId": customer_id,
+ "checkoutSuccessUrl": success_url,
+ "checkoutCancelUrl": cancel_url,
+ "checkoutMetadata": SafeJson(metadata),
+ },
+ )
+ except UniqueViolationError:
+ row = await SubscriptionTrial.prisma().find_unique_or_raise(
+ where={"userId": user_id}
+ )
+ return TrialState.from_db(row)
+
+
+async def record_subscription_trial_cost(
+ user_id: str, cost_microdollars: int, trial_id: str | None = None
+) -> None:
+ if cost_microdollars <= 0:
+ return
+ where: SubscriptionTrialWhereInput = {"userId": user_id, "status": "trialing"}
+ if trial_id is not None:
+ where = {"userId": user_id, "id": trial_id, "consumedAt": {"not": None}}
+ updated = await SubscriptionTrial.prisma().update_many(
+ where=where,
+ data={"costMicrodollars": {"increment": cost_microdollars}},
+ )
+ if trial_id is not None and updated != 1:
+ raise ValueError("Trial cost attribution was not found for this user")
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_billing.py b/autogpt_platform/backend/backend/data/subscription_trial_billing.py
new file mode 100644
index 0000000000..4ba0418d27
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_billing.py
@@ -0,0 +1,131 @@
+"""Refresh owned trials when Stripe billing-card details change."""
+
+import logging
+
+import stripe
+from pydantic import BaseModel, Field
+
+from backend.data.credit import sync_subscription_from_stripe
+from backend.data.db import query_raw_with_schema
+from backend.data.stripe_client import stripe_call
+
+logger = logging.getLogger(__name__)
+
+TRIAL_BILLING_EVENTS = frozenset(
+ {
+ "customer.updated",
+ "customer.deleted",
+ "payment_method.attached",
+ "payment_method.updated",
+ "payment_method.automatically_updated",
+ "payment_method.detached",
+ "setup_intent.succeeded",
+ "setup_intent.requires_action",
+ "setup_intent.setup_failed",
+ "setup_intent.canceled",
+ }
+)
+
+
+class BillingObject(BaseModel):
+ id: str = Field(min_length=1)
+ customer: str | None = None
+
+
+class PreviousBillingAttributes(BaseModel):
+ customer: str | None = None
+
+
+class BillingEventData(BaseModel):
+ object: BillingObject
+ previous_attributes: PreviousBillingAttributes | None = None
+
+
+class TrialBillingTarget(BaseModel):
+ id: str
+ user_id: str
+ customer_id: str
+ subscription_id: str
+
+
+class SubscriptionOwner(BaseModel):
+ id: str
+ customer: str
+ metadata: dict[str, str] = Field(default_factory=dict)
+
+
+async def sync_trials_for_billing_event(event_type: str, event_data: object) -> None:
+ customer_ids = billing_event_customer_ids(event_type, event_data)
+ if not customer_ids:
+ return
+ after_id = ""
+ failed = False
+ while targets := await get_trial_billing_targets(customer_ids, after_id):
+ for target in targets:
+ try:
+ await _refresh_trial(target)
+ except Exception:
+ failed = True
+ logger.exception(
+ f"Could not refresh billing card for trial {target.id}"
+ )
+ after_id = targets[-1].id
+ if failed:
+ raise RuntimeError("Trial billing refresh failed; retry the event")
+
+
+def billing_event_customer_ids(event_type: str, event_data: object) -> list[str]:
+ if event_type not in TRIAL_BILLING_EVENTS:
+ return []
+ event = BillingEventData.model_validate(event_data)
+ if event_type in {"customer.updated", "customer.deleted"}:
+ return [event.object.id]
+ previous = event.previous_attributes
+ return sorted(
+ {
+ customer
+ for customer in (
+ event.object.customer,
+ previous.customer if previous else None,
+ )
+ if customer
+ }
+ )
+
+
+async def get_trial_billing_targets(
+ customer_ids: list[str], after_id: str = ""
+) -> list[TrialBillingTarget]:
+ return await query_raw_with_schema(
+ """
+ SELECT t."id", t."userId" AS user_id,
+ t."stripeCustomerId" AS customer_id,
+ t."stripeSubscriptionId" AS subscription_id
+ FROM {schema_prefix}"SubscriptionTrial" t
+ JOIN {schema_prefix}"User" u ON u."id" = t."userId"
+ WHERE t."stripeCustomerId" = ANY($1::text[]) AND t."id" > $2
+ AND t."consumedAt" IS NOT NULL AND t."convertedAt" IS NULL
+ AND t."stripeSubscriptionId" IS NOT NULL
+ AND u."stripeCustomerId" = t."stripeCustomerId"
+ AND u."subscriptionTier" != 'ENTERPRISE'
+ ORDER BY t."id" LIMIT 100
+ """,
+ customer_ids,
+ after_id,
+ model=TrialBillingTarget,
+ )
+
+
+async def _refresh_trial(target: TrialBillingTarget) -> None:
+ subscription = await stripe_call(
+ stripe.Subscription.retrieve_async, target.subscription_id
+ )
+ owner = SubscriptionOwner.model_validate(subscription)
+ if (
+ owner.id != target.subscription_id
+ or owner.customer != target.customer_id
+ or owner.metadata.get("trial_enrollment_id") != target.id
+ or owner.metadata.get("user_id") != target.user_id
+ ):
+ raise ValueError("Stripe billing change does not match trial ownership")
+ await sync_subscription_from_stripe(dict(subscription))
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_billing_integration_test.py b/autogpt_platform/backend/backend/data/subscription_trial_billing_integration_test.py
new file mode 100644
index 0000000000..458e457723
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_billing_integration_test.py
@@ -0,0 +1,104 @@
+"""Selection boundaries for billing events, against an explicitly disposable DB."""
+
+import os
+from datetime import UTC, datetime
+from urllib.parse import urlparse
+from uuid import uuid4
+
+import pytest
+import pytest_asyncio
+from prisma.models import SubscriptionTrial, User
+
+from backend.data import db
+from backend.data.subscription_trial_billing import get_trial_billing_targets
+from backend.util.json import SafeJson
+
+pytestmark = pytest.mark.skipif(
+ os.environ.get("TRIAL_TEST_DATABASE") != "1",
+ reason="Requires explicitly selected disposable trial database",
+)
+
+
+@pytest_asyncio.fixture
+async def customer_id():
+ target = urlparse(db.DATABASE_URL)
+ assert (target.hostname, target.port, target.path) == (
+ "127.0.0.1",
+ 15432,
+ "/trial_test",
+ ) or (
+ os.environ.get("GITHUB_ACTIONS") == "true"
+ and (target.hostname, target.port, target.path)
+ == ("localhost", 5432, "/postgres")
+ )
+ owns_connection = not db.is_connected()
+ await db.connect()
+ customer = f"cus_billing_test_{uuid4()}"
+ yield customer
+ rows = await SubscriptionTrial.prisma().find_many(
+ where={"stripeCustomerId": customer}
+ )
+ await User.prisma().delete_many(where={"id": {"in": [row.userId for row in rows]}})
+ if owns_connection:
+ await db.disconnect()
+
+
+async def create_trial(
+ customer_id,
+ *,
+ consumed=True,
+ converted=False,
+ subscription=True,
+ current_customer=None,
+ enterprise=False,
+):
+ user_id = str(uuid4())
+ await User.prisma().create(
+ data={
+ "id": user_id,
+ "email": f"{user_id}@example.com",
+ "stripeCustomerId": current_customer or customer_id,
+ "subscriptionTier": "ENTERPRISE" if enterprise else "TRIAL",
+ }
+ )
+ return await SubscriptionTrial.prisma().create(
+ data={
+ "userId": user_id,
+ "stripeCustomerId": customer_id,
+ "stripeSubscriptionId": f"sub_{uuid4()}" if subscription else None,
+ "offer": SafeJson({"validation": "billing-target-selection"}),
+ "checkoutSuccessUrl": "https://example.com/success",
+ "checkoutCancelUrl": "https://example.com/cancel",
+ "consumedAt": datetime.now(UTC) if consumed else None,
+ "convertedAt": datetime.now(UTC) if converted else None,
+ }
+ )
+
+
+async def test_billing_targets_exclude_unowned_pending_converted_and_enterprise(
+ customer_id,
+):
+ expected = await create_trial(customer_id)
+ await create_trial(customer_id, consumed=False)
+ await create_trial(customer_id, converted=True)
+ await create_trial(customer_id, subscription=False)
+ await create_trial(customer_id, current_customer="cus_changed_mapping")
+ await create_trial(customer_id, enterprise=True)
+ rows = await get_trial_billing_targets([customer_id])
+ assert [row.id for row in rows] == [expected.id]
+ assert rows[0].user_id == expected.userId
+ assert rows[0].subscription_id == expected.stripeSubscriptionId
+ assert await get_trial_billing_targets(["cus_not_this_customer"]) == []
+ assert await get_trial_billing_targets([]) == []
+
+
+async def test_billing_targets_keyset_pagination_does_not_skip_trials(customer_id):
+ rows = [await create_trial(customer_id) for _ in range(101)]
+ first = await get_trial_billing_targets([customer_id])
+ assert len(first) == 100
+ second = await get_trial_billing_targets([customer_id], first[-1].id)
+ assert len(second) == 1
+ assert [row.id for row in first + second] == sorted(row.id for row in rows)
+ assert await get_trial_billing_targets([customer_id], second[-1].id) == []
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_billing_test.py b/autogpt_platform/backend/backend/data/subscription_trial_billing_test.py
new file mode 100644
index 0000000000..45c8e83727
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_billing_test.py
@@ -0,0 +1,195 @@
+from unittest.mock import AsyncMock, call, patch
+
+import pytest
+import stripe
+from pydantic import ValidationError
+
+from backend.data import subscription_trial_billing as billing
+
+
+ "event_type,data,expected",
+ [
+ ("customer.updated", {"object": {"id": "cus_1"}}, ["cus_1"]),
+ ("customer.deleted", {"object": {"id": "cus_1", "deleted": True}}, ["cus_1"]),
+ (
+ "payment_method.attached",
+ {"object": {"id": "pm_1", "customer": "cus_1"}},
+ ["cus_1"],
+ ),
+ (
+ "payment_method.updated",
+ {
+ "object": {"id": "pm_1", "customer": "cus_1"},
+ "previous_attributes": {"customer": "cus_1"},
+ },
+ ["cus_1"],
+ ),
+ (
+ "payment_method.detached",
+ {
+ "object": {"id": "pm_1", "customer": None},
+ "previous_attributes": {"customer": "cus_old"},
+ },
+ ["cus_old"],
+ ),
+ (
+ "payment_method.updated",
+ {
+ "object": {"id": "pm_1", "customer": "cus_new"},
+ "previous_attributes": {"customer": "cus_old"},
+ },
+ ["cus_new", "cus_old"],
+ ),
+ (
+ "payment_method.automatically_updated",
+ {"object": {"id": "pm_1", "customer": "cus_1"}},
+ ["cus_1"],
+ ),
+ (
+ "setup_intent.succeeded",
+ {"object": {"id": "seti_1", "customer": "cus_1"}},
+ ["cus_1"],
+ ),
+ ("payment_method.detached", {"object": {"id": "pm_1", "customer": None}}, []),
+ ("unrelated.event", None, []),
+ ],
+)
+def test_billing_event_customer_identity(event_type, data, expected):
+ assert billing.billing_event_customer_ids(event_type, data) == expected
+
+
+ "data",
+ [
+ None,
+ {},
+ {"object": {"id": ""}},
+ {"object": {"id": "pm_1", "customer": {"id": "cus_1"}}},
+ ],
+)
+def test_malformed_event_does_not_invent_customer_identity(data):
+ with pytest.raises(ValidationError):
+ billing.billing_event_customer_ids("payment_method.updated", data)
+
+
+def target(number):
+ return billing.TrialBillingTarget(
+ id=f"trial_{number}",
+ user_id=f"user_{number}",
+ customer_id="cus_1",
+ subscription_id=f"sub_{number}",
+ )
+
+
+def subscription(number):
+ return {
+ "id": f"sub_{number}",
+ "customer": "cus_1",
+ "status": "trialing",
+ "metadata": {
+ "trial_enrollment_id": f"trial_{number}",
+ "user_id": f"user_{number}",
+ },
+ }
+
+
+def boundaries():
+ with (
+ patch.object(
+ billing,
+ "get_trial_billing_targets",
+ AsyncMock(side_effect=[[target(1)], []]),
+ ) as targets,
+ patch.object(
+ stripe.Subscription,
+ "retrieve_async",
+ AsyncMock(return_value=subscription(1)),
+ ) as retrieve,
+ patch.object(billing, "sync_subscription_from_stripe", AsyncMock()) as sync,
+ ):
+ yield targets, retrieve, sync
+
+
+async def test_event_payload_only_routes_current_stripe_reconciliation(boundaries):
+ targets, retrieve, sync = boundaries
+ await billing.sync_trials_for_billing_event(
+ "customer.updated",
+ {
+ "object": {
+ "id": "cus_1",
+ "default_payment_method": None,
+ "status": "canceled",
+ },
+ },
+ )
+ retrieve.assert_awaited_once_with("sub_1")
+ sync.assert_awaited_once_with(subscription(1))
+ assert targets.await_args_list == [call(["cus_1"], ""), call(["cus_1"], "trial_1")]
+
+
+async def test_unattached_method_does_not_query_trials(boundaries):
+ targets, retrieve, sync = boundaries
+ await billing.sync_trials_for_billing_event(
+ "payment_method.updated", {"object": {"id": "pm_unattached", "customer": None}}
+ )
+ targets.assert_not_awaited()
+ retrieve.assert_not_awaited()
+ sync.assert_not_awaited()
+
+
+ "changed",
+ [
+ {"id": "sub_other"},
+ {"customer": "cus_other"},
+ {"metadata": {"trial_enrollment_id": "trial_other", "user_id": "user_1"}},
+ {"metadata": {"trial_enrollment_id": "trial_1", "user_id": "user_other"}},
+ ],
+)
+async def test_foreign_subscription_cannot_change_trial(boundaries, changed):
+ _, retrieve, sync = boundaries
+ retrieve.return_value.update(changed)
+ with pytest.raises(RuntimeError, match="retry the event"):
+ await billing.sync_trials_for_billing_event(
+ "customer.updated", {"object": {"id": "cus_1"}}
+ )
+ sync.assert_not_awaited()
+
+
+async def test_failed_target_does_not_starve_other_pages_and_event_is_retryable(
+ boundaries,
+):
+ targets, retrieve, sync = boundaries
+ targets.side_effect = [[target(1)], [target(2)], []]
+ retrieve.side_effect = [
+ stripe.APIConnectionError("temporary failure"),
+ subscription(2),
+ ]
+ with pytest.raises(RuntimeError, match="retry the event"):
+ await billing.sync_trials_for_billing_event(
+ "customer.updated", {"object": {"id": "cus_1"}}
+ )
+ sync.assert_awaited_once_with(subscription(2))
+ assert targets.await_args_list == [
+ call(["cus_1"], ""),
+ call(["cus_1"], "trial_1"),
+ call(["cus_1"], "trial_2"),
+ ]
+
+
+async def test_database_failure_is_not_acknowledged(boundaries):
+ targets, retrieve, sync = boundaries
+ targets.side_effect = RuntimeError("database unavailable")
+ with pytest.raises(RuntimeError, match="database unavailable"):
+ await billing.sync_trials_for_billing_event(
+ "customer.updated", {"object": {"id": "cus_1"}}
+ )
+ retrieve.assert_not_awaited()
+ sync.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_card_test.py b/autogpt_platform/backend/backend/data/subscription_trial_card_test.py
new file mode 100644
index 0000000000..af5f03b762
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_card_test.py
@@ -0,0 +1,147 @@
+from unittest.mock import AsyncMock, patch
+
+import pytest
+import stripe
+from prisma.enums import SubscriptionTier
+
+from backend.data import subscription_trial_stripe as fulfillment
+
+pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+
+
+def customer_lookup(boundaries, subscription):
+ customer = {
+ "id": "cus_1",
+ "invoice_settings": {
+ "default_payment_method": subscription["default_payment_method"],
+ },
+ }
+ with patch.object(
+ stripe.Customer, "retrieve_async", AsyncMock(return_value=customer)
+ ) as lookup:
+ yield lookup
+
+
+async def test_trial_accepts_customer_invoice_default(
+ trial, subscription, boundaries, customer_lookup
+):
+ subscription["default_payment_method"] = None
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.TRIAL
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["cardVerifiedAt"] is not None
+ assert saved["consumedAt"] is not None
+ customer_lookup.assert_awaited_once_with(
+ "cus_1", expand=["invoice_settings.default_payment_method"]
+ )
+
+
+ "method,expected",
+ [
+ (
+ {
+ "id": "pm_valid",
+ "type": "card",
+ "card": {"exp_month": 12, "exp_year": 2034, "fingerprint": "fp_valid"},
+ },
+ SubscriptionTier.TRIAL,
+ ),
+ (
+ {
+ "id": "pm_expired",
+ "type": "card",
+ "card": {"exp_month": 1, "exp_year": 2020},
+ },
+ SubscriptionTier.NO_TIER,
+ ),
+ ({"id": "pm_bank", "type": "us_bank_account"}, SubscriptionTier.NO_TIER),
+ ],
+)
+async def test_subscription_method_takes_precedence_over_customer_default(
+ trial, subscription, boundaries, customer_lookup, method, expected
+):
+ subscription["default_payment_method"] = method
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == expected
+ customer_lookup.assert_not_awaited()
+
+
+async def test_legacy_subscription_source_does_not_use_customer_fallback(
+ trial, subscription, boundaries, customer_lookup
+):
+ subscription.update(default_payment_method=None, default_source="src_legacy")
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ customer_lookup.assert_not_awaited()
+
+
+ "method",
+ [
+ None,
+ {
+ "id": "pm_expired",
+ "type": "card",
+ "card": {"exp_month": 1, "exp_year": 2020},
+ },
+ {"id": "pm_bank", "type": "us_bank_account"},
+ {"id": "pm_no_card_details", "type": "card"},
+ ],
+)
+async def test_invalid_customer_default_does_not_grant_trial(
+ trial, subscription, boundaries, customer_lookup, method
+):
+ subscription["default_payment_method"] = None
+ customer_lookup.return_value["invoice_settings"]["default_payment_method"] = method
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["cardVerifiedAt"] is None
+
+
+async def test_customer_default_cannot_bypass_pending_setup(
+ trial, subscription, boundaries, customer_lookup
+):
+ subscription.update(default_payment_method=None, pending_setup_intent="seti_auth")
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+
+
+async def test_customer_lookup_failure_does_not_commit_entitlements(
+ trial, subscription, boundaries, customer_lookup
+):
+ subscription["default_payment_method"] = None
+ customer_lookup.side_effect = stripe.APIConnectionError("temporary failure")
+ with pytest.raises(stripe.APIConnectionError):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ boundaries.subscriptiontrial.update.assert_not_awaited()
+ boundaries.user.update_many.assert_not_awaited()
+
+
+async def test_customer_fallback_rejects_other_customer(
+ trial, subscription, boundaries, customer_lookup
+):
+ subscription["default_payment_method"] = None
+ customer_lookup.return_value["id"] = "cus_other"
+ with pytest.raises(ValueError, match="customer ownership"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ boundaries.subscriptiontrial.update.assert_not_awaited()
+
+
+async def test_deleted_customer_cannot_grant_trial(
+ trial, subscription, boundaries, customer_lookup
+):
+ subscription["default_payment_method"] = None
+ customer_lookup.return_value = {"id": "cus_1", "deleted": True}
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_checkout.py b/autogpt_platform/backend/backend/data/subscription_trial_checkout.py
new file mode 100644
index 0000000000..464f68baca
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_checkout.py
@@ -0,0 +1,229 @@
+"""Card-only Checkout using the durable, server-selected trial offer."""
+
+import stripe
+from prisma.enums import SubscriptionTier
+from prisma.models import SubscriptionTrial
+
+from backend.data.credit import (
+ get_stripe_customer_id,
+ get_subscription_price_id,
+ sync_tier_from_checkout_session,
+)
+from backend.data.stripe_client import stripe_call, stripe_list_items
+from backend.data.subscription_checkout import (
+ SubscriptionCheckoutUnavailable as TrialUnavailable,
+)
+from backend.data.subscription_checkout import (
+ expire_other_subscription_checkouts,
+ subscription_checkout_lock,
+)
+from backend.data.subscription_trial import (
+ TrialState,
+ get_subscription_trial,
+ reserve_subscription_trial,
+)
+from backend.data.subscription_trial_config import (
+ AcceptedTrialOffer,
+ TrialOffer,
+ get_trial_offer,
+)
+from backend.data.subscription_trial_eligibility import (
+ verify_trial_eligibility as _verify_eligibility,
+)
+
+
+async def confirm_trial_checkout(user_id: str) -> None:
+ trial = await get_subscription_trial(user_id)
+ if trial is None:
+ raise TrialUnavailable("There is no trial checkout for this account")
+ session = await _find_checkout(trial)
+ if session is None or session.status != "complete":
+ raise TrialUnavailable("Card setup is not complete yet")
+ if session.customer != trial.customer_id or session.mode != "subscription":
+ raise TrialUnavailable("Checkout does not match the trial enrollment")
+ await sync_tier_from_checkout_session(dict(session))
+
+
+async def create_trial_checkout(
+ user_id: str,
+ offer_token: str,
+ success_url: str,
+ cancel_url: str,
+ metadata: dict[str, str],
+) -> str:
+ async with subscription_checkout_lock(user_id):
+ return await _create_trial_checkout(
+ user_id, offer_token, success_url, cancel_url, metadata
+ )
+
+
+async def _create_trial_checkout(
+ user_id: str,
+ offer_token: str,
+ success_url: str,
+ cancel_url: str,
+ metadata: dict[str, str],
+) -> str:
+ offer = await get_trial_offer(user_id)
+ if offer is None:
+ raise TrialUnavailable("Trials are not available right now")
+ existing = await get_subscription_trial(user_id)
+ if existing:
+ if existing.consumed_at is not None or existing.status != "checkout_pending":
+ raise TrialUnavailable("A trial has already been used for this account")
+ if existing.offer.token != offer_token:
+ raise TrialUnavailable("Refresh to accept the reserved trial terms")
+ return await _resume_checkout(existing)
+ customer_id = await get_stripe_customer_id(user_id)
+ await _verify_eligibility(user_id, customer_id, offer)
+ accepted = await resolve_trial_price(offer)
+ if accepted.token != offer_token:
+ raise TrialUnavailable(
+ "The trial offer changed. Refresh to see the current terms"
+ )
+ trial = await reserve_subscription_trial(
+ user_id, accepted, customer_id, success_url, cancel_url, metadata
+ )
+ if trial.offer.token != offer_token:
+ raise TrialUnavailable(
+ "Another checkout reserved different trial terms. Refresh"
+ )
+ return await _resume_checkout(trial)
+
+
+async def resolve_trial_price(offer: TrialOffer) -> AcceptedTrialOffer:
+ price_id = await get_subscription_price_id(
+ SubscriptionTier(offer.tier), offer.billing_cycle
+ )
+ if not price_id:
+ raise TrialUnavailable("The trial's paid plan is not configured")
+ price = await stripe_call(stripe.Price.retrieve_async, price_id)
+ interval = "month" if offer.billing_cycle == "monthly" else "year"
+ if (
+ not price.active
+ or price.unit_amount is None
+ or price.unit_amount <= 0
+ or price.recurring is None
+ or price.recurring.interval != interval
+ or price.recurring.interval_count != 1
+ or price.recurring.usage_type != "licensed"
+ ):
+ raise TrialUnavailable(
+ "The trial's paid price must be an active recurring price"
+ )
+ return AcceptedTrialOffer(
+ **offer.model_dump(),
+ price_id=price.id,
+ unit_amount=price.unit_amount,
+ currency=price.currency,
+ )
+
+
+async def _resume_checkout(trial: TrialState) -> str:
+ session = await _find_checkout(trial)
+ if session is None or session.status == "open":
+ await expire_other_subscription_checkouts(
+ trial.customer_id, session.id if session else None
+ )
+ await _verify_eligibility(
+ trial.user_id, trial.customer_id, trial.offer, trial=trial, session=session
+ )
+ if session is None:
+ session = await stripe_call(
+ stripe.checkout.Session.create_async,
+ **trial_checkout_params(trial),
+ idempotency_key=f"trial-checkout-{trial.id}-{trial.checkout_attempt}",
+ )
+ await SubscriptionTrial.prisma().update_many(
+ where={"id": trial.id, "checkoutAttempt": trial.checkout_attempt},
+ data={"stripeCheckoutSessionId": session.id},
+ )
+ if session.status == "expired":
+ return await _replace_expired_checkout(trial, session)
+ if session.status != "open" or not session.url:
+ raise TrialUnavailable(
+ "Trial checkout is complete. Refresh your billing status"
+ )
+ return session.url
+
+
+async def _find_checkout(trial: TrialState) -> stripe.checkout.Session | None:
+ if trial.checkout_session_id:
+ return await stripe_call(
+ stripe.checkout.Session.retrieve_async, trial.checkout_session_id
+ )
+ sessions = await stripe_call(
+ stripe.checkout.Session.list_async, customer=trial.customer_id, limit=100
+ )
+ async for session in stripe_list_items(sessions):
+ metadata = session.metadata or {}
+ if metadata.get("trial_enrollment_id") == trial.id and metadata.get(
+ "trial_checkout_attempt"
+ ) == str(trial.checkout_attempt):
+ await SubscriptionTrial.prisma().update_many(
+ where={"id": trial.id, "checkoutAttempt": trial.checkout_attempt},
+ data={"stripeCheckoutSessionId": session.id},
+ )
+ return session
+ return None
+
+
+async def _replace_expired_checkout(
+ trial: TrialState, session: stripe.checkout.Session
+) -> str:
+ await _verify_eligibility(
+ trial.user_id, trial.customer_id, trial.offer, trial=trial, session=session
+ )
+ await SubscriptionTrial.prisma().update_many(
+ where={
+ "id": trial.id,
+ "checkoutAttempt": trial.checkout_attempt,
+ "status": "checkout_pending",
+ "consumedAt": None,
+ },
+ data={
+ "checkoutAttempt": {"increment": 1},
+ "stripeCheckoutSessionId": None,
+ "stripeSubscriptionId": None,
+ "startedAt": None,
+ "endsAt": None,
+ "cardVerifiedAt": None,
+ },
+ )
+ current = await get_subscription_trial(trial.user_id)
+ if current is None or current.consumed_at is not None:
+ raise TrialUnavailable("Trial checkout is no longer available")
+ if current.checkout_attempt == trial.checkout_attempt:
+ raise TrialUnavailable("Trial checkout changed. Refresh your billing status")
+ return await _resume_checkout(current)
+
+
+def trial_checkout_params(trial: TrialState) -> dict:
+ metadata = {
+ **trial.checkout_metadata,
+ "user_id": trial.user_id,
+ "tier": trial.offer.tier,
+ "billing_cycle": trial.offer.billing_cycle,
+ "trial_enrollment_id": trial.id,
+ "trial_offer_version": trial.offer.version,
+ "trial_checkout_attempt": str(trial.checkout_attempt),
+ }
+ return {
+ "customer": trial.customer_id,
+ "mode": "subscription",
+ "line_items": [{"price": trial.offer.price_id, "quantity": 1}],
+ "success_url": trial.success_url,
+ "cancel_url": trial.cancel_url,
+ "payment_method_types": ["card"],
+ "payment_method_collection": "always",
+ "subscription_data": {
+ "trial_period_days": trial.offer.duration_days,
+ "trial_settings": {"end_behavior": {"missing_payment_method": "cancel"}},
+ "metadata": metadata,
+ },
+ "allow_promotion_codes": False,
+ "automatic_tax": {"enabled": True},
+ "billing_address_collection": "auto",
+ "customer_update": {"address": "auto"},
+ "metadata": metadata,
+ }
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py b/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py
new file mode 100644
index 0000000000..652454dfc6
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py
@@ -0,0 +1,223 @@
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import SubscriptionTier
+
+from backend.data import subscription_trial_checkout as checkout
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+from backend.data.subscription_trial_stripe import (
+ SubscriptionSnapshot,
+ trial_subscription_tier,
+)
+
+
+def checkout_guard():
+ with patch.object(checkout, "subscription_checkout_lock", return_value=AsyncMock()):
+ yield
+
+
+def trial() -> TrialState:
+ return TrialState(
+ id="trial-1",
+ user_id="user-1",
+ offer=AcceptedTrialOffer(
+ version="offer-a",
+ new_users_from=datetime(2026, 9, 10, tzinfo=UTC),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_pro",
+ unit_amount=2000,
+ currency="usd",
+ ),
+ customer_id="cus_1",
+ checkout_session_id=None,
+ subscription_id=None,
+ checkout_attempt=0,
+ success_url="https://platform.agpt.co/settings/billing?trial=success",
+ cancel_url="https://platform.agpt.co/settings/billing",
+ checkout_metadata={"datafast_visitor_id": "visitor-1"},
+ status="checkout_pending",
+ card_verified_at=None,
+ started_at=None,
+ ends_at=None,
+ consumed_at=None,
+ converted_at=None,
+ cancel_at_period_end=False,
+ cost_microdollars=0,
+ )
+
+
+def test_card_required_and_cancel_if_card_disappears(trial):
+ params = checkout.trial_checkout_params(trial)
+ assert params["mode"] == "subscription"
+ assert params["payment_method_types"] == ["card"]
+ assert params["payment_method_collection"] == "always"
+ assert params["subscription_data"]["trial_period_days"] == 7
+ assert params["subscription_data"]["trial_settings"] == {
+ "end_behavior": {"missing_payment_method": "cancel"}
+ }
+ assert params["allow_promotion_codes"] is False
+
+
+def test_uses_accepted_price_and_preserves_attribution(trial):
+ params = checkout.trial_checkout_params(trial)
+ assert params["line_items"] == [{"price": "price_pro", "quantity": 1}]
+ assert params["metadata"]["datafast_visitor_id"] == "visitor-1"
+ assert params["subscription_data"]["metadata"] == params["metadata"]
+ assert params["metadata"]["trial_enrollment_id"] == trial.id
+ assert params["metadata"]["trial_offer_version"] == trial.offer.version
+
+
+def test_attribution_cannot_overwrite_server_owned_identity(trial):
+ trial.checkout_metadata.update(user_id="other-user", trial_enrollment_id="other")
+ params = checkout.trial_checkout_params(trial)
+ assert params["metadata"]["user_id"] == trial.user_id
+ assert params["metadata"]["trial_enrollment_id"] == trial.id
+
+
+ "change",
+ [
+ {"duration_days": 14},
+ {"price_id": "price_other"},
+ {"unit_amount": 3000},
+ {"total_cost_limit": 2_000_000},
+ ],
+)
+def test_terms_token_changes_even_if_operator_reuses_offer_version(trial, change):
+ changed = AcceptedTrialOffer.model_validate({**trial.offer.model_dump(), **change})
+ assert changed.token != trial.offer.token
+
+
+async def test_disabled_offer_does_not_create_stripe_customer_or_session(
+ trial, checkout_guard
+):
+ with (
+ patch.object(checkout, "get_trial_offer", AsyncMock(return_value=None)),
+ patch.object(checkout, "get_stripe_customer_id", AsyncMock()) as customer,
+ patch.object(checkout, "_resume_checkout", AsyncMock()) as resume,
+ ):
+ with pytest.raises(checkout.TrialUnavailable, match="not available"):
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ )
+ customer.assert_not_awaited()
+ resume.assert_not_awaited()
+
+
+async def test_previously_consumed_trial_is_never_reopened(trial, checkout_guard):
+ trial.consumed_at = datetime(2026, 9, 10, tzinfo=UTC)
+ trial.status = "canceled"
+ with (
+ patch.object(checkout, "get_trial_offer", AsyncMock(return_value=trial.offer)),
+ patch.object(checkout, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(checkout, "_resume_checkout", AsyncMock()) as resume,
+ ):
+ with pytest.raises(checkout.TrialUnavailable, match="already been used"):
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ )
+ resume.assert_not_awaited()
+
+
+async def test_pending_checkout_reuses_accepted_offer(trial, checkout_guard):
+ future_offer = trial.offer.model_copy(update={"duration_days": 14})
+ with (
+ patch.object(checkout, "get_trial_offer", AsyncMock(return_value=future_offer)),
+ patch.object(checkout, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(
+ checkout, "_resume_checkout", AsyncMock(return_value="checkout")
+ ) as resume,
+ ):
+ result = await checkout.create_trial_checkout(
+ trial.user_id, trial.offer.token, trial.success_url, trial.cancel_url, {}
+ )
+ assert result == "checkout"
+ resume.assert_awaited_once_with(trial)
+
+
+ "overrides,expected",
+ [
+ ({}, SubscriptionTier.TRIAL),
+ ({"cancel_at_period_end": True}, SubscriptionTier.TRIAL),
+ ({"default_payment_method": None}, SubscriptionTier.NO_TIER),
+ ({"pending_setup_intent": "seti_needs_auth"}, SubscriptionTier.NO_TIER),
+ ({"status": "past_due"}, SubscriptionTier.NO_TIER),
+ ({"status": "canceled"}, SubscriptionTier.NO_TIER),
+ ({"trial_end": 0}, SubscriptionTier.NO_TIER),
+ ({"status": "active"}, SubscriptionTier.NO_TIER),
+ ],
+)
+def test_entitlement_requires_completed_card_setup_and_unexpired_trial(
+ trial, overrides, expected
+):
+ now = datetime(2026, 9, 10, tzinfo=UTC)
+ subscription = SubscriptionSnapshot.model_validate(
+ {
+ "id": "sub_1",
+ "customer": "cus_1",
+ "status": "trialing",
+ "trial_end": int(now.timestamp()) + 86400,
+ "default_payment_method": {
+ "id": "pm_1",
+ "type": "card",
+ "card": {"exp_month": 12, "exp_year": 2030},
+ },
+ **overrides,
+ }
+ )
+ assert trial_subscription_tier(trial, subscription, now) == expected
+
+
+ "invoice_status,reason,created_delta,expected",
+ [
+ ("paid", "subscription_cycle", 0, SubscriptionTier.PRO),
+ ("open", "subscription_cycle", 0, SubscriptionTier.NO_TIER),
+ ("draft", "subscription_cycle", 0, SubscriptionTier.NO_TIER),
+ ("uncollectible", "subscription_cycle", 0, SubscriptionTier.NO_TIER),
+ ("paid", "subscription_create", 0, SubscriptionTier.NO_TIER),
+ ("paid", "subscription_cycle", -1, SubscriptionTier.NO_TIER),
+ ],
+)
+def test_paid_conversion_requires_paid_post_trial_invoice(
+ trial, invoice_status, reason, created_delta, expected
+):
+ now = datetime(2026, 9, 10, tzinfo=UTC)
+ end = int(now.timestamp())
+ subscription = SubscriptionSnapshot.model_validate(
+ {
+ "id": "sub_1",
+ "customer": "cus_1",
+ "status": "active",
+ "trial_end": end,
+ "latest_invoice": {
+ "id": "in_1",
+ "status": invoice_status,
+ "billing_reason": reason,
+ "created": end + created_delta,
+ },
+ }
+ )
+ assert trial_subscription_tier(trial, subscription, now) == expected
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_claims.py b/autogpt_platform/backend/backend/data/subscription_trial_claims.py
new file mode 100644
index 0000000000..4c82aec268
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_claims.py
@@ -0,0 +1,64 @@
+"""Durable introductory-offer claims, independent of account deletion."""
+
+import json
+from hashlib import sha256
+
+from prisma import Prisma
+from pydantic import BaseModel
+
+from backend.data.db import query_raw_with_schema
+from backend.data.subscription_trial import TrialState
+
+
+class LinkedIdentity(BaseModel):
+ provider: str
+ subject: str
+
+
+def trial_identity_key(kind: str, value: str) -> str:
+ payload = json.dumps([kind, value], separators=(",", ":"))
+ return sha256(payload.encode()).hexdigest()
+
+
+async def claim_trial_identities(
+ trial: TrialState, fingerprint: str | None, tx: Prisma
+) -> bool:
+ if not fingerprint:
+ return False
+ identities = await query_raw_with_schema(
+ 'SELECT "providerId" AS provider, "accountId" AS subject '
+ 'FROM {schema_prefix}"UserAuthAccount" '
+ 'WHERE "userId" = $1 AND "providerId" <> \'credential\'',
+ trial.user_id,
+ model=LinkedIdentity,
+ client=tx,
+ )
+ keys = sorted(
+ {
+ trial_identity_key("card", fingerprint),
+ trial_identity_key("user", trial.user_id),
+ trial_identity_key("customer", trial.customer_id),
+ *(
+ trial_identity_key(f"provider:{identity.provider}", identity.subject)
+ for identity in identities
+ ),
+ }
+ )
+ return await _claim_keys(trial.id, keys, tx)
+
+
+async def _claim_keys(trial_id: str, keys: list[str], tx: Prisma) -> bool:
+ for key in keys:
+ await query_raw_with_schema(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))::text",
+ f"intro-offer:{key}",
+ client=tx,
+ )
+ existing = await tx.subscriptiontrialclaim.find_many(where={"key": {"in": keys}})
+ if any(claim.trialId != trial_id for claim in existing):
+ return False
+ await tx.subscriptiontrialclaim.create_many(
+ data=[{"key": key, "trialId": trial_id} for key in keys],
+ skip_duplicates=True,
+ )
+ return True
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_claims_integration_test.py b/autogpt_platform/backend/backend/data/subscription_trial_claims_integration_test.py
new file mode 100644
index 0000000000..46a7ae2581
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_claims_integration_test.py
@@ -0,0 +1,114 @@
+import asyncio
+from uuid import uuid4
+
+import pytest
+from prisma.models import AuthAccount, AuthUser, SubscriptionTrialClaim, User
+
+from backend.data import subscription_trial_integration_fixtures as fixtures
+from backend.data.db import transaction
+from backend.data.subscription_trial_claims import (
+ claim_trial_identities,
+ trial_identity_key,
+)
+
+enrollment = fixtures.enrollment
+pytestmark = fixtures.pytestmark
+
+
+async def claim(trial, fingerprint):
+ async with transaction() as tx:
+ return await claim_trial_identities(trial, fingerprint, tx)
+
+
+async def test_concurrent_accounts_cannot_share_one_intro_card(enrollment):
+ fingerprint = f"fp_{uuid4()}"
+ trials = [
+ enrollment.model_copy(
+ update={
+ "id": f"{enrollment.id}-{index}",
+ "user_id": str(uuid4()),
+ "customer_id": f"cus_{uuid4()}",
+ }
+ )
+ for index in range(10)
+ ]
+ results = await asyncio.gather(*(claim(trial, fingerprint) for trial in trials))
+ assert sum(results) == 1
+ winner = trials[results.index(True)]
+ rows = await SubscriptionTrialClaim.prisma().find_many(
+ where={"trialId": {"startsWith": enrollment.id}}
+ )
+ assert len(rows) == 3
+ assert {row.trialId for row in rows} == {winner.id}
+ assert await claim(winner, fingerprint)
+
+
+async def test_claim_survives_account_deletion_and_card_changes(enrollment):
+ fingerprint = f"fp_{uuid4()}"
+ assert await claim(enrollment, fingerprint)
+ assert await claim(enrollment, f"fp_{uuid4()}")
+ await User.prisma().delete(where={"id": enrollment.user_id})
+ recreated = enrollment.model_copy(
+ update={
+ "id": f"{enrollment.id}-recreated",
+ "user_id": str(uuid4()),
+ "customer_id": f"cus_{uuid4()}",
+ }
+ )
+ assert not await claim(recreated, fingerprint)
+ assert await claim(recreated, f"fp_{uuid4()}")
+
+
+async def test_recreated_linked_login_cannot_claim_with_a_different_card(enrollment):
+ subject = str(uuid4())
+ other_user = str(uuid4())
+ try:
+ for user_id in (enrollment.user_id, other_user):
+ await AuthUser.prisma().create(
+ data={
+ "id": user_id,
+ "name": "Trial test",
+ "email": f"{user_id}@example.com",
+ }
+ )
+ await AuthAccount.prisma().create(
+ data={
+ "id": str(uuid4()),
+ "userId": user_id,
+ "providerId": "google",
+ "accountId": subject,
+ }
+ )
+ assert await claim(enrollment, f"fp_{uuid4()}")
+ await AuthUser.prisma().delete(where={"id": enrollment.user_id})
+ recreated = enrollment.model_copy(
+ update={
+ "id": f"{enrollment.id}-recreated",
+ "user_id": other_user,
+ "customer_id": f"cus_{uuid4()}",
+ }
+ )
+ assert not await claim(recreated, f"fp_{uuid4()}")
+ finally:
+ await AuthUser.prisma().delete_many(
+ where={"id": {"in": [enrollment.user_id, other_user]}}
+ )
+
+
+async def test_missing_fingerprint_fails_closed_without_claiming(enrollment):
+ assert not await claim(enrollment, None)
+ assert not await claim(enrollment, "")
+ assert (
+ await SubscriptionTrialClaim.prisma().count(where={"trialId": enrollment.id})
+ == 0
+ )
+
+
+def test_claim_keys_are_domain_separated_and_do_not_store_raw_identifiers():
+ key = trial_identity_key("card", "fp_example")
+ assert len(key) == 64 and "fp_example" not in key
+ assert key != trial_identity_key("customer", "fp_example")
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_config.py b/autogpt_platform/backend/backend/data/subscription_trial_config.py
new file mode 100644
index 0000000000..51ba9363df
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_config.py
@@ -0,0 +1,96 @@
+"""Validated, versioned terms for a card-required subscription trial."""
+
+import logging
+from datetime import UTC, datetime
+from hashlib import sha256
+from typing import Literal
+
+from pydantic import (
+ AwareDatetime,
+ BaseModel,
+ ConfigDict,
+ Field,
+ ValidationError,
+ model_validator,
+)
+
+from backend.util.feature_flag import Flag, get_feature_flag_value, is_feature_enabled
+
+logger = logging.getLogger(__name__)
+
+
+class TrialOffer(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ version: str = Field(min_length=1, max_length=100, pattern=r"^[a-zA-Z0-9_.-]+$")
+ new_users_from: AwareDatetime
+ duration_days: int = Field(ge=1, le=730, strict=True)
+ tier: Literal["BASIC", "PRO", "MAX", "BUSINESS"]
+ billing_cycle: Literal["monthly", "yearly"]
+ daily_cost_limit: int = Field(gt=0, strict=True)
+ weekly_cost_limit: int = Field(gt=0, strict=True)
+ total_cost_limit: int = Field(gt=0, strict=True)
+ onboarding_credit_amount: int = Field(ge=0, le=2_147_483_647, strict=True)
+ allow_existing_beta_users: bool = Field(default=False, strict=True)
+
+ @model_validator(mode="after")
+ def ordered_limits(self) -> "TrialOffer":
+ if not self.daily_cost_limit <= self.weekly_cost_limit <= self.total_cost_limit:
+ raise ValueError("Trial limits must satisfy daily <= weekly <= total")
+ return self
+
+ def is_eligible(
+ self,
+ *,
+ created_at: datetime,
+ current_tier: str,
+ has_subscription_history: bool,
+ ) -> bool:
+ if current_tier != "NO_TIER" or has_subscription_history:
+ return False
+ return created_at >= self.new_users_from or self.allow_existing_beta_users
+
+
+class AcceptedTrialOffer(TrialOffer):
+ price_id: str = Field(pattern=r"^price_", min_length=7)
+ unit_amount: int = Field(gt=0, strict=True)
+ currency: str = Field(pattern=r"^[a-z]{3}$")
+
+ @property
+ def token(self) -> str:
+ return sha256(self.model_dump_json().encode()).hexdigest()
+
+
+async def get_trial_offer(user_id: str) -> TrialOffer | None:
+ try:
+ if not await is_feature_enabled(
+ Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False
+ ):
+ return None
+ raw = await get_feature_flag_value(
+ Flag.CARD_REQUIRED_TRIAL_OFFER, user_id, None
+ )
+ if raw is None:
+ return None
+ return TrialOffer.model_validate(raw)
+ except (ValidationError, ValueError, TypeError):
+ logger.error("Invalid card-required-trial-offer; refusing trial enrollment")
+ return None
+ except Exception:
+ logger.exception("Trial offer unavailable; refusing trial enrollment")
+ return None
+
+
+def trial_is_active(
+ *,
+ status: str,
+ trial_end: datetime | None,
+ card_verified: bool,
+ now: datetime | None = None,
+) -> bool:
+ return bool(
+ status == "trialing"
+ and card_verified
+ and trial_end is not None
+ and trial_end > (now or datetime.now(UTC))
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_config_test.py b/autogpt_platform/backend/backend/data/subscription_trial_config_test.py
new file mode 100644
index 0000000000..61618b7b81
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_config_test.py
@@ -0,0 +1,161 @@
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from pydantic import ValidationError
+
+from backend.data import subscription_trial_config as trials
+
+
+def offer_data() -> dict:
+ return {
+ "version": "trial-experiment-a-v1",
+ "new_users_from": "2026-09-10T00:00:00Z",
+ "duration_days": 7,
+ "tier": "PRO",
+ "billing_cycle": "monthly",
+ "daily_cost_limit": 250_000,
+ "weekly_cost_limit": 1_000_000,
+ "total_cost_limit": 1_000_000,
+ "onboarding_credit_amount": 300,
+ }
+
+
+def test_offer_has_no_implicit_existing_user_eligibility():
+ offer = trials.TrialOffer.model_validate(offer_data())
+ assert offer.allow_existing_beta_users is False
+
+
+ "overrides",
+ [
+ {"duration_days": 0},
+ {"duration_days": 731},
+ {"duration_days": True},
+ {"daily_cost_limit": -1},
+ {"weekly_cost_limit": 0},
+ {"total_cost_limit": "1000000"},
+ {"total_cost_limit": True},
+ {"daily_cost_limit": 2_000_000},
+ {"weekly_cost_limit": 2_000_000},
+ {"new_users_from": "2026-09-10T00:00:00"},
+ {"tier": "TRIAL"},
+ {"tier": "ENTERPRISE"},
+ {"billing_cycle": "weekly"},
+ {"allow_existing_beta_users": "true"},
+ {"version": ""},
+ {"unknown_setting": 1},
+ ],
+)
+def test_rejects_invalid_or_ambiguous_offer(overrides):
+ with pytest.raises(ValidationError):
+ trials.TrialOffer.model_validate({**offer_data(), **overrides})
+
+
+ "days_from_cutoff,beta_allowed,has_history,tier,expected",
+ [
+ (0, False, False, "NO_TIER", True),
+ (1, False, False, "NO_TIER", True),
+ (-1, False, False, "NO_TIER", False),
+ (-1, True, False, "NO_TIER", True),
+ (-1, True, True, "NO_TIER", False),
+ (1, False, True, "NO_TIER", False),
+ (1, True, False, "PRO", False),
+ (1, True, False, "TRIAL", False),
+ (1, True, False, "ENTERPRISE", False),
+ ],
+)
+def test_eligibility_never_retrials_or_overwrites_paid_access(
+ days_from_cutoff, beta_allowed, has_history, tier, expected
+):
+ offer = trials.TrialOffer.model_validate(
+ {**offer_data(), "allow_existing_beta_users": beta_allowed}
+ )
+ assert (
+ offer.is_eligible(
+ created_at=datetime(2026, 9, 10, tzinfo=UTC)
+ + timedelta(days=days_from_cutoff),
+ current_tier=tier,
+ has_subscription_history=has_history,
+ )
+ is expected
+ )
+
+
+def test_accepted_terms_survive_future_offer_changes():
+ original = offer_data()
+ accepted = trials.TrialOffer.model_validate(original)
+ original.update(duration_days=14, total_cost_limit=9_000_000)
+ assert accepted.duration_days == 7
+ assert accepted.total_cost_limit == 1_000_000
+ with pytest.raises(ValidationError):
+ accepted.duration_days = 14
+
+
+ "seconds_remaining,expected", [(1, True), (0, False), (-1, False)]
+)
+def test_trial_expires_at_exact_deadline(seconds_remaining, expected):
+ now = datetime(2026, 9, 10, tzinfo=UTC)
+ assert (
+ trials.trial_is_active(
+ status="trialing",
+ trial_end=now + timedelta(seconds=seconds_remaining),
+ card_verified=True,
+ now=now,
+ )
+ is expected
+ )
+
+
[email protected]("status", ["trialing", "active", "past_due", "canceled"])
+def test_no_trial_entitlement_without_verified_card(status):
+ now = datetime(2026, 9, 10, tzinfo=UTC)
+ assert not trials.trial_is_active(
+ status=status,
+ trial_end=now + timedelta(days=7),
+ card_verified=False,
+ now=now,
+ )
+
+
+async def test_platform_payment_disabled_hides_trial_offer():
+ with patch.object(
+ trials, "is_feature_enabled", AsyncMock(return_value=False)
+ ), patch.object(
+ trials,
+ "get_feature_flag_value",
+ AsyncMock(
+ side_effect=lambda flag, *args, **kwargs: (
+ offer_data() if flag == trials.Flag.CARD_REQUIRED_TRIAL_OFFER else False
+ )
+ ),
+ ):
+ assert await trials.get_trial_offer("user-1") is None
+
+
+async def test_invalid_remote_offer_fails_closed():
+ with patch.object(
+ trials, "is_feature_enabled", AsyncMock(return_value=True)
+ ), patch.object(
+ trials, "get_feature_flag_value", AsyncMock(return_value={"duration_days": "7"})
+ ):
+ assert await trials.get_trial_offer("user-1") is None
+
+
+async def test_payment_enabled_and_valid_offer_is_available():
+ with patch.object(
+ trials, "is_feature_enabled", AsyncMock(return_value=True)
+ ) as enabled, patch.object(
+ trials, "get_feature_flag_value", AsyncMock(return_value=offer_data())
+ ):
+ assert await trials.get_trial_offer(
+ "user-1"
+ ) == trials.TrialOffer.model_validate(offer_data())
+ enabled.assert_awaited_once_with(
+ trials.Flag.ENABLE_PLATFORM_PAYMENT, "user-1", default=False
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_cost_integration_test.py b/autogpt_platform/backend/backend/data/subscription_trial_cost_integration_test.py
new file mode 100644
index 0000000000..4ccae71992
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_cost_integration_test.py
@@ -0,0 +1,105 @@
+"""Late trial costs remain user-scoped after access changes."""
+
+import asyncio
+from datetime import UTC, datetime
+from uuid import uuid4
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from prisma.models import SubscriptionTrial
+
+from backend.data import subscription_trial_integration_fixtures as fixtures
+from backend.data.db_manager import DatabaseManager
+from backend.data.subscription_trial import (
+ get_subscription_trial,
+ record_subscription_trial_cost,
+)
+
+enrollment = fixtures.enrollment
+pytestmark = fixtures.pytestmark
+
+
[email protected]("status", ["active", "canceled", "past_due", "trialing"])
+async def test_attributed_cost_survives_status_and_card_changes(enrollment, status):
+ await SubscriptionTrial.prisma().update(
+ where={"id": enrollment.id},
+ data={"status": status, "consumedAt": datetime.now(UTC)},
+ )
+ await asyncio.gather(
+ *[
+ record_subscription_trial_cost(
+ enrollment.user_id, 100, trial_id=enrollment.id
+ )
+ for _ in range(12)
+ ]
+ )
+ trial = await get_subscription_trial(enrollment.user_id)
+ assert trial is not None and trial.cost_microdollars == 1200
+
+
[email protected]("wrong_field", ["user", "trial", "unconsumed"])
+async def test_invalid_cost_attribution_is_rejected(enrollment, wrong_field):
+ if wrong_field != "unconsumed":
+ await SubscriptionTrial.prisma().update(
+ where={"id": enrollment.id}, data={"consumedAt": datetime.now(UTC)}
+ )
+ with pytest.raises(ValueError, match="Trial cost attribution"):
+ await record_subscription_trial_cost(
+ str(uuid4()) if wrong_field == "user" else enrollment.user_id,
+ 100,
+ trial_id=str(uuid4()) if wrong_field == "trial" else enrollment.id,
+ )
+ trial = await get_subscription_trial(enrollment.user_id)
+ assert trial is not None and trial.cost_microdollars == 0
+
+
+async def test_attribution_crosses_actual_database_rpc_models(enrollment):
+ manager = DatabaseManager()
+ app = FastAPI()
+ manager._register_exception_handlers(app)
+ app.add_api_route(
+ "/record_subscription_trial_cost",
+ manager._create_fastapi_endpoint(record_subscription_trial_cost),
+ methods=["POST"],
+ )
+ await SubscriptionTrial.prisma().update(
+ where={"id": enrollment.id},
+ data={"status": "active", "consumedAt": datetime.now(UTC)},
+ )
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://trial-rpc"
+ ) as client:
+ request = {
+ "user_id": enrollment.user_id,
+ "trial_id": enrollment.id,
+ "cost_microdollars": 200,
+ }
+ response = await client.post("/record_subscription_trial_cost", json=request)
+ assert response.status_code == 200 and response.json() is None
+ response = await client.post(
+ "/record_subscription_trial_cost", json={**request, "user_id": str(uuid4())}
+ )
+ assert response.status_code == 400
+ response = await client.post(
+ "/record_subscription_trial_cost", json={**request, "trial_id": 123}
+ )
+ assert response.status_code == 422
+ trial = await get_subscription_trial(enrollment.user_id)
+ assert trial is not None and trial.cost_microdollars == 200
+
+
+async def test_unscoped_calls_do_not_charge_a_previous_trial(enrollment):
+ await SubscriptionTrial.prisma().update(
+ where={"id": enrollment.id},
+ data={"status": "active", "consumedAt": datetime.now(UTC)},
+ )
+ await record_subscription_trial_cost(enrollment.user_id, 100)
+ await record_subscription_trial_cost(enrollment.user_id, 0, trial_id=enrollment.id)
+ await record_subscription_trial_cost(enrollment.user_id, -1, trial_id=enrollment.id)
+ trial = await get_subscription_trial(enrollment.user_id)
+ assert trial is not None and trial.cost_microdollars == 0
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_eligibility.py b/autogpt_platform/backend/backend/data/subscription_trial_eligibility.py
new file mode 100644
index 0000000000..aab402c56c
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_eligibility.py
@@ -0,0 +1,83 @@
+import stripe
+
+from backend.data.stripe_client import stripe_call, stripe_list_items
+from backend.data.subscription_checkout import SubscriptionCheckoutUnavailable
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import TrialOffer
+from backend.data.user import get_user_by_id
+
+
+async def verify_trial_eligibility(
+ user_id: str,
+ customer_id: str,
+ offer: TrialOffer,
+ *,
+ trial: TrialState | None = None,
+ session: stripe.checkout.Session | None = None,
+) -> None:
+ user = await get_user_by_id(user_id)
+ if trial and session and not _owned_checkout(trial, session):
+ raise SubscriptionCheckoutUnavailable("Checkout does not match this trial")
+ result = await stripe_call(
+ stripe.Subscription.list_async, customer=customer_id, status="all", limit=100
+ )
+ subscriptions = [sub async for sub in stripe_list_items(result)]
+ allowed = await _unfinished_subscriptions(trial, session) if subscriptions else {}
+ has_history = any(
+ sub.status not in allowed.get(sub.id, ()) for sub in subscriptions
+ )
+ if not offer.is_eligible(
+ created_at=user.created_at,
+ current_tier=user.subscription_tier.value,
+ has_subscription_history=has_history,
+ ):
+ raise SubscriptionCheckoutUnavailable(
+ "This account is not eligible for a trial"
+ )
+
+
+async def _unfinished_subscriptions(
+ trial: TrialState | None, current: stripe.checkout.Session | None
+) -> dict[str, tuple[str, ...]]:
+ if trial is None or trial.consumed_at is not None:
+ return {}
+ allowed: dict[str, tuple[str, ...]] = {}
+ if current and current.status == "open" and _owned_checkout(trial, current):
+ sub_id = current.subscription or trial.subscription_id
+ if sub_id:
+ allowed[str(sub_id)] = ("trialing", "incomplete")
+ sessions = await stripe_call(
+ stripe.checkout.Session.list_async, customer=trial.customer_id, limit=100
+ )
+ async for session in stripe_list_items(sessions):
+ if session.status != "expired" or not _owned_checkout(
+ trial, session, previous=True
+ ):
+ continue
+ if session.subscription:
+ allowed[str(session.subscription)] = ("canceled", "incomplete_expired")
+ return allowed
+
+
+def _owned_checkout(
+ trial: TrialState, session: stripe.checkout.Session, *, previous: bool = False
+) -> bool:
+ metadata = session.metadata or {}
+ attempt = metadata.get("trial_checkout_attempt", "")
+ try:
+ attempt_number = int(attempt)
+ except ValueError:
+ return False
+ return bool(
+ session.customer == trial.customer_id
+ and session.mode == "subscription"
+ and metadata.get("user_id") == trial.user_id
+ and metadata.get("trial_enrollment_id") == trial.id
+ and metadata.get("trial_offer_version") == trial.offer.version
+ and str(attempt_number) == attempt
+ and (
+ 0 <= attempt_number <= trial.checkout_attempt
+ if previous
+ else attempt_number == trial.checkout_attempt
+ )
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py b/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py
new file mode 100644
index 0000000000..5356815755
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py
@@ -0,0 +1,144 @@
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import stripe
+from prisma import Prisma
+
+from backend.data import subscription_trial_stripe as fulfillment
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+
+
+def trial():
+ now = datetime.now(UTC)
+ return TrialState(
+ id="trial-1",
+ user_id="user-1",
+ customer_id="cus_1",
+ offer=AcceptedTrialOffer(
+ version="fulfillment-v1",
+ new_users_from=now - timedelta(days=1),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_pro",
+ unit_amount=5000,
+ currency="usd",
+ ),
+ checkout_session_id="cs_1",
+ subscription_id=None,
+ checkout_attempt=0,
+ success_url="https://example.com/ok",
+ cancel_url="https://example.com/no",
+ checkout_metadata={},
+ status="checkout_pending",
+ card_verified_at=None,
+ started_at=None,
+ ends_at=None,
+ consumed_at=None,
+ converted_at=None,
+ cancel_at_period_end=False,
+ cost_microdollars=0,
+ )
+
+
+def subscription(trial):
+ now = datetime.now(UTC)
+ return {
+ "id": "sub_1",
+ "customer": trial.customer_id,
+ "status": "trialing",
+ "metadata": {
+ "user_id": trial.user_id,
+ "trial_enrollment_id": trial.id,
+ "trial_offer_version": trial.offer.version,
+ "trial_checkout_attempt": "0",
+ },
+ "trial_start": int(now.timestamp()),
+ "trial_end": int((now + timedelta(days=7)).timestamp()),
+ "default_payment_method": {
+ "id": "pm_1",
+ "type": "card",
+ "card": {"exp_month": 12, "exp_year": 2030, "fingerprint": "fp_test"},
+ },
+ "pending_setup_intent": None,
+ "items": {
+ "data": [{"price": {"id": trial.offer.price_id}, "quantity": 1}],
+ "has_more": False,
+ },
+ }
+
+
+def session(trial):
+ return {
+ "id": "cs_1",
+ "status": "complete",
+ "mode": "subscription",
+ "customer": trial.customer_id,
+ "subscription": "sub_1",
+ "payment_method_types": ["card"],
+ "payment_method_collection": "always",
+ "metadata": {
+ "user_id": trial.user_id,
+ "trial_enrollment_id": trial.id,
+ "trial_offer_version": trial.offer.version,
+ "trial_checkout_attempt": "0",
+ },
+ }
+
+
+def boundaries(subscription, session):
+ tx = MagicMock(spec=Prisma)
+ tx.subscriptiontrial = MagicMock(update=AsyncMock())
+ tx.user = MagicMock(update_many=AsyncMock())
+ with (
+ patch.object(
+ fulfillment, "claim_trial_identities", AsyncMock(return_value=True)
+ ),
+ patch.object(
+ stripe.Customer,
+ "retrieve_async",
+ AsyncMock(
+ return_value={
+ "id": "cus_1",
+ "invoice_settings": {"default_payment_method": None},
+ }
+ ),
+ ),
+ patch.object(
+ stripe.Subscription, "retrieve_async", AsyncMock(return_value=subscription)
+ ),
+ patch.object(
+ stripe.Subscription,
+ "list_async",
+ AsyncMock(return_value=MagicMock(data=[], has_more=False)),
+ ),
+ patch.object(
+ stripe.checkout.Session,
+ "retrieve_async",
+ AsyncMock(
+ side_effect=lambda *args, **kwargs: stripe.checkout.Session.construct_from(
+ session, "test-key"
+ )
+ ),
+ ),
+ patch.object(
+ stripe.checkout.Session,
+ "list_async",
+ AsyncMock(
+ return_value=stripe.ListObject.construct_from(
+ {"data": [], "has_more": False}, "test-key"
+ )
+ ),
+ ),
+ ):
+ yield tx
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.py b/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.py
new file mode 100644
index 0000000000..501009964a
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.py
@@ -0,0 +1,226 @@
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from prisma.enums import SubscriptionTier
+
+from backend.data import subscription_trial_stripe as fulfillment
+
+pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+
+
+async def test_open_checkout_never_grants_or_consumes_trial(trial, session, boundaries):
+ session["status"] = "open"
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["consumedAt"] is None
+ assert saved["cardVerifiedAt"] is None
+ assert saved["status"] == "checkout_pending"
+
+
+async def test_completed_checkout_consumes_trial_even_if_card_removed(
+ trial, subscription, boundaries
+):
+ subscription["default_payment_method"] = None
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["consumedAt"] is not None
+ assert saved["cardVerifiedAt"] is None
+
+
+ "changed",
+ [
+ {"customer": "cus_other"},
+ {"subscription": "sub_other"},
+ {"metadata": {"user_id": "other", "trial_enrollment_id": "trial-1"}},
+ {"payment_method_collection": "if_required"},
+ {"payment_method_types": ["card", "us_bank_account"]},
+ ],
+)
+async def test_checkout_proof_rejects_mismatched_identity_or_collection(
+ trial, session, boundaries, changed
+):
+ session.update(changed)
+ with pytest.raises(ValueError, match="Checkout"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ boundaries.user.update_many.assert_not_awaited()
+
+
+async def test_conversion_invoice_identity_is_immutable(trial, boundaries):
+ now = datetime.now(UTC)
+ invoice = fulfillment.Invoice(
+ id="in_first",
+ status="paid",
+ created=int(now.timestamp()),
+ billing_reason="subscription_cycle",
+ )
+ snapshot = fulfillment.SubscriptionSnapshot(
+ id="sub_1",
+ customer="cus_1",
+ status="active",
+ latest_invoice=invoice,
+ )
+ await fulfillment._save_snapshot(
+ trial, snapshot, SubscriptionTier.PRO, now, boundaries, True
+ )
+ first = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert first["stripeConversionInvoiceId"] == "in_first"
+ converted = trial.model_copy(
+ update={"converted_at": now, "conversion_invoice_id": "in_first"}
+ )
+ invoice.id = "in_renewal"
+ await fulfillment._save_snapshot(
+ converted, snapshot, SubscriptionTier.PRO, now, boundaries, True
+ )
+ later = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert later["stripeConversionInvoiceId"] == "in_first"
+
+
+async def test_completed_card_checkout_grants_trial(trial, boundaries):
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.TRIAL
+
+
+async def test_replayed_cancellation_does_not_advance_notice_revision(
+ trial, boundaries
+):
+ now = datetime.now(UTC)
+ snapshot = fulfillment.SubscriptionSnapshot(
+ id="sub_1", customer="cus_1", status="trialing", cancel_at_period_end=True
+ )
+ await fulfillment._save_snapshot(
+ trial, snapshot, SubscriptionTier.TRIAL, now, boundaries, True
+ )
+ assert (
+ boundaries.subscriptiontrial.update.await_args.kwargs["data"][
+ "notificationRevision"
+ ]
+ == 1
+ )
+ canceled = trial.model_copy(
+ update={"cancel_at_period_end": True, "notification_revision": 1}
+ )
+ await fulfillment._save_snapshot(
+ canceled, snapshot, SubscriptionTier.TRIAL, now, boundaries, True
+ )
+ assert (
+ boundaries.subscriptiontrial.update.await_args.kwargs["data"][
+ "notificationRevision"
+ ]
+ == 1
+ )
+
+
+ "items",
+ [
+ None,
+ {"data": [], "has_more": False},
+ {"data": [{"price": {"id": "price_other"}, "quantity": 1}], "has_more": False},
+ {"data": [{"price": {"id": "price_pro"}, "quantity": 2}], "has_more": False},
+ {"data": [{"price": {"id": "price_pro"}, "quantity": 1}], "has_more": True},
+ ],
+)
+async def test_first_conversion_rejects_unaccepted_price_or_quantity(
+ trial, subscription, boundaries, items
+):
+ end = int(datetime.now(UTC).timestamp()) - 60
+ subscription.update(
+ status="active",
+ trial_end=end,
+ items=items,
+ latest_invoice={
+ "id": "in_1",
+ "status": "paid",
+ "created": end,
+ "billing_reason": "subscription_cycle",
+ },
+ )
+ with pytest.raises(ValueError, match="accepted"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ boundaries.user.update_many.assert_not_awaited()
+
+
+async def test_old_attempt_is_acknowledged_without_rewriting_current_state(
+ trial, boundaries
+):
+ trial.checkout_attempt = 1
+ trial.subscription_id = "sub_current"
+ boundaries.user.find_unique_or_raise = AsyncMock(
+ return_value=MagicMock(subscriptionTier=SubscriptionTier.PRO)
+ )
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.PRO
+ boundaries.user.update_many.assert_not_awaited()
+ boundaries.subscriptiontrial.update.assert_not_awaited()
+
+
+async def test_reused_identity_cancels_trial_before_granting_access(
+ trial, subscription, boundaries
+):
+ canceled = {**subscription, "status": "canceled"}
+ with (
+ patch.object(
+ fulfillment,
+ "claim_trial_identities",
+ AsyncMock(return_value=False),
+ create=True,
+ ),
+ patch.object(
+ fulfillment.stripe.Subscription,
+ "cancel_async",
+ AsyncMock(return_value=canceled),
+ ) as cancel,
+ ):
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ cancel.assert_awaited_once()
+ assert cancel.await_args.kwargs["invoice_now"] is False
+ assert cancel.await_args.kwargs["prorate"] is False
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["status"] == "canceled"
+ assert saved["consumedAt"] is not None
+
+
[email protected]("changed_items", [False, True])
+async def test_scheduled_portal_cancellation_ends_trial_immediately(
+ trial, subscription, boundaries, changed_items
+):
+ subscription["cancel_at_period_end"] = True
+ if changed_items:
+ subscription["items"] = None
+ canceled = {**subscription, "status": "canceled", "cancel_at_period_end": False}
+ with patch.object(
+ fulfillment.stripe.Subscription,
+ "cancel_async",
+ AsyncMock(return_value=canceled),
+ ) as cancel:
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ cancel.assert_awaited_once()
+
+
+async def test_canceled_subscription_revokes_access_even_if_items_changed(
+ trial, subscription, boundaries
+):
+ subscription.update(status="canceled", items=None)
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert result is not None and result[1] == SubscriptionTier.NO_TIER
+ assert (
+ boundaries.subscriptiontrial.update.await_args.kwargs["data"]["cardVerifiedAt"]
+ is None
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_integration_fixtures.py b/autogpt_platform/backend/backend/data/subscription_trial_integration_fixtures.py
new file mode 100644
index 0000000000..2ea4ba36bc
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_integration_fixtures.py
@@ -0,0 +1,67 @@
+import os
+from datetime import UTC, datetime
+from urllib.parse import urlparse
+from uuid import uuid4
+
+import pytest
+import pytest_asyncio
+from prisma.models import SubscriptionTrialClaim, User
+
+from backend.data import db
+from backend.data.subscription_trial import reserve_subscription_trial
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+
+pytestmark = pytest.mark.skipif(
+ os.environ.get("TRIAL_TEST_DATABASE") != "1",
+ reason="Requires disposable trial database",
+)
+
+
+@pytest_asyncio.fixture
+async def enrollment():
+ target = urlparse(db.DATABASE_URL)
+ local = (target.hostname, target.port, target.path) == (
+ "127.0.0.1",
+ 15432,
+ "/trial_test",
+ )
+ ci = os.environ.get("GITHUB_ACTIONS") == "true" and (
+ target.hostname,
+ target.port,
+ target.path,
+ ) == ("localhost", 5432, "/postgres")
+ assert (
+ local or ci
+ ), "Trial integration tests require an approved disposable database"
+ owns_connection = not db.is_connected()
+ await db.connect()
+ user_id = str(uuid4())
+ await User.prisma().create(data={"id": user_id, "email": f"{user_id}@example.com"})
+ trial = await reserve_subscription_trial(
+ user_id,
+ AcceptedTrialOffer(
+ version="trial-test-v1",
+ new_users_from=datetime.now(UTC),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=100,
+ weekly_cost_limit=100,
+ total_cost_limit=100,
+ onboarding_credit_amount=300,
+ price_id="price_test",
+ unit_amount=2000,
+ currency="usd",
+ ),
+ "cus_test",
+ "https://example.com/ok",
+ "https://example.com/no",
+ {},
+ )
+ yield trial
+ await User.prisma().delete_many(where={"id": user_id})
+ await SubscriptionTrialClaim.prisma().delete_many(
+ where={"trialId": {"startsWith": trial.id}}
+ )
+ if owns_connection:
+ await db.disconnect()
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_integration_test.py b/autogpt_platform/backend/backend/data/subscription_trial_integration_test.py
new file mode 100644
index 0000000000..b9ef6ea785
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_integration_test.py
@@ -0,0 +1,284 @@
+"""Run only against a disposable database with TRIAL_TEST_DATABASE=1."""
+
+import asyncio
+import os
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, patch
+from urllib.parse import urlparse
+from uuid import uuid4
+
+import pytest
+import pytest_asyncio
+from prisma.models import (
+ CreditTransaction,
+ SubscriptionTrial,
+ User,
+ UserBalance,
+ UserOnboarding,
+)
+
+from backend.data import credit, db, subscription_trial_checkout
+from backend.data.credit import UserCredit
+from backend.data.onboarding import _reward_user
+from backend.data.onboarding_steps import OnboardingStep
+from backend.data.subscription_checkout import subscription_checkout_lock
+from backend.data.subscription_trial import (
+ get_subscription_trial,
+ record_subscription_trial_cost,
+ reserve_subscription_trial,
+)
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+from backend.data.subscription_trial_stripe import (
+ Invoice,
+ SubscriptionSnapshot,
+ _save_snapshot,
+)
+
+pytestmark = pytest.mark.skipif(
+ os.environ.get("TRIAL_TEST_DATABASE") != "1",
+ reason="Requires explicitly selected disposable trial database",
+)
+
+
+@pytest_asyncio.fixture
+async def user_id():
+ target = urlparse(db.DATABASE_URL)
+ local = (target.hostname, target.port, target.path) == (
+ "127.0.0.1",
+ 15432,
+ "/trial_test",
+ )
+ ci = os.environ.get("GITHUB_ACTIONS") == "true" and (
+ target.hostname,
+ target.port,
+ target.path,
+ ) == ("localhost", 5432, "/postgres")
+ assert (
+ local or ci
+ ), "Trial integration tests require an approved disposable database"
+ owns_connection = not db.is_connected()
+ await db.connect()
+ user_id = str(uuid4())
+ await User.prisma().create(data={"id": user_id, "email": f"{user_id}@example.com"})
+ yield user_id
+ await CreditTransaction.prisma().delete_many(where={"userId": user_id})
+ await User.prisma().delete(where={"id": user_id})
+ if owns_connection:
+ await db.disconnect()
+
+
+def offer(credits: int = 300) -> AcceptedTrialOffer:
+ return AcceptedTrialOffer(
+ version="integration-v1",
+ new_users_from=datetime(2026, 9, 1, tzinfo=UTC),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=credits,
+ price_id="price_integration",
+ unit_amount=2000,
+ currency="usd",
+ )
+
+
+async def reserve(user_id: str, credits: int = 300):
+ return await reserve_subscription_trial(
+ user_id,
+ offer(credits),
+ "cus_integration",
+ "https://example.com/success",
+ "https://example.com/cancel",
+ {"datafast_visitor_id": "visitor"},
+ )
+
+
+async def test_parallel_enrollment_keeps_one_accepted_offer(user_id):
+ results = await asyncio.gather(*[reserve(user_id, 300 + i) for i in range(12)])
+ assert len({trial.id for trial in results}) == 1
+ assert len({trial.offer.token for trial in results}) == 1
+ assert await SubscriptionTrial.prisma().count(where={"userId": user_id}) == 1
+
+
+async def test_concurrent_checkout_is_rejected_and_lock_is_released(user_id):
+ async with subscription_checkout_lock(user_id):
+ with pytest.raises(ValueError, match="checkout is already"):
+ async with subscription_checkout_lock(user_id):
+ pytest.fail("A second checkout entered the critical section")
+ async with subscription_checkout_lock(str(uuid4())):
+ pass
+ async with subscription_checkout_lock(user_id):
+ pass
+
+
+async def test_checkout_failure_releases_lock(user_id):
+ with pytest.raises(RuntimeError):
+ async with subscription_checkout_lock(user_id):
+ raise RuntimeError("Stripe failed")
+ async with subscription_checkout_lock(user_id):
+ pass
+
+
[email protected]("trial_first", [True, False])
+async def test_paid_and_trial_checkouts_cannot_run_together(user_id, trial_first):
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def paused_checkout(*args, **kwargs):
+ entered.set()
+ await release.wait()
+ return "https://checkout.stripe.com/test"
+
+ async def trial_checkout():
+ return await subscription_trial_checkout.create_trial_checkout(
+ user_id,
+ offer().token,
+ "https://example.com/ok",
+ "https://example.com/no",
+ {},
+ )
+
+ async def paid_checkout():
+ return await credit.create_subscription_checkout(
+ user_id,
+ credit.SubscriptionTier.PRO,
+ "https://example.com/ok",
+ "https://example.com/no",
+ )
+
+ first, second = (
+ (trial_checkout, paid_checkout)
+ if trial_first
+ else (paid_checkout, trial_checkout)
+ )
+ with (
+ patch.object(
+ credit,
+ "_create_subscription_checkout",
+ AsyncMock(side_effect=paused_checkout),
+ ),
+ patch.object(
+ subscription_trial_checkout,
+ "_create_trial_checkout",
+ AsyncMock(side_effect=paused_checkout),
+ ),
+ ):
+ task = asyncio.create_task(first())
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ with pytest.raises(ValueError, match="checkout is already"):
+ await second()
+ finally:
+ release.set()
+ assert await task == "https://checkout.stripe.com/test"
+
+
+async def test_trial_cost_increments_are_atomic_and_do_not_reset(user_id):
+ await reserve(user_id)
+ await SubscriptionTrial.prisma().update(
+ where={"userId": user_id}, data={"status": "trialing"}
+ )
+ await asyncio.gather(
+ *[record_subscription_trial_cost(user_id, 100) for _ in range(30)]
+ )
+ trial = await get_subscription_trial(user_id)
+ assert trial is not None and trial.cost_microdollars == 3000
+ await reserve(user_id, 500)
+ trial = await get_subscription_trial(user_id)
+ assert trial is not None and trial.cost_microdollars == 3000
+
+
+async def test_conversion_invoice_survives_database_roundtrip_and_renewal(user_id):
+ trial = await reserve(user_id)
+ now = datetime.now(UTC)
+ invoice = Invoice(
+ id=f"in_first_{user_id}", status="paid", created=int(now.timestamp())
+ )
+ snapshot = SubscriptionSnapshot(
+ id=f"sub_{user_id}",
+ customer=trial.customer_id,
+ status="active",
+ latest_invoice=invoice,
+ )
+ async with db.transaction() as tx:
+ await _save_snapshot(
+ trial, snapshot, credit.SubscriptionTier.PRO, now, tx, True
+ )
+ converted = await get_subscription_trial(user_id)
+ assert converted is not None and converted.converted_at is not None
+ assert converted.conversion_invoice_id == f"in_first_{user_id}"
+ invoice.id = f"in_renewal_{user_id}"
+ async with db.transaction() as tx:
+ await _save_snapshot(
+ converted, snapshot, credit.SubscriptionTier.PRO, now, tx, True
+ )
+ renewed = await get_subscription_trial(user_id)
+ assert renewed is not None
+ assert renewed.conversion_invoice_id == converted.conversion_invoice_id
+ assert renewed.converted_at == converted.converted_at
+ assert trial.offer.onboarding_credit_amount == 300
+
+
+async def test_trial_reuses_onboarding_reward_key_and_never_grants_twice(user_id):
+ await reserve(user_id, 500)
+ now = datetime.now(UTC)
+ await SubscriptionTrial.prisma().update(
+ where={"userId": user_id},
+ data={
+ "status": "trialing",
+ "cardVerifiedAt": now,
+ "consumedAt": now,
+ "endsAt": now + timedelta(days=7),
+ },
+ )
+ onboarding = await UserOnboarding.prisma().create(data={"userId": user_id})
+ with (
+ patch(
+ "backend.data.onboarding.get_user_credit_model",
+ AsyncMock(return_value=UserCredit()),
+ ),
+ patch(
+ "backend.executor.billing.clear_insufficient_funds_notifications",
+ AsyncMock(),
+ ),
+ ):
+ await _reward_user(user_id, onboarding, OnboardingStep.ONBOARDING_COMPLETE)
+ await _reward_user(user_id, onboarding, OnboardingStep.ONBOARDING_COMPLETE)
+ balance = await UserBalance.prisma().find_unique_or_raise(where={"userId": user_id})
+ assert balance.balance == 500
+ transactions = await CreditTransaction.prisma().find_many(where={"userId": user_id})
+ assert len(transactions) == 1
+ assert transactions[0].transactionKey == f"REWARD-{user_id}-ONBOARDING_COMPLETE"
+
+
+async def test_existing_onboarding_recipient_gets_no_trial_topup(user_id):
+ onboarding = await UserOnboarding.prisma().create(data={"userId": user_id})
+ with (
+ patch(
+ "backend.data.onboarding.get_user_credit_model",
+ AsyncMock(return_value=UserCredit()),
+ ),
+ patch(
+ "backend.executor.billing.clear_insufficient_funds_notifications",
+ AsyncMock(),
+ ),
+ ):
+ await _reward_user(user_id, onboarding, OnboardingStep.ONBOARDING_COMPLETE)
+ await reserve(user_id, 500)
+ await SubscriptionTrial.prisma().update(
+ where={"userId": user_id}, data={"consumedAt": datetime.now(UTC)}
+ )
+ await _reward_user(user_id, onboarding, OnboardingStep.ONBOARDING_COMPLETE)
+ balance = await UserBalance.prisma().find_unique_or_raise(where={"userId": user_id})
+ assert balance.balance == 300
+ assert await CreditTransaction.prisma().count(where={"userId": user_id}) == 1
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_pagination_test.py b/autogpt_platform/backend/backend/data/subscription_trial_pagination_test.py
new file mode 100644
index 0000000000..70d1712afd
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_pagination_test.py
@@ -0,0 +1,50 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import stripe
+
+from backend.data import subscription_trial_stripe as fulfillment
+
+pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+
+
[email protected]("status", ["active", "trialing"])
[email protected]("page_error", [False, True])
+async def test_tier_clear_checks_later_subscription_pages(
+ trial, subscription, boundaries, status, page_error
+):
+ subscription.update(status=status, default_payment_method=None)
+ first = MagicMock(
+ data=[stripe.Subscription.construct_from(subscription, "test")],
+ has_more=True,
+ )
+ second = MagicMock(
+ data=[
+ stripe.Subscription.construct_from(
+ {"id": "sub_other", "status": status}, "test"
+ )
+ ],
+ has_more=False,
+ )
+ first.next_page_async = AsyncMock(
+ return_value=second,
+ side_effect=(
+ stripe.APIConnectionError("Later page unavailable") if page_error else None
+ ),
+ )
+ empty = MagicMock(data=[], has_more=False)
+ with patch.object(
+ fulfillment.stripe.Subscription,
+ "list_async",
+ AsyncMock(side_effect=[first, empty] if status == "active" else [empty, first]),
+ ):
+ if page_error:
+ with pytest.raises(stripe.APIConnectionError, match="Later page"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ else:
+ _, tier = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert tier is None
+
+ first.next_page_async.assert_awaited_once_with()
+ boundaries.user.update_many.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_payment.py b/autogpt_platform/backend/backend/data/subscription_trial_payment.py
new file mode 100644
index 0000000000..1205f67d36
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_payment.py
@@ -0,0 +1,113 @@
+"""Read the effective customer billing card without changing payment defaults."""
+
+from datetime import datetime
+
+import stripe
+from pydantic import BaseModel, Field
+
+from backend.data.stripe_client import stripe_call
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+
+
+class Card(BaseModel):
+ exp_month: int
+ exp_year: int
+ fingerprint: str | None = None
+
+
+class PaymentMethod(BaseModel):
+ id: str
+ type: str
+ card: Card | None = None
+
+
+class CustomerInvoiceSettings(BaseModel):
+ default_payment_method: PaymentMethod | None = None
+
+
+class CustomerSnapshot(BaseModel):
+ id: str
+ deleted: bool = False
+ invoice_settings: CustomerInvoiceSettings | None = None
+
+
+async def get_customer_default_payment_method(customer_id: str) -> PaymentMethod | None:
+ customer = CustomerSnapshot.model_validate(
+ await stripe_call(
+ stripe.Customer.retrieve_async,
+ customer_id,
+ expand=["invoice_settings.default_payment_method"],
+ )
+ )
+ if customer.id != customer_id:
+ raise ValueError("Stripe customer ownership does not match the enrollment")
+ if customer.deleted or customer.invoice_settings is None:
+ return None
+ return customer.invoice_settings.default_payment_method
+
+
+class Invoice(BaseModel):
+ id: str
+ status: str | None = None
+ created: int
+ billing_reason: str | None = None
+
+
+class SubscriptionPrice(BaseModel):
+ id: str
+
+
+class SubscriptionItem(BaseModel):
+ price: SubscriptionPrice
+ quantity: int | None = None
+
+
+class SubscriptionItems(BaseModel):
+ data: list[SubscriptionItem]
+ has_more: bool = False
+
+
+class CancellationDetails(BaseModel):
+ comment: str | None = None
+
+
+class SubscriptionSnapshot(BaseModel):
+ id: str
+ customer: str
+ status: str
+ metadata: dict[str, str] = Field(default_factory=dict)
+ trial_start: int | None = None
+ trial_end: int | None = None
+ ended_at: int | None = None
+ cancel_at_period_end: bool = False
+ cancellation_details: CancellationDetails | None = None
+ default_payment_method: PaymentMethod | None = None
+ default_source: str | dict | None = None
+ customer_default_payment_method: PaymentMethod | None = None
+ pending_setup_intent: str | dict | None = None
+ latest_invoice: Invoice | None = None
+ items: SubscriptionItems | None = None
+
+ def has_accepted_price(self, offer: AcceptedTrialOffer) -> bool:
+ return bool(
+ self.items
+ and not self.items.has_more
+ and len(self.items.data) == 1
+ and self.items.data[0].price.id == offer.price_id
+ and self.items.data[0].quantity == 1
+ )
+
+ def has_verified_card(self, now: datetime) -> bool:
+ method = self.effective_payment_method()
+ return bool(
+ method
+ and method.type == "card"
+ and method.card
+ and (method.card.exp_year, method.card.exp_month) >= (now.year, now.month)
+ and not self.pending_setup_intent
+ )
+
+ def effective_payment_method(self) -> PaymentMethod | None:
+ if self.default_payment_method is None and self.default_source is None:
+ return self.customer_default_payment_method
+ return self.default_payment_method
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_rejection.py b/autogpt_platform/backend/backend/data/subscription_trial_rejection.py
new file mode 100644
index 0000000000..ceee40b78b
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_rejection.py
@@ -0,0 +1,18 @@
+"""Public, non-identifying reasons an introductory offer could not be started."""
+
+from enum import StrEnum
+
+
+class TrialRejectionReason(StrEnum):
+ INTRO_OFFER_ALREADY_USED = "intro_offer_already_used"
+ CARD_VERIFICATION_FAILED = "card_verification_failed"
+
+ @property
+ def stripe_comment(self) -> str:
+ return f"autogpt_trial:{self.value}"
+
+ @classmethod
+ def from_stripe_comment(cls, comment: str | None) -> "TrialRejectionReason | None":
+ return next(
+ (reason for reason in cls if reason.stripe_comment == comment), None
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_rejection_integration_test.py b/autogpt_platform/backend/backend/data/subscription_trial_rejection_integration_test.py
new file mode 100644
index 0000000000..28a27444c1
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_rejection_integration_test.py
@@ -0,0 +1,22 @@
+import pytest
+from prisma.models import SubscriptionTrial
+
+from backend.data import subscription_trial_integration_fixtures as fixtures
+from backend.data.subscription_trial import get_subscription_trial
+from backend.data.subscription_trial_rejection import TrialRejectionReason
+
+enrollment = fixtures.enrollment
+pytestmark = fixtures.pytestmark
+
+
[email protected]("reason", list(TrialRejectionReason))
+async def test_rejection_reason_round_trips_through_database(enrollment, reason):
+ await SubscriptionTrial.prisma().update(
+ where={"id": enrollment.id},
+ data={"status": "canceled", "rejectionReason": reason},
+ )
+ trial = await get_subscription_trial(enrollment.user_id)
+ assert trial is not None
+ assert trial.rejection_reason == reason
+ assert not trial.active
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_rejection_test.py b/autogpt_platform/backend/backend/data/subscription_trial_rejection_test.py
new file mode 100644
index 0000000000..15f795fb43
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_rejection_test.py
@@ -0,0 +1,79 @@
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from backend.data import subscription_trial_stripe as fulfillment
+
+pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+
+
[email protected]("comment", [None, "I want to cancel", "unrecognized_reason"])
+async def test_ordinary_cancellation_is_not_labeled_as_rejection(
+ trial, subscription, boundaries, comment
+):
+ subscription.update(status="canceled", cancellation_details={"comment": comment})
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert (
+ boundaries.subscriptiontrial.update.await_args.kwargs["data"]["rejectionReason"]
+ is None
+ )
+
+
[email protected]("missing_fingerprint", [False, True])
+async def test_auto_cancellation_records_rejection_reason(
+ trial, subscription, boundaries, missing_fingerprint
+):
+ reason = (
+ "card_verification_failed"
+ if missing_fingerprint
+ else "intro_offer_already_used"
+ )
+ if missing_fingerprint:
+ subscription["default_payment_method"]["card"]["fingerprint"] = None
+ canceled = {**subscription, "status": "canceled"}
+ with (
+ patch.object(
+ fulfillment, "claim_trial_identities", AsyncMock(return_value=False)
+ ),
+ patch.object(
+ fulfillment.stripe.Subscription,
+ "cancel_async",
+ AsyncMock(return_value=canceled),
+ ) as cancel,
+ ):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert cancel.await_args.kwargs["cancellation_details"] == {
+ "comment": f"autogpt_trial:{reason}"
+ }
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["rejectionReason"] == reason
+
+
+async def test_reconciliation_recovers_rejection_from_stripe(
+ trial, subscription, boundaries
+):
+ subscription.update(
+ status="canceled",
+ cancellation_details={"comment": "autogpt_trial:intro_offer_already_used"},
+ )
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert (
+ boundaries.subscriptiontrial.update.await_args.kwargs["data"]["rejectionReason"]
+ == "intro_offer_already_used"
+ )
+
+
+async def test_reconciliation_preserves_rejection_on_replay(
+ trial, subscription, boundaries
+):
+ trial = trial.model_copy(update={"rejection_reason": "intro_offer_already_used"})
+ subscription.update(status="canceled")
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+ assert (
+ boundaries.subscriptiontrial.update.await_args.kwargs["data"]["rejectionReason"]
+ == "intro_offer_already_used"
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_resume_test.py b/autogpt_platform/backend/backend/data/subscription_trial_resume_test.py
new file mode 100644
index 0000000000..9ca0a80b35
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_resume_test.py
@@ -0,0 +1,133 @@
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import stripe
+from prisma.enums import SubscriptionTier
+
+from backend.data import subscription_trial_checkout as checkout
+from backend.data import subscription_trial_eligibility as eligibility
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+
+
+def trial():
+ return TrialState(
+ id="trial-1",
+ user_id="user-1",
+ customer_id="cus_1",
+ offer=AcceptedTrialOffer(
+ version="resume-v1",
+ new_users_from=datetime(2026, 9, 1, tzinfo=UTC),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_pro",
+ unit_amount=5000,
+ currency="usd",
+ ),
+ checkout_session_id="cs_1",
+ subscription_id="sub_1",
+ checkout_attempt=0,
+ success_url="https://example.com/ok",
+ cancel_url="https://example.com/no",
+ checkout_metadata={},
+ status="checkout_pending",
+ card_verified_at=None,
+ started_at=None,
+ ends_at=None,
+ consumed_at=None,
+ converted_at=None,
+ cancel_at_period_end=False,
+ cost_microdollars=0,
+ )
+
+
+def session(trial):
+ return stripe.checkout.Session.construct_from(
+ {
+ "id": "cs_1",
+ "status": "open",
+ "mode": "subscription",
+ "url": "https://checkout.stripe.com/test",
+ "customer": trial.customer_id,
+ "subscription": "sub_1",
+ "metadata": {
+ "trial_enrollment_id": trial.id,
+ "user_id": trial.user_id,
+ "trial_checkout_attempt": "0",
+ "trial_offer_version": trial.offer.version,
+ },
+ },
+ "test-key",
+ )
+
+
+def subscriptions(session):
+ return [{"id": "sub_1", "status": "trialing", "metadata": dict(session.metadata)}]
+
+
+def boundaries(trial, session, subscriptions):
+ user = MagicMock(
+ created_at=datetime(2026, 9, 4, tzinfo=UTC),
+ subscription_tier=SubscriptionTier.NO_TIER,
+ )
+ with (
+ patch.object(checkout, "_find_checkout", AsyncMock(return_value=session)),
+ patch.object(checkout, "expire_other_subscription_checkouts", AsyncMock()),
+ patch.object(eligibility, "get_user_by_id", AsyncMock(return_value=user)),
+ patch.object(
+ stripe.Subscription,
+ "list_async",
+ AsyncMock(
+ side_effect=lambda *args, **kwargs: stripe.ListObject.construct_from(
+ {"data": subscriptions, "has_more": False}, "test-key"
+ )
+ ),
+ ),
+ patch.object(
+ stripe.checkout.Session,
+ "list_async",
+ AsyncMock(
+ return_value=stripe.ListObject.construct_from(
+ {"data": [], "has_more": False}, "test-key"
+ )
+ ),
+ ),
+ ):
+ yield
+
+
[email protected]("status", ["trialing", "incomplete"])
+async def test_pending_checkout_can_resume_its_own_unfinished_subscription(
+ trial, subscriptions, boundaries, status
+):
+ subscriptions[0]["status"] = status
+ assert await checkout._resume_checkout(trial) == "https://checkout.stripe.com/test"
+
+
+async def test_another_subscription_still_disqualifies_trial(
+ trial, subscriptions, boundaries
+):
+ subscriptions.append({"id": "sub_previous", "status": "canceled", "metadata": {}})
+ with pytest.raises(checkout.TrialUnavailable, match="not eligible"):
+ await checkout._resume_checkout(trial)
+
+
+async def test_paid_subscription_cannot_be_ignored_as_unfinished_checkout(
+ trial, subscriptions, boundaries
+):
+ subscriptions[0]["status"] = "active"
+ with pytest.raises(checkout.TrialUnavailable, match="not eligible"):
+ await checkout._resume_checkout(trial)
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_stripe.py b/autogpt_platform/backend/backend/data/subscription_trial_stripe.py
new file mode 100644
index 0000000000..480e7b5279
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_stripe.py
@@ -0,0 +1,268 @@
+"""Reconcile trial entitlements from current Stripe state, never event order."""
+
+from datetime import UTC, datetime
+
+import stripe
+from prisma import Prisma
+from prisma.enums import SubscriptionTier
+
+from backend.data.db import query_raw_with_schema, transaction
+from backend.data.stripe_client import stripe_call, stripe_list_items
+from backend.data.subscription_trial import TrialState, get_subscription_trial
+from backend.data.subscription_trial_claims import claim_trial_identities
+from backend.data.subscription_trial_payment import Invoice as Invoice
+from backend.data.subscription_trial_payment import (
+ SubscriptionSnapshot as SubscriptionSnapshot,
+)
+from backend.data.subscription_trial_payment import get_customer_default_payment_method
+from backend.data.subscription_trial_rejection import TrialRejectionReason
+
+
+async def reconcile_trial_subscription(
+ user_id: str, subscription_id: str
+) -> tuple[dict, SubscriptionTier | None] | None:
+ trial = await get_subscription_trial(user_id)
+ if trial is None:
+ return None
+ async with transaction() as tx:
+ await query_raw_with_schema(
+ 'SELECT "id" FROM {schema_prefix}"SubscriptionTrial" '
+ 'WHERE "userId" = $1 FOR UPDATE',
+ user_id,
+ client=tx,
+ )
+ row = await tx.subscriptiontrial.find_unique_or_raise(where={"userId": user_id})
+ return await _reconcile_locked(TrialState.from_db(row), subscription_id, tx)
+
+
+async def _reconcile_locked(
+ trial: TrialState, subscription_id: str, tx: Prisma
+) -> tuple[dict, SubscriptionTier | None] | None:
+ raw = await stripe_call(
+ stripe.Subscription.retrieve_async,
+ subscription_id,
+ expand=["default_payment_method", "latest_invoice"],
+ )
+ snapshot = SubscriptionSnapshot.model_validate(raw)
+ if snapshot.metadata.get("trial_enrollment_id") != trial.id:
+ return None
+ if (
+ snapshot.customer != trial.customer_id
+ or snapshot.metadata.get("user_id") != trial.user_id
+ ):
+ raise ValueError("Stripe trial ownership does not match the enrollment")
+ if snapshot.metadata.get("trial_checkout_attempt") != str(trial.checkout_attempt):
+ user = await tx.user.find_unique_or_raise(where={"id": trial.user_id})
+ return dict(raw), user.subscriptionTier
+ if trial.subscription_id and trial.subscription_id != snapshot.id:
+ raise ValueError("A different subscription already consumed this trial")
+ if snapshot.default_payment_method is None and snapshot.default_source is None:
+ snapshot.customer_default_payment_method = (
+ await get_customer_default_payment_method(trial.customer_id)
+ )
+ now = datetime.now(UTC)
+ checkout_complete = trial.consumed_at is not None or await _completed_card_checkout(
+ trial, snapshot.id, tx
+ )
+ rejection_reason = (
+ trial.rejection_reason
+ or TrialRejectionReason.from_stripe_comment(
+ snapshot.cancellation_details.comment
+ if snapshot.cancellation_details
+ else None
+ )
+ )
+ if (
+ checkout_complete
+ and snapshot.status == "trialing"
+ and trial.converted_at is None
+ ):
+ method = snapshot.effective_payment_method()
+ fingerprint = method.card.fingerprint if method and method.card else None
+ if snapshot.has_verified_card(now):
+ if not fingerprint:
+ rejection_reason = TrialRejectionReason.CARD_VERIFICATION_FAILED
+ elif not await claim_trial_identities(trial, fingerprint, tx):
+ rejection_reason = TrialRejectionReason.INTRO_OFFER_ALREADY_USED
+ if snapshot.cancel_at_period_end or rejection_reason:
+ cancel_params: stripe.Subscription.CancelParams = {
+ "invoice_now": False,
+ "prorate": False,
+ "expand": ["default_payment_method", "latest_invoice"],
+ }
+ if rejection_reason:
+ cancel_params["cancellation_details"] = {
+ "comment": rejection_reason.stripe_comment
+ }
+ raw = await stripe_call(
+ stripe.Subscription.cancel_async,
+ snapshot.id,
+ **cancel_params,
+ )
+ snapshot = SubscriptionSnapshot.model_validate(raw)
+ if snapshot.id != subscription_id or snapshot.status != "canceled":
+ raise ValueError("Stripe did not confirm trial cancellation")
+ if (
+ trial.converted_at is None
+ and snapshot.status in ("active", "trialing")
+ and not snapshot.has_accepted_price(trial.offer)
+ ):
+ raise ValueError(
+ "Stripe items do not match the accepted trial price and quantity"
+ )
+ tier = (
+ trial_subscription_tier(trial, snapshot, now)
+ if checkout_complete
+ else SubscriptionTier.NO_TIER
+ )
+ await _save_snapshot(
+ trial, snapshot, tier, now, tx, checkout_complete, rejection_reason
+ )
+ if trial.converted_at:
+ return dict(raw), None
+ if tier == SubscriptionTier.NO_TIER:
+ for status in ("active", "trialing"):
+ others = await stripe_call(
+ stripe.Subscription.list_async,
+ customer=trial.customer_id,
+ status=status,
+ limit=100,
+ )
+ async for other in stripe_list_items(others):
+ if other.id != snapshot.id:
+ return dict(raw), None
+ await tx.user.update_many(
+ where={
+ "id": trial.user_id,
+ "subscriptionTier": {"not": SubscriptionTier.ENTERPRISE},
+ },
+ data={"subscriptionTier": tier},
+ )
+ return dict(raw), tier
+
+
+async def _completed_card_checkout(
+ trial: TrialState, subscription_id: str, tx: Prisma
+) -> bool:
+ if trial.checkout_session_id:
+ session = await stripe_call(
+ stripe.checkout.Session.retrieve_async, trial.checkout_session_id
+ )
+ return _checkout_proves_card_collection(trial, subscription_id, session)
+ sessions = await stripe_call(
+ stripe.checkout.Session.list_async, customer=trial.customer_id, limit=100
+ )
+ async for session in stripe_list_items(sessions):
+ if (session.metadata or {}).get("trial_enrollment_id") != trial.id:
+ continue
+ if (session.metadata or {}).get("trial_checkout_attempt") != str(
+ trial.checkout_attempt
+ ):
+ continue
+ complete = _checkout_proves_card_collection(trial, subscription_id, session)
+ await tx.subscriptiontrial.update(
+ where={"id": trial.id}, data={"stripeCheckoutSessionId": session.id}
+ )
+ return complete
+ return False
+
+
+def _checkout_proves_card_collection(
+ trial: TrialState, subscription_id: str, session: stripe.checkout.Session
+) -> bool:
+ if session.status != "complete":
+ return False
+ metadata = session.metadata or {}
+ if (
+ session.mode != "subscription"
+ or session.customer != trial.customer_id
+ or session.subscription != subscription_id
+ or metadata.get("user_id") != trial.user_id
+ or metadata.get("trial_enrollment_id") != trial.id
+ or metadata.get("trial_checkout_attempt") != str(trial.checkout_attempt)
+ or metadata.get("trial_offer_version") != trial.offer.version
+ or session.payment_method_collection != "always"
+ or session.payment_method_types != ["card"]
+ ):
+ raise ValueError("Checkout does not prove this enrollment's card collection")
+ return True
+
+
+def trial_subscription_tier(
+ trial: TrialState, subscription: SubscriptionSnapshot, now: datetime
+) -> SubscriptionTier:
+ end = subscription.trial_end
+ if end is None:
+ return SubscriptionTier.NO_TIER
+ if subscription.status == "trialing" and end > now.timestamp():
+ if subscription.has_verified_card(now):
+ return SubscriptionTier.TRIAL
+ return SubscriptionTier.NO_TIER
+ invoice = subscription.latest_invoice
+ if (
+ subscription.status == "active"
+ and end <= now.timestamp()
+ and invoice is not None
+ and invoice.status == "paid"
+ and invoice.created >= end
+ and invoice.billing_reason != "subscription_create"
+ ):
+ return SubscriptionTier(trial.offer.tier)
+ return SubscriptionTier.NO_TIER
+
+
+async def _save_snapshot(
+ trial: TrialState,
+ snapshot: SubscriptionSnapshot,
+ tier: SubscriptionTier,
+ now: datetime,
+ tx: Prisma,
+ checkout_complete: bool,
+ rejection_reason: TrialRejectionReason | None = None,
+) -> None:
+ verified_at = (
+ (trial.card_verified_at or now)
+ if checkout_complete and tier == SubscriptionTier.TRIAL
+ else None
+ )
+ consumed_at = trial.consumed_at
+ if checkout_complete:
+ consumed_at = consumed_at or now
+ converted_at = trial.converted_at
+ conversion_invoice_id = trial.conversion_invoice_id
+ if converted_at is None and tier.value == trial.offer.tier:
+ if snapshot.latest_invoice is None:
+ raise ValueError("Trial conversion requires a paid invoice")
+ converted_at = now
+ conversion_invoice_id = snapshot.latest_invoice.id
+ await tx.subscriptiontrial.update(
+ where={"userId": trial.user_id},
+ data={
+ "stripeSubscriptionId": snapshot.id,
+ "rejectionReason": rejection_reason,
+ "status": (
+ "checkout_pending"
+ if not checkout_complete
+ and snapshot.status
+ in ("trialing", "incomplete", "canceled", "incomplete_expired")
+ else snapshot.status
+ ),
+ "cardVerifiedAt": verified_at,
+ "startedAt": _timestamp(snapshot.trial_start),
+ "endsAt": _timestamp(
+ snapshot.ended_at
+ if snapshot.status == "canceled" and snapshot.ended_at is not None
+ else snapshot.trial_end
+ ),
+ "consumedAt": consumed_at,
+ "convertedAt": converted_at,
+ "stripeConversionInvoiceId": conversion_invoice_id,
+ "cancelAtPeriodEnd": snapshot.cancel_at_period_end,
+ "notificationRevision": trial.notification_revision
+ + int(trial.cancel_at_period_end != snapshot.cancel_at_period_end),
+ },
+ )
+
+
+def _timestamp(value: int | None) -> datetime | None:
+ return datetime.fromtimestamp(value, UTC) if value is not None else None
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_stripe_captured_test.py b/autogpt_platform/backend/backend/data/subscription_trial_stripe_captured_test.py
new file mode 100644
index 0000000000..5a1d16b78f
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_stripe_captured_test.py
@@ -0,0 +1,95 @@
+"""Replay actual Stripe test-clock states through the entitlement decision."""
+
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from prisma.enums import SubscriptionTier
+from pydantic import BaseModel
+
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+from backend.data.subscription_trial_stripe import (
+ SubscriptionSnapshot,
+ trial_subscription_tier,
+)
+
+
+class CapturedScenario(BaseModel):
+ before: SubscriptionSnapshot
+ after: SubscriptionSnapshot
+
+
+class CapturedSimulation(BaseModel):
+ start_time: int
+ end_time: int
+ scenarios: dict[str, CapturedScenario]
+
+
+CAPTURE = CapturedSimulation.model_validate_json(
+ (Path(__file__).parent / "test_data" / "trial_stripe_simulation.json").read_text()
+)
+
+
[email protected]("scenario", ["success", "failure", "cancel"])
+def test_real_zero_dollar_initial_invoice_is_trial_not_paid_access(scenario: str):
+ snapshot = CAPTURE.scenarios[scenario].before
+ now = datetime.fromtimestamp(CAPTURE.start_time, UTC)
+ assert snapshot.latest_invoice is not None
+ assert snapshot.latest_invoice.status == "paid"
+ assert snapshot.latest_invoice.billing_reason == "subscription_create"
+ assert (
+ trial_subscription_tier(enrollment(snapshot), snapshot, now)
+ == SubscriptionTier.TRIAL
+ )
+
+
+ "scenario,expected",
+ [
+ ("success", SubscriptionTier.PRO),
+ ("failure", SubscriptionTier.NO_TIER),
+ ("cancel", SubscriptionTier.NO_TIER),
+ ],
+)
+def test_real_trial_conversion_states(scenario: str, expected: SubscriptionTier):
+ snapshot = CAPTURE.scenarios[scenario].after
+ now = datetime.fromtimestamp(CAPTURE.end_time, UTC)
+ assert trial_subscription_tier(enrollment(snapshot), snapshot, now) == expected
+
+
+def enrollment(snapshot: SubscriptionSnapshot) -> TrialState:
+ start = datetime.fromtimestamp(CAPTURE.start_time, UTC)
+ return TrialState(
+ id="captured-trial",
+ user_id="captured-user",
+ customer_id=snapshot.customer,
+ offer=AcceptedTrialOffer(
+ version="stripe-simulation-not-launch-offer",
+ new_users_from=start,
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_test_1",
+ unit_amount=5000,
+ currency="usd",
+ ),
+ checkout_session_id=None,
+ subscription_id=snapshot.id,
+ checkout_attempt=0,
+ success_url="https://example.com/ok",
+ cancel_url="https://example.com/no",
+ checkout_metadata={},
+ status="trialing",
+ card_verified_at=start,
+ started_at=start,
+ ends_at=datetime.fromtimestamp(CAPTURE.start_time + 7 * 86400, UTC),
+ consumed_at=start,
+ converted_at=None,
+ cancel_at_period_end=False,
+ cost_microdollars=0,
+ )
diff --git a/autogpt_platform/backend/backend/data/test_data/trial_stripe_simulation.json b/autogpt_platform/backend/backend/data/test_data/trial_stripe_simulation.json
new file mode 100644
index 0000000000..e5edd5be54
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/test_data/trial_stripe_simulation.json
@@ -0,0 +1,188 @@
+{
+ "scope": "Captured Stripe test-mode subscription API states, not hosted Checkout or webhook delivery proof. Object identifiers use stable test labels; states, dates, card expiry, and amounts are unchanged.",
+ "api_version": "2025-02-24.acacia",
+ "clock": {
+ "id": "clock_test_1",
+ "livemode": false,
+ "status": "ready",
+ "frozen_time": 1789135200,
+ "error": null
+ },
+ "start_time": 1788523200,
+ "end_time": 1789135200,
+ "price": {
+ "id": "price_test_1",
+ "unit_amount": 5000,
+ "currency": "usd"
+ },
+ "scenarios": {
+ "success": {
+ "before": {
+ "id": "sub_test_1",
+ "livemode": false,
+ "customer": "cus_test_1",
+ "status": "trialing",
+ "test_clock": "clock_test_1",
+ "trial_start": 1788523200,
+ "trial_end": 1789128000,
+ "cancel_at_period_end": false,
+ "default_payment_method": {
+ "id": "pm_test_1",
+ "type": "card",
+ "card": {
+ "exp_month": 9,
+ "exp_year": 2027
+ }
+ },
+ "pending_setup_intent": null,
+ "latest_invoice": {
+ "id": "in_test_1",
+ "created": 1788523200,
+ "status": "paid",
+ "billing_reason": "subscription_create",
+ "amount_paid": 0
+ },
+ "error": null
+ },
+ "after": {
+ "id": "sub_test_1",
+ "livemode": false,
+ "customer": "cus_test_1",
+ "status": "active",
+ "test_clock": "clock_test_1",
+ "trial_start": 1788523200,
+ "trial_end": 1789128000,
+ "cancel_at_period_end": false,
+ "default_payment_method": {
+ "id": "pm_test_1",
+ "type": "card",
+ "card": {
+ "exp_month": 9,
+ "exp_year": 2027
+ }
+ },
+ "pending_setup_intent": null,
+ "latest_invoice": {
+ "id": "in_test_2",
+ "created": 1789128000,
+ "status": "paid",
+ "billing_reason": "subscription_cycle",
+ "amount_paid": 5000
+ },
+ "error": null
+ }
+ },
+ "failure": {
+ "before": {
+ "id": "sub_test_2",
+ "livemode": false,
+ "customer": "cus_test_2",
+ "status": "trialing",
+ "test_clock": "clock_test_1",
+ "trial_start": 1788523200,
+ "trial_end": 1789128000,
+ "cancel_at_period_end": false,
+ "default_payment_method": {
+ "id": "pm_test_2",
+ "type": "card",
+ "card": {
+ "exp_month": 9,
+ "exp_year": 2027
+ }
+ },
+ "pending_setup_intent": null,
+ "latest_invoice": {
+ "id": "in_test_3",
+ "created": 1788523200,
+ "status": "paid",
+ "billing_reason": "subscription_create",
+ "amount_paid": 0
+ },
+ "error": null
+ },
+ "after": {
+ "id": "sub_test_2",
+ "livemode": false,
+ "customer": "cus_test_2",
+ "status": "past_due",
+ "test_clock": "clock_test_1",
+ "trial_start": 1788523200,
+ "trial_end": 1789128000,
+ "cancel_at_period_end": false,
+ "default_payment_method": {
+ "id": "pm_test_3",
+ "type": "card",
+ "card": {
+ "exp_month": 9,
+ "exp_year": 2027
+ }
+ },
+ "pending_setup_intent": null,
+ "latest_invoice": {
+ "id": "in_test_4",
+ "created": 1789128000,
+ "status": "open",
+ "billing_reason": "subscription_cycle",
+ "amount_paid": 0
+ },
+ "error": null
+ }
+ },
+ "cancel": {
+ "before": {
+ "id": "sub_test_3",
+ "livemode": false,
+ "customer": "cus_test_3",
+ "status": "trialing",
+ "test_clock": "clock_test_1",
+ "trial_start": 1788523200,
+ "trial_end": 1789128000,
+ "cancel_at_period_end": false,
+ "default_payment_method": {
+ "id": "pm_test_4",
+ "type": "card",
+ "card": {
+ "exp_month": 9,
+ "exp_year": 2027
+ }
+ },
+ "pending_setup_intent": null,
+ "latest_invoice": {
+ "id": "in_test_5",
+ "created": 1788523200,
+ "status": "paid",
+ "billing_reason": "subscription_create",
+ "amount_paid": 0
+ },
+ "error": null
+ },
+ "after": {
+ "id": "sub_test_3",
+ "livemode": false,
+ "customer": "cus_test_3",
+ "status": "canceled",
+ "test_clock": "clock_test_1",
+ "trial_start": 1788523200,
+ "trial_end": 1789128000,
+ "cancel_at_period_end": true,
+ "default_payment_method": {
+ "id": "pm_test_4",
+ "type": "card",
+ "card": {
+ "exp_month": 9,
+ "exp_year": 2027
+ }
+ },
+ "pending_setup_intent": null,
+ "latest_invoice": {
+ "id": "in_test_5",
+ "created": 1788523200,
+ "status": "paid",
+ "billing_reason": "subscription_create",
+ "amount_paid": 0
+ },
+ "error": null
+ }
+ }
+ }
+}
diff --git a/autogpt_platform/backend/backend/data/trial_billing_regression_test.py b/autogpt_platform/backend/backend/data/trial_billing_regression_test.py
new file mode 100644
index 0000000000..062c5c25e4
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/trial_billing_regression_test.py
@@ -0,0 +1,136 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import stripe
+from prisma.enums import SubscriptionTier
+
+from backend.data.credit import _cancel_customer_subscriptions
+from backend.data.stripe_reconciliation import _collect_status_page
+
+
+ "error",
+ [ValueError("Missing enrollment"), stripe.APIConnectionError("Unavailable")],
+)
+async def test_stale_trial_does_not_abort_later_pages(error: Exception):
+ stale = stripe.Subscription.construct_from(
+ {
+ "id": "sub_stale",
+ "customer": "cus_stale",
+ "metadata": {"trial_enrollment_id": "missing"},
+ },
+ "test",
+ )
+ paid = stripe.Subscription.construct_from(
+ {
+ "id": "sub_paid",
+ "customer": "cus_paid",
+ "items": {"data": [{"price": {"id": "price_pro"}}]},
+ },
+ "test",
+ )
+ pages = [
+ MagicMock(data=[stale], has_more=True),
+ MagicMock(data=[paid], has_more=False),
+ ]
+ with (
+ patch(
+ "backend.data.stripe_reconciliation.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
+ side_effect=pages,
+ ) as listing,
+ patch(
+ "backend.data.stripe_reconciliation.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
+ side_effect=error,
+ ),
+ ):
+ tiers: dict[str, SubscriptionTier] = {}
+ incomplete = await _collect_status_page(
+ "active", {"price_pro": SubscriptionTier.PRO}, tiers
+ )
+ assert incomplete is True
+ assert tiers == {"cus_paid": SubscriptionTier.PRO}
+ assert listing.await_args_list[1].kwargs["starting_after"] == "sub_stale"
+
+
[email protected]("status", ["active", "trialing"])
+async def test_cancellation_follows_all_pages(status: str):
+ subscriptions = [
+ stripe.Subscription.construct_from(
+ {
+ "id": f"sub_{index}",
+ "schedule": None,
+ "metadata": (
+ {"trial_enrollment_id": "trial"} if status == "trialing" else {}
+ ),
+ },
+ "test",
+ )
+ for index in range(11)
+ ]
+ second = MagicMock(data=subscriptions[10:], has_more=False)
+ first = MagicMock(data=subscriptions[:10], has_more=True)
+ first.next_page_async = AsyncMock(return_value=second)
+ empty = MagicMock(data=[], has_more=False)
+ with (
+ patch(
+ "backend.data.credit.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
+ side_effect=[first, empty] if status == "active" else [empty, first],
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ ) as modify,
+ patch(
+ "backend.data.credit.stripe.Subscription.cancel_async",
+ new_callable=AsyncMock,
+ side_effect=subscriptions,
+ ) as cancel,
+ patch(
+ "backend.data.credit.sync_subscription_from_stripe", new_callable=AsyncMock
+ ) as sync,
+ ):
+ count = await _cancel_customer_subscriptions("cus_test", at_period_end=True)
+ assert count == 11
+ first.next_page_async.assert_awaited_once_with()
+ if status == "active":
+ assert modify.await_count == 11
+ modify.assert_any_await("sub_10", cancel_at_period_end=True)
+ cancel.assert_not_awaited()
+ else:
+ assert cancel.await_count == 11
+ cancel.assert_any_await("sub_10", invoice_now=False, prorate=False)
+ assert sync.await_count == 11
+ modify.assert_not_awaited()
+
+
+async def test_cancellation_propagates_later_page_failure():
+ first = MagicMock(
+ data=[
+ stripe.Subscription.construct_from(
+ {"id": "sub_first", "schedule": None}, "test"
+ )
+ ],
+ has_more=True,
+ )
+ first.next_page_async = AsyncMock(
+ side_effect=stripe.APIConnectionError("Next page unavailable")
+ )
+ with (
+ patch(
+ "backend.data.credit.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
+ return_value=first,
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ ),
+ pytest.raises(stripe.APIConnectionError, match="Next page unavailable"),
+ ):
+ await _cancel_customer_subscriptions("cus_test", at_period_end=True)
diff --git a/autogpt_platform/backend/backend/data/trial_usage_export_integration_test.py b/autogpt_platform/backend/backend/data/trial_usage_export_integration_test.py
new file mode 100644
index 0000000000..fa6dfee016
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/trial_usage_export_integration_test.py
@@ -0,0 +1,47 @@
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import SubscriptionTier
+from prisma.models import PlatformCostLog, User
+
+from backend.data import subscription_trial_integration_fixtures as fixtures
+from backend.data.platform_cost import get_copilot_weekly_usage_for_export
+
+enrollment = fixtures.enrollment
+pytestmark = fixtures.pytestmark
+
+
+async def test_export_joins_accepted_trial_terms_without_multiplying_usage(enrollment):
+ start = datetime(2026, 9, 7, tzinfo=UTC)
+ await User.prisma().update(
+ where={"id": enrollment.user_id},
+ data={"subscriptionTier": SubscriptionTier.TRIAL},
+ )
+ try:
+ for cost in (15, 25):
+ await PlatformCostLog.prisma().create(
+ data={
+ "userId": enrollment.user_id,
+ "createdAt": start,
+ "provider": "test",
+ "blockName": "copilot:test",
+ "costMicrodollars": cost,
+ }
+ )
+ with patch(
+ "backend.copilot.rate_limit.get_tier_multipliers",
+ AsyncMock(return_value={"TRIAL": 0}),
+ ):
+ rows = await get_copilot_weekly_usage_for_export(
+ start, start + timedelta(days=1)
+ )
+ (row,) = [row for row in rows if row.user_id == enrollment.user_id]
+ assert row.copilot_cost_microdollars == 40
+ assert (
+ row.weekly_limit_microdollars == enrollment.offer.weekly_cost_limit == 100
+ )
+ assert row.percent_used == 40
+ finally:
+ await PlatformCostLog.prisma().delete_many(where={"userId": enrollment.user_id})
diff --git a/autogpt_platform/backend/backend/data/trial_usage_export_test.py b/autogpt_platform/backend/backend/data/trial_usage_export_test.py
new file mode 100644
index 0000000000..f2050c8ddb
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/trial_usage_export_test.py
@@ -0,0 +1,65 @@
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from backend.data.platform_cost import get_copilot_weekly_usage_for_export
+
+
+async def test_trial_export_uses_frozen_weekly_limit():
+ with (
+ patch(
+ "backend.data.platform_cost.query_raw_with_schema",
+ AsyncMock(
+ return_value=[
+ {
+ "user_id": "trial-user",
+ "user_email": "[email protected]",
+ "tier": "TRIAL",
+ "week_start": "2026-09-07T00:00:00Z",
+ "cost_microdollars": 500_000,
+ "trial_weekly_limit": 1_000_000,
+ }
+ ]
+ ),
+ ) as query,
+ patch(
+ "backend.copilot.rate_limit.get_tier_multipliers",
+ AsyncMock(return_value={"TRIAL": 0}),
+ ),
+ ):
+ rows = await get_copilot_weekly_usage_for_export(
+ datetime(2026, 9, 7, tzinfo=UTC), datetime(2026, 9, 8, tzinfo=UTC)
+ )
+ assert rows[0].weekly_limit_microdollars == 1_000_000
+ assert rows[0].percent_used == 50
+ assert "SubscriptionTrial" in query.call_args.args[0]
+
+
+async def test_trial_export_rejects_missing_accepted_limit():
+ with (
+ patch(
+ "backend.data.platform_cost.query_raw_with_schema",
+ AsyncMock(
+ return_value=[
+ {
+ "user_id": "trial-user",
+ "tier": "TRIAL",
+ "week_start": "2026-09-07T00:00:00Z",
+ "cost_microdollars": 500_000,
+ "trial_weekly_limit": None,
+ }
+ ]
+ ),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_tier_multipliers",
+ AsyncMock(return_value={"TRIAL": 0}),
+ ),
+ ):
+ with pytest.raises(ValueError, match="accepted weekly limit"):
+ await get_copilot_weekly_usage_for_export(
+ datetime(2026, 9, 7, tzinfo=UTC), datetime(2026, 9, 8, tzinfo=UTC)
+ )
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index a6b38a65d1..8137764072 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -34,6 +34,7 @@ from backend.data.model import (
)
from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
from backend.data.org_migration import ensure_personal_org
+from backend.data.subscription_trial import get_subscription_trial
from backend.util.cache import cached
from backend.util.encryption import JSONCryptor
from backend.util.exceptions import DatabaseError, NotFoundError
@@ -221,6 +222,11 @@ async def get_user_subscription_tier(user_id: str) -> SubscriptionTier:
user = await prisma.user.find_unique(where={"id": user_id})
if not user:
raise ValueError(f"User not found with ID: {user_id}")
+ if user.subscriptionTier == SubscriptionTier.TRIAL:
+ trial = await get_subscription_trial(user_id)
+ if trial is None or not trial.active:
+ return SubscriptionTier.NO_TIER
+ return SubscriptionTier(trial.offer.tier)
return user.subscriptionTier or SubscriptionTier.NO_TIER
diff --git a/autogpt_platform/backend/backend/notifications/lifecycle.py b/autogpt_platform/backend/backend/notifications/lifecycle.py
index dffdc764a8..cb63eb0a07 100644
--- a/autogpt_platform/backend/backend/notifications/lifecycle.py
+++ b/autogpt_platform/backend/backend/notifications/lifecycle.py
@@ -5,8 +5,7 @@ keep them from misfiring — first subscription only, first failed charge only,
the false→true flip rather than every subscription update — live here rather
than in the webhook router, so the webhook stays a dispatcher.
-There is deliberately no trial handler: the platform does not offer a trial, so
-`customer.subscription.trial_will_end` is not listened for.
+Trial enrollment and conversion notices are handled separately in `trial.py`.
"""
import logging
@@ -37,6 +36,7 @@ from backend.notifications.lifecycle_plan import (
plan_from_subscription,
)
from backend.notifications.queue import queue_audience_change, queue_notification_async
+from backend.notifications.trial import notify_trial, on_trial_subscription_updated
from backend.util.clients import get_database_manager_async_client
from backend.util.logging import TruncatedLogger
from backend.util.settings import Settings
@@ -100,6 +100,8 @@ async def on_checkout_completed(session: dict, subscription: dict) -> None:
"""First subscription → welcome email and the onboarding tour. A returning
customer is not greeted like a stranger: they go straight into the
changelog audience instead."""
+ if await notify_trial(subscription, "started"):
+ return
user = await _user_for(session.get("customer"))
if user is None:
return
@@ -211,6 +213,8 @@ async def on_payment_failed(invoice: dict) -> None:
async def on_subscription_updated(subscription: dict, previous: dict) -> None:
"""Only the cancel_at_period_end flip matters here; this event fires for
many unrelated changes."""
+ if await on_trial_subscription_updated(subscription, previous):
+ return
if "cancel_at_period_end" not in previous:
return
user = await _user_for(subscription.get("customer"))
@@ -273,6 +277,8 @@ async def on_subscription_updated(subscription: dict, previous: dict) -> None:
async def on_subscription_deleted(subscription: dict) -> None:
"""Two roads lead here — a cancellation reaching period end, and dunning
exhaustion — so the copy branches on which one the customer took."""
+ if await notify_trial(subscription, "ended"):
+ return
user = await _user_for(subscription.get("customer"))
if user is None:
return
diff --git a/autogpt_platform/backend/backend/notifications/notifications.py b/autogpt_platform/backend/backend/notifications/notifications.py
index f40407d191..a6da10b5b3 100644
--- a/autogpt_platform/backend/backend/notifications/notifications.py
+++ b/autogpt_platform/backend/backend/notifications/notifications.py
@@ -14,6 +14,7 @@ from datetime import date, datetime, timezone
from typing import Awaitable, Callable, Coroutine
import aio_pika
+from prisma.enums import NotificationType
from backend.data import rabbitmq
from backend.data.notifications import (
@@ -23,6 +24,7 @@ from backend.data.notifications import (
NotificationEventModel,
NotificationResult,
PassWorkEvent,
+ TrialUpdateData,
get_notif_data_type,
)
from backend.data.user import (
@@ -42,6 +44,7 @@ from backend.notifications.queue import (
create_notification_config,
queue_notification_async,
)
+from backend.notifications.trial import trial_notice_disposition
from backend.util.clients import get_database_manager_async_client
from backend.util.logging import TruncatedLogger
from backend.util.metrics import DiscordChannel, discord_send_alert
@@ -195,6 +198,16 @@ class NotificationManager(AppService):
if not event:
return False
+ if event.type == NotificationType.TRIAL_UPDATE:
+ data = TrialUpdateData.model_validate(event.data.model_dump())
+ disposition = await trial_notice_disposition(event.user_id, data)
+ if disposition == "obsolete":
+ return True
+ if disposition == "suppressed":
+ # Keep the claim: this queued message owns retries, not a new
+ # webhook publication. Exhausted retries use the shared DLQ.
+ raise RuntimeError("Trial notice is temporarily suppressed")
+
preference = await get_database_manager_async_client(
should_retry=False
).get_user_notification_preference(event.user_id)
diff --git a/autogpt_platform/backend/backend/notifications/preferences.py b/autogpt_platform/backend/backend/notifications/preferences.py
index 89850d6b10..2dab567c67 100644
--- a/autogpt_platform/backend/backend/notifications/preferences.py
+++ b/autogpt_platform/backend/backend/notifications/preferences.py
@@ -19,6 +19,7 @@ SERVICE_MESSAGES = frozenset(
NotificationType.SUBSCRIPTION_CANCELLED,
NotificationType.SUBSCRIPTION_RESUMED,
NotificationType.SUBSCRIPTION_ENDED,
+ NotificationType.TRIAL_UPDATE,
}
)
diff --git a/autogpt_platform/backend/backend/notifications/renderer_test.py b/autogpt_platform/backend/backend/notifications/renderer_test.py
index 71700a1210..ee331f40b1 100644
--- a/autogpt_platform/backend/backend/notifications/renderer_test.py
+++ b/autogpt_platform/backend/backend/notifications/renderer_test.py
@@ -27,6 +27,7 @@ from backend.data.notifications import (
SubscriptionPlan,
SubscriptionResumedData,
SubscriptionWelcomeData,
+ TrialUpdateData,
VerdictData,
supports_list_unsubscribe,
)
@@ -227,6 +228,14 @@ def test_the_preheader_still_comes_from_the_templates_second_line():
SERVICE_PAYLOADS = {
+ NotificationType.TRIAL_UPDATE: TrialUpdateData(
+ user_name="Sam",
+ plan=PLAN,
+ kind="started",
+ ends_label="17 Sep 2026",
+ onboarding_credit_amount=300,
+ offer_version="trial-v1",
+ ),
NotificationType.SUBSCRIPTION_WELCOME: WELCOME,
NotificationType.SUBSCRIPTION_ENDED: ENDED,
NotificationType.PAYMENT_FAILED: PaymentFailedData(
diff --git a/autogpt_platform/backend/backend/notifications/templates/trial.html.j2 b/autogpt_platform/backend/backend/notifications/templates/trial.html.j2
new file mode 100644
index 0000000000..80d9882830
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/trial.html.j2
@@ -0,0 +1,41 @@
+{%- import "_lifecycle_ui.j2" as ui with context -%}
+<!doctype html>
+<html lang="en">
+<head>{{ ui.head_block(subject) }}</head>
+<body style="margin:0; padding:0; background-color:#f1efe9; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader) }}
+{{ ui.page_open() }}
+{{ ui.masthead() }}
+<tr><td bgcolor="#ffffff" style="border-radius:0 0 14px 14px;">
+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+{% call ui.eyebrow() %}YOUR AUTOGPT TRIAL{% endcall %}
+{% call ui.headline() %}{{ subject }}{% endcall %}
+{% call ui.para() %}Hi {{ user_name }},{% endcall %}
+{% if kind == 'started' %}
+{% call ui.para() %}Your card is set up and your trial is ready. Pick a real task, connect the accounts it needs, and give AutoGPT a first run.{% endcall %}
+{% elif kind == 'ending' %}
+{% call ui.para() %}Your trial ends on {{ ends_label }}. Unless you cancel before then, your saved card will be charged for your {{ plan.name }} plan at {{ plan.price_display }}. Applicable tax may be added.{% endcall %}
+{% elif kind == 'canceled' %}
+{% call ui.para() %}Your trial will not convert to a paid plan. You can keep using your remaining trial allowance until {{ ends_label }}.{% endcall %}
+{% elif kind == 'resumed' %}
+{% call ui.para() %}Your cancellation has been removed. Your saved card will be charged for your {{ plan.name }} plan when the trial ends on {{ ends_label }}. Applicable tax may be added.{% endcall %}
+{% elif kind == 'converted' %}
+{% call ui.para() %}Your trial has ended, your payment is confirmed, and your {{ plan.name }} plan is active. You can view the invoice and manage future renewals in billing.{% endcall %}
+{% elif kind == 'payment_failed' %}
+{% call ui.para() %}We couldn't complete the payment after your trial. Your paid access is paused until payment succeeds. Open billing to update your card or complete any verification requested by your bank.{% endcall %}
+{% else %}
+{% call ui.para() %}Your trial access has ended. Your saved work remains in your account. Open billing to review your plan and payment status if you'd like to continue.{% endcall %}
+{% endif %}
+{{ ui.kvpanel([('Plan', plan.label, false), ('Trial ends', ends_label, true), ('Paid price', plan.price_display, true)]) }}
+{% if kind == 'started' %}
+{% call ui.para() %}Unless you cancel before {{ ends_label }}, your plan starts automatically at {{ plan.price_display }}. Applicable tax may be added. Trial access is subject to your trial allowance.{% endcall %}
+{{ ui.cta('Start using AutoGPT', urls.dashboard) }}
+{% endif %}
+{{ ui.cta('Manage trial and billing', urls.billing) }}
+{{ ui.close_row('Review your plan or cancel in billing settings.', 'Billing settings', urls.billing) }}
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{{ ui.legal_footer('This is a service message about the AutoGPT account for ' ~ user_email ~ '.', 'Email preferences', urls.prefs, discord=false) }}
+</td></tr></table>
+</body></html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2
new file mode 100644
index 0000000000..4c96e85ef8
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2
@@ -0,0 +1,15 @@
+{% if kind == 'started' %}Your AutoGPT trial has started
+Your trial ends {{ ends_label }}. Review your plan and next steps.
+{% elif kind == 'ending' %}Your AutoGPT trial ends {{ ends_label }}
+Your {{ plan.name }} plan starts at {{ plan.price_display }} unless you cancel.
+{% elif kind == 'canceled' %}Your AutoGPT trial cancellation is confirmed
+Your trial will not convert to a paid plan.
+{% elif kind == 'resumed' %}Your AutoGPT trial will continue into your plan
+Your {{ plan.name }} plan starts {{ ends_label }} at {{ plan.price_display }}.
+{% elif kind == 'converted' %}Your AutoGPT {{ plan.name }} plan is active
+Your trial has ended and your payment is confirmed.
+{% elif kind == 'payment_failed' %}Action needed: your AutoGPT trial payment
+Your trial has ended. Update your payment method to activate your plan.
+{% else %}Your AutoGPT trial has ended
+Review your billing settings to continue using AutoGPT.
+{% endif %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/trial.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/trial.txt.j2
new file mode 100644
index 0000000000..4507b37bad
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/trial.txt.j2
@@ -0,0 +1,29 @@
+{{ subject }}
+
+Hi {{ user_name }},
+
+{% if kind == 'started' %}
+Your card is set up and your trial is ready. Pick a real task and give AutoGPT a first run.
+Unless you cancel before {{ ends_label }}, your plan starts automatically at {{ plan.price_display }}. Applicable tax may be added. Trial access is subject to your trial allowance.
+{% elif kind == 'ending' %}
+Your trial ends {{ ends_label }}. Unless you cancel before then, your saved card will be charged {{ plan.price_display }} for your {{ plan.name }} plan. Applicable tax may be added.
+{% elif kind == 'canceled' %}
+Your trial will not convert to a paid plan. You can keep using your remaining trial allowance until {{ ends_label }}.
+{% elif kind == 'resumed' %}
+Your cancellation has been removed. Your saved card will be charged for your {{ plan.name }} plan when the trial ends {{ ends_label }}. Applicable tax may be added.
+{% elif kind == 'converted' %}
+Your trial has ended, your payment is confirmed, and your {{ plan.name }} plan is active. View your invoice and manage future renewals in billing.
+{% elif kind == 'payment_failed' %}
+We couldn't complete the payment after your trial. Your paid access is paused until payment succeeds. Open billing to update your card or complete verification requested by your bank.
+{% else %}
+Your trial access has ended. Your saved work remains in your account. Open billing to review your plan and payment status if you'd like to continue.
+{% endif %}
+
+Plan: {{ plan.label }}
+Trial ends: {{ ends_label }}
+Paid price: {{ plan.price_display }}
+
+Manage trial and billing: {{ urls.billing }}
+
+This is a service message about the AutoGPT account for {{ user_email }}.
+Email preferences: {{ urls.prefs }}
diff --git a/autogpt_platform/backend/backend/notifications/trial.py b/autogpt_platform/backend/backend/notifications/trial.py
new file mode 100644
index 0000000000..62afe0d1ca
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/trial.py
@@ -0,0 +1,250 @@
+"""Trial notices use accepted terms and current subscription state."""
+
+import logging
+from datetime import UTC, datetime, timedelta
+from typing import Literal
+
+import stripe
+from prisma.enums import NotificationType
+
+from backend.data.credit import (
+ _invoice_subscription_id,
+ _invoice_subscription_metadata,
+ _track_billing_event,
+ sync_subscription_from_stripe,
+)
+from backend.data.db_accessors import credit_db, user_db
+from backend.data.notifications import (
+ NotificationEventModel,
+ SubscriptionPlan,
+ TrialUpdateData,
+)
+from backend.data.stripe_client import stripe_call
+from backend.data.subscription_trial import TrialState
+from backend.notifications.dedupe import claim_once, release_claim
+from backend.notifications.lifecycle_plan import format_amount
+from backend.notifications.queue import queue_notification_async
+
+logger = logging.getLogger(__name__)
+TRIAL_REMINDER_WINDOW = timedelta(days=3)
+
+TrialNoticeKind = Literal[
+ "started", "ending", "canceled", "resumed", "ended", "converted", "payment_failed"
+]
+
+
+async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:
+ metadata = subscription.get("metadata") or {}
+ if not metadata.get("trial_enrollment_id"):
+ return False
+ current = dict(
+ await stripe_call(stripe.Subscription.retrieve_async, subscription["id"])
+ )
+ user_id = (current.get("metadata") or {}).get("user_id")
+ if not user_id:
+ raise ValueError("Trial notification has no user identity")
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None:
+ raise ValueError("Trial notification has no matching enrollment")
+ if not _owns_subscription(trial, current):
+ raise ValueError("Trial notification ownership does not match the enrollment")
+ attempt = (current.get("metadata") or {}).get("trial_checkout_attempt", "")
+ if attempt.isdecimal() and int(attempt) < trial.checkout_attempt:
+ return True
+ if attempt != str(trial.checkout_attempt) or trial.subscription_id != current["id"]:
+ raise ValueError(
+ "Trial notification does not match the current checkout attempt"
+ )
+ if trial.consumed_at is None:
+ return True
+ if trial.converted_at is not None and kind in (
+ "ended",
+ "canceled",
+ "resumed",
+ "payment_failed",
+ ):
+ return False
+ if not _notice_applies(trial, kind, current):
+ return True
+ user = await user_db().get_user_by_id(user_id)
+ data = trial_notice_data(trial, kind, user.name or "there")
+ claim = trial_notice_key(trial, kind)
+ data.notice_key = claim
+ if not await claim_once(claim):
+ return True
+ try:
+ result = await queue_notification_async(
+ NotificationEventModel[TrialUpdateData](
+ user_id=user_id, type=NotificationType.TRIAL_UPDATE, data=data
+ )
+ )
+ if not result.success:
+ raise RuntimeError(f"Could not queue trial notice: {result.message}")
+ except Exception:
+ await release_claim(claim)
+ raise
+ _track_billing_event(
+ f"subscription_trial_{kind}",
+ user_id,
+ {
+ "trial_id": trial.id,
+ "trial_offer_version": trial.offer.version,
+ "subscription_tier": trial.offer.tier,
+ "billing_cycle": trial.offer.billing_cycle,
+ "trial_duration_days": trial.offer.duration_days,
+ },
+ )
+ return True
+
+
+async def on_trial_invoice(invoice: dict, *, paid: bool) -> bool:
+ if not _invoice_subscription_metadata(invoice).get("trial_enrollment_id"):
+ return False
+ sub_id = _invoice_subscription_id(invoice)
+ if not sub_id:
+ return False
+ subscription = dict(await stripe_call(stripe.Subscription.retrieve_async, sub_id))
+ if not (subscription.get("metadata") or {}).get("trial_enrollment_id"):
+ return False
+ await sync_subscription_from_stripe(subscription)
+ user_id = (subscription.get("metadata") or {}).get("user_id")
+ if not user_id:
+ raise ValueError("Trial invoice has no user identity")
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None:
+ raise ValueError("Trial invoice has no matching enrollment")
+ if paid and trial.converted_at:
+ if invoice.get("id") != trial.conversion_invoice_id:
+ return False
+ await notify_trial(subscription, "converted")
+ return True
+ if not paid and trial.converted_at is None:
+ await notify_trial(subscription, "payment_failed")
+ return True
+ return False
+
+
+async def trial_notice_disposition(
+ user_id: str, data: TrialUpdateData
+) -> Literal["current", "suppressed", "obsolete"]:
+ if not data.notice_key:
+ return "obsolete"
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None or trial.subscription_id is None:
+ return "obsolete"
+ current = dict(
+ await stripe_call(stripe.Subscription.retrieve_async, trial.subscription_id)
+ )
+ if (
+ not _owns_subscription(trial, current)
+ or current.get("id") != trial.subscription_id
+ ):
+ return "obsolete"
+ await credit_db().sync_subscription_from_stripe(current)
+ trial = await credit_db().get_subscription_trial(user_id)
+ if (
+ trial is None
+ or trial.consumed_at is None
+ or trial.ends_at is None
+ or trial.subscription_id != current.get("id")
+ or (current.get("metadata") or {}).get("trial_checkout_attempt")
+ != str(trial.checkout_attempt)
+ ):
+ return "obsolete"
+ if data.notice_key != trial_notice_key(trial, data.kind):
+ return "obsolete"
+ expected = trial_notice_data(trial, data.kind, data.user_name)
+ if data.model_copy(update={"notice_key": None}) != expected:
+ return "obsolete"
+ if trial.status != current.get("status") or trial.cancel_at_period_end != bool(
+ current.get("cancel_at_period_end")
+ ):
+ return "suppressed"
+ return "current" if _notice_applies(trial, data.kind, current) else "suppressed"
+
+
+def _owns_subscription(trial: TrialState, current: dict) -> bool:
+ metadata = current.get("metadata") or {}
+ return (
+ trial.customer_id == current.get("customer")
+ and trial.id == metadata.get("trial_enrollment_id")
+ and trial.user_id == metadata.get("user_id")
+ )
+
+
+async def on_trial_subscription_updated(subscription: dict, previous: dict) -> bool:
+ if not (subscription.get("metadata") or {}).get("trial_enrollment_id"):
+ return False
+ user_id = (subscription.get("metadata") or {}).get("user_id")
+ if not user_id:
+ raise ValueError("Trial update has no user identity")
+ trial = await credit_db().get_subscription_trial(user_id)
+ if trial is None or trial.converted_at is not None:
+ return False
+ if "cancel_at_period_end" in previous:
+ kind = "canceled" if trial.cancel_at_period_end else "resumed"
+ await notify_trial(subscription, kind)
+ return True
+
+
+def trial_notice_key(trial: TrialState, kind: TrialNoticeKind) -> str:
+ key = f"trial:{trial.id}:{kind}"
+ if kind in ("canceled", "resumed"):
+ return f"{key}:{trial.notification_revision}"
+ if kind == "ending":
+ if trial.ends_at is None:
+ raise ValueError("Trial reminder requires an end date")
+ return f"{key}:{int(trial.ends_at.timestamp())}"
+ if kind == "converted":
+ if not trial.conversion_invoice_id:
+ raise ValueError("Trial conversion notice requires its invoice")
+ return f"{key}:{trial.conversion_invoice_id}"
+ return key
+
+
+def trial_notice_data(
+ trial: TrialState, kind: TrialNoticeKind, name: str
+) -> TrialUpdateData:
+ if trial.ends_at is None:
+ raise ValueError("Cannot send a trial notice without the accepted end date")
+ offer = trial.offer
+ cycle_noun = "month" if offer.billing_cycle == "monthly" else "year"
+ return TrialUpdateData(
+ user_name=name,
+ kind=kind,
+ plan=SubscriptionPlan(
+ name=offer.tier.title(),
+ cycle=offer.billing_cycle,
+ cycle_noun=cycle_noun,
+ label=f"{offer.tier.title()} — {offer.billing_cycle}",
+ price_display=f"{format_amount(offer.unit_amount, offer.currency)} {offer.currency.upper()} / {cycle_noun}",
+ ),
+ ends_label=trial.ends_at.astimezone(UTC).strftime("%d %b %Y at %H:%M UTC"),
+ onboarding_credit_amount=offer.onboarding_credit_amount,
+ offer_version=offer.version,
+ )
+
+
+def _notice_applies(trial: TrialState, kind: TrialNoticeKind, current: dict) -> bool:
+ status = current.get("status")
+ trial_end = current.get("trial_end") or 0
+ now = datetime.now(UTC).timestamp()
+ in_trial = status == "trialing" and trial_end > now
+ if kind == "ending" and trial_end > now + TRIAL_REMINDER_WINDOW.total_seconds():
+ return False
+ if kind in ("started", "ending", "resumed"):
+ return (
+ in_trial
+ and trial.card_verified_at is not None
+ and not current.get("cancel_at_period_end")
+ )
+ if kind == "canceled":
+ return in_trial and bool(current.get("cancel_at_period_end"))
+ if kind == "converted":
+ return status == "active" and trial.converted_at is not None
+ if kind == "payment_failed":
+ return (
+ status in ("past_due", "unpaid", "incomplete")
+ and trial.converted_at is None
+ )
+ return status in ("canceled", "unpaid", "paused") and trial.converted_at is None
diff --git a/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.py b/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.py
new file mode 100644
index 0000000000..839c072b6a
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.py
@@ -0,0 +1,168 @@
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.notifications import trial as notices
+from backend.notifications import trial_test as fixtures
+
+trial = fixtures.trial
+
+
+def subscription(trial):
+ return {
+ "id": trial.subscription_id,
+ "customer": trial.customer_id,
+ "status": trial.status,
+ "trial_end": int(trial.ends_at.timestamp()),
+ "cancel_at_period_end": trial.cancel_at_period_end,
+ "metadata": {
+ "user_id": trial.user_id,
+ "trial_enrollment_id": trial.id,
+ "trial_checkout_attempt": str(trial.checkout_attempt),
+ },
+ }
+
+
+ "changes,expected",
+ [
+ ({"card_verified_at": None}, "suppressed"),
+ ({"ends_at": datetime.now(UTC) + timedelta(days=8)}, "obsolete"),
+ ({"notification_revision": 4}, "obsolete"),
+ ],
+)
+async def test_delivery_reconciles_and_suppresses_outdated_notice(
+ trial, changes, expected
+):
+ trial.notification_revision = 2
+ data = notices.trial_notice_data(trial, "resumed", "Sam").model_copy(
+ update={"notice_key": notices.trial_notice_key(trial, "resumed")}
+ )
+ fresh = trial.model_copy(update=changes)
+ database = MagicMock(
+ get_subscription_trial=AsyncMock(side_effect=[trial, fresh]),
+ sync_subscription_from_stripe=AsyncMock(),
+ )
+ raw = subscription(fresh)
+ with (
+ patch.object(notices, "credit_db", return_value=database),
+ patch.object(notices, "stripe_call", AsyncMock(return_value=raw)),
+ ):
+ assert await notices.trial_notice_disposition(trial.user_id, data) == expected
+ database.sync_subscription_from_stripe.assert_awaited_once_with(raw)
+
+
+async def test_old_checkout_attempt_is_acknowledged_without_a_notice(trial):
+ stale = subscription(trial)
+ trial = trial.model_copy(
+ update={"checkout_attempt": 1, "subscription_id": "sub_new"}
+ )
+ database = MagicMock(get_subscription_trial=AsyncMock(return_value=trial))
+ with (
+ patch.object(notices, "credit_db", return_value=database),
+ patch.object(notices, "stripe_call", AsyncMock(return_value=stale)),
+ patch.object(notices, "queue_notification_async", AsyncMock()) as queue,
+ ):
+ assert await notices.notify_trial(stale, "started")
+ queue.assert_not_awaited()
+
+
+async def test_unconsumed_checkout_without_end_date_does_not_publish(trial):
+ raw = subscription(trial)
+ raw["trial_end"] = None
+ pending = trial.model_copy(update={"consumed_at": None, "ends_at": None})
+ database = MagicMock(get_subscription_trial=AsyncMock(return_value=pending))
+ with (
+ patch.object(notices, "credit_db", return_value=database),
+ patch.object(notices, "stripe_call", AsyncMock(return_value=raw)),
+ patch.object(notices, "queue_notification_async", AsyncMock()) as queue,
+ ):
+ assert await notices.notify_trial(raw, "started")
+ queue.assert_not_awaited()
+
+
+ "kind,changes",
+ [
+ ("started", {}),
+ ("ending", {"ends_at": datetime.now(UTC) + timedelta(days=2)}),
+ ("canceled", {"cancel_at_period_end": True, "notification_revision": 1}),
+ ("resumed", {"notification_revision": 2}),
+ ("ended", {"status": "canceled"}),
+ ("payment_failed", {"status": "past_due"}),
+ (
+ "converted",
+ {
+ "status": "active",
+ "converted_at": datetime.now(UTC),
+ "conversion_invoice_id": "in_first",
+ },
+ ),
+ ],
+)
+async def test_current_notice_survives_authoritative_refresh(trial, kind, changes):
+ trial = trial.model_copy(update=changes)
+ data = notices.trial_notice_data(trial, kind, "Sam")
+ data.notice_key = notices.trial_notice_key(trial, kind)
+ database = MagicMock(
+ get_subscription_trial=AsyncMock(return_value=trial),
+ sync_subscription_from_stripe=AsyncMock(),
+ )
+ raw = subscription(trial)
+ with (
+ patch.object(notices, "credit_db", return_value=database),
+ patch.object(notices, "stripe_call", AsyncMock(return_value=raw)),
+ ):
+ assert await notices.trial_notice_disposition(trial.user_id, data) == "current"
+ database.sync_subscription_from_stripe.assert_awaited_once_with(raw)
+
+
+async def test_unidentified_legacy_payload_cannot_bypass_freshness_check(trial):
+ data = notices.trial_notice_data(trial, "started", "Sam")
+ with patch.object(notices, "credit_db") as database:
+ assert await notices.trial_notice_disposition(trial.user_id, data) == "obsolete"
+ database.assert_not_called()
+
+
+async def test_state_change_during_refresh_does_not_send_old_welcome(trial):
+ data = notices.trial_notice_data(trial, "started", "Sam")
+ data.notice_key = notices.trial_notice_key(trial, "started")
+ fresh = trial.model_copy(update={"cancel_at_period_end": True})
+ database = MagicMock(
+ get_subscription_trial=AsyncMock(side_effect=[trial, fresh]),
+ sync_subscription_from_stripe=AsyncMock(),
+ )
+ with (
+ patch.object(notices, "credit_db", return_value=database),
+ patch.object(
+ notices, "stripe_call", AsyncMock(return_value=subscription(trial))
+ ),
+ ):
+ assert (
+ await notices.trial_notice_disposition(trial.user_id, data) == "suppressed"
+ )
+
+
+async def test_delivery_marks_changed_terms_obsolete_without_sending(trial):
+ data = notices.trial_notice_data(trial, "started", "Sam")
+ data.notice_key = notices.trial_notice_key(trial, "started")
+ data.ends_label = "Obsolete end date"
+ database = MagicMock(
+ get_subscription_trial=AsyncMock(return_value=trial),
+ sync_subscription_from_stripe=AsyncMock(),
+ )
+ with (
+ patch.object(notices, "credit_db", return_value=database),
+ patch.object(
+ notices, "stripe_call", AsyncMock(return_value=subscription(trial))
+ ),
+ ):
+ assert await notices.trial_notice_disposition(trial.user_id, data) == "obsolete"
diff --git a/autogpt_platform/backend/backend/notifications/trial_shared_delivery_test.py b/autogpt_platform/backend/backend/notifications/trial_shared_delivery_test.py
new file mode 100644
index 0000000000..3d720a9b4b
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/trial_shared_delivery_test.py
@@ -0,0 +1,135 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from prisma.enums import NotificationType
+
+from backend.data.notifications import NotificationEventModel, TrialUpdateData
+from backend.notifications import notifications as delivery
+from backend.notifications import trial_test as fixtures
+from backend.notifications.queue import create_notification_config, get_routing_key
+from backend.notifications.trial import trial_notice_data, trial_notice_key
+
+trial = fixtures.trial
+
+
+ "current,verified,fail",
+ [
+ (True, True, False),
+ (False, True, False),
+ (True, False, False),
+ (True, True, True),
+ ],
+)
+async def test_trial_mail_uses_shared_sender_and_preserves_delivery_gates(
+ trial, db_client, current, verified, fail
+):
+ data = trial_notice_data(trial, "started", "Sam")
+ data.notice_key = trial_notice_key(trial, "started")
+ event = NotificationEventModel[TrialUpdateData](
+ user_id=trial.user_id, type=NotificationType.TRIAL_UPDATE, data=data
+ )
+ manager = delivery.NotificationManager.__new__(delivery.NotificationManager)
+ sender = AsyncMock(
+ side_effect=RuntimeError("provider unavailable") if fail else None
+ )
+ manager.email_sender = MagicMock(send_notification=sender)
+ db_client.get_user_email_verification.return_value = verified
+ db_client.get_user_notification_preference.return_value.daily_limit = 0
+ with (
+ patch.object(
+ delivery,
+ "trial_notice_disposition",
+ AsyncMock(return_value="current" if current else "obsolete"),
+ ),
+ patch.object(
+ delivery, "get_database_manager_async_client", return_value=db_client
+ ),
+ patch.object(
+ delivery,
+ "generate_unsubscribe_link",
+ return_value="https://example.com/prefs",
+ ),
+ patch.object(
+ delivery,
+ "generate_preference_link",
+ return_value="https://example.com/prefs",
+ ),
+ patch.object(
+ delivery, "claim_daily_send", AsyncMock(return_value=False)
+ ) as cap,
+ ):
+ if fail:
+ with pytest.raises(RuntimeError, match="provider unavailable"):
+ await manager._process_user_notification(event.model_dump_json())
+ else:
+ assert await manager._process_user_notification(event.model_dump_json())
+ assert sender.await_count == int(current and verified)
+ cap.assert_not_awaited()
+
+
+def test_trial_notices_have_no_separate_queue():
+ assert (
+ get_routing_key(NotificationType.TRIAL_UPDATE)
+ == "notification.user.TRIAL_UPDATE"
+ )
+ assert all(
+ "trial" not in queue.name for queue in create_notification_config().queues
+ )
+
+
[email protected]("recovers", [True, False])
+async def test_suppressed_trial_mail_uses_shared_retry_and_dlq(
+ trial, db_client, recovers
+):
+ data = trial_notice_data(trial, "started", "Sam")
+ data.notice_key = trial_notice_key(trial, "started")
+ event = NotificationEventModel[TrialUpdateData](
+ user_id=trial.user_id, type=NotificationType.TRIAL_UPDATE, data=data
+ )
+ manager = delivery.NotificationManager.__new__(delivery.NotificationManager)
+ sender = AsyncMock()
+ manager.email_sender = MagicMock(send_notification=sender)
+ message = MagicMock(
+ body=event.model_dump_json().encode(), ack=AsyncMock(), reject=AsyncMock()
+ )
+ dispositions = (
+ ["suppressed", "current"]
+ if recovers
+ else ["suppressed"] * delivery.MAX_CONSUMER_RETRY_ATTEMPTS
+ )
+ with (
+ patch.object(
+ delivery, "trial_notice_disposition", AsyncMock(side_effect=dispositions)
+ ),
+ patch.object(
+ delivery, "get_database_manager_async_client", return_value=db_client
+ ),
+ patch.object(
+ delivery,
+ "generate_unsubscribe_link",
+ return_value="https://example.com/prefs",
+ ),
+ patch.object(
+ delivery,
+ "generate_preference_link",
+ return_value="https://example.com/prefs",
+ ),
+ patch.object(delivery.asyncio, "sleep", AsyncMock()) as sleep,
+ patch("backend.notifications.trial.release_claim", AsyncMock()) as release,
+ patch(
+ "backend.notifications.trial.queue_notification_async", AsyncMock()
+ ) as publish,
+ ):
+ await manager._process_message_with_retry(
+ message, manager._process_user_notification, "user_notifications_v3"
+ )
+ assert sender.await_count == int(recovers)
+ assert message.ack.await_count == int(recovers)
+ if not recovers:
+ message.reject.assert_awaited_once_with(requeue=False)
+ assert sleep.await_count > 0
+ release.assert_not_awaited()
+ publish.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/notifications/trial_test.py b/autogpt_platform/backend/backend/notifications/trial_test.py
new file mode 100644
index 0000000000..b86e939e86
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/trial_test.py
@@ -0,0 +1,248 @@
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from prisma.enums import NotificationType
+
+from backend.data.notifications import NotificationResult
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+from backend.notifications import trial as notices
+from backend.notifications.renderer import EmailUrls, render
+
+
+def trial() -> TrialState:
+ now = datetime.now(UTC)
+ return TrialState(
+ id="trial-1",
+ user_id="user-1",
+ customer_id="cus_1",
+ offer=AcceptedTrialOffer(
+ version="offer-v1",
+ new_users_from=now - timedelta(days=1),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_pro",
+ unit_amount=2000,
+ currency="usd",
+ ),
+ checkout_session_id="cs_1",
+ subscription_id="sub_1",
+ checkout_attempt=0,
+ success_url="https://example.com",
+ cancel_url="https://example.com",
+ checkout_metadata={},
+ status="trialing",
+ card_verified_at=now,
+ started_at=now,
+ ends_at=now + timedelta(days=7),
+ consumed_at=now,
+ converted_at=None,
+ cancel_at_period_end=False,
+ cost_microdollars=0,
+ )
+
+
+def urls() -> EmailUrls:
+ return EmailUrls(
+ dashboard="https://example.com/library",
+ settings="https://example.com/settings",
+ unsubscribe="https://example.com/unsubscribe",
+ attention="https://example.com/attention",
+ billing="https://example.com/settings/billing",
+ prefs="https://example.com/prefs",
+ marketplace="https://example.com/marketplace",
+ docs="https://example.com/docs",
+ discord="https://example.com/discord",
+ )
+
+
+ "kind",
+ [
+ "started",
+ "ending",
+ "canceled",
+ "resumed",
+ "ended",
+ "converted",
+ "payment_failed",
+ ],
+)
+def test_all_trial_notices_render_exact_terms_and_billing_link(trial, urls, kind):
+ data = notices.trial_notice_data(trial, kind, "Sam")
+ email = render(NotificationType.TRIAL_UPDATE, data, "[email protected]", urls)
+ assert email.subject and email.preheader
+ for body in (email.html, email.text):
+ assert "$20.00 USD / month" in body
+ assert data.ends_label in body
+ assert urls.billing in body
+ if kind == "payment_failed":
+ assert "paid access is paused" in email.text
+ assert "keep running normally" not in email.html
+ if kind == "canceled":
+ assert "will not convert" in email.text
+
+
+def test_trial_email_escapes_user_supplied_name(trial, urls):
+ data = notices.trial_notice_data(trial, "started", "<script>alert(1)</script>")
+ email = render(NotificationType.TRIAL_UPDATE, data, "[email protected]", urls)
+ assert "<script>" not in email.html
+ assert "&lt;script&gt;" in email.html
+
+
+def test_trial_welcome_does_not_advertise_onboarding_credits(trial, urls):
+ data = notices.trial_notice_data(trial, "started", "Sam")
+ email = render(NotificationType.TRIAL_UPDATE, data, "[email protected]", urls)
+ for body in (email.html, email.text):
+ assert "onboarding credits" not in body
+ assert "automation credits" not in body
+
+
[email protected]("outcome", ["sent", "duplicate", "publish_failed", "raised"])
+async def test_notice_uses_shared_notification_queue(trial, outcome):
+ raw = {
+ "id": trial.subscription_id,
+ "customer": trial.customer_id,
+ "status": "trialing",
+ "trial_end": int(trial.ends_at.timestamp()),
+ "metadata": {
+ "trial_enrollment_id": trial.id,
+ "user_id": trial.user_id,
+ "trial_checkout_attempt": str(trial.checkout_attempt),
+ },
+ }
+ queue = AsyncMock(
+ return_value=NotificationResult(success=outcome != "publish_failed"),
+ side_effect=RuntimeError("queue unavailable") if outcome == "raised" else None,
+ )
+ with (
+ patch.object(notices, "stripe_call", AsyncMock(return_value=raw)),
+ patch.object(
+ notices,
+ "credit_db",
+ return_value=MagicMock(
+ get_subscription_trial=AsyncMock(return_value=trial)
+ ),
+ ),
+ patch.object(
+ notices,
+ "user_db",
+ return_value=MagicMock(
+ get_user_by_id=AsyncMock(return_value=SimpleNamespace(name="Sam"))
+ ),
+ ),
+ patch.object(
+ notices, "claim_once", AsyncMock(return_value=outcome != "duplicate")
+ ),
+ patch.object(notices, "release_claim", AsyncMock()) as release,
+ patch.object(notices, "queue_notification_async", queue),
+ patch.object(notices, "_track_billing_event") as track,
+ ):
+ if outcome in ("publish_failed", "raised"):
+ with pytest.raises(RuntimeError):
+ await notices.notify_trial(raw, "started")
+ else:
+ assert await notices.notify_trial(raw, "started")
+ if outcome == "duplicate":
+ queue.assert_not_awaited()
+ else:
+ queue.assert_awaited_once()
+ event = queue.await_args.args[0]
+ assert event.type == NotificationType.TRIAL_UPDATE
+ assert event.user_id == trial.user_id
+ assert event.data.notice_key == notices.trial_notice_key(trial, "started")
+ if outcome in ("publish_failed", "raised"):
+ release.assert_awaited_once_with(notices.trial_notice_key(trial, "started"))
+ else:
+ release.assert_not_awaited()
+ assert track.call_count == int(outcome == "sent")
+
+
+def test_canceled_trial_suppresses_late_ending_reminder(trial):
+ raw = {
+ "status": "trialing",
+ "trial_end": int(trial.ends_at.timestamp()),
+ "cancel_at_period_end": True,
+ }
+ assert not notices._notice_applies(trial, "ending", raw)
+ assert notices._notice_applies(trial, "canceled", raw)
+
+
+def test_ending_reminder_waits_for_current_reminder_window(trial):
+ raw = {
+ "status": "trialing",
+ "trial_end": int((datetime.now(UTC) + timedelta(days=7)).timestamp()),
+ "cancel_at_period_end": False,
+ }
+ assert not notices._notice_applies(trial, "ending", raw)
+
+
+def test_failed_conversion_suppresses_paid_confirmation(trial):
+ assert not notices._notice_applies(trial, "converted", {"status": "past_due"})
+
+
+def test_cancellation_notice_key_changes_only_with_durable_revision(trial):
+ first = notices.trial_notice_key(trial, "canceled")
+ assert notices.trial_notice_key(trial, "canceled") == first
+ trial.notification_revision += 1
+ assert notices.trial_notice_key(trial, "canceled") != first
+ assert notices.trial_notice_key(trial, "resumed") != notices.trial_notice_key(
+ trial, "canceled"
+ )
+
+
+ "invoice_id,expected", [("in_first", True), ("in_renewal", False)]
+)
+async def test_only_conversion_invoice_triggers_trial_confirmation(
+ trial, invoice_id, expected
+):
+ trial = trial.model_copy(
+ update={"converted_at": datetime.now(UTC), "conversion_invoice_id": "in_first"}
+ )
+ subscription = {
+ "id": "sub_1",
+ "customer": "cus_1",
+ "metadata": {
+ "user_id": trial.user_id,
+ "trial_enrollment_id": trial.id,
+ "trial_checkout_attempt": "0",
+ },
+ }
+ invoice = {
+ "id": invoice_id,
+ "subscription": "sub_1",
+ "subscription_details": {"metadata": subscription["metadata"]},
+ }
+ with (
+ patch.object(
+ notices.stripe.Subscription,
+ "retrieve_async",
+ AsyncMock(return_value=subscription),
+ ),
+ patch.object(notices, "sync_subscription_from_stripe", AsyncMock()),
+ patch.object(
+ notices,
+ "credit_db",
+ return_value=MagicMock(
+ get_subscription_trial=AsyncMock(return_value=trial)
+ ),
+ ),
+ patch.object(notices, "notify_trial", AsyncMock()) as notify,
+ ):
+ assert await notices.on_trial_invoice(invoice, paid=True) is expected
+ if expected:
+ notify.assert_awaited_once_with(subscription, "converted")
+ else:
+ notify.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/util/entitlements.py b/autogpt_platform/backend/backend/util/entitlements.py
index e62141bfb3..cce0c8fd88 100644
--- a/autogpt_platform/backend/backend/util/entitlements.py
+++ b/autogpt_platform/backend/backend/util/entitlements.py
@@ -39,6 +39,7 @@ ENTITLEMENT_POLICIES: Mapping[Entitlement, EntitlementPolicy] = MappingProxyType
_TIER_ORDER = (
SubscriptionTier.NO_TIER,
+ SubscriptionTier.TRIAL,
SubscriptionTier.BASIC,
SubscriptionTier.PRO,
SubscriptionTier.MAX,
diff --git a/autogpt_platform/backend/backend/util/entitlements_test.py b/autogpt_platform/backend/backend/util/entitlements_test.py
index 878ff75e54..bd6412b4a7 100644
--- a/autogpt_platform/backend/backend/util/entitlements_test.py
+++ b/autogpt_platform/backend/backend/util/entitlements_test.py
@@ -37,6 +37,7 @@ async def test_local_entitlement_bypasses_database_manager():
("tier", "allowed"),
[
(SubscriptionTier.NO_TIER, False),
+ (SubscriptionTier.TRIAL, False),
(SubscriptionTier.BASIC, False),
(SubscriptionTier.PRO, False),
(SubscriptionTier.MAX, True),
@@ -154,3 +155,7 @@ def test_codex_policy_is_centralized_as_max_plus_with_local_access():
assert policy.minimum_tier == SubscriptionTier.MAX
assert policy.allow_local is True
+
+
+def test_tier_order_covers_all_persisted_tiers():
+ assert set(entitlements._TIER_ORDER) == set(SubscriptionTier)
diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.py
index 7cc689ae39..8ebeeaa0b7 100644
--- a/autogpt_platform/backend/backend/util/feature_flag.py
+++ b/autogpt_platform/backend/backend/util/feature_flag.py
@@ -63,6 +63,7 @@ class Flag(str, Enum):
COPILOT_TIER_MULTIPLIERS = "copilot-tier-multipliers"
COPILOT_TIER_WORKSPACE_STORAGE_LIMITS = "copilot-tier-workspace-storage-limits"
COPILOT_TIER_STRIPE_PRICES = "copilot-tier-stripe-prices"
+ CARD_REQUIRED_TRIAL_OFFER = "card-required-trial-offer"
GRAPHITI_MEMORY = "graphiti-memory"
# Gates AutoPilot voice mode end-to-end. The speech endpoint 404s when
diff --git a/autogpt_platform/backend/migrations/20260904210000_add_card_required_trials/migration.sql b/autogpt_platform/backend/migrations/20260904210000_add_card_required_trials/migration.sql
new file mode 100644
index 0000000000..9b53f3ead3
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260904210000_add_card_required_trials/migration.sql
@@ -0,0 +1,36 @@
+ALTER TYPE "SubscriptionTier" ADD VALUE 'TRIAL';
+ALTER TYPE "NotificationType" ADD VALUE 'TRIAL_UPDATE';
+
+CREATE TABLE "SubscriptionTrial" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "offer" JSONB NOT NULL,
+ "stripeCustomerId" TEXT NOT NULL,
+ "stripeCheckoutSessionId" TEXT,
+ "stripeSubscriptionId" TEXT,
+ "stripeConversionInvoiceId" TEXT,
+ "checkoutAttempt" INTEGER NOT NULL DEFAULT 0,
+ "checkoutSuccessUrl" TEXT NOT NULL,
+ "checkoutCancelUrl" TEXT NOT NULL,
+ "checkoutMetadata" JSONB NOT NULL DEFAULT '{}',
+ "status" TEXT NOT NULL DEFAULT 'checkout_pending',
+ "cardVerifiedAt" TIMESTAMP(3),
+ "startedAt" TIMESTAMP(3),
+ "endsAt" TIMESTAMP(3),
+ "consumedAt" TIMESTAMP(3),
+ "convertedAt" TIMESTAMP(3),
+ "cancelAtPeriodEnd" BOOLEAN NOT NULL DEFAULT false,
+ "costMicrodollars" BIGINT NOT NULL DEFAULT 0,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ CONSTRAINT "SubscriptionTrial_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "SubscriptionTrial_cost_nonnegative" CHECK ("costMicrodollars" >= 0)
+);
+
+CREATE UNIQUE INDEX "SubscriptionTrial_userId_key" ON "SubscriptionTrial"("userId");
+CREATE UNIQUE INDEX "SubscriptionTrial_stripeCheckoutSessionId_key" ON "SubscriptionTrial"("stripeCheckoutSessionId");
+CREATE UNIQUE INDEX "SubscriptionTrial_stripeSubscriptionId_key" ON "SubscriptionTrial"("stripeSubscriptionId");
+CREATE UNIQUE INDEX "SubscriptionTrial_stripeConversionInvoiceId_key" ON "SubscriptionTrial"("stripeConversionInvoiceId");
+CREATE INDEX "SubscriptionTrial_status_endsAt_idx" ON "SubscriptionTrial"("status", "endsAt");
+ALTER TABLE "SubscriptionTrial" ADD CONSTRAINT "SubscriptionTrial_userId_fkey"
+ FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/migrations/20260904220000_add_trial_notification_outbox/migration.sql b/autogpt_platform/backend/migrations/20260904220000_add_trial_notification_outbox/migration.sql
new file mode 100644
index 0000000000..915db05825
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260904220000_add_trial_notification_outbox/migration.sql
@@ -0,0 +1,24 @@
+ALTER TABLE "SubscriptionTrial" ADD COLUMN "notificationRevision" INTEGER NOT NULL DEFAULT 0;
+CREATE TABLE "TrialNotificationDelivery" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "trialId" TEXT NOT NULL REFERENCES "SubscriptionTrial"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ "userId" TEXT NOT NULL,
+ "idempotencyKey" TEXT NOT NULL,
+ "payload" JSONB NOT NULL,
+ "status" TEXT NOT NULL DEFAULT 'pending',
+ "attempts" INTEGER NOT NULL DEFAULT 0,
+ "nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "nextWakeAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "leaseToken" TEXT,
+ "leaseExpiresAt" TIMESTAMP(3),
+ "providerMessageId" TEXT,
+ "acceptedAt" TIMESTAMP(3),
+ "lastError" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ CONSTRAINT "TrialNotificationDelivery_status_check" CHECK ("status" IN ('pending', 'sending', 'accepted', 'suppressed', 'failed')),
+ CONSTRAINT "TrialNotificationDelivery_attempts_check" CHECK ("attempts" >= 0)
+);
+CREATE UNIQUE INDEX "TrialNotificationDelivery_idempotencyKey_key" ON "TrialNotificationDelivery"("idempotencyKey");
+CREATE UNIQUE INDEX "TrialNotificationDelivery_providerMessageId_key" ON "TrialNotificationDelivery"("providerMessageId");
+CREATE INDEX "TrialNotificationDelivery_status_nextWakeAt_idx" ON "TrialNotificationDelivery"("status", "nextWakeAt");
diff --git a/autogpt_platform/backend/migrations/20260905030000_index_trial_billing_customer/migration.sql b/autogpt_platform/backend/migrations/20260905030000_index_trial_billing_customer/migration.sql
new file mode 100644
index 0000000000..5e22bac8af
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260905030000_index_trial_billing_customer/migration.sql
@@ -0,0 +1,2 @@
+CREATE INDEX "SubscriptionTrial_stripeCustomerId_id_idx"
+ON "SubscriptionTrial"("stripeCustomerId", "id");
diff --git a/autogpt_platform/backend/migrations/20260905031000_trial_notice_obsolete_state/migration.sql b/autogpt_platform/backend/migrations/20260905031000_trial_notice_obsolete_state/migration.sql
new file mode 100644
index 0000000000..be3578c919
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260905031000_trial_notice_obsolete_state/migration.sql
@@ -0,0 +1,4 @@
+ALTER TABLE "TrialNotificationDelivery"
+ DROP CONSTRAINT "TrialNotificationDelivery_status_check",
+ ADD CONSTRAINT "TrialNotificationDelivery_status_check"
+ CHECK ("status" IN ('pending', 'sending', 'accepted', 'suppressed', 'obsolete', 'failed'));
diff --git a/autogpt_platform/backend/migrations/20260907235900_simplify_trial_delivery_and_claims/migration.sql b/autogpt_platform/backend/migrations/20260907235900_simplify_trial_delivery_and_claims/migration.sql
new file mode 100644
index 0000000000..d85f44bd42
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260907235900_simplify_trial_delivery_and_claims/migration.sql
@@ -0,0 +1,9 @@
+DROP TABLE IF EXISTS "TrialNotificationDelivery";
+
+CREATE TABLE "SubscriptionTrialClaim" (
+ "key" TEXT NOT NULL PRIMARY KEY,
+ "trialId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX "SubscriptionTrialClaim_trialId_idx" ON "SubscriptionTrialClaim"("trialId");
diff --git a/autogpt_platform/backend/migrations/20260908121500_trial_rejection_reason/migration.sql b/autogpt_platform/backend/migrations/20260908121500_trial_rejection_reason/migration.sql
new file mode 100644
index 0000000000..d160030fd2
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260908121500_trial_rejection_reason/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "SubscriptionTrial" ADD COLUMN "rejectionReason" TEXT;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index f7cf84e5ef..a3a89e88df 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -137,7 +137,8 @@ model User {
defaultChatAuthProvider String?
defaultChatCredentialId String?
- subscriptionTier SubscriptionTier @default(NO_TIER)
+ subscriptionTier SubscriptionTier @default(NO_TIER)
+ subscriptionTrial SubscriptionTrial?
// Relations
@@ -196,6 +197,7 @@ enum ChatSessionStatus {
enum SubscriptionTier {
NO_TIER
+ TRIAL
BASIC
PRO
MAX
@@ -203,6 +205,45 @@ enum SubscriptionTier {
ENTERPRISE
}
+model SubscriptionTrial {
+ id String @id @default(uuid())
+ userId String @unique
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ offer Json
+ stripeCustomerId String
+ stripeCheckoutSessionId String? @unique
+ stripeSubscriptionId String? @unique
+ stripeConversionInvoiceId String? @unique
+ notificationRevision Int @default(0)
+ checkoutAttempt Int @default(0)
+ checkoutSuccessUrl String
+ checkoutCancelUrl String
+ checkoutMetadata Json @default("{}")
+ status String @default("checkout_pending")
+ rejectionReason String?
+ cardVerifiedAt DateTime?
+ startedAt DateTime?
+ endsAt DateTime?
+ consumedAt DateTime?
+ convertedAt DateTime?
+ cancelAtPeriodEnd Boolean @default(false)
+ costMicrodollars BigInt @default(0)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([status, endsAt])
+ @@index([stripeCustomerId, id])
+}
+
+// No account/trial foreign key: deleting an account must not reset intro eligibility.
+model SubscriptionTrialClaim {
+ key String @id
+ trialId String
+ createdAt DateTime @default(now())
+
+ @@index([trialId])
+}
+
model UserOnboarding {
id String @id @default(uuid())
createdAt DateTime @default(now())
@@ -212,19 +253,19 @@ model UserOnboarding {
// backend, OpenAPI-generated union on the frontend). Storing as String[]
// means renames/adds/retires are code-only — legacy values become inert
// strings instead of stuck enum members. See SECRT-2355.
- completedSteps String[] @default([])
- walletShown Boolean @default(false)
- notified String[] @default([])
- rewardedFor String[] @default([])
+ completedSteps String[] @default([])
+ walletShown Boolean @default(false)
+ notified String[] @default([])
+ rewardedFor String[] @default([])
usageReason String?
- integrations String[] @default([])
+ integrations String[] @default([])
otherIntegrations String?
selectedStoreListingVersionId String?
agentInput Json?
onboardingAgentExecutionId String?
- agentRuns Int @default(0)
+ agentRuns Int @default(0)
lastRunAt DateTime?
- consecutiveRunDays Int @default(0)
+ consecutiveRunDays Int @default(0)
userId String @unique
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -289,13 +330,13 @@ model OnboardingBrainDump {
/// Written once when the dump is processed, read by the copilot home's
/// greeting. Generated up-front rather than on page load so the greeting
/// is instant — the user has already waited through the loading screen.
- greeting String?
+ greeting String?
/// List of {title, prompt} objects the user can pick from under the
/// greeting. JSON so the shape can evolve without a migration.
- suggestedPrompts Json @default("[]")
+ suggestedPrompts Json @default("[]")
/// True once the user has sent their first message. The greeting is
/// never shown again after this, but its content is kept.
- greetingSeen Boolean @default(false)
+ greetingSeen Boolean @default(false)
/// List of {provider, reason} objects Claude picks from the transcript
/// and the live provider registry. Null until the recommendation
/// background job (separate from the greeting one) writes its result.
@@ -777,6 +818,7 @@ enum NotificationType {
SUBSCRIPTION_CANCELLED
SUBSCRIPTION_RESUMED
SUBSCRIPTION_ENDED
+ TRIAL_UPDATE
}
// How often the Briefing is delivered. OFF is the "alerts only" / "pause"
@@ -826,7 +868,7 @@ model AlertCondition {
userId String
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
- cause AlertCause
+ cause AlertCause
// Stable identity of the underlying problem (e.g. "auth_expired:gmail:<graph
// id>"), so re-raising the same condition updates one row instead of piling
// up duplicates, and resolving it can find the row without the payload.
@@ -838,7 +880,7 @@ model AlertCondition {
resolvedAt DateTime?
// Set once the condition has been carried into a Briefing's attention
// block, so the next Briefing doesn't repeat it.
- briefedAt DateTime?
+ briefedAt DateTime?
@@unique([userId, causeKey])
@@index([status, createdAt])
@@ -902,9 +944,9 @@ model PushSubscription {
// For the library page
// It is a user controlled list of agents, that they will see in their library
model LibraryAgent {
- id String @id @default(uuid())
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
lastRunAt DateTime?
userId String
@@ -996,17 +1038,17 @@ model Expert {
ownerUserId String?
OwnerUser User? @relation(fields: [ownerUserId], references: [id], onDelete: Cascade)
- name String
- avatarUrl String?
+ name String
+ avatarUrl String?
// Accent color token picked while raising (e.g. "sky-300"); "" = unset.
- color String @default("")
- role String
- tagline String?
- identity String
- bio String?
- skills String[] @default([])
- voicePreferences String @default("")
- boundaries String @default("")
+ color String @default("")
+ role String
+ tagline String?
+ identity String
+ bio String?
+ skills String[] @default([])
+ voicePreferences String @default("")
+ boundaries String @default("")
toolProfile Json?
@@ -1020,7 +1062,7 @@ model Expert {
// Weekly credit guardrail: null = platform default from config.
// Spend is tracked per ISO week in Redis and reconciled from
// CreditTransaction via the execution's expertId.
- weeklyBudget Int?
+ weeklyBudget Int?
// Set when a budget breach (or archive) paused this expert's schedules
// and triggers. Chat is never paused. Cleared by the resume endpoint.
schedulesPausedAt DateTime?
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index ca18a5f26a..7f520ac899 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -104,7 +104,7 @@
"lodash": "4.17.21",
"lucide-react": "0.552.0",
"motion": "12.38.0",
- "next": "15.5.21",
+ "next": "15.5.24",
"next-themes": "0.4.6",
"nuqs": "2.7.2",
"pg": "8.21.0",
diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yaml
index e3ff029a93..e887d791aa 100644
--- a/autogpt_platform/frontend/pnpm-lock.yaml
+++ b/autogpt_platform/frontend/pnpm-lock.yaml
@@ -36,7 +36,7 @@ importers:
version: 1.1.9([email protected])
'@next/third-parties':
specifier: 15.4.6
'@number-flow/react':
specifier: 0.6.0
@@ -123,7 +123,7 @@ importers:
version: 6.1.2(@rjsf/[email protected]([email protected]))
'@sentry/nextjs':
specifier: 10.27.0
'@streamdown/cjk':
specifier: 1.0.1
@@ -144,10 +144,10 @@ importers:
version: 0.2.4
'@vercel/analytics':
specifier: 1.5.0
'@vercel/speed-insights':
specifier: 1.2.0
'@xyflow/react':
specifier: 12.9.2
@@ -159,7 +159,7 @@ importers:
version: 3.0.3
better-auth:
specifier: 1.6.22
boring-avatars:
specifier: 1.11.2
version: 1.11.2
@@ -198,7 +198,7 @@ importers:
geist:
specifier: 1.5.1
highlight.js:
specifier: 11.11.1
version: 11.11.1
@@ -227,14 +227,14 @@ importers:
specifier: 12.38.0
next:
- specifier: 15.5.21
+ specifier: 15.5.24
next-themes:
specifier: 0.4.6
nuqs:
specifier: 2.7.2
pg:
specifier: 8.21.0
version: 8.21.0
@@ -361,7 +361,7 @@ importers:
'@storybook/nextjs':
specifier: 9.1.5
'@tanstack/eslint-plugin-query':
specifier: 5.91.2
@@ -1324,9 +1324,6 @@ packages:
'@emnapi/[email protected]':
resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==}
- '@emnapi/[email protected]':
- resolution: {integrity: sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==}
-
'@emnapi/[email protected]':
resolution: {integrity: sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==}
@@ -2009,60 +2006,60 @@ packages:
'@neoconfetti/[email protected]':
resolution: {integrity: sha512-klcSooChXXOzIm+SE5IISIAn3bYzYfPjbX7D7HoqZL84oAfgREeSg5vSIaSFH+DaGzzvImTyWe1OyrJ67vik4A==}
- resolution: {integrity: sha512-hjJI/GfrjWHgNguRIBzItjRRu0m3Nrz17GhxsjuHfjIvg9hyg3239REd2dpI+bpMTFuVrVprHzEQ19m++cDtbw==}
+ resolution: {integrity: sha512-mBDF7T0XKZjs9SpUAl0buizVO+O02ULjOvWX8o/AZo/5AGw/UAS1Zzcylmd4pqbftzmKQi+L/nB4jgBYKEAl5Q==}
resolution: {integrity: sha512-DtRU2N7BkGr8r+pExfuWHwMEPX5SD57FeA6pxdgCHODo+b/UgIgjE+rgWKtJAbEbGhVZ2jtHn4g3wNhWFoNBQQ==}
- resolution: {integrity: sha512-ZfjqPEdi6TRC/fWx7UDbwb1fbVgyh2uD5tVTRKIDZDlYM+UNuE/LafDG2fwuAoZilADpABh46OY/F5qf9JjqLQ==}
+ resolution: {integrity: sha512-AGdNLvxZNY6eR2iSnV+6wUa8CiHTMr4F7g3uHH7fT4ICIJBE00R9u4tzN/Vuwsw0cOi8MTD2HJcTCb6siMH88Q==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
- resolution: {integrity: sha512-TlCf1NpxgQLzTrexuev75xwmNCJMd1/qkJpTVP1GRRcih93hlIBn1P72hkh8T0gnRFr6BmWksQtbyG3jT6jnww==}
+ resolution: {integrity: sha512-9HrQajBMmGcrrrvDfRimiCrbAPh3E6uHJmwBovYr6Yrmi9p9PZqI876BrXX280wICh3o2XwUlp4blkB0NNBqFg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
- resolution: {integrity: sha512-LXRsq1p+HvHSi7ygwNcSEEcK0zuo5jS75ZlqFHtOH+LF7qntXAJVJxah+1Pi/GyBm7EpkwU7m4EgbvIKrMqm9A==}
+ resolution: {integrity: sha512-rl9LSfE75si0WT3cDgdUC1XYCKS+TgxC+/IjitmeycrAG18X/plIP1/vy8dd/HPycYcIvE688PD7FuvEAiEAew==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-hyGixhFxpDKjqoev6l4KlcRBlt9AXWrGhDZwmwg49sMJM5tnKQPSi+SEj9+e5n+l/bthRGZUdh59GKIs6lQPRw==}
+ resolution: {integrity: sha512-TlNAnpsjxSF3aAUtqnfmtXXf8m9sIDBlmF3c7bTAlnshUYu2U0OxN2uf5d0gcFwqHVEdivJNBcCaqNOwPGNimw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-qfE+YfOba6S2+13e8qn1/UozDVNZ2clBlrs8UtDoax4s8ediu6sq93z66OEHUYlb69Tffh5JTNkgtsAKiSuugg==}
+ resolution: {integrity: sha512-7dwtlhr0SLndqTG1z9ncRkbJswDZiKWlxzFyXDvJ2RDZRDRHp8zyMJ4D9UH/FgnQeXxxB6gZy2pMcIUoNKQ4pA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-BXLGG+EvIwp/Rrgl6HY8sqvD6BOUOIRz8/naDbeLNX7mlA5H2XRcL6MW/0IGnJISfj5BA9gNhFyJj5yOoiIDJQ==}
+ resolution: {integrity: sha512-kGZxM+WhkYs0276lFrMkj7PRtXT3Btp6cwvfSO/cCVLxJJttB5Ccnl2niaCgUja8HgSbEVnMHpg3FJWoOJ9e/g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-tNGNOlT0Wn7E4IMsSnufjXN/l2L2/AGdLLpa2vzS89SYCBuihgLn3ngLsIrvndAnWo9nAkus+4gZHTI/Ijx9HA==}
+ resolution: {integrity: sha512-jBDDkZ/qKAqkWivWDMkJSXUzbzV0QKRBKJjEHUAvSB97Hzw7NLzJ6yV56Lts/wjir7s4P31GYgpbS6ZL+hasAA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
- resolution: {integrity: sha512-DmIdWmC9p4rdNIiQqo8ap0+Cnj6kKtTZnuSCxoYydSc8sgpDgAg9wFhxplunak9imLV0pTvc5WVCOHwm5eHLtQ==}
+ resolution: {integrity: sha512-JqtwjvvorjacQ0spgjmUJoxySoYgPwdT1sFdQ0/zmW4iMlP2hjYlCoJIyS7o6Epb4Fug8eco3HXFoBDUCDeH7Q==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
@@ -4205,6 +4202,7 @@ packages:
resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
+ deprecated: Potential CWE-502 - Update to 1.3.1 or higher
resolution: {integrity: sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==}
@@ -7433,11 +7431,6 @@ packages:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
- engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
- hasBin: true
-
resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -7468,8 +7461,8 @@ packages:
react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc
react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc
- resolution: {integrity: sha512-/TsdBtkWLhkl+NVL3Uqws2UphNd6IPzOtzSk1fHaf+0P7GQKLZDUytyhns/Ykbzdy9+YRjwG7ONvrHaaTDdFqQ==}
+ resolution: {integrity: sha512-Y+xn8EQCoC3ZbsFPyzE+tE8XOdrWeUdUF7NeXbmg9DsgAxl5UYxlsrvgVESHTyTGigoTa1bCUrxn70F5bqt0Gw==}
engines: {node: ^18.18.0 || ^19.8.0 || >= 20.0.0}
hasBin: true
peerDependencies:
@@ -9077,6 +9070,7 @@ packages:
resolution: {integrity: sha512-ghqN1b0puy3MhhviwO2kGF8SeMDNhEbnKxjK7h6+fvY9JAxqvXi8y5NAHSQv687OVboS2uZIByzGd45/YxrRHg==}
engines: {node: ^14.13.1 || ^16 || >=18}
+ deprecated: unmaintained
hasBin: true
peerDependencies:
typescript: ^4.3.5 || ^5.0.0
@@ -9087,6 +9081,7 @@ packages:
resolution: {integrity: sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==}
engines: {node: ^18 || >=20}
+ deprecated: unmaintained
hasBin: true
peerDependencies:
typescript: ^5.0.0
@@ -10735,11 +10730,6 @@ snapshots:
tslib: 2.8.1
optional: true
- '@emnapi/[email protected]':
- dependencies:
- tslib: 2.8.1
- optional: true
-
'@emnapi/[email protected]':
dependencies:
tslib: 2.8.1
@@ -11124,7 +11114,7 @@ snapshots:
dependencies:
- '@emnapi/runtime': 1.8.1
+ '@emnapi/runtime': 1.11.2
optional: true
@@ -11231,7 +11221,7 @@ snapshots:
'@napi-rs/[email protected]':
dependencies:
'@emnapi/core': 1.8.1
- '@emnapi/runtime': 1.8.1
+ '@emnapi/runtime': 1.11.2
'@tybys/wasm-util': 0.10.1
optional: true
@@ -11244,39 +11234,39 @@ snapshots:
'@neoconfetti/[email protected]': {}
- '@next/[email protected]': {}
+ '@next/[email protected]': {}
dependencies:
fast-glob: 3.3.1
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
dependencies:
react: 18.3.1
third-party-capital: 1.0.20
@@ -12725,7 +12715,7 @@ snapshots:
'@sentry/[email protected]': {}
dependencies:
'@opentelemetry/api': 1.9.0
'@opentelemetry/semantic-conventions': 1.38.0
@@ -12738,7 +12728,7 @@ snapshots:
'@sentry/react': 10.27.0([email protected])
'@sentry/vercel-edge': 10.27.0
'@sentry/webpack-plugin': 4.6.1([email protected]([email protected]))
resolve: 1.22.8
rollup: 4.55.1
stacktrace-parser: 0.1.11
@@ -13117,7 +13107,7 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
'@babel/core': 7.28.5
'@babel/plugin-syntax-bigint': 7.8.3(@babel/[email protected])
@@ -13141,7 +13131,7 @@ snapshots:
image-size: 2.0.2
loader-utils: 3.3.1
node-polyfill-webpack-plugin: 2.0.1([email protected]([email protected]))
postcss: 8.5.23
@@ -13790,16 +13780,16 @@ snapshots:
optional: true
optionalDependencies:
react: 18.3.1
'@vercel/[email protected]': {}
optionalDependencies:
react: 18.3.1
@@ -14314,7 +14304,7 @@ snapshots:
dependencies:
'@better-auth/drizzle-adapter': 1.6.22(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
@@ -14334,7 +14324,7 @@ snapshots:
nanostores: 1.3.0
zod: 4.4.3
optionalDependencies:
pg: 8.21.0
react: 18.3.1
react-dom: 18.3.1([email protected])
@@ -15433,8 +15423,8 @@ snapshots:
'@typescript-eslint/parser': 8.52.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))([email protected])
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected])
eslint-plugin-jsx-a11y: 6.10.2([email protected])
eslint-plugin-react: 7.37.5([email protected])
eslint-plugin-react-hooks: 5.2.0([email protected])
@@ -15453,7 +15443,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -15464,22 +15454,22 @@ snapshots:
tinyglobby: 0.2.15
unrs-resolver: 1.11.1
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.52.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))([email protected])
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -15490,7 +15480,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3
@@ -15911,9 +15901,9 @@ snapshots:
dependencies:
@@ -17548,8 +17538,6 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
-
@@ -17567,9 +17555,9 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
- '@next/env': 15.5.21
+ '@next/env': 15.5.24
'@swc/helpers': 0.5.15
caniuse-lite: 1.0.30001762
postcss: 8.4.31
@@ -17577,14 +17565,14 @@ snapshots:
react-dom: 18.3.1([email protected])
styled-jsx: 5.1.6(@babel/[email protected])([email protected])
optionalDependencies:
- '@next/swc-darwin-arm64': 15.5.21
- '@next/swc-darwin-x64': 15.5.21
- '@next/swc-linux-arm64-gnu': 15.5.21
- '@next/swc-linux-arm64-musl': 15.5.21
- '@next/swc-linux-x64-gnu': 15.5.21
- '@next/swc-linux-x64-musl': 15.5.21
- '@next/swc-win32-arm64-msvc': 15.5.21
- '@next/swc-win32-x64-msvc': 15.5.21
+ '@next/swc-darwin-arm64': 15.5.24
+ '@next/swc-darwin-x64': 15.5.24
+ '@next/swc-linux-arm64-gnu': 15.5.24
+ '@next/swc-linux-arm64-musl': 15.5.24
+ '@next/swc-linux-x64-gnu': 15.5.24
+ '@next/swc-linux-x64-musl': 15.5.24
+ '@next/swc-win32-arm64-msvc': 15.5.24
+ '@next/swc-win32-x64-msvc': 15.5.24
'@opentelemetry/api': 1.9.0
'@playwright/test': 1.56.1
sharp: 0.34.5
@@ -17675,12 +17663,12 @@ snapshots:
dependencies:
esm-env: 1.2.2
dependencies:
'@standard-schema/spec': 1.0.0
react: 18.3.1
optionalDependencies:
dependencies:
@@ -18181,7 +18169,7 @@ snapshots:
dependencies:
- nanoid: 3.3.11
+ nanoid: 3.3.16
picocolors: 1.1.1
source-map-js: 1.2.1
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx
index 815f5d3659..ad16cd9479 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx
@@ -17,6 +17,8 @@ import {
import { useOnboardingPage } from "./useOnboardingPage";
import { ArrowLeft01Icon, Logout03Icon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
export default function OnboardingPage() {
const {
@@ -29,11 +31,17 @@ export default function OnboardingPage() {
steps,
preparingStep,
totalSteps,
+ trialConfirmation,
} = useOnboardingPage();
const prevStep = useOnboardingWizardStore((s) => s.prevStep);
const isStepBusy = useOnboardingWizardStore((s) => s.isStepBusy);
- if (isLoading) return null;
+ if (isLoading)
+ return !trialConfirmation.ready ? (
+ <Text variant="body" role="status">
+ Confirming your trial and card setup…
+ </Text>
+ ) : null;
// ProgressBar + StepIndicator track only the user-interactive steps.
// PreparingStep is a transition view that hides both indicators.
@@ -50,6 +58,13 @@ export default function OnboardingPage() {
return (
<div className="flex min-h-screen w-full flex-col items-center">
+ {trialConfirmation.error ? (
+ <ErrorCard
+ context="your trial"
+ responseError={{ message: trialConfirmation.error }}
+ onRetry={trialConfirmation.retry}
+ />
+ ) : null}
{showProgressBar && (
<ProgressBar currentStep={currentStep} totalSteps={totalSteps} />
)}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx
index 0364458eb7..edb2972eed 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx
@@ -7,6 +7,7 @@ import { cn } from "@/lib/utils";
import { PlanCard } from "@/components/molecules/PlanCard/PlanCard";
import { PLAN_KEYS } from "@/components/molecules/PlanCard/plans";
import { useSubscriptionStep } from "./useSubscriptionStep";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
export function SubscriptionStep() {
const {
@@ -44,6 +45,9 @@ export function SubscriptionStep() {
</Text>
</div>
+ <div className="w-full max-w-2xl">
+ <TrialCard returnTo="onboarding" />
+ </div>
<div className="inline-flex rounded-full border border-[#d8d8d8] bg-zinc-100 p-[3px]">
{(["monthly", "yearly"] as const).map((cycle) => (
<button
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx
index 8f988fb931..1d7f46cda3 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx
@@ -25,6 +25,7 @@ const postHog = vi.hoisted(() => ({
vi.mock("@posthog/react", () => ({
useFeatureFlagVariantKey: () => postHog.variant,
+ usePostHog: () => undefined,
}));
vi.mock("@/components/atoms/FadeIn/FadeIn", () => ({
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts
index 7feaedded6..690d4a7fef 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts
@@ -9,6 +9,7 @@ import { resolveResponse } from "@/app/api/helpers";
import { useAuth } from "@/lib/auth/hooks/useAuth";
import { trackAdsConversion } from "@/services/analytics/google-ads";
import { environment } from "@/services/environment";
+import { useTrialCheckoutReturn } from "@/services/trials/useTrialCheckoutReturn";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { useLDClient } from "launchdarkly-react-client-sdk";
import { useRouter, useSearchParams } from "next/navigation";
@@ -59,6 +60,7 @@ export function useOnboardingPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { isLoggedIn, isUserLoading, refreshSession, user } = useAuth();
+ const trialConfirmation = useTrialCheckoutReturn();
const currentStep = useOnboardingWizardStore((s) => s.currentStep);
const goToStep = useOnboardingWizardStore((s) => s.goToStep);
@@ -117,7 +119,8 @@ export function useOnboardingPage() {
: null,
},
});
- const userHasActivePlan = !!tier && tier !== "NO_TIER";
+ const userHasActivePlan =
+ trialConfirmation.active || (!!tier && tier !== "NO_TIER");
const isPaymentEnabled =
(paymentEnabledSnapshot.current ?? false) && !userHasActivePlan;
@@ -138,7 +141,10 @@ export function useOnboardingPage() {
// isLoggedIn is transiently false, the tier query stays disabled
// (isTierLoading=false), and init fires with the wrong preparingStep.
const isReady =
- areFlagsReady && !isUserLoading && (!isLoggedIn || !isTierLoading);
+ areFlagsReady &&
+ !isUserLoading &&
+ (!isLoggedIn || !isTierLoading) &&
+ trialConfirmation.ready;
const [isOnboardingStateLoading, setIsOnboardingStateLoading] =
useState(true);
@@ -166,7 +172,8 @@ export function useOnboardingPage() {
// subscription step before redirect) would clamp the user back onto the
// paywall they just paid through.
const isSubscriptionSuccess =
- searchParams.get("subscription") === "success";
+ searchParams.get("subscription") === "success" ||
+ trialConfirmation.active;
const ceiling = isSubscriptionSuccess
? steps.welcome
: (Math.min(readHighestStep(), preparingStep) as Step);
@@ -175,7 +182,14 @@ export function useOnboardingPage() {
) as Step;
goToStep(target);
setIsStepSettled(true);
- }, [isReady, searchParams, goToStep, preparingStep, steps]);
+ }, [
+ isReady,
+ searchParams,
+ goToStep,
+ preparingStep,
+ steps,
+ trialConfirmation.active,
+ ]);
// Report the step the wizard is actually showing. `isOnboardingStateLoading`
// is the same gate the page renders on — it also covers the window holding
@@ -303,5 +317,6 @@ export function useOnboardingPage() {
steps,
preparingStep,
totalSteps,
+ trialConfirmation,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx
index 302249b15d..2f5da7170b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx
@@ -71,7 +71,12 @@ export default function ArtifactsPage() {
isLoadingMore,
loadMore,
} = useArtifactsPage();
- const { folders, isLoading: isFoldersLoading } = useArtifactsFolders();
+ const {
+ folders,
+ isLoading: isFoldersLoading,
+ isError: isFoldersError,
+ error: foldersError,
+ } = useArtifactsFolders();
const { activeExperts, expertsById } = useExpertMap();
const isSearching = searchTerm.length > 0;
@@ -192,8 +197,8 @@ export default function ArtifactsPage() {
<ArtifactsList
files={files}
isLoading={isListLoading}
- isError={isError}
- error={error}
+ isError={isError || (showFolders && isFoldersError)}
+ error={isError ? error : showFolders ? foldersError : undefined}
emptyState={getEmptyState({
hasSearchTerm: isSearching,
isInFolder,
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsx
new file mode 100644
index 0000000000..6e492a7059
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsx
@@ -0,0 +1,128 @@
+import {
+ getGetTrialsGetTrialStatusMockHandler200,
+ getPostTrialsCancelTrialMockHandler200,
+ getPostTrialsStartTrialCheckoutMockHandler200,
+} from "@/app/api/__generated__/endpoints/trials/trials.msw";
+import type { TrialCheckoutResponse } from "@/app/api/__generated__/models/trialCheckoutResponse";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+import { server } from "@/mocks/mock-server";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import {
+ deferredTrialResponse,
+ setTrialUser,
+ trialOffer,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+beforeEach(() => setTrialUser("user-a"));
+afterEach(() => {
+ setTrialUser(null);
+ vi.restoreAllMocks();
+});
+
+function offerForCurrentUser() {
+ return trialResponse({
+ eligible: true,
+ active: false,
+ status: null,
+ offer: {
+ ...trialOffer,
+ duration_days: useAuthStore.getState().user?.id === "user-b" ? 10 : 7,
+ },
+ });
+}
+
+describe("trial account isolation", () => {
+ it("hides user A's status immediately when switching to user B", async () => {
+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(() =>
+ useAuthStore.getState().user?.id === "user-a"
+ ? trialResponse()
+ : pending.promise,
+ ),
+ );
+ render(<TrialCard />);
+ await screen.findByRole("button", { name: "Cancel trial" });
+ act(() => setTrialUser("user-b"));
+ expect(screen.queryByText("Your trial")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();
+ pending.resolve(offerForCurrentUser());
+ await screen.findByRole("button", { name: /start 10-day trial/i });
+ act(() => setTrialUser(null));
+ expect(screen.queryByRole("region", { name: "AutoGPT trial" })).toBeNull();
+ });
+
+ it("never redirects user B to a checkout requested by user A", async () => {
+ const pending = deferredTrialResponse<TrialCheckoutResponse>();
+ const checkout = vi.fn(() => pending.promise);
+ const assign = vi
+ .spyOn(window.location, "assign")
+ .mockImplementation(() => {});
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(offerForCurrentUser),
+ getPostTrialsStartTrialCheckoutMockHandler200(checkout),
+ );
+ render(<TrialCard />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /start 7-day trial/i }),
+ );
+ await waitFor(() => expect(checkout).toHaveBeenCalledOnce());
+ act(() => setTrialUser("user-b"));
+ await screen.findByRole("button", { name: /start 10-day trial/i });
+ pending.resolve({ url: "https://checkout.stripe.com/c/pay/user_a" });
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole("button", { name: /start 10-day trial/i })
+ .hasAttribute("disabled"),
+ ).toBe(false),
+ );
+ expect(assign).not.toHaveBeenCalled();
+ });
+
+ it("does not apply user A's late cancellation result to user B", async () => {
+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();
+ const cancel = vi.fn(() => pending.promise);
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(() =>
+ trialResponse({
+ offer: {
+ ...trialOffer,
+ unit_amount:
+ useAuthStore.getState().user?.id === "user-a" ? 2000 : 3000,
+ },
+ }),
+ ),
+ getPostTrialsCancelTrialMockHandler200(cancel),
+ );
+ render(<TrialCard />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Cancel trial" }),
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "End trial now" }),
+ );
+ await waitFor(() => expect(cancel).toHaveBeenCalledOnce());
+ act(() => setTrialUser("user-b"));
+ await screen.findByText(/\$30\.00/);
+ pending.resolve(trialResponse({ active: false, status: "canceled" }));
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole("button", { name: "Cancel trial" })
+ .hasAttribute("disabled"),
+ ).toBe(false),
+ );
+ expect(screen.queryByText(/Cancellation confirmed/)).toBeNull();
+ expect(screen.getByText(/\$30\.00/)).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx
new file mode 100644
index 0000000000..15213bee0e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx
@@ -0,0 +1,207 @@
+import {
+ getGetTrialsGetTrialStatusMockHandler200,
+ getPostTrialsCancelTrialMockHandler200,
+ getPostTrialsStartTrialCheckoutMockHandler200,
+} from "@/app/api/__generated__/endpoints/trials/trials.msw";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import {
+ deferredTrialResponse,
+ setTrialUser,
+ trialOffer,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+beforeEach(() => setTrialUser());
+afterEach(() => {
+ setTrialUser(null);
+ vi.restoreAllMocks();
+});
+
+describe("trial billing actions", () => {
+ it("hides trial usage and ends access immediately on cancellation", async () => {
+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();
+ const cancel = vi.fn(() => pending.promise);
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),
+ getPostTrialsCancelTrialMockHandler200(cancel),
+ );
+ render(<TrialCard />);
+ const button = await screen.findByRole("button", { name: "Cancel trial" });
+ expect(screen.queryByRole("progressbar")).toBeNull();
+ expect(screen.queryByText(/trial allowance used/i)).toBeNull();
+ expect(screen.getByText(/Your trial ends.*\$20\.00/)).toBeDefined();
+ expect(
+ screen.getByText(/Canceling ends trial access immediately/),
+ ).toBeDefined();
+ fireEvent.click(button);
+ fireEvent.click(
+ await screen.findByRole("button", { name: "End trial now" }),
+ );
+ await waitFor(() => expect(cancel).toHaveBeenCalledOnce());
+ expect(button.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(button);
+ pending.resolve(trialResponse({ active: false, status: "canceled" }));
+ expect(await screen.findByText(/Cancellation confirmed/)).toBeDefined();
+ expect(screen.getByText("Your trial has ended")).toBeDefined();
+ expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+
+ it("keeps cancellation retryable when the request fails", async () => {
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),
+ http.post("*/api/credits/trial/cancel", () =>
+ HttpResponse.json({ detail: "Stripe is unavailable" }, { status: 502 }),
+ ),
+ );
+ render(<TrialCard />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Cancel trial" }),
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "End trial now" }),
+ );
+ expect(await screen.findByRole("alert")).toBeDefined();
+ expect(
+ screen
+ .getByRole("button", { name: "Cancel trial" })
+ .hasAttribute("disabled"),
+ ).toBe(false);
+ expect(screen.queryByText(/Cancellation confirmed/)).toBeNull();
+ server.use(
+ getPostTrialsCancelTrialMockHandler200(
+ trialResponse({ active: false, status: "canceled" }),
+ ),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Cancel trial" }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: "End trial now" }),
+ );
+ await screen.findByText(/Cancellation confirmed/);
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it.each(["billing", "onboarding"] as const)(
+ "sends the accepted token and %s destination before redirecting",
+ async (returnTo) => {
+ const assign = vi
+ .spyOn(window.location, "assign")
+ .mockImplementation(() => {});
+ const body = vi.fn();
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({ eligible: true, active: false, status: null }),
+ ),
+ getPostTrialsStartTrialCheckoutMockHandler200(async ({ request }) => {
+ body(await request.json());
+ return { url: "https://checkout.stripe.com/c/pay/test_trial" };
+ }),
+ );
+ render(<TrialCard returnTo={returnTo} />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /start 7-day trial/i }),
+ );
+ await waitFor(() =>
+ expect(assign).toHaveBeenCalledWith(
+ "https://checkout.stripe.com/c/pay/test_trial",
+ ),
+ );
+ expect(body).toHaveBeenCalledWith({
+ offer_token: trialOffer.token,
+ return_to: returnTo,
+ });
+ },
+ );
+
+ it("refreshes an expired offer after checkout is rejected", async () => {
+ let rejected = false;
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(() =>
+ trialResponse({
+ eligible: true,
+ active: false,
+ status: null,
+ offer: rejected
+ ? { ...trialOffer, duration_days: 10, token: "b".repeat(64) }
+ : trialOffer,
+ }),
+ ),
+ http.post("*/api/credits/trial", () => {
+ rejected = true;
+ return HttpResponse.json(
+ { detail: "Refresh the offer" },
+ { status: 409 },
+ );
+ }),
+ );
+ render(<TrialCard />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /start 7-day trial/i }),
+ );
+ await screen.findByRole("alert");
+ expect(
+ (
+ await screen.findByRole("button", { name: /start 10-day trial/i })
+ ).hasAttribute("disabled"),
+ ).toBe(false);
+ });
+
+ it("does not offer cancellation or imply paid access after expiry", async () => {
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({ active: false, status: "past_due", ends_at: null }),
+ ),
+ );
+ render(<TrialCard />);
+ await screen.findByText("Your trial has ended");
+ expect(
+ screen.getByText(/Paid access requires a successful payment/),
+ ).toBeDefined();
+ expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();
+ expect(screen.queryByRole("progressbar")).toBeNull();
+ });
+
+ it("recovers a failed status request through the visible retry action", async () => {
+ server.use(
+ http.get("*/api/credits/trial", () =>
+ HttpResponse.json({ detail: "Unavailable" }, { status: 503 }),
+ ),
+ );
+ render(<TrialCard />);
+ const retry = await screen.findByRole("button", { name: /try again/i });
+ server.use(getGetTrialsGetTrialStatusMockHandler200(trialResponse()));
+ fireEvent.click(retry);
+ await screen.findByRole("button", { name: "Cancel trial" });
+ expect(screen.queryByRole("button", { name: /try again/i })).toBeNull();
+ });
+
+ it("renders a tunable yearly Team offer in a zero-decimal currency", async () => {
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({
+ eligible: true,
+ active: false,
+ offer: {
+ ...trialOffer,
+ tier: "BUSINESS",
+ billing_cycle: "yearly",
+ currency: "jpy",
+ unit_amount: 1000,
+ },
+ }),
+ ),
+ );
+ render(<TrialCard />);
+ await screen.findByText(/Try AutoGPT Team for 7 days/);
+ expect(screen.getByText(/¥1,000 \/ year/)).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsx
new file mode 100644
index 0000000000..bf057c0b05
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsx
@@ -0,0 +1,105 @@
+import {
+ getGetTrialsGetTrialStatusMockHandler200,
+ getPostTrialsCancelTrialMockHandler200,
+} from "@/app/api/__generated__/endpoints/trials/trials.msw";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { server } from "@/mocks/mock-server";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import {
+ setTrialUser,
+ trialOffer,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+beforeEach(() => setTrialUser("user-a"));
+afterEach(() => setTrialUser(null));
+
+it("requires confirmation before irreversibly ending a trial", async () => {
+ const cancel = vi.fn(() =>
+ trialResponse({ active: false, status: "canceled" }),
+ );
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),
+ getPostTrialsCancelTrialMockHandler200(cancel),
+ );
+ render(<TrialCard />);
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel trial" }));
+ expect(
+ await screen.findByRole("dialog", { name: "End your trial now?" }),
+ ).toBeDefined();
+ expect(cancel).not.toHaveBeenCalled();
+ expect(screen.getByText(/You cannot restart this trial/)).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: "Keep trial" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(cancel).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel trial" }));
+ fireEvent.click(await screen.findByRole("button", { name: "End trial now" }));
+ await screen.findByText(/Cancellation confirmed/);
+ expect(cancel).toHaveBeenCalledOnce();
+});
+
+it("dismisses confirmation on Escape without canceling", async () => {
+ const cancel = vi.fn(() => trialResponse());
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),
+ getPostTrialsCancelTrialMockHandler200(cancel),
+ );
+ render(<TrialCard />);
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel trial" }));
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.keyDown(dialog, { key: "Escape" });
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(cancel).not.toHaveBeenCalled();
+});
+
+it("does not carry an open cancellation confirmation across accounts", async () => {
+ const cancel = vi.fn(() => trialResponse());
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),
+ getPostTrialsCancelTrialMockHandler200(cancel),
+ );
+ render(<TrialCard />);
+ await screen.findByRole("button", { name: "Cancel trial" });
+ act(() => setTrialUser("user-b"));
+ await screen.findByRole("button", { name: "Cancel trial" });
+ fireEvent.click(screen.getByRole("button", { name: "Cancel trial" }));
+ await screen.findByRole("dialog");
+ act(() => setTrialUser("user-a"));
+ await screen.findByRole("button", { name: "Cancel trial" });
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(cancel).not.toHaveBeenCalled();
+});
+
+it.each([
+ ["BASIC", "Basic"],
+ ["PRO", "Pro"],
+ ["MAX", "Max"],
+ ["BUSINESS", "Team"],
+] as const)(
+ "uses the %s plan's display name and masks personalized billing copy",
+ async (tier, label) => {
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({
+ eligible: true,
+ active: false,
+ offer: { ...trialOffer, tier },
+ }),
+ ),
+ );
+ render(<TrialCard />);
+ await screen.findByText(`Try AutoGPT ${label} for 7 days`);
+ expect(
+ screen
+ .getByText(/Card required. No subscription charge today/)
+ .classList.contains("sentry-unmask"),
+ ).toBe(false);
+ },
+);
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsx
new file mode 100644
index 0000000000..0ed05e2b65
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsx
@@ -0,0 +1,156 @@
+import {
+ getGetTrialsGetTrialStatusMockHandler200,
+ getPostTrialsConfirmTrialMockHandler200,
+} from "@/app/api/__generated__/endpoints/trials/trials.msw";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import {
+ deferredTrialResponse,
+ setTrialUser,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let searchParams = new URLSearchParams();
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => searchParams,
+ usePathname: () => "/settings/billing",
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+}));
+
+beforeEach(() => {
+ setTrialUser();
+ searchParams = new URLSearchParams("trial=success");
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({
+ eligible: true,
+ active: false,
+ status: "checkout_pending",
+ }),
+ ),
+ );
+});
+afterEach(() => setTrialUser(null));
+
+function renderTrialReturn() {
+ return render(
+ <>
+ <TrialCheckoutConfirmation />
+ <TrialCard />
+ </>,
+ );
+}
+
+describe("trial Checkout return", () => {
+ it("requires backend confirmation before displaying active trial access", async () => {
+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();
+ const confirm = vi.fn(() => pending.promise);
+ server.use(getPostTrialsConfirmTrialMockHandler200(confirm));
+ renderTrialReturn();
+ expect((await screen.findByRole("status")).textContent).toMatch(
+ /Confirming your trial/,
+ );
+ await screen.findByRole("button", { name: /start 7-day trial/i });
+ expect(screen.queryByText("Your trial")).toBeNull();
+ pending.resolve(trialResponse());
+ expect(
+ await screen.findByRole("button", { name: "Cancel trial" }),
+ ).toBeDefined();
+ expect(screen.queryByRole("status")).toBeNull();
+ expect(confirm).toHaveBeenCalledOnce();
+ });
+
+ it("keeps a failed confirmation visible and lets the user retry", async () => {
+ server.use(
+ http.post("*/api/credits/trial/confirm", () =>
+ HttpResponse.json(
+ { detail: "Card setup is not complete yet" },
+ { status: 409 },
+ ),
+ ),
+ );
+ renderTrialReturn();
+ const retry = await screen.findByRole("button", { name: /try again/i });
+ expect(screen.queryByText("Your trial")).toBeNull();
+ server.use(getPostTrialsConfirmTrialMockHandler200(trialResponse()));
+ fireEvent.click(retry);
+ expect(
+ await screen.findByRole("button", { name: "Cancel trial" }),
+ ).toBeDefined();
+ expect(screen.queryByRole("button", { name: /try again/i })).toBeNull();
+ });
+
+ it("does not treat an inactive 200 response as completed card setup", async () => {
+ server.use(
+ getPostTrialsConfirmTrialMockHandler200(
+ trialResponse({ active: false, status: "trialing" }),
+ ),
+ );
+ renderTrialReturn();
+ expect(await screen.findByText(/Your trial is not active/)).toBeDefined();
+ expect(screen.getByRole("button", { name: /try again/i })).toBeDefined();
+ expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();
+ });
+
+ it("accepts an already converted trial without showing another trial offer", async () => {
+ const confirm = vi.fn(() =>
+ trialResponse({ active: false, converted: true, status: "active" }),
+ );
+ server.use(getPostTrialsConfirmTrialMockHandler200(confirm));
+ renderTrialReturn();
+ await waitFor(() => expect(confirm).toHaveBeenCalledOnce());
+ await waitFor(() => expect(screen.queryByRole("status")).toBeNull());
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("region", { name: "AutoGPT trial" }),
+ ).toBeNull(),
+ );
+ });
+
+ it("does not confirm on ordinary billing visits", async () => {
+ searchParams = new URLSearchParams();
+ const confirm = vi.fn(() => trialResponse());
+ server.use(getPostTrialsConfirmTrialMockHandler200(confirm));
+ renderTrialReturn();
+ await screen.findByRole("button", { name: /start 7-day trial/i });
+ expect(screen.queryByRole("status")).toBeNull();
+ expect(confirm).not.toHaveBeenCalled();
+ });
+
+ it("cancels an older status request before publishing confirmed access", async () => {
+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();
+ let statusRequest: Request | undefined;
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(({ request }) => {
+ statusRequest = request;
+ return pending.promise;
+ }),
+ getPostTrialsConfirmTrialMockHandler200(async () => {
+ await waitFor(() => expect(statusRequest).toBeDefined());
+ return trialResponse();
+ }),
+ );
+ try {
+ renderTrialReturn();
+ await screen.findByRole("button", { name: "Cancel trial" });
+ expect(statusRequest?.signal.aborted).toBe(true);
+ } finally {
+ pending.resolve(
+ trialResponse({
+ eligible: true,
+ active: false,
+ status: "checkout_pending",
+ }),
+ );
+ }
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-pending-plan.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-pending-plan.test.tsx
new file mode 100644
index 0000000000..821eaf7753
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-pending-plan.test.tsx
@@ -0,0 +1,39 @@
+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 {
+ deferredTrialResponse,
+ setTrialUser,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
+import { SubscriptionTab } from "../components/SubscriptionTab/SubscriptionTab";
+
+vi.mock("../components/SubscriptionTab/YourPlanCard/YourPlanCard", () => ({
+ YourPlanCard: () => <div data-testid="paid-plan">Paid plan</div>,
+}));
+
+beforeEach(() => setTrialUser());
+afterEach(() => setTrialUser(null));
+
+it("does not mount the paid plan while initial trial status is pending", async () => {
+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();
+ server.use(getGetTrialsGetTrialStatusMockHandler200(() => pending.promise));
+ render(<SubscriptionTab />);
+ expect(screen.queryByTestId("paid-plan")).toBeNull();
+ pending.resolve(trialResponse());
+ await screen.findByRole("button", { name: "Cancel trial" });
+ expect(screen.queryByTestId("paid-plan")).toBeNull();
+});
+
+it("retains the paid plan fallback when trial status fails", async () => {
+ server.use(
+ http.get("*/api/credits/trial", () =>
+ HttpResponse.json({ detail: "Unavailable" }, { status: 503 }),
+ ),
+ );
+ render(<SubscriptionTab />);
+ await screen.findByRole("button", { name: /try again/i });
+ expect(screen.getByTestId("paid-plan")).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.tsx
new file mode 100644
index 0000000000..469e2e3dcb
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx
@@ -0,0 +1,56 @@
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, expect, it } 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";
+
+beforeEach(() => setTrialUser());
+afterEach(() => setTrialUser(null));
+
+it.each(["past_due", "unpaid", "incomplete_expired", "trialing", "canceled"])(
+ "keeps plan selection available for an inactive %s trial",
+ async (status) => {
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({ active: false, status }),
+ ),
+ 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([])),
+ );
+ render(<SettingsBillingPage />);
+ await screen.findByText("Your trial has ended");
+ expect(
+ await screen.findByText("Pick a plan to continue using AutoGPT."),
+ ).toBeDefined();
+ expect(screen.getByRole("button", { name: "Get Pro" })).toBeDefined();
+ },
+);
+
+it("keeps the regular plan card hidden during an active trial", async () => {
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),
+ http.get("*/api/credits/subscription", () =>
+ HttpResponse.json({
+ tier: "TRIAL",
+ monthly_cost: 0,
+ has_active_stripe_subscription: false,
+ }),
+ ),
+ http.get("*/api/credits/invoices", () => HttpResponse.json([])),
+ );
+ render(<SettingsBillingPage />);
+ await screen.findByRole("button", { name: "Cancel trial" });
+ expect(screen.queryByText("Your plan")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Get Pro" })).toBeNull();
+});
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.tsx
new file mode 100644
index 0000000000..14aeced7d9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-rejection.test.tsx
@@ -0,0 +1,112 @@
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";
+import { server } from "@/mocks/mock-server";
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import SettingsBillingPage from "../page";
+import {
+ setTrialUser,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
+
+let searchParams = new URLSearchParams();
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => searchParams,
+ usePathname: () => "/settings/billing",
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+}));
+beforeEach(() => setTrialUser());
+afterEach(() => setTrialUser(null));
+
+it.each([true, false])(
+ "explains a used introductory offer on checkout return=%s without a retry dead end",
+ async (isReturn) => {
+ searchParams = new URLSearchParams(isReturn ? "trial=success" : "");
+ const response = {
+ ...trialResponse({ active: false, status: "canceled" }),
+ rejection_reason: "intro_offer_already_used",
+ };
+ server.use(
+ http.get("*/api/credits/trial", () => HttpResponse.json(response)),
+ http.post("*/api/credits/trial/confirm", () =>
+ HttpResponse.json(response),
+ ),
+ );
+ render(
+ <>
+ <TrialCheckoutConfirmation />
+ <TrialCard />
+ </>,
+ );
+ await screen.findByText("This introductory offer has already been used");
+ await waitFor(() =>
+ expect(screen.queryByText(/Confirming your trial/)).toBeNull(),
+ );
+ expect(
+ screen.getByText(/card or account has already redeemed/),
+ ).toBeDefined();
+ expect(screen.getByText(/choose a paid plan/i)).toBeDefined();
+ expect(
+ screen.queryByText(/Cancellation confirmed|review your card setup/i),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("button", {
+ name: /try again|cancel trial|start.*trial/i,
+ }),
+ ).toBeNull();
+ },
+);
+
+it("does not accuse a card of reuse when fingerprint verification fails", async () => {
+ searchParams = new URLSearchParams("trial=success");
+ const response = {
+ ...trialResponse({ active: false, status: "canceled" }),
+ rejection_reason: "card_verification_failed",
+ };
+ server.use(
+ http.get("*/api/credits/trial", () => HttpResponse.json(response)),
+ http.post("*/api/credits/trial/confirm", () => HttpResponse.json(response)),
+ );
+ render(
+ <>
+ <TrialCheckoutConfirmation />
+ <TrialCard />
+ </>,
+ );
+ await screen.findByText("We couldn’t verify your card for this trial");
+ await waitFor(() =>
+ expect(screen.queryByText(/Confirming your trial/)).toBeNull(),
+ );
+ expect(
+ screen.queryByText(/already redeemed|Cancellation confirmed/),
+ ).toBeNull();
+ expect(screen.queryByRole("button", { name: /try again/i })).toBeNull();
+});
+
+it("keeps a paid-plan action and support available after rejection", async () => {
+ searchParams = new URLSearchParams("trial=success");
+ const response = trialResponse({
+ active: false,
+ status: "canceled",
+ rejection_reason: "intro_offer_already_used",
+ });
+ server.use(
+ http.get("*/api/credits/trial", () => HttpResponse.json(response)),
+ http.post("*/api/credits/trial/confirm", () => HttpResponse.json(response)),
+ 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([])),
+ );
+ render(<SettingsBillingPage />);
+ await screen.findByText("This introductory offer has already been used");
+ expect(await screen.findByRole("button", { name: "Get Pro" })).toBeDefined();
+ 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__/trial.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial.test.tsx
new file mode 100644
index 0000000000..87becbd6a4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial.test.tsx
@@ -0,0 +1,95 @@
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+import { server } from "@/mocks/mock-server";
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+
+const offer = {
+ token: "a".repeat(64),
+ version: "trial-v1",
+ duration_days: 7,
+ tier: "PRO",
+ billing_cycle: "monthly",
+ unit_amount: 2000,
+ currency: "usd",
+ onboarding_credit_amount: 300,
+};
+
+beforeEach(() => {
+ useAuthStore.setState({
+ user: { id: "trial-user", email: "[email protected]", user_metadata: {} },
+ isUserLoading: false,
+ hasLoadedUser: true,
+ });
+});
+
+afterEach(() => {
+ useAuthStore.setState({ user: null, hasLoadedUser: false });
+});
+
+describe("trial billing", () => {
+ it("does not describe a disabled pending checkout as an ended trial", async () => {
+ server.use(
+ http.get("*/api/credits/trial", () =>
+ HttpResponse.json({
+ eligible: false,
+ offer,
+ status: "checkout_pending",
+ }),
+ ),
+ );
+ const { container } = render(<TrialCard />);
+ expect(container.querySelector(".animate-pulse")).not.toBeNull();
+ await waitFor(() =>
+ expect(container.querySelector(".animate-pulse")).toBeNull(),
+ );
+ expect(screen.queryByRole("region", { name: "AutoGPT trial" })).toBeNull();
+ });
+
+ it("does not advertise a zero-credit onboarding grant", async () => {
+ server.use(
+ http.get("*/api/credits/trial", () =>
+ HttpResponse.json({
+ eligible: true,
+ offer: { ...offer, onboarding_credit_amount: 0 },
+ }),
+ ),
+ );
+ render(<TrialCard />);
+ await screen.findByRole("button", { name: /start 7-day trial/i });
+ expect(screen.queryByText(/0 one-time onboarding credits/i)).toBeNull();
+ });
+
+ it("shows accepted terms without onboarding-credit messaging", async () => {
+ server.use(
+ http.get("*/api/credits/trial", () =>
+ HttpResponse.json({ eligible: true, offer }),
+ ),
+ );
+ render(<TrialCard />);
+ expect(
+ await screen.findByRole("button", { name: /start 7-day trial/i }),
+ ).toBeDefined();
+ expect(screen.getByText(/card required/i)).toBeDefined();
+ expect(screen.getByText(/\$20\.00.*month/i)).toBeDefined();
+ expect(
+ screen.queryByText(/onboarding credits|one-time onboarding/i),
+ ).toBeNull();
+ });
+
+ it("omits credit messaging for an existing onboarding recipient", async () => {
+ server.use(
+ http.get("*/api/credits/trial", () =>
+ HttpResponse.json({
+ eligible: true,
+ offer,
+ onboarding_credits_previously_received: true,
+ }),
+ ),
+ );
+ render(<TrialCard />);
+ await screen.findByRole("button", { name: /start 7-day trial/i });
+ expect(screen.queryByText(/onboarding credits/i)).toBeNull();
+ });
+});
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.tsx
index 987ef0a085..ce6c69fa16 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
@@ -4,11 +4,18 @@ import { AutopilotUsageCard } from "./AutopilotUsageCard/AutopilotUsageCard";
import { InvoicesCard } from "./InvoicesCard/InvoicesCard";
import { PaymentMethodCard } from "./PaymentMethodCard/PaymentMethodCard";
import { YourPlanCard } from "./YourPlanCard/YourPlanCard";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";
+import { useTrialStatus } from "@/services/trials/useTrialStatus";
export function SubscriptionTab() {
+ const { data: trial, isLoading } = useTrialStatus();
+ const showPlan = !isLoading && (!trial?.active || trial.converted);
return (
<div className="flex flex-col gap-6">
- <YourPlanCard index={0} />
+ <TrialCheckoutConfirmation />
+ <TrialCard />
+ {showPlan ? <YourPlanCard index={0} /> : null}
<AutopilotUsageCard index={1} />
<PaymentMethodCard index={2} />
<InvoicesCard index={3} />
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.tsx
index 9ef0403df3..86a84b3c96 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
@@ -58,6 +58,8 @@ export function YourPlanCard({ index = 0 }: Props) {
const sectionMotion = getSectionMotionProps(index, Boolean(reduceMotion));
+ if (plan?.tierKey === "TRIAL") return null;
+
if (isLoading || !plan) {
return (
<motion.div {...sectionMotion}>
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index e747c25dd0..42a9bcc8e8 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -5767,6 +5767,139 @@
}
}
},
+ "/api/credits/trial": {
+ "get": {
+ "tags": ["trials"],
+ "summary": "Get Trial Status",
+ "operationId": "getTrialsGetTrialStatus",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/TrialStatusResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ }
+ },
+ "post": {
+ "tags": ["trials"],
+ "summary": "Start Trial Checkout",
+ "operationId": "postTrialsStartTrialCheckout",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "x-datafast-visitor-id",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "X-Datafast-Visitor-Id"
+ }
+ },
+ {
+ "name": "x-datafast-session-id",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "X-Datafast-Session-Id"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/TrialCheckoutRequest" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TrialCheckoutResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "409": { "description": "Trial offer unavailable" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "502": { "description": "Stripe checkout unavailable" },
+ "503": { "description": "Billing return URL not configured" }
+ }
+ }
+ },
+ "/api/credits/trial/cancel": {
+ "post": {
+ "tags": ["trials"],
+ "summary": "Cancel Trial",
+ "operationId": "postTrialsCancelTrial",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/TrialStatusResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "409": { "description": "No cancelable trial subscription" },
+ "502": {
+ "description": "Stripe cancellation temporarily unavailable"
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
+ "/api/credits/trial/confirm": {
+ "post": {
+ "tags": ["trials"],
+ "summary": "Confirm Trial",
+ "operationId": "postTrialsConfirmTrial",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/TrialStatusResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "409": {
+ "description": "Trial checkout is unavailable or no longer current"
+ },
+ "502": {
+ "description": "Stripe confirmation temporarily unavailable"
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/credits/{transaction_key}/refund": {
"post": {
"tags": ["v1", "credits"],
@@ -27651,6 +27784,7 @@
"type": "string",
"enum": [
"NO_TIER",
+ "TRIAL",
"BASIC",
"PRO",
"MAX",
@@ -27742,7 +27876,15 @@
},
"SubscriptionTier": {
"type": "string",
- "enum": ["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"],
+ "enum": [
+ "NO_TIER",
+ "TRIAL",
+ "BASIC",
+ "PRO",
+ "MAX",
+ "BUSINESS",
+ "ENTERPRISE"
+ ],
"title": "SubscriptionTier",
"description": "Subscription tiers with increasing cost allowances.\n\nMirrors the ``SubscriptionTier`` enum in ``schema.prisma``.\nOnce ``prisma generate`` is run, this can be replaced with::\n\n from prisma.enums import SubscriptionTier"
},
@@ -28899,6 +29041,124 @@
],
"title": "TransferResponse"
},
+ "TrialCheckoutRequest": {
+ "properties": {
+ "offer_token": {
+ "type": "string",
+ "pattern": "^[a-f0-9]{64}$",
+ "title": "Offer Token"
+ },
+ "return_to": {
+ "type": "string",
+ "enum": ["onboarding", "billing"],
+ "title": "Return To",
+ "default": "billing"
+ }
+ },
+ "type": "object",
+ "required": ["offer_token"],
+ "title": "TrialCheckoutRequest"
+ },
+ "TrialCheckoutResponse": {
+ "properties": { "url": { "type": "string", "title": "Url" } },
+ "type": "object",
+ "required": ["url"],
+ "title": "TrialCheckoutResponse"
+ },
+ "TrialOfferResponse": {
+ "properties": {
+ "token": { "type": "string", "title": "Token" },
+ "version": { "type": "string", "title": "Version" },
+ "duration_days": { "type": "integer", "title": "Duration Days" },
+ "tier": {
+ "type": "string",
+ "enum": ["BASIC", "PRO", "MAX", "BUSINESS"],
+ "title": "Tier"
+ },
+ "billing_cycle": {
+ "type": "string",
+ "enum": ["monthly", "yearly"],
+ "title": "Billing Cycle"
+ },
+ "unit_amount": { "type": "integer", "title": "Unit Amount" },
+ "currency": { "type": "string", "title": "Currency" },
+ "onboarding_credit_amount": {
+ "type": "integer",
+ "title": "Onboarding Credit Amount"
+ }
+ },
+ "type": "object",
+ "required": [
+ "token",
+ "version",
+ "duration_days",
+ "tier",
+ "billing_cycle",
+ "unit_amount",
+ "currency",
+ "onboarding_credit_amount"
+ ],
+ "title": "TrialOfferResponse"
+ },
+ "TrialRejectionReason": {
+ "type": "string",
+ "enum": ["intro_offer_already_used", "card_verification_failed"],
+ "title": "TrialRejectionReason"
+ },
+ "TrialStatusResponse": {
+ "properties": {
+ "eligible": {
+ "type": "boolean",
+ "title": "Eligible",
+ "default": false
+ },
+ "offer": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/TrialOfferResponse" },
+ { "type": "null" }
+ ]
+ },
+ "status": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Status"
+ },
+ "rejection_reason": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/TrialRejectionReason" },
+ { "type": "null" }
+ ]
+ },
+ "ends_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Ends At"
+ },
+ "cancel_at_period_end": {
+ "type": "boolean",
+ "title": "Cancel At Period End",
+ "default": false
+ },
+ "allowance_used_percent": {
+ "anyOf": [{ "type": "number" }, { "type": "null" }],
+ "title": "Allowance Used Percent"
+ },
+ "active": { "type": "boolean", "title": "Active", "default": false },
+ "converted": {
+ "type": "boolean",
+ "title": "Converted",
+ "default": false
+ },
+ "onboarding_credits_previously_received": {
+ "type": "boolean",
+ "title": "Onboarding Credits Previously Received",
+ "default": false
+ }
+ },
+ "type": "object",
+ "title": "TrialStatusResponse"
+ },
"TriggeredPresetSetupRequest": {
"properties": {
"name": { "type": "string", "title": "Name" },
diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx
index bbfaad0654..2a8975f8ba 100644
--- a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx
@@ -1,6 +1,7 @@
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
-import { expect, test } from "vitest";
+import { toast } from "sonner";
+import { afterEach, expect, test } from "vitest";
import {
getGetV2GetPendingReviewsMockHandler200,
getPostV2ProcessReviewActionMockHandler200,
@@ -11,6 +12,10 @@ import { server } from "@/mocks/mock-server";
import { render, screen, waitFor } from "@/tests/integrations/test-utils";
import { NeedsAttentionList } from "../NeedsAttentionList";
+afterEach(() => {
+ toast.dismiss();
+});
+
const review: PendingHumanReviewModel = {
node_exec_id: "ne-1",
node_id: "n-1",
@@ -51,6 +56,12 @@ test("renders attributed rows and approves in one tap", async () => {
reviews: [{ node_exec_id: "ne-1", approved: true }],
}),
);
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: /^Approve:/ })).toHaveProperty(
+ "disabled",
+ false,
+ ),
+ );
});
test("only the acted row locks while its decision is in flight", async () => {
@@ -82,6 +93,11 @@ test("only the acted row locks while its decision is in flight", async () => {
expect(first.disabled).toBe(true);
expect(second.disabled).toBe(false);
});
+ await waitFor(() =>
+ expect(
+ screen.getAllByRole("button", { name: /^Approve:/ })[0],
+ ).toHaveProperty("disabled", false),
+ );
});
test("confirms a successful decision with a toast", async () => {
@@ -135,6 +151,12 @@ test("decline sends a rejection", async () => {
// No canned reason: this surface has no field to write one in, so nothing
// should reach the agent context / audit trail as if the user typed it.
expect(actionBody?.reviews[0].message).toBeUndefined();
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: /^Decline:/ })).toHaveProperty(
+ "disabled",
+ false,
+ ),
+ );
});
test("armed decline is announced and visually distinct, not just relabelled", async () => {
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsx
new file mode 100644
index 0000000000..53b4bbcfc5
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsx
@@ -0,0 +1,50 @@
+import { useState } from "react";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+
+interface Props {
+ isCanceling: boolean;
+ onCancel: () => void;
+}
+
+export function CancelTrialDialog({ isCanceling, onCancel }: Props) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ function confirmCancellation() {
+ setIsOpen(false);
+ onCancel();
+ }
+
+ return (
+ <Dialog
+ title="End your trial now?"
+ styling={{ maxWidth: "440px" }}
+ controlled={{ isOpen, set: setIsOpen }}
+ >
+ <Dialog.Trigger>
+ <Button variant="outline" loading={isCanceling} disabled={isCanceling}>
+ Cancel trial
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <Text variant="body">
+ Your trial access will end immediately and your trial will not convert
+ to a paid plan. You cannot restart this trial.
+ </Text>
+ <Dialog.Footer>
+ <Button variant="outline" onClick={() => setIsOpen(false)}>
+ Keep trial
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={confirmCancellation}
+ disabled={isCanceling}
+ >
+ End trial now
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx
new file mode 100644
index 0000000000..56ce8e332e
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { TrialOffer } from "./TrialOffer";
+import { TrialStatus } from "./TrialStatus";
+import { useTrialCard } from "./useTrialCard";
+
+interface Props {
+ returnTo?: "onboarding" | "billing";
+}
+
+export function TrialCard({ returnTo = "billing" }: Props) {
+ const {
+ userID,
+ trial,
+ isLoading,
+ queryError,
+ error,
+ retry,
+ isStarting,
+ isCanceling,
+ startTrial,
+ cancelTrial,
+ } = useTrialCard(returnTo);
+ if (isLoading) return <Skeleton className="h-36 w-full rounded-2xl" />;
+ if (queryError)
+ return <ErrorCard context="trial information" onRetry={retry} />;
+ if (
+ !trial?.offer ||
+ trial.converted ||
+ (!trial.eligible && trial.status === "checkout_pending")
+ )
+ return null;
+ return (
+ <section
+ aria-label="AutoGPT trial"
+ className="w-full rounded-2xl border border-border bg-background p-6 text-textBlack"
+ >
+ {trial.eligible ? (
+ <TrialOffer
+ trial={trial}
+ isStarting={isStarting}
+ onStart={startTrial}
+ />
+ ) : (
+ <TrialStatus
+ key={userID}
+ trial={trial}
+ isCanceling={isCanceling}
+ onCancel={cancelTrial}
+ />
+ )}
+ {error ? (
+ <p role="alert" className="mt-3 text-sm text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCheckoutConfirmation.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCheckoutConfirmation.tsx
new file mode 100644
index 0000000000..d4557d58ff
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCheckoutConfirmation.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { useTrialCheckoutReturn } from "@/services/trials/useTrialCheckoutReturn";
+
+export function TrialCheckoutConfirmation() {
+ const confirmation = useTrialCheckoutReturn();
+ if (confirmation.error)
+ return (
+ <ErrorCard
+ context="your trial"
+ responseError={{ message: confirmation.error }}
+ onRetry={confirmation.retry}
+ />
+ );
+ if (!confirmation.ready)
+ return (
+ <Text variant="body" role="status">
+ Confirming your trial and card setup…
+ </Text>
+ );
+ return null;
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx
new file mode 100644
index 0000000000..b67c1219f1
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx
@@ -0,0 +1,39 @@
+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { formatTrialPrice, trialPlanLabels } from "./helpers";
+
+interface Props {
+ trial: TrialStatusResponse;
+ isStarting: boolean;
+ onStart: () => void;
+}
+
+export function TrialOffer({ trial, isStarting, onStart }: Props) {
+ const offer = trial.offer;
+ if (!offer) return null;
+ return (
+ <div className="flex flex-col gap-3">
+ <Text variant="h4">
+ Try AutoGPT {trialPlanLabels[offer.tier]} for {offer.duration_days} days
+ </Text>
+ <Text variant="body" unmask={false}>
+ Card required. No subscription charge today. Then{" "}
+ {formatTrialPrice(offer)}, plus applicable tax, unless you cancel before
+ the trial ends.
+ </Text>
+ <Text variant="small">
+ Trial usage is limited. Canceling ends trial access immediately. You can
+ manage your plan in billing.
+ </Text>
+ <Button
+ variant="primary"
+ onClick={onStart}
+ loading={isStarting}
+ disabled={isStarting}
+ >
+ Start {offer.duration_days}-day trial
+ </Button>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialRejection.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialRejection.tsx
new file mode 100644
index 0000000000..710152b237
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialRejection.tsx
@@ -0,0 +1,40 @@
+import type { TrialRejectionReason } from "@/app/api/__generated__/models/trialRejectionReason";
+import { Text } from "@/components/atoms/Text/Text";
+import { Button } from "@/components/atoms/Button/Button";
+
+interface Props {
+ reason: TrialRejectionReason;
+}
+
+export function TrialRejection({ reason }: Props) {
+ const alreadyUsed = reason === "intro_offer_already_used";
+ return (
+ <div role="status" className="flex flex-col gap-3">
+ <Text variant="h4">
+ {alreadyUsed
+ ? "This introductory offer has already been used"
+ : "We couldn’t verify your card for this trial"}
+ </Text>
+ <Text variant="body">
+ {alreadyUsed
+ ? "This card or account has already redeemed an introductory offer. Each card and account can use one introductory offer."
+ : "Your card could not be verified for trial eligibility, so this trial was not activated."}
+ </Text>
+ <Text variant="body">
+ This trial will not convert to a paid subscription. You can choose a
+ paid plan below. If you think this is a mistake, contact support.
+ </Text>
+ <Button
+ as="NextLink"
+ href="https://discord.gg/autogpt"
+ target="_blank"
+ rel="noopener noreferrer"
+ variant="outline"
+ size="small"
+ className="self-start"
+ >
+ Contact support
+ </Button>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsx
new file mode 100644
index 0000000000..25c9b86bb9
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsx
@@ -0,0 +1,60 @@
+import type { Meta, StoryObj } from "@storybook/nextjs";
+import { TrialStatus } from "./TrialStatus";
+
+const meta = {
+ title: "Organisms/TrialStatus",
+ component: TrialStatus,
+ args: {
+ trial: {
+ active: true,
+ ends_at: new Date("2030-09-17T15:00:00Z"),
+ allowance_used_percent: 42.4,
+ cancel_at_period_end: false,
+ offer: {
+ token: "a".repeat(64),
+ version: "storybook-trial",
+ duration_days: 7,
+ tier: "PRO",
+ billing_cycle: "monthly",
+ unit_amount: 2000,
+ currency: "usd",
+ onboarding_credit_amount: 300,
+ },
+ },
+ isCanceling: false,
+ onCancel: function onCancel() {},
+ },
+} satisfies Meta<typeof TrialStatus>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Active: Story = {};
+
+export const Canceled: Story = {
+ args: {
+ trial: { ...meta.args.trial, active: false, status: "canceled" },
+ },
+};
+
+export const IntroductoryOfferUsed: Story = {
+ args: {
+ trial: {
+ ...meta.args.trial,
+ active: false,
+ status: "canceled",
+ rejection_reason: "intro_offer_already_used",
+ },
+ },
+};
+
+export const CardVerificationFailed: Story = {
+ args: {
+ trial: {
+ ...meta.args.trial,
+ active: false,
+ status: "canceled",
+ rejection_reason: "card_verification_failed",
+ },
+ },
+};
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx
new file mode 100644
index 0000000000..bdd894dd4e
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx
@@ -0,0 +1,40 @@
+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";
+import { Text } from "@/components/atoms/Text/Text";
+import { CancelTrialDialog } from "./CancelTrialDialog";
+import { formatTrialEnd, formatTrialPrice } from "./helpers";
+import { TrialRejection } from "./TrialRejection";
+
+interface Props {
+ trial: TrialStatusResponse;
+ isCanceling: boolean;
+ onCancel: () => void;
+}
+
+export function TrialStatus({ trial, isCanceling, onCancel }: Props) {
+ if (!trial.offer) return null;
+ if (trial.status === "canceled" && trial.rejection_reason)
+ return <TrialRejection reason={trial.rejection_reason} />;
+ const end = formatTrialEnd(trial.ends_at);
+ return (
+ <div className="flex flex-col gap-3">
+ <Text variant="h4">
+ {trial.active ? "Your trial" : "Your trial has ended"}
+ </Text>
+ <Text variant="body" unmask={false}>
+ {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">Canceling ends trial access immediately.</Text>
+ ) : null}
+ {trial.active && !trial.cancel_at_period_end ? (
+ <CancelTrialDialog isCanceling={isCanceling} onCancel={onCancel} />
+ ) : null}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts
new file mode 100644
index 0000000000..8af6569a64
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts
@@ -0,0 +1,26 @@
+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";
+
+export const trialPlanLabels: Record<TrialOfferResponse["tier"], string> = {
+ BASIC: "Basic",
+ PRO: "Pro",
+ MAX: "Max",
+ BUSINESS: "Team",
+};
+
+export function formatTrialPrice(offer: TrialOfferResponse) {
+ const formatter = new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: offer.currency,
+ });
+ const decimals = formatter.resolvedOptions().maximumFractionDigits ?? 2;
+ const amount = formatter.format(offer.unit_amount / 10 ** decimals);
+ return `${amount} / ${offer.billing_cycle === "yearly" ? "year" : "month"}`;
+}
+
+export function formatTrialEnd(value: Date | string | null | undefined) {
+ if (!value) return "the end of your trial";
+ return new Date(value).toLocaleString(undefined, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ });
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts
new file mode 100644
index 0000000000..2f8603ca53
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts
@@ -0,0 +1,100 @@
+import {
+ usePostTrialsCancelTrial,
+ usePostTrialsStartTrialCheckout,
+} from "@/app/api/__generated__/endpoints/trials/trials";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+import { useTrialStatus } from "@/services/trials/useTrialStatus";
+import { updateTrialStatusCache } from "@/services/trials/updateTrialStatusCache";
+import { useQueryClient } from "@tanstack/react-query";
+import { usePostHog } from "@posthog/react";
+import { useEffect, useRef, useState } from "react";
+
+export function useTrialCard(returnTo: "onboarding" | "billing") {
+ const userID = useAuthStore((state) => state.user?.id);
+ const queryClient = useQueryClient();
+ const posthog = usePostHog();
+ const seenOffer = useRef<string | null>(null);
+ const [failure, setFailure] = useState<{
+ userID: string;
+ message: string;
+ } | null>(null);
+ const query = useTrialStatus();
+ const { mutateAsync: checkout, isPending: isStarting } =
+ usePostTrialsStartTrialCheckout();
+ const { mutateAsync: cancel, isPending: isCanceling } =
+ usePostTrialsCancelTrial();
+ const offer = query.data?.eligible ? query.data.offer : null;
+
+ useEffect(() => {
+ if (!offer || !userID) return;
+ const identity = `${userID}:${offer.token}`;
+ if (seenOffer.current === identity) return;
+ seenOffer.current = identity;
+ posthog?.capture("subscription_trial_offer_viewed", {
+ trial_offer_version: offer.version,
+ subscription_tier: offer.tier,
+ trial_duration_days: offer.duration_days,
+ surface: returnTo,
+ });
+ }, [offer, userID, posthog, returnTo]);
+
+ async function startTrial() {
+ if (!offer || !userID || isStarting) return;
+ setFailure(null);
+ try {
+ const response = await checkout({
+ data: { offer_token: offer.token, return_to: returnTo },
+ });
+ if (useAuthStore.getState().user?.id !== userID) return;
+ if (response.status !== 200)
+ throw new Error("Unable to start trial checkout.");
+ posthog?.capture("subscription_trial_checkout_started", {
+ trial_offer_version: offer.version,
+ surface: returnTo,
+ });
+ window.location.assign(response.data.url);
+ } catch (error) {
+ setFailure({
+ userID,
+ message:
+ error instanceof Error
+ ? error.message
+ : "Unable to start trial checkout.",
+ });
+ await query.refetch();
+ }
+ }
+
+ async function cancelTrial() {
+ if (!userID || isCanceling) return;
+ setFailure(null);
+ try {
+ const response = await cancel();
+ if (useAuthStore.getState().user?.id !== userID) return;
+ if (response.status !== 200)
+ throw new Error("Unable to cancel your trial.");
+ await updateTrialStatusCache({ queryClient, userID, response });
+ } catch (error) {
+ setFailure({
+ userID,
+ message:
+ error instanceof Error
+ ? error.message
+ : "Unable to cancel your trial.",
+ });
+ }
+ }
+
+ return {
+ userID,
+ trial: query.data,
+ isLoading: Boolean(userID) && query.isLoading,
+ error: failure && failure.userID === userID ? failure.message : null,
+ queryError: query.isError,
+ retry: () => query.refetch(),
+ isStarting,
+ isCanceling,
+ startTrial,
+ cancelTrial,
+ };
+}
diff --git a/autogpt_platform/frontend/src/playwright/pages/settings.page.ts b/autogpt_platform/frontend/src/playwright/pages/settings.page.ts
index 3a39bb792c..b018fa42be 100644
--- a/autogpt_platform/frontend/src/playwright/pages/settings.page.ts
+++ b/autogpt_platform/frontend/src/playwright/pages/settings.page.ts
@@ -11,7 +11,7 @@ export class SettingsPage extends BasePage {
await expect(this.page).toHaveURL(/\/profile\/settings/);
await expect(
this.page.getByText("Manage your account settings and preferences."),
- ).toBeVisible();
+ ).toBeVisible({ timeout: 15000 });
}
getAlertsSwitch(): Locator {
diff --git a/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.ts b/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.ts
new file mode 100644
index 0000000000..4fcda74cb1
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.ts
@@ -0,0 +1,26 @@
+import { getGetSubscriptionStatusQueryKey } from "@/app/api/__generated__/endpoints/credits/credits";
+import {
+ getGetTrialsGetTrialStatusQueryKey,
+ type getTrialsGetTrialStatusResponseSuccess,
+} from "@/app/api/__generated__/endpoints/trials/trials";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+import type { QueryClient } from "@tanstack/react-query";
+
+export async function updateTrialStatusCache({
+ queryClient,
+ userID,
+ response,
+}: {
+ queryClient: QueryClient;
+ userID: string;
+ response: getTrialsGetTrialStatusResponseSuccess;
+}) {
+ const queryKey = [...getGetTrialsGetTrialStatusQueryKey(), userID];
+ await queryClient.cancelQueries({ queryKey, exact: true });
+ if (useAuthStore.getState().user?.id !== userID) return false;
+ queryClient.setQueryData(queryKey, response);
+ await queryClient.invalidateQueries({
+ queryKey: getGetSubscriptionStatusQueryKey(),
+ });
+ return useAuthStore.getState().user?.id === userID;
+}
diff --git a/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.ts b/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.ts
new file mode 100644
index 0000000000..3cb7553dfe
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.ts
@@ -0,0 +1,73 @@
+import { usePostTrialsConfirmTrial } from "@/app/api/__generated__/endpoints/trials/trials";
+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+import { useQueryClient } from "@tanstack/react-query";
+import { useSearchParams } from "next/navigation";
+import { useEffect, useRef, useState } from "react";
+import { updateTrialStatusCache } from "./updateTrialStatusCache";
+
+export function useTrialCheckoutReturn() {
+ const userID = useAuthStore((state) => state.user?.id);
+ const params = useSearchParams();
+ const isReturn = useRef(false);
+ if (params.get("trial") === "success") isReturn.current = true;
+ const requested = useRef<string | null>(null);
+ const [attempt, setAttempt] = useState(0);
+ const [result, setResult] = useState<{
+ userID: string;
+ trial?: TrialStatusResponse;
+ error?: string;
+ } | null>(null);
+ const queryClient = useQueryClient();
+ const { mutateAsync: confirm } = usePostTrialsConfirmTrial();
+
+ useEffect(() => {
+ if (
+ !isReturn.current ||
+ !userID ||
+ requested.current === `${userID}:${attempt}`
+ )
+ return;
+ requested.current = `${userID}:${attempt}`;
+ confirm()
+ .then(async (response) => {
+ if (useAuthStore.getState().user?.id !== userID) return;
+ if (response.status !== 200)
+ throw new Error("Could not confirm your trial.");
+ if (!(await updateTrialStatusCache({ queryClient, userID, response })))
+ return;
+ if (
+ !response.data.active &&
+ !response.data.converted &&
+ response.data.status !== "canceled"
+ )
+ throw new Error(
+ "Your trial is not active. Review your card setup and try again.",
+ );
+ setResult({ userID, trial: response.data });
+ })
+ .catch((error: unknown) => {
+ if (useAuthStore.getState().user?.id === userID) {
+ setResult({
+ userID,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Could not confirm your trial.",
+ });
+ }
+ });
+ }, [userID, attempt, confirm, queryClient]);
+
+ const current = result && result.userID === userID ? result : null;
+ function retry() {
+ setResult(null);
+ setAttempt((value) => value + 1);
+ }
+ return {
+ ready: !isReturn.current || current !== null,
+ error: current?.error,
+ active: current?.trial?.active || current?.trial?.converted,
+ retry,
+ };
+}
diff --git a/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts b/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts
new file mode 100644
index 0000000000..043da8a2ee
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts
@@ -0,0 +1,18 @@
+import {
+ getGetTrialsGetTrialStatusQueryKey,
+ useGetTrialsGetTrialStatus,
+} from "@/app/api/__generated__/endpoints/trials/trials";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+
+export function useTrialStatus() {
+ const userID = useAuthStore((state) => state.user?.id);
+ return useGetTrialsGetTrialStatus({
+ query: {
+ queryKey: [...getGetTrialsGetTrialStatusQueryKey(), userID],
+ enabled: Boolean(userID),
+ retry: false,
+ select: (response) =>
+ response.status === 200 ? response.data : undefined,
+ },
+ });
+}
diff --git a/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.ts b/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.ts
new file mode 100644
index 0000000000..d9f2457864
--- /dev/null
+++ b/autogpt_platform/frontend/src/tests/integrations/trial-fixtures.ts
@@ -0,0 +1,49 @@
+import { getGetTrialsGetTrialStatusResponseMock200 } from "@/app/api/__generated__/endpoints/trials/trials.msw";
+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";
+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+
+export const trialOffer: TrialOfferResponse = {
+ token: "a".repeat(64),
+ version: "trial-v1",
+ duration_days: 7,
+ tier: "PRO",
+ billing_cycle: "monthly",
+ unit_amount: 2000,
+ currency: "usd",
+ onboarding_credit_amount: 300,
+};
+
+export function trialResponse(overrides: Partial<TrialStatusResponse> = {}) {
+ return getGetTrialsGetTrialStatusResponseMock200({
+ eligible: false,
+ offer: trialOffer,
+ status: "trialing",
+ rejection_reason: null,
+ ends_at: new Date("2030-09-17T15:00:00Z"),
+ cancel_at_period_end: false,
+ allowance_used_percent: 42.4,
+ active: true,
+ converted: false,
+ onboarding_credits_previously_received: false,
+ ...overrides,
+ });
+}
+
+export function setTrialUser(userID: string | null = "trial-user") {
+ useAuthStore.setState({
+ user: userID
+ ? { id: userID, email: `${userID}@example.com`, user_metadata: {} }
+ : null,
+ isUserLoading: false,
+ hasLoadedUser: true,
+ });
+}
+
+export function deferredTrialResponse<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((complete) => {
+ resolve = complete;
+ });
+ return { promise, resolve };
+}
diff --git a/docs/platform/getting-started.md b/docs/platform/getting-started.md
index c0588b4ebb..9d1210d8d6 100644
--- a/docs/platform/getting-started.md
+++ b/docs/platform/getting-started.md
@@ -140,8 +140,8 @@ make help
You can check if the server is running by visiting [http://localhost:3000](http://localhost:3000) in your browser.
**Notes:**
-
-By default the application for different services run on the following ports:
+
+By default the application for different services run on the following ports:
Frontend UI Server: 3000
Backend Websocket Server: 8001
@@ -462,7 +462,7 @@ make format
To run the tests:
```sh
-poetry run pytest -s
+poetry run pytest -s
```
## Adding a New Agent Block