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(platform): show NO_TIER in admin rate-limit display + aggregate reconciliation alerting into one Discord alert (#13291)

Zamil Majdy2675d26996d1
diff --git a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py
index 3b9c762f21..58d65bec9a 100644
--- a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py
+++ b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py
@@ -11,6 +11,7 @@ from backend.copilot.config import ChatConfig
from backend.copilot.rate_limit import (
SubscriptionTier,
get_global_rate_limits,
+ get_tier_multipliers,
get_usage_status,
get_user_tier,
reset_user_usage,
@@ -37,6 +38,9 @@ class UserRateLimitResponse(BaseModel):
daily_cost_used_microdollars: int
weekly_cost_used_microdollars: int
tier: SubscriptionTier
+ # Full per-tier multiplier map incl. admin-managed tiers like ENTERPRISE,
+ # unlike the price-filtered /credits/subscription map.
+ tier_multipliers: dict[str, float] = {}
class UserTierResponse(BaseModel):
@@ -106,6 +110,7 @@ async def get_user_rate_limit(
config.weekly_cost_limit_microdollars,
)
usage = await get_usage_status(resolved_id, daily_limit, weekly_limit, tier=tier)
+ multipliers = await get_tier_multipliers()
return UserRateLimitResponse(
user_id=resolved_id,
@@ -115,6 +120,7 @@ async def get_user_rate_limit(
daily_cost_used_microdollars=usage.daily.used,
weekly_cost_used_microdollars=usage.weekly.used,
tier=tier,
+ tier_multipliers=multipliers,
)
@@ -148,6 +154,7 @@ async def reset_user_rate_limit(
config.weekly_cost_limit_microdollars,
)
usage = await get_usage_status(user_id, daily_limit, weekly_limit, tier=tier)
+ multipliers = await get_tier_multipliers()
try:
resolved_email = await get_user_email_by_id(user_id)
@@ -163,6 +170,7 @@ async def reset_user_rate_limit(
daily_cost_used_microdollars=usage.daily.used,
weekly_cost_used_microdollars=usage.weekly.used,
tier=tier,
+ tier_multipliers=multipliers,
)
diff --git a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py
index 95c3e589cb..8b3db9d407 100644
--- a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py
@@ -22,6 +22,14 @@ _MOCK_MODULE = "backend.api.features.admin.rate_limit_admin_routes"
_TARGET_EMAIL = "[email protected]"
+_MOCK_TIER_MULTIPLIERS = {
+ "NO_TIER": 0.0,
+ "BASIC": 1.0,
+ "PRO": 5.0,
+ "BUSINESS": 20.0,
+ "ENTERPRISE": 60.0,
+}
+
@pytest.fixture(autouse=True)
def setup_app_admin_auth(mock_jwt_admin):
@@ -69,6 +77,11 @@ def _patch_rate_limit_deps(
new_callable=AsyncMock,
return_value=_TARGET_EMAIL,
)
+ mocker.patch(
+ f"{_MOCK_MODULE}.get_tier_multipliers",
+ new_callable=AsyncMock,
+ return_value=dict(_MOCK_TIER_MULTIPLIERS),
+ )
def test_get_rate_limit(
@@ -90,6 +103,8 @@ def test_get_rate_limit(
assert data["daily_cost_used_microdollars"] == 500_000
assert data["weekly_cost_used_microdollars"] == 3_000_000
assert data["tier"] == "BASIC"
+ # Full per-tier map incl. admin-managed tiers (ENTERPRISE) is passed through.
+ assert data["tier_multipliers"] == _MOCK_TIER_MULTIPLIERS
configured_snapshot.assert_match(
json.dumps(data, indent=2, sort_keys=True) + "\n",
@@ -164,6 +179,7 @@ def test_reset_user_usage_daily_only(
# Weekly is untouched
assert data["weekly_cost_used_microdollars"] == 3_000_000
assert data["tier"] == "BASIC"
+ assert data["tier_multipliers"] == _MOCK_TIER_MULTIPLIERS
mock_reset.assert_awaited_once_with(target_user_id, reset_weekly=False)
@@ -243,6 +259,11 @@ def test_get_rate_limit_email_lookup_failure(
new_callable=AsyncMock,
side_effect=Exception("DB connection lost"),
)
+ mocker.patch(
+ f"{_MOCK_MODULE}.get_tier_multipliers",
+ new_callable=AsyncMock,
+ return_value=dict(_MOCK_TIER_MULTIPLIERS),
+ )
response = client.get("/admin/rate_limit", params={"user_id": target_user_id})
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 0a41042c0e..ac12310e6c 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
@@ -555,15 +555,16 @@ async def test_reconcile_stripe_tier_no_active_sub_downgrades_payer(
assert await reconcile_stripe_tier_for_user("user_abc") is True
mock_set.assert_awaited_once_with("user_abc", SubscriptionTier.NO_TIER)
- # A silently-missed cancellation webhook must alert ops, not be corrected quietly.
- mock_alert.assert_awaited_once()
- assert "DOWNGRADED" in mock_alert.await_args.args[0]
+ # The lazy path does NOT ping ops per-user; the sweep's aggregate Discord
+ # alert reports corrections. The change is still recorded (log + PostHog).
+ mock_alert.assert_not_awaited()
-async def test_reconcile_stripe_tier_lazy_upgrade_alerts(
+async def test_reconcile_stripe_tier_lazy_upgrade_no_per_user_alert(
mocker: pytest_mock.MockFixture,
) -> None:
- """A lazy reconcile that finds an active sub the DB missed also alerts ops."""
+ """A lazy reconcile that finds an active sub the DB missed converts the tier
+ but does NOT ping ops per-user (the sweep aggregates alerts)."""
user = MagicMock(
stripe_customer_id="cus_abc",
subscription_tier=SubscriptionTier.NO_TIER,
@@ -588,8 +589,7 @@ async def test_reconcile_stripe_tier_lazy_upgrade_alerts(
)
assert await reconcile_stripe_tier_for_user("user_abc") is True
- mock_alert.assert_awaited_once()
- assert "upgrade" in mock_alert.await_args.args[0]
+ mock_alert.assert_not_awaited()
async def test_reconcile_stripe_tier_enterprise_user_skipped(
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 6f154ebe47..a7a01100b8 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -2424,18 +2424,15 @@ async def reconcile_stripe_tier_for_user(user_id: str) -> bool:
).subscription_tier or SubscriptionTier.NO_TIER
if new_tier == current_tier:
return False
- direction = log_tier_reconciliation_discrepancy(
+ # Recorded (info + PostHog) only; ops alerting is aggregated by the
+ # sweep's Discord system alert, not pinged per-user here.
+ log_tier_reconciliation_discrepancy(
user_id=user_id,
stripe_customer_id=user.stripe_customer_id,
previous_tier=current_tier,
new_tier=new_tier,
via="lazy-reconcile",
)
- await alert_tier_reconciliation_discrepancy(
- f"⚠️ Payments integrity: on-access reconcile {direction} user "
- f"`{user_id}` {current_tier.value} → {new_tier.value} — Stripe "
- f"disagreed with our DB, a subscription webhook was likely missed."
- )
return True
# No active/trialing sub — downgrade a reconcilable row to NO_TIER.
if current_tier == SubscriptionTier.NO_TIER:
@@ -2448,12 +2445,6 @@ async def reconcile_stripe_tier_for_user(user_id: str) -> bool:
new_tier=SubscriptionTier.NO_TIER,
via="lazy-reconcile",
)
- await alert_tier_reconciliation_discrepancy(
- f"🚨 Payments integrity: on-access reconcile DOWNGRADED user `{user_id}` "
- f"{current_tier.value} → NO_TIER — no active Stripe subscription, but our "
- f"DB had them on a paid tier. A cancellation webhook was likely missed; "
- f"investigate the webhook pipeline."
- )
return True
@@ -2799,18 +2790,16 @@ def log_tier_reconciliation_discrepancy(
new_tier: SubscriptionTier,
via: str,
) -> str:
- """Record a Stripe<->DB tier discrepancy that reconciliation had to correct.
+ """Record a Stripe<->DB tier discrepancy that reconciliation corrected.
- A correction means a Stripe webhook was missed or dropped — a payments-
- integrity signal to investigate, NOT a routine fix. Emits an ERROR log
- (captured by Sentry via the logging integration) plus a PostHog event so the
- rate of discrepancies is trended. Returns the direction ("downgrade"/"upgrade").
+ Emits an INFO log + a PostHog event so the rate of discrepancies is trended.
+ Ops alerting is handled in aggregate by the sweep's Discord system alert
+ (:func:`_alert_sweep_discrepancies`) — one ping with the affected user-id
+ list + counts, rather than a per-user Sentry event. Returns the direction.
"""
direction = "upgrade" if is_tier_upgrade(previous_tier, new_tier) else "downgrade"
- logger.error(
- "Stripe tier reconciliation %s for user %s (%s -> %s, via %s): a Stripe "
- "webhook was likely missed. Investigate the webhook pipeline — payments-"
- "integrity signal, not a routine correction.",
+ logger.info(
+ "Stripe tier reconciliation %s for user %s (%s -> %s, via %s)",
direction,
user_id[:8],
previous_tier.value,
@@ -2833,12 +2822,20 @@ def log_tier_reconciliation_discrepancy(
async def alert_tier_reconciliation_discrepancy(message: str) -> None:
"""Best-effort ops alert to the platform Discord channel. Never raises so a
- Discord outage can't break reconciliation."""
+ Discord outage can't break reconciliation — but a delivery failure is logged
+ at ERROR (→ Sentry) so a broken bot token surfaces loudly instead of leaving
+ ops blind. Discord is the primary alert surface; this is the fallback."""
try:
await discord_send_alert(message, DiscordChannel.PLATFORM)
except Exception:
- logger.warning(
- "failed to send tier-reconciliation Discord alert", exc_info=True
+ # Discord delivery failed (bad token / channel / gateway timeout) — log
+ # the FULL alert content at ERROR so Sentry carries the same payload the
+ # Discord message would have, and ops isn't left blind.
+ logger.error(
+ "Discord reconciliation alert delivery FAILED — ops NOT notified via "
+ "Discord; full alert content follows:\n%s",
+ message,
+ exc_info=True,
)
diff --git a/autogpt_platform/backend/backend/data/stripe_reconciliation.py b/autogpt_platform/backend/backend/data/stripe_reconciliation.py
index c98b0db591..90593b2062 100644
--- a/autogpt_platform/backend/backend/data/stripe_reconciliation.py
+++ b/autogpt_platform/backend/backend/data/stripe_reconciliation.py
@@ -29,10 +29,6 @@ from backend.data.credit import (
logger = logging.getLogger(__name__)
-# Cap how many per-user lines are inlined into the Discord ops alert so a mass
-# incident doesn't post a wall of text; the full set is in the logs/PostHog.
-_ALERT_DETAIL_CAP = 25
-
# Bound the Stripe pagination so a runaway/unexpected dataset can't loop forever.
# At 100 subs/page this caps a single sweep at 500k subscriptions; if it's ever
# hit the sweep logs and stops rather than silently truncating without notice.
@@ -103,35 +99,34 @@ async def reconcile_all_stripe_tiers() -> ReconciliationSummary:
async def _alert_sweep_discrepancies(summary: ReconciliationSummary) -> None:
- """Loudly surface that the sweep had to correct tiers.
+ """Post a Discord (PLATFORM) system alert summarizing the sweep's corrections.
A non-empty sweep means Stripe webhooks were dropped or missed — a payments-
- integrity incident, not a routine correction. Steady state must be ZERO, so
- any correction pages the ops channel and logs at ERROR (→ Sentry).
+ integrity signal, not a routine correction. ONE aggregate ops notification:
+ a count header (how many reconciled, up vs down) followed by the FULL
+ affected-user list — each line ``user_id from_tier → to_tier (direction)``.
+ Sent as a single message; ``SendDiscordMessageBlock`` splits anything over
+ Discord's 2000-char limit on its own. Discord is the alert surface; this path
+ logs at WARNING and never raises to Sentry.
"""
- lines = "\n".join(
- f"- {d.direction}: {d.previous_tier.value} → {d.new_tier.value} "
- f"user={d.user_id} customer={d.stripe_customer_id}"
- for d in summary.discrepancies[:_ALERT_DETAIL_CAP]
- )
- overflow = len(summary.discrepancies) - _ALERT_DETAIL_CAP
- if overflow > 0:
- lines += f"\n…and {overflow} more"
- logger.error(
- "Stripe tier reconciliation sweep corrected %d discrepancy(ies) "
- "(%d downgrade, %d upgrade) — Stripe webhooks are likely dropping events; "
- "steady state must be ZERO.",
- len(summary.discrepancies),
- summary.downgrades,
+ n = len(summary.discrepancies)
+ logger.warning(
+ "Stripe tier reconciliation sweep reconciled %d account(s) "
+ "(%d upgraded, %d downgraded); webhooks likely dropping events — "
+ "steady state should be ZERO.",
+ n,
summary.upgrades,
+ summary.downgrades,
+ )
+ user_lines = "\n".join(
+ f"- `{d.user_id}` {d.previous_tier.value} → {d.new_tier.value} ({d.direction})"
+ for d in summary.discrepancies
)
await alert_tier_reconciliation_discrepancy(
- f"🚨 **Stripe tier reconciliation sweep corrected "
- f"{len(summary.discrepancies)} discrepancy(ies)** "
- f"({summary.downgrades} downgrade, {summary.upgrades} upgrade).\n"
- f"Each means a Stripe webhook was likely missed — **investigate the "
- f"webhook pipeline**; this is a payments-integrity signal, not a routine "
- f"correction. Steady state must be ZERO.\n{lines}"
+ f"🔁 **Stripe tier reconciliation: reconciled {n} account(s)** — "
+ f"{summary.upgrades} upgraded, {summary.downgrades} downgraded.\n"
+ f"Each means a Stripe webhook was likely missed — investigate the webhook "
+ f"pipeline; steady state should be ZERO.\nAffected users:\n{user_lines}"
)
diff --git a/autogpt_platform/backend/backend/data/stripe_reconciliation_test.py b/autogpt_platform/backend/backend/data/stripe_reconciliation_test.py
index 0a6949b53b..fa08b807aa 100644
--- a/autogpt_platform/backend/backend/data/stripe_reconciliation_test.py
+++ b/autogpt_platform/backend/backend/data/stripe_reconciliation_test.py
@@ -118,8 +118,14 @@ async def test_sweep_upgrades_downgrades_and_skips_unchanged(
assert len(summary.discrepancies) == 2
mock_alert.assert_awaited_once()
alert_msg = mock_alert.await_args.args[0]
- assert "2 discrepancy" in alert_msg
- assert "1 downgrade" in alert_msg and "1 upgrade" in alert_msg
+ # Count header up front.
+ assert "reconciled 2 account" in alert_msg
+ assert "1 upgraded" in alert_msg and "1 downgraded" in alert_msg
+ # Full affected-user list at the end, each with its tier change.
+ assert "Affected users:" in alert_msg
+ assert "u_up" in alert_msg and "u_down" in alert_msg
+ assert "NO_TIER → PRO (upgrade)" in alert_msg
+ assert "PRO → NO_TIER (downgrade)" in alert_msg
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/snapshots/get_rate_limit b/autogpt_platform/backend/snapshots/get_rate_limit
index 623f3ee649..8dbe45e95a 100644
--- a/autogpt_platform/backend/snapshots/get_rate_limit
+++ b/autogpt_platform/backend/snapshots/get_rate_limit
@@ -2,6 +2,13 @@
"daily_cost_limit_microdollars": 2500000,
"daily_cost_used_microdollars": 500000,
"tier": "BASIC",
+ "tier_multipliers": {
+ "BASIC": 1.0,
+ "BUSINESS": 20.0,
+ "ENTERPRISE": 60.0,
+ "NO_TIER": 0.0,
+ "PRO": 5.0
+ },
"user_email": "[email protected]",
"user_id": "5e53486c-cf57-477e-ba2a-cb02dc828e1c",
"weekly_cost_limit_microdollars": 12500000,
diff --git a/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly b/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly
index 17fd49d458..1331ccc862 100644
--- a/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly
+++ b/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly
@@ -2,6 +2,13 @@
"daily_cost_limit_microdollars": 2500000,
"daily_cost_used_microdollars": 0,
"tier": "BASIC",
+ "tier_multipliers": {
+ "BASIC": 1.0,
+ "BUSINESS": 20.0,
+ "ENTERPRISE": 60.0,
+ "NO_TIER": 0.0,
+ "PRO": 5.0
+ },
"user_email": "[email protected]",
"user_id": "5e53486c-cf57-477e-ba2a-cb02dc828e1c",
"weekly_cost_limit_microdollars": 12500000,
diff --git a/autogpt_platform/backend/snapshots/reset_user_usage_daily_only b/autogpt_platform/backend/snapshots/reset_user_usage_daily_only
index 72d1888633..0fd844f9ab 100644
--- a/autogpt_platform/backend/snapshots/reset_user_usage_daily_only
+++ b/autogpt_platform/backend/snapshots/reset_user_usage_daily_only
@@ -2,6 +2,13 @@
"daily_cost_limit_microdollars": 2500000,
"daily_cost_used_microdollars": 0,
"tier": "BASIC",
+ "tier_multipliers": {
+ "BASIC": 1.0,
+ "BUSINESS": 20.0,
+ "ENTERPRISE": 60.0,
+ "NO_TIER": 0.0,
+ "PRO": 5.0
+ },
"user_email": "[email protected]",
"user_id": "5e53486c-cf57-477e-ba2a-cb02dc828e1c",
"weekly_cost_limit_microdollars": 12500000,
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx
index 2c192342ce..bcca469887 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx
@@ -6,18 +6,18 @@ import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userR
import { useToast } from "@/components/molecules/Toast/use-toast";
import { UsageBar } from "../../components/UsageBar";
-const TIERS = ["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"] as const;
+const TIERS = [
+ "NO_TIER",
+ "BASIC",
+ "PRO",
+ "MAX",
+ "BUSINESS",
+ "ENTERPRISE",
+] as const;
type Tier = (typeof TIERS)[number];
-const TIER_MULTIPLIERS: Record<Tier, string> = {
- BASIC: "1x base limits",
- PRO: "5x base limits",
- MAX: "20x base limits",
- BUSINESS: "60x base limits",
- ENTERPRISE: "60x base limits",
-};
-
const TIER_COLORS: Record<Tier, string> = {
+ NO_TIER: "bg-red-100 text-red-700",
BASIC: "bg-gray-100 text-gray-700",
PRO: "bg-blue-100 text-blue-700",
MAX: "bg-indigo-100 text-indigo-700",
@@ -25,10 +25,29 @@ const TIER_COLORS: Record<Tier, string> = {
ENTERPRISE: "bg-amber-100 text-amber-700",
};
+// Derives the per-tier label from the live, LaunchDarkly-driven multiplier map.
+// NO_TIER is paywalled (0 / absent), and tiers missing from the map fall back
+// to a generic label rather than a fabricated number.
+function tierLabel(
+ tier: Tier,
+ tierMultipliers?: Record<string, number>,
+): string {
+ if (tier === "NO_TIER") return "no access (paywalled)";
+
+ const multiplier = tierMultipliers?.[tier];
+ if (multiplier === undefined || multiplier <= 0) return "tier limits";
+
+ // Round to at most 2 decimals (5 → "5", 42.664 → "42.66").
+ const rounded = Math.round(multiplier * 100) / 100;
+ return `${rounded}× base limits`;
+}
+
interface Props {
data: UserRateLimitResponse;
onReset: (resetWeekly: boolean) => Promise<void>;
onTierChange?: (newTier: string) => Promise<void>;
+ /** Full per-tier multiplier map (incl. admin-managed tiers) from the admin rate-limit endpoint. */
+ tierMultipliers?: Record<string, number>;
/** Override the outer container classes (default: bordered card). */
className?: string;
}
@@ -37,6 +56,7 @@ export function RateLimitDisplay({
data,
onReset,
onTierChange,
+ tierMultipliers,
className,
}: Props) {
const [isResetting, setIsResetting] = useState(false);
@@ -46,7 +66,7 @@ export function RateLimitDisplay({
const currentTier = TIERS.includes(data.tier as Tier)
? (data.tier as Tier)
- : "BASIC";
+ : "NO_TIER";
async function handleReset() {
const msg = resetWeekly
@@ -76,7 +96,7 @@ export function RateLimitDisplay({
await onTierChange(newTier);
toast({
title: "Tier updated",
- description: `Changed to ${newTier} (${TIER_MULTIPLIERS[newTier as Tier]}).`,
+ description: `Changed to ${newTier} (${tierLabel(newTier as Tier, tierMultipliers)}).`,
});
} catch {
toast({
@@ -125,7 +145,7 @@ export function RateLimitDisplay({
>
{TIERS.map((tier) => (
<option key={tier} value={tier}>
- {tier} — {TIER_MULTIPLIERS[tier]}
+ {tier} — {tierLabel(tier, tierMultipliers)}
</option>
))}
</select>
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx
index 79693bf558..81ddc4bc90 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx
@@ -11,6 +11,7 @@ export function RateLimitManager() {
searchResults,
selectedUser,
rateLimitData,
+ tierMultipliers,
handleSearch,
handleSelectUser,
handleReset,
@@ -79,6 +80,7 @@ export function RateLimitManager() {
data={rateLimitData}
onReset={handleReset}
onTierChange={handleTierChange}
+ tierMultipliers={tierMultipliers}
/>
)}
</div>
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx
index d4a5df3c4e..0e7eb24750 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx
@@ -71,22 +71,42 @@ describe("RateLimitDisplay", () => {
expect(badge.className).toContain("bg-blue-100");
});
- it("defaults unknown tier to BASIC", () => {
+ it("defaults unknown tier to NO_TIER", () => {
render(
<RateLimitDisplay
data={makeData({ tier: "UNKNOWN" as UserRateLimitResponse["tier"] })}
onReset={vi.fn()}
/>,
);
- const badge = screen.getByText("BASIC");
+ const badge = screen.getByText("NO_TIER");
expect(badge).toBeDefined();
+ expect(screen.queryByText("BASIC")).toBeNull();
+ });
+
+ it("displays NO_TIER as a first-class tier instead of masking as BASIC", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ tier: "NO_TIER" })}
+ onReset={vi.fn()}
+ />,
+ );
+ const badge = screen.getByText("NO_TIER");
+ expect(badge).toBeDefined();
+ expect(badge.className).toContain("bg-red-100");
+ expect(screen.queryByText("BASIC")).toBeNull();
+ expect(screen.getByText(/no access \(paywalled\)/)).toBeDefined();
+
+ const select = screen.getByLabelText(
+ "Subscription tier",
+ ) as HTMLSelectElement;
+ expect(select.value).toBe("NO_TIER");
});
it("renders tier dropdown with all tiers", () => {
render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
const select = screen.getByLabelText("Subscription tier");
expect(select).toBeDefined();
- expect(select.querySelectorAll("option").length).toBe(5);
+ expect(select.querySelectorAll("option").length).toBe(6);
});
it("disables tier dropdown when onTierChange is not provided", () => {
@@ -268,6 +288,88 @@ describe("RateLimitDisplay", () => {
});
});
+ it("shows live multiplier label for PRO from the tierMultipliers map", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ tier: "PRO" })}
+ onReset={vi.fn()}
+ tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
+ />,
+ );
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select.textContent).toContain("PRO — 5× base limits");
+ });
+
+ it("renders a non-default fractional multiplier (MAX 42.66) from the map", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData()}
+ onReset={vi.fn()}
+ tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
+ />,
+ );
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select.textContent).toContain("MAX — 42.66× base limits");
+ // The old hardcoded "20x" value must not appear.
+ expect(select.textContent).not.toContain("20x");
+ });
+
+ it("keeps NO_TIER paywalled label even with a multipliers map present", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ tier: "NO_TIER" })}
+ onReset={vi.fn()}
+ tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
+ />,
+ );
+ expect(screen.getByText(/no access \(paywalled\)/)).toBeDefined();
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select.textContent).not.toContain("NO_TIER — 0");
+ });
+
+ it("does not fabricate a number for a tier missing from the map", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData()}
+ onReset={vi.fn()}
+ tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
+ />,
+ );
+ const select = screen.getByLabelText("Subscription tier");
+ // ENTERPRISE has no entry -> generic label, never a hardcoded multiplier.
+ expect(select.textContent).toContain("ENTERPRISE — tier limits");
+ expect(select.textContent).not.toContain("ENTERPRISE — 60");
+ });
+
+ it("shows the multiplier for ENTERPRISE when present in the full map", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData()}
+ onReset={vi.fn()}
+ tierMultipliers={{
+ NO_TIER: 0,
+ BASIC: 1,
+ PRO: 5,
+ BUSINESS: 20,
+ ENTERPRISE: 60,
+ }}
+ />,
+ );
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select.textContent).toContain("ENTERPRISE — 60× base limits");
+ expect(select.textContent).toContain("BUSINESS — 20× base limits");
+ expect(select.textContent).not.toContain("ENTERPRISE — tier limits");
+ // NO_TIER's 0 short-circuits to the paywalled label, not "0× base limits".
+ expect(select.textContent).toContain("NO_TIER — no access (paywalled)");
+ });
+
+ it("falls back to generic labels when no multipliers map is provided", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select.textContent).toContain("PRO — tier limits");
+ expect(select.textContent).not.toContain("5x");
+ });
+
it("applies custom className when provided", () => {
const { container } = render(
<RateLimitDisplay
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts
index b68489f613..b17e8c9832 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts
@@ -35,6 +35,8 @@ export function useRateLimitManager() {
const [rateLimitData, setRateLimitData] =
useState<UserRateLimitResponse | null>(null);
+ const tierMultipliers = rateLimitData?.tier_multipliers;
+
async function handleDirectLookup(trimmed: string) {
setIsSearching(true);
setSearchResults([]);
@@ -206,6 +208,7 @@ export function useRateLimitManager() {
searchResults,
selectedUser,
rateLimitData,
+ tierMultipliers,
handleSearch,
handleSelectUser,
handleReset,
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 91855bef02..28aa61f06a 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -20219,7 +20219,13 @@
"type": "integer",
"title": "Weekly Cost Used Microdollars"
},
- "tier": { "$ref": "#/components/schemas/SubscriptionTier" }
+ "tier": { "$ref": "#/components/schemas/SubscriptionTier" },
+ "tier_multipliers": {
+ "additionalProperties": { "type": "number" },
+ "type": "object",
+ "title": "Tier Multipliers",
+ "default": {}
+ }
},
"type": "object",
"required": [