Skip to content

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

fix(backend/credit): reserve TOP_UP for real Stripe checkouts; refunds use grant_credits (#12959)

Zamil Majdy21e487ea8da0
diff --git a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py
index 8930172c7f..c84ca292d9 100644
--- a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py
+++ b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py
@@ -56,6 +56,7 @@ async def admin_get_all_user_history(
page: int = 1,
page_size: int = 20,
transaction_filter: typing.Optional[CreditTransactionType] = None,
+ include_inactive: bool = False,
):
""" """
logger.info(f"Admin user {admin_user_id} is getting grant history")
@@ -66,6 +67,7 @@ async def admin_get_all_user_history(
page_size=page_size,
search=search,
transaction_filter=transaction_filter,
+ include_inactive=include_inactive,
)
logger.info(f"Admin user {admin_user_id} got {len(resp.history)} grant history")
return resp
diff --git a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py
index db2d3cb41a..d590f95a5f 100644
--- a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py
@@ -220,6 +220,7 @@ def test_get_user_history_with_filters(
page_size=10,
transaction_filter=prisma.enums.CreditTransactionType.TOP_UP,
+ include_inactive=False,
)
# Snapshot test the response
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 768ebf2121..550dc99b84 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -758,10 +758,15 @@ async def reset_copilot_usage(
# Reset daily usage in Redis. If this fails, refund the credits
# so the user is not charged for a service they did not receive.
if not await reset_daily_usage(user_id, daily_cost_limit=daily_limit):
- # Compensate: refund the charged credits.
+ # Compensate: refund the charged credits as a GRANT (no Stripe
+ # charge — TOP_UP is reserved for real user-initiated checkouts).
refunded = False
try:
- await credit_model.top_up_credits(user_id, cost)
+ await credit_model.grant_credits(
+ user_id,
+ cost,
+ "Refund for failed CoPilot rate-limit reset",
+ )
refunded = True
logger.warning(
"Refunded %d credits to user %s after Redis reset failure",
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 914a15f58f..7aba4b7e97 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -1368,6 +1368,7 @@ def _mock_reset_internals(
mock_credit_model = MagicMock()
mock_credit_model.spend_credits = AsyncMock(return_value=remaining_balance)
mock_credit_model.top_up_credits = AsyncMock(return_value=None)
+ mock_credit_model.grant_credits = AsyncMock(return_value=remaining_balance)
mocker.patch(
"backend.api.features.chat.routes.get_user_credit_model",
new_callable=AsyncMock,
@@ -1586,8 +1587,10 @@ def test_reset_usage_refunds_on_redis_failure(
response = client.post("/usage/reset")
assert response.status_code == 503
- # Credits should be refunded via top_up_credits
- mock_credit.top_up_credits.assert_called_once()
+ # Credits should be refunded via grant_credits (GRANT, not TOP_UP), and
+ # the Stripe-charging top_up_credits path must not be hit.
+ mock_credit.grant_credits.assert_called_once()
+ mock_credit.top_up_credits.assert_not_called()
# ─── resume_session_stream ───────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/copilot/reset_usage_test.py b/autogpt_platform/backend/backend/copilot/reset_usage_test.py
index d5b4ee140e..b9ffc81da5 100644
--- a/autogpt_platform/backend/backend/copilot/reset_usage_test.py
+++ b/autogpt_platform/backend/backend/copilot/reset_usage_test.py
@@ -282,14 +282,16 @@ class TestResetCopilotUsage:
await reset_copilot_usage(user_id="user-1")
assert exc_info.value.status_code == 503
assert "not been charged" in exc_info.value.detail
- mock_credit_model.top_up_credits.assert_awaited_once()
+ mock_credit_model.grant_credits.assert_awaited_once()
+ # Refund must NOT route through Stripe top-up.
+ mock_credit_model.top_up_credits.assert_not_called()
async def test_redis_reset_failure_refund_also_fails(self):
"""When both reset and refund fail, error message reflects the truth."""
mock_credit_model = AsyncMock()
mock_credit_model.spend_credits.return_value = 1500
- mock_credit_model.top_up_credits.side_effect = RuntimeError("db down")
+ mock_credit_model.grant_credits.side_effect = RuntimeError("db down")
cfg = _make_config()
with (
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 12c8ccd220..0f84ff2f04 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -167,6 +167,37 @@ class UserCreditBase(ABC):
"""
pass
+ @abstractmethod
+ async def grant_credits(
+ self,
+ user_id: str,
+ amount: int,
+ reason: str,
+ transaction_key: str | None = None,
+ ) -> int:
+ """
+ Grant non-purchased credits to the user (no Stripe charge).
+
+ Use this for any credit movement that is NOT a user-initiated Stripe
+ checkout: in-app refunds for failed services, beta-tester top-ups,
+ manual corrections, subscription credit grants, etc. Writes a
+ ``GRANT`` row so the dashboard does not misreport free credits as
+ ``TOP_UP`` (which is reserved for real Stripe checkouts).
+
+ Args:
+ user_id (str): The user ID.
+ amount (int): The amount of credits to grant (positive).
+ reason (str): Human-readable reason recorded in transaction metadata.
+ transaction_key (str | None): Optional deterministic key for
+ idempotent retries. If supplied and a row already exists with
+ this key for the user, the existing balance is returned
+ without inserting a new row.
+
+ Returns:
+ int: The new balance after the grant.
+ """
+ pass
+
@abstractmethod
async def onboarding_reward(
self, user_id: str, credits: int, step: OnboardingStep
@@ -681,6 +712,29 @@ class UserCredit(UserCreditBase):
user_id=user_id, amount=amount, top_up_type=top_up_type
)
+ async def grant_credits(
+ self,
+ user_id: str,
+ amount: int,
+ reason: str,
+ transaction_key: str | None = None,
+ ) -> int:
+ if amount < 0:
+ raise ValueError(f"Grant amount must not be negative: {amount}")
+ try:
+ balance, _ = await self._add_transaction(
+ user_id=user_id,
+ amount=amount,
+ transaction_type=CreditTransactionType.GRANT,
+ transaction_key=transaction_key,
+ metadata=SafeJson({"reason": reason}),
+ )
+ except UniqueViolationError:
+ # Idempotent: another request with the same transaction_key already
+ # granted this — return the current balance without double-crediting.
+ balance, _ = await self._get_credits(user_id)
+ return balance
+
async def onboarding_reward(self, user_id: str, credits: int, step: OnboardingStep):
try:
await self._add_transaction(
@@ -1279,6 +1333,9 @@ class DisabledUserCredit(UserCreditBase):
async def top_up_credits(self, *args, **kwargs):
pass
+ async def grant_credits(self, *args, **kwargs) -> int:
+ return 100
+
async def onboarding_reward(self, *args, **kwargs) -> bool:
return True
@@ -2583,12 +2640,16 @@ async def admin_get_user_history(
page_size: int = 20,
search: str | None = None,
transaction_filter: CreditTransactionType | None = None,
+ include_inactive: bool = False,
) -> UserHistoryResponse:
if page < 1 or page_size < 1:
raise ValueError("Invalid pagination input")
where_clause: CreditTransactionWhereInput = {}
+ # Off by default so phantom rows from abandoned Stripe checkouts aren't surfaced.
+ if not include_inactive:
+ where_clause["isActive"] = True
if transaction_filter:
where_clause["type"] = transaction_filter
if search:
@@ -2622,7 +2683,12 @@ async def admin_get_user_history(
if admin_id
else ""
)
- reason = metadata.get("reason", "No reason provided")
+ # Older _top_up_credits rows wrap reason as {"reason": {"reason": "..."}};
+ # unwrap so the dashboard column shows the plain string.
+ raw_reason = metadata.get("reason", "No reason provided")
+ if isinstance(raw_reason, dict):
+ raw_reason = raw_reason.get("reason", "No reason provided")
+ reason = str(raw_reason)
user_credit_model = await get_user_credit_model(tx.userId)
balance, _ = await user_credit_model._get_credits(tx.userId)
diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.py
index 05f06621dd..69d59e15f4 100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@ -3140,3 +3140,86 @@ async def test_release_pending_subscription_schedule_invalidates_cache_on_partia
await release_pending_subscription_schedule("user-partial")
mock_cache_delete.assert_called_once_with("user-partial")
+
+
+# ─── TOP_UP vs GRANT routing ─────────────────────────────────────────────
+
+
+async def test_grant_credits_writes_grant_not_top_up():
+ """grant_credits writes a GRANT row and never touches Stripe — TOP_UP is
+ reserved for actual user-initiated Stripe checkouts."""
+ from prisma.enums import CreditTransactionType
+
+ from backend.data.credit import UserCredit
+ from backend.util.json import SafeJson
+
+ credit_system = UserCredit()
+ add_tx_mock = AsyncMock(return_value=(1500, "grant-txkey"))
+ with patch.object(credit_system, "_add_transaction", add_tx_mock):
+ balance = await credit_system.grant_credits(
+ "user-1", 500, "Refund for failed CoPilot rate-limit reset"
+ )
+
+ assert balance == 1500
+ add_tx_mock.assert_awaited_once()
+ kwargs = add_tx_mock.await_args.kwargs
+ assert kwargs["transaction_type"] == CreditTransactionType.GRANT
+ metadata = kwargs["metadata"]
+ assert isinstance(metadata, SafeJson)
+ assert metadata.data["reason"] == "Refund for failed CoPilot rate-limit reset"
+
+
+async def test_grant_credits_rejects_negative_amount():
+ """grant_credits only adds credits — negative amounts must raise."""
+ from backend.data.credit import UserCredit
+
+ credit_system = UserCredit()
+ with pytest.raises(ValueError, match="must not be negative"):
+ await credit_system.grant_credits("user-1", -100, "bug")
+
+
+async def test_admin_get_user_history_excludes_inactive_by_default():
+ """Default call must filter out inactive ledger rows so phantom TOP_UP entries
+ from abandoned Stripe checkouts don't pollute the admin dashboard."""
+ from backend.data.credit import admin_get_user_history
+
+ prisma_mock = MagicMock(
+ find_many=AsyncMock(return_value=[]),
+ count=AsyncMock(return_value=0),
+ )
+ with patch(
+ "backend.data.credit.CreditTransaction.prisma", return_value=prisma_mock
+ ):
+ await admin_get_user_history()
+
+ where = prisma_mock.find_many.await_args.kwargs["where"]
+ assert where == {"isActive": True}
+ count_where = prisma_mock.count.await_args.kwargs["where"]
+ assert count_where == {"isActive": True}
+
+
+async def test_admin_get_user_history_include_inactive_omits_filter():
+ """include_inactive=True surfaces phantom rows for debugging abandoned checkouts."""
+ from prisma.enums import CreditTransactionType
+
+ from backend.data.credit import admin_get_user_history
+
+ prisma_mock = MagicMock(
+ find_many=AsyncMock(return_value=[]),
+ count=AsyncMock(return_value=0),
+ )
+ with patch(
+ "backend.data.credit.CreditTransaction.prisma", return_value=prisma_mock
+ ):
+ await admin_get_user_history(
+ transaction_filter=CreditTransactionType.TOP_UP,
+ include_inactive=True,
+ )
+
+ where = prisma_mock.find_many.await_args.kwargs["where"]
+ assert "isActive" not in where
+ assert where["type"] == CreditTransactionType.TOP_UP
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 25871bb0b7..2996b73d65 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3104,6 +3104,16 @@
],
"title": "Transaction Filter"
}
+ },
+ {
+ "name": "include_inactive",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "default": false,
+ "title": "Include Inactive"
+ }
}
],
"responses": {