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): LD-configurable rate-limit multipliers + relative UI display (#12910)
Zamil Majdy408b205515fc
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.pyindex 5f13f8fd22..e353a2e777 100644--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py@@ -70,7 +70,8 @@ _DEFAULT_TIER_PRICES: dict[SubscriptionTier, str | None] = {@pytest.fixture(autouse=True)def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:- """Stub Stripe price + proration lookups used by get_subscription_status.+ """Stub Stripe price + proration + tier-multiplier lookups used by+ get_subscription_status.The POST /credits/subscription handler now returns the full subscriptionstatus payload from every branch (same-tier, BASIC downgrade, paid→paid@@ -90,6 +91,16 @@ def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:new_callable=AsyncMock,return_value=0,)+ # Default tier-multiplier resolver to the backend defaults so the endpoint+ # never reaches LaunchDarkly during tests. Individual tests override for+ # LD-override scenarios.+ from backend.copilot.rate_limit import _DEFAULT_TIER_MULTIPLIERS++ mocker.patch(+ "backend.api.features.v1.get_tier_multipliers",+ new_callable=AsyncMock,+ return_value=dict(_DEFAULT_TIER_MULTIPLIERS),+ )@pytest.mark.parametrize(@@ -187,6 +198,51 @@ def test_get_subscription_status_pro(assert data["tier_costs"]["BASIC"] == 0assert "ENTERPRISE" not in data["tier_costs"]assert data["proration_credit_cents"] == 500+ # tier_multipliers mirrors the same set of tiers that land in tier_costs,+ # so the frontend never renders a multiplier badge for a hidden row.+ assert set(data["tier_multipliers"].keys()) == set(data["tier_costs"].keys())+ assert data["tier_multipliers"]["BASIC"] == 1.0+ assert data["tier_multipliers"]["PRO"] == 5.0+ assert data["tier_multipliers"]["MAX"] == 20.0+ assert data["tier_multipliers"]["BUSINESS"] == 60.0+++def test_get_subscription_status_tier_multipliers_ld_override(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """A LaunchDarkly-overridden tier multiplier flows through the response."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.BASIC++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )++ # LD says PRO is 7.5× (instead of the 5× default); other tiers unchanged.+ mocker.patch(+ "backend.api.features.v1.get_tier_multipliers",+ new_callable=AsyncMock,+ return_value={+ SubscriptionTier.BASIC: 1.0,+ SubscriptionTier.PRO: 7.5,+ SubscriptionTier.MAX: 20.0,+ SubscriptionTier.BUSINESS: 60.0,+ SubscriptionTier.ENTERPRISE: 60.0,+ },+ )++ response = client.get("/credits/subscription")+ assert response.status_code == 200+ data = response.json()+ # Only tiers that made it into tier_costs get a multiplier (default stub+ # exposes PRO + MAX via _DEFAULT_TIER_PRICES).+ assert data["tier_multipliers"]["PRO"] == 7.5+ assert data["tier_multipliers"]["MAX"] == 20.0+ # BUSINESS has no price configured → hidden from both maps.+ assert "BUSINESS" not in data["tier_multipliers"]def test_get_subscription_status_defaults_to_basic(diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex ad65428a32..e47b05fa3d 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -44,6 +44,7 @@ from backend.api.model import (UploadFileResponse,)from backend.blocks import get_block, get_blocks+from backend.copilot.rate_limit import get_tier_multipliersfrom backend.data import execution as execution_dbfrom backend.data import graph as graph_dbfrom backend.data.auth import api_key as api_key_db@@ -708,6 +709,15 @@ class SubscriptionStatusResponse(BaseModel):tier: Literal["BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]monthly_cost: int # amount in cents (Stripe convention)tier_costs: dict[str, int] # tier name -> amount in cents+ tier_multipliers: dict[str, float] = Field(+ default_factory=dict,+ description=(+ "Tier → rate-limit multiplier. Covers the same tiers listed in"+ " ``tier_costs`` so the frontend can render rate-limit badges"+ " relative to the lowest visible tier without knowing backend"+ " defaults."+ ),+ )proration_credit_cents: int # unused portion of current sub to convert on upgradepending_tier: Optional[Literal["BASIC", "PRO", "MAX", "BUSINESS"]] = Nonepending_tier_effective_at: Optional[datetime] = None@@ -816,6 +826,18 @@ async def get_subscription_status(if pid:tier_costs[t.value] = cost+ # Expose the effective rate-limit multipliers alongside prices so the+ # frontend can render "Nx rate limits" relative to the lowest visible+ # tier without hard-coding backend defaults. Only emit entries for tiers+ # that land in ``tier_costs`` — rows hidden at the price layer must stay+ # hidden in the multiplier layer too.+ multipliers = await get_tier_multipliers()+ tier_multipliers: dict[str, float] = {+ t.value: multipliers.get(t, 1.0)+ for t in priceable_tiers+ if t.value in tier_costs+ }+current_monthly_cost = tier_costs.get(tier.value, 0)proration_credit = await get_proration_credit_cents(user_id, current_monthly_cost)@@ -837,6 +859,7 @@ async def get_subscription_status(tier=tier.value,monthly_cost=current_monthly_cost,tier_costs=tier_costs,+ tier_multipliers=tier_multipliers,proration_credit_cents=proration_credit,)if pending is not None:diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.pyindex a582463cb5..67c37374fc 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py@@ -80,22 +80,101 @@ class SubscriptionTier(str, Enum):ENTERPRISE = "ENTERPRISE"-# Multiplier applied to the base cost limits (from LD / config) for each tier.-# Intentionally int (not float): keeps limits as whole microdollars and avoids-# floating-point rounding. If fractional multipliers are ever needed, change-# the type and round the result in get_global_rate_limits().-# BUSINESS matches ENTERPRISE (60x); MAX sits at 20x as the self-service $320 tier.-TIER_MULTIPLIERS: dict[SubscriptionTier, int] = {- SubscriptionTier.BASIC: 1,- SubscriptionTier.PRO: 5,- SubscriptionTier.MAX: 20,- SubscriptionTier.BUSINESS: 60,- SubscriptionTier.ENTERPRISE: 60,+# Default multiplier applied to the base cost limits (from LD / config) for each+# tier. Used as the fallback when the LD flag ``copilot-tier-multipliers`` is+# unset or unparseable — see ``get_tier_multipliers``. BUSINESS matches+# ENTERPRISE (60x); MAX sits at 20x as the self-service $320 tier. Float-typed+# so LD-provided fractional multipliers (e.g. 8.5×) compose naturally; the+# eventual ``int(base * multiplier)`` in ``get_global_rate_limits`` keeps the+# downstream microdollar math integer.+_DEFAULT_TIER_MULTIPLIERS: dict[SubscriptionTier, float] = {+ SubscriptionTier.BASIC: 1.0,+ SubscriptionTier.PRO: 5.0,+ SubscriptionTier.MAX: 20.0,+ SubscriptionTier.BUSINESS: 60.0,+ SubscriptionTier.ENTERPRISE: 60.0,}+# Public re-export retained for backward compatibility with call-sites / tests+# that historically read ``TIER_MULTIPLIERS`` directly. New code should prefer+# ``get_tier_multipliers`` so LD overrides are honoured.+TIER_MULTIPLIERS = _DEFAULT_TIER_MULTIPLIERS+DEFAULT_TIER = SubscriptionTier.BASIC+@cached(ttl_seconds=60, maxsize=1, cache_none=False)+async def _fetch_tier_multipliers_flag() -> dict[SubscriptionTier, float] | None:+ """Fetch the ``copilot-tier-multipliers`` LD flag and parse it.++ Returns a sparse ``{tier: multiplier}`` map built from whichever keys are+ valid in the flag payload, or ``None`` when the flag is unset / invalid /+ LD is unavailable. ``cache_none=False`` avoids pinning a transient LD+ failure for a full minute — the next call retries.++ The LD value is expected to be a JSON object keyed by tier enum name+ (``{"BASIC": 1, "PRO": 5, "BUSINESS": 20.5}``). Unknown tier keys and+ non-numeric / non-positive values are skipped; callers merge whatever+ survives into :data:`_DEFAULT_TIER_MULTIPLIERS`.+ """+ # Lazy import: rate_limit -> feature_flag -> settings -> ... -> rate_limit.+ from backend.util.feature_flag import Flag, get_feature_flag_value++ raw = await get_feature_flag_value(+ Flag.COPILOT_TIER_MULTIPLIERS.value, "system", None+ )+ if raw is None:+ return None+ if not isinstance(raw, dict):+ logger.warning(+ "Invalid LD value for copilot-tier-multipliers (expected JSON object): %r",+ raw,+ )+ return None++ parsed: dict[SubscriptionTier, float] = {}+ for key, value in raw.items():+ try:+ tier = SubscriptionTier(key)+ except ValueError:+ continue+ try:+ multiplier = float(value)+ except (TypeError, ValueError):+ continue+ if multiplier <= 0:+ continue+ parsed[tier] = multiplier+ return parsed or None+++async def get_tier_multipliers() -> dict[str, float]:+ """Return the effective ``{tier_value: multiplier}`` map.++ Honours the ``copilot-tier-multipliers`` LD flag when set; missing tiers+ inherit :data:`_DEFAULT_TIER_MULTIPLIERS`. Unparseable flag values or LD+ fetch failures fall back to the defaults without raising.++ Keys are the tier enum string values (``"BASIC"``, ``"PRO"``, …) rather+ than the enum itself so callers holding ``prisma.enums.SubscriptionTier``+ don't hit a spurious mismatch against this module's local mirror.++ The flag is evaluated system-wide — per-tier multipliers are a global knob.+ If per-cohort overrides are ever needed, add a user_id parameter here and+ thread it through ``_fetch_tier_multipliers_flag`` to LD.+ """+ try:+ override = await _fetch_tier_multipliers_flag()+ except Exception:+ # LD SDK / Redis / network failures here are best-effort — fall back.+ logger.warning("get_tier_multipliers: LD lookup failed", exc_info=True)+ override = None+ merged: dict[SubscriptionTier, float] = dict(_DEFAULT_TIER_MULTIPLIERS)+ if override:+ merged.update(override)+ return {tier.value: multiplier for tier, multiplier in merged.items()}++class UsageWindow(BaseModel):"""Usage within a single time window.@@ -698,12 +777,18 @@ async def get_global_rate_limits(logger.warning("Invalid LD value for weekly cost limit: %r", weekly_raw)weekly = config_weekly- # Apply tier multiplier+ # Apply tier multiplier — resolved through LD (copilot-tier-multipliers)+ # so multipliers can be tuned without a deploy. Falls back to the defaults+ # when LD is unavailable.tier = await get_user_tier(user_id)- multiplier = TIER_MULTIPLIERS.get(tier, 1)- if multiplier != 1:- daily = daily * multiplier- weekly = weekly * multiplier+ multipliers = await get_tier_multipliers()+ multiplier = multipliers.get(tier.value, 1.0)+ if multiplier != 1.0:+ # Cast back to int to preserve the microdollar integer contract+ # downstream — fractional LD multipliers (e.g. 8.5×) truncate at the+ # last microdollar, which is well below any meaningful precision.+ daily = int(daily * multiplier)+ weekly = int(weekly * multiplier)return daily, weekly, tierdiff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.pyindex 9ea0ba413c..699c6fa9f6 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py@@ -7,6 +7,7 @@ import pytestfrom redis.exceptions import RedisErrorfrom .rate_limit import (+ _DEFAULT_TIER_MULTIPLIERS,DEFAULT_TIER,TIER_MULTIPLIERS,CoPilotUsageStatus,@@ -15,12 +16,14 @@ from .rate_limit import (UsageWindow,_daily_key,_daily_reset_time,+ _fetch_tier_multipliers_flag,_weekly_key,_weekly_reset_time,acquire_reset_lock,check_rate_limit,get_daily_reset_count,get_global_rate_limits,+ get_tier_multipliers,get_usage_status,get_user_tier,increment_daily_reset_count,@@ -353,11 +356,14 @@ class TestSubscriptionTier:assert SubscriptionTier.ENTERPRISE.value == "ENTERPRISE"def test_tier_multipliers(self):- assert TIER_MULTIPLIERS[SubscriptionTier.BASIC] == 1- assert TIER_MULTIPLIERS[SubscriptionTier.PRO] == 5- assert TIER_MULTIPLIERS[SubscriptionTier.MAX] == 20- assert TIER_MULTIPLIERS[SubscriptionTier.BUSINESS] == 60- assert TIER_MULTIPLIERS[SubscriptionTier.ENTERPRISE] == 60+ # Float-typed so LD-provided fractional multipliers compose naturally;+ # equality against int literals still holds for the whole defaults.+ assert TIER_MULTIPLIERS[SubscriptionTier.BASIC] == 1.0+ assert TIER_MULTIPLIERS[SubscriptionTier.PRO] == 5.0+ assert TIER_MULTIPLIERS[SubscriptionTier.MAX] == 20.0+ assert TIER_MULTIPLIERS[SubscriptionTier.BUSINESS] == 60.0+ assert TIER_MULTIPLIERS[SubscriptionTier.ENTERPRISE] == 60.0+ assert TIER_MULTIPLIERS is _DEFAULT_TIER_MULTIPLIERSdef test_default_tier_is_basic(self):assert DEFAULT_TIER == SubscriptionTier.BASIC@@ -380,6 +386,87 @@ class TestSubscriptionTier:assert status.tier == SubscriptionTier.PRO+# ---------------------------------------------------------------------------+# get_tier_multipliers (LD-backed resolver)+# ---------------------------------------------------------------------------+++class TestGetTierMultipliers:+ @pytest.fixture(autouse=True)+ def _clear_flag_cache(self):+ """Clear the LD flag cache between tests so patches don't leak."""+ _fetch_tier_multipliers_flag.cache_clear() # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_defaults_when_flag_unset(self):+ """With no LD override, the resolver returns the default map."""+ with patch(+ "backend.util.feature_flag.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value=None,+ ):+ result = await get_tier_multipliers()+ assert result == {t.value: m for t, m in _DEFAULT_TIER_MULTIPLIERS.items()}++ @pytest.mark.asyncio+ async def test_ld_override(self):+ """LD override populates the targeted tiers; others inherit defaults."""+ with patch(+ "backend.util.feature_flag.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value={"PRO": 7.5, "BUSINESS": 25},+ ):+ result = await get_tier_multipliers()+ assert result["PRO"] == 7.5+ assert result["BUSINESS"] == 25.0+ # Untouched tiers inherit defaults.+ assert result["BASIC"] == _DEFAULT_TIER_MULTIPLIERS[SubscriptionTier.BASIC]+ assert result["MAX"] == _DEFAULT_TIER_MULTIPLIERS[SubscriptionTier.MAX]+ assert (+ result["ENTERPRISE"]+ == _DEFAULT_TIER_MULTIPLIERS[SubscriptionTier.ENTERPRISE]+ )++ @pytest.mark.asyncio+ async def test_invalid_json_falls_back(self):+ """A non-object LD value (string, list, bool) falls back to defaults."""+ with patch(+ "backend.util.feature_flag.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value="broken",+ ):+ result = await get_tier_multipliers()+ assert result == {t.value: m for t, m in _DEFAULT_TIER_MULTIPLIERS.items()}++ @pytest.mark.asyncio+ async def test_unknown_tier_key_skipped(self):+ """Unknown tier keys and non-positive values are silently ignored."""+ with patch(+ "backend.util.feature_flag.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value={"PRO": 3, "BOGUS": 99, "MAX": -1, "BUSINESS": "nope"},+ ):+ result = await get_tier_multipliers()+ assert result["PRO"] == 3.0+ # MAX had a non-positive override → falls back to default.+ assert result["MAX"] == _DEFAULT_TIER_MULTIPLIERS[SubscriptionTier.MAX]+ # BUSINESS had an unparseable override → falls back to default.+ assert (+ result["BUSINESS"] == _DEFAULT_TIER_MULTIPLIERS[SubscriptionTier.BUSINESS]+ )++ @pytest.mark.asyncio+ async def test_ld_failure_falls_back(self):+ """LD lookup raising propagates to defaults, not up the call stack."""+ with patch(+ "backend.util.feature_flag.get_feature_flag_value",+ new_callable=AsyncMock,+ side_effect=RuntimeError("LD SDK not initialized"),+ ):+ result = await get_tier_multipliers()+ assert result == {t.value: m for t, m in _DEFAULT_TIER_MULTIPLIERS.items()}++# ---------------------------------------------------------------------------# get_user_tier# ---------------------------------------------------------------------------@@ -652,11 +739,20 @@ class TestSetUserTier:class TestGetGlobalRateLimitsWithTiers:+ @pytest.fixture(autouse=True)+ def _clear_flag_cache(self):+ """Clear the LD flag cache between tests so patches don't leak."""+ _fetch_tier_multipliers_flag.cache_clear() # type: ignore[attr-defined]+@staticmethoddef _ld_side_effect(daily: int, weekly: int):- """Return an async side_effect that dispatches by flag_key."""+ """Return an async side_effect that dispatches by flag_key.++ Returns the raw default for the tier-multipliers flag so existing+ tests continue to exercise the default multiplier map.+ """- async def _side_effect(flag_key: str, _uid: str, default: int) -> int:+ async def _side_effect(flag_key: str, _uid: str, default):if "daily" in flag_key.lower():return dailyif "weekly" in flag_key.lower():@@ -665,6 +761,41 @@ class TestGetGlobalRateLimitsWithTiers:return _side_effect+ @pytest.mark.asyncio+ async def test_ld_override_applies_fractional_multiplier(self):+ """A fractional LD multiplier is applied and truncated back to int."""++ async def _ld(flag_key: str, _uid: str, default):+ if "daily" in flag_key.lower():+ return 1_000_000+ if "weekly" in flag_key.lower():+ return 5_000_000+ if "tier-multipliers" in flag_key.lower():+ return {"PRO": 8.5}+ return default++ with (+ patch(+ "backend.copilot.rate_limit.get_user_tier",+ new_callable=AsyncMock,+ return_value=SubscriptionTier.PRO,+ ),+ patch(+ "backend.util.feature_flag.get_feature_flag_value",+ side_effect=_ld,+ ),+ ):+ daily, weekly, tier = await get_global_rate_limits(+ _USER, 1_000_000, 5_000_000+ )++ assert tier == SubscriptionTier.PRO+ assert daily == 8_500_000 # 1_000_000 * 8.5+ assert weekly == 42_500_000 # 5_000_000 * 8.5+ # Both results are plain ints so microdollar math stays integer.+ assert isinstance(daily, int)+ assert isinstance(weekly, int)+@pytest.mark.asyncioasync def test_free_tier_no_multiplier(self):"""Free tier should not change limits."""@@ -789,10 +920,14 @@ class TestTierLimitsRespected:_BASE_DAILY = 2_500_000_BASE_WEEKLY = 12_500_000+ @pytest.fixture(autouse=True)+ def _clear_flag_cache(self):+ _fetch_tier_multipliers_flag.cache_clear() # type: ignore[attr-defined]+@staticmethoddef _ld_side_effect(daily: int, weekly: int):- async def _side_effect(flag_key: str, _uid: str, default: int) -> int:+ async def _side_effect(flag_key: str, _uid: str, default):if "daily" in flag_key.lower():return dailyif "weekly" in flag_key.lower():@@ -1002,11 +1137,15 @@ class TestTierLimitsEnforced:_BASE_DAILY = 1_000_000_BASE_WEEKLY = 5_000_000+ @pytest.fixture(autouse=True)+ def _clear_flag_cache(self):+ _fetch_tier_multipliers_flag.cache_clear() # type: ignore[attr-defined]+@staticmethoddef _ld_side_effect(daily: int, weekly: int):"""Mock LD flag lookup returning the given raw limits."""- async def _side_effect(flag_key: str, _uid: str, default: int) -> int:+ async def _side_effect(flag_key: str, _uid: str, default):if "daily" in flag_key.lower():return dailyif "weekly" in flag_key.lower():@@ -1018,7 +1157,7 @@ class TestTierLimitsEnforced:@pytest.mark.asyncioasync def test_pro_within_limit_allowed(self):"""Usage under PRO daily limit should not raise."""- pro_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO]+ pro_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO])mock_redis = AsyncMock()# Simulate usage just under the PRO daily limitmock_redis.get = AsyncMock(side_effect=[str(pro_daily - 1), "0"])@@ -1049,7 +1188,7 @@ class TestTierLimitsEnforced:@pytest.mark.asyncioasync def test_pro_at_limit_rejected(self):"""Usage at exactly the PRO daily limit should raise."""- pro_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO]+ pro_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO])mock_redis = AsyncMock()mock_redis.get = AsyncMock(side_effect=[str(pro_daily), "0"])@@ -1078,8 +1217,8 @@ class TestTierLimitsEnforced:@pytest.mark.asyncioasync def test_business_higher_limit_allows_pro_overflow(self):"""Usage exceeding PRO but under BUSINESS should pass for BUSINESS."""- pro_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO]- biz_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BUSINESS]+ pro_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO])+ biz_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BUSINESS])# Usage between PRO and BUSINESS limitsusage = pro_daily + 1_000_000assert usage < biz_daily, "test sanity: usage must be under BUSINESS limit"@@ -1113,7 +1252,7 @@ class TestTierLimitsEnforced:@pytest.mark.asyncioasync def test_weekly_limit_enforced_for_tier(self):"""Weekly limit should also be tier-multiplied and enforced."""- pro_weekly = self._BASE_WEEKLY * TIER_MULTIPLIERS[SubscriptionTier.PRO]+ pro_weekly = int(self._BASE_WEEKLY * TIER_MULTIPLIERS[SubscriptionTier.PRO])mock_redis = AsyncMock()# Daily usage fine, weekly at limitmock_redis.get = AsyncMock(side_effect=["0", str(pro_weekly)])@@ -1177,8 +1316,8 @@ class TestTierLimitsEnforced:rate-limit check, so a lower-tier user cannot 'bypass' limits thatwould be acceptable for a higher tier."""- basic_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BASIC]- pro_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO]+ basic_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BASIC])+ pro_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.PRO])# Usage above BASIC limit but below PRO limitusage = basic_daily + 500_000assert usage < pro_daily, "test sanity: usage must be under PRO limit"@@ -1219,8 +1358,8 @@ class TestTierLimitsEnforced:change, and that usage that was over the BASIC limit is within the newBUSINESS limit."""- basic_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BASIC]- biz_daily = self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BUSINESS]+ basic_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BASIC])+ biz_daily = int(self._BASE_DAILY * TIER_MULTIPLIERS[SubscriptionTier.BUSINESS])# Usage above BASIC limit but below BUSINESS limitusage = basic_daily + 500_000assert usage < biz_daily, "test sanity: usage must be under BUSINESS limit"diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex 8f7bf86d3c..dd26d443e5 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -44,6 +44,7 @@ class Flag(str, Enum):COPILOT_SDK = "copilot-sdk"COPILOT_DAILY_COST_LIMIT = "copilot-daily-cost-limit-microdollars"COPILOT_WEEKLY_COST_LIMIT = "copilot-weekly-cost-limit-microdollars"+ COPILOT_TIER_MULTIPLIERS = "copilot-tier-multipliers"STRIPE_PRICE_BASIC = "stripe-price-id-basic"STRIPE_PRICE_PRO = "stripe-price-id-pro"STRIPE_PRICE_MAX = "stripe-price-id-max"diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsxindex 7b4dd359a7..cba09d7c3c 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx@@ -10,6 +10,7 @@ import {TIER_ORDER,formatCost,formatPendingDate,+ formatRelativeMultiplier,getTierLabel,} from "./helpers";@@ -155,6 +156,10 @@ export function SubscriptionTierSection() {const isThisPending = pendingTier === tier.key;const isScheduledTier =hasPendingChange && pendingTierFromSubscription === tier.key;+ const rateLimitLabel = formatRelativeMultiplier(+ tier.key,+ subscription.tier_multipliers ?? {},+ );return (<div@@ -178,9 +183,11 @@ export function SubscriptionTierSection() {<p className="mb-1 text-2xl font-bold">{formatCost(cost, tier.key)}</p>- <p className="mb-1 text-sm font-medium text-neutral-600 dark:text-neutral-400">- {tier.multiplier} rate limits- </p>+ {rateLimitLabel && (+ <p className="mb-1 text-sm font-medium text-neutral-600 dark:text-neutral-400">+ {rateLimitLabel}+ </p>+ )}<p className="mb-4 text-sm text-neutral-500 dark:text-neutral-400">{tier.description}</p>diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsxindex cffa430a44..9ee4a41742 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx@@ -70,6 +70,7 @@ function makeSubscription({tier = "BASIC",monthlyCost = 0,tierCosts = { BASIC: 0, PRO: 1999, MAX: 32000, ENTERPRISE: 0 },+ tierMultipliers = { BASIC: 1, PRO: 5, MAX: 20, BUSINESS: 60 },prorationCreditCents = 0,pendingTier = null as string | null,pendingTierEffectiveAt = null as Date | string | null,@@ -77,6 +78,7 @@ function makeSubscription({tier?: string;monthlyCost?: number;tierCosts?: Record<string, number>;+ tierMultipliers?: Record<string, number>;prorationCreditCents?: number;pendingTier?: string | null;pendingTierEffectiveAt?: Date | string | null;@@ -85,6 +87,7 @@ function makeSubscription({tier,monthly_cost: monthlyCost,tier_costs: tierCosts,+ tier_multipliers: tierMultipliers,proration_credit_cents: prorationCreditCents,pending_tier: pendingTier,pending_tier_effective_at: pendingTierEffectiveAt,@@ -378,6 +381,50 @@ describe("SubscriptionTierSection", () => {expect(screen.queryByText("Basic")).toBeNull();});+ it("renders rate-limit badges relative to the lowest visible tier", () => {+ // BASIC is baseline (1×) → no badge; PRO/MAX/BUSINESS show their ratio.+ setupMocks({+ subscription: makeSubscription({+ tier: "BASIC",+ tierCosts: { BASIC: 0, PRO: 1999, MAX: 32000, BUSINESS: 14999 },+ tierMultipliers: { BASIC: 1, PRO: 5, MAX: 20, BUSINESS: 60 },+ }),+ });+ render(<SubscriptionTierSection />);+ expect(screen.queryByText(/1\.0x rate limits/i)).toBeNull();+ expect(screen.getByText(/5\.0x rate limits/i)).toBeDefined();+ expect(screen.getByText(/20\.0x rate limits/i)).toBeDefined();+ expect(screen.getByText(/60\.0x rate limits/i)).toBeDefined();+ });++ it("rebases relative multipliers when the lowest tier is hidden", () => {+ // With BASIC hidden, PRO becomes the baseline (no badge) and MAX shows+ // "4.0x rate limits" (20 / 5).+ setupMocks({+ subscription: makeSubscription({+ tier: "PRO",+ tierCosts: { PRO: 1999, MAX: 32000 },+ tierMultipliers: { PRO: 5, MAX: 20 },+ }),+ });+ render(<SubscriptionTierSection />);+ expect(screen.queryByText(/5\.0x rate limits/i)).toBeNull();+ expect(screen.getByText(/4\.0x rate limits/i)).toBeDefined();+ });++ it("honours fractional LD-provided multipliers in the relative display", () => {+ // LD can override the multiplier to a non-integer value (e.g. PRO=8.5×).+ setupMocks({+ subscription: makeSubscription({+ tier: "BASIC",+ tierCosts: { BASIC: 0, PRO: 1999 },+ tierMultipliers: { BASIC: 1, PRO: 8.5 },+ }),+ });+ render(<SubscriptionTierSection />);+ expect(screen.getByText(/8\.5x rate limits/i)).toBeDefined();+ });+it("shows ENTERPRISE message for ENTERPRISE tier users", () => {setupMocks({ subscription: makeSubscription({ tier: "ENTERPRISE" }) });render(<SubscriptionTierSection />);diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.tsindex b7e2144067..5d0c3204f3 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import {formatCost,formatPendingDate,+ formatRelativeMultiplier,getTierLabel,TIERS,TIER_ORDER,@@ -66,3 +67,67 @@ describe("TIERS / TIER_ORDER", () => {}});});++describe("formatRelativeMultiplier", () => {+ it("returns null for the lowest visible tier — it's the baseline", () => {+ expect(+ formatRelativeMultiplier("BASIC", { BASIC: 1, PRO: 5, MAX: 20 }),+ ).toBeNull();+ });++ it("formats a clean integer multiplier as 'N.0x rate limits'", () => {+ expect(formatRelativeMultiplier("PRO", { BASIC: 1, PRO: 4, MAX: 20 })).toBe(+ "4.0x rate limits",+ );+ });++ it("rounds to one decimal when the ratio isn't a whole number", () => {+ expect(formatRelativeMultiplier("MAX", { BASIC: 2, PRO: 5, MAX: 17 })).toBe(+ "8.5x rate limits",+ );+ });++ it("returns null when the tier isn't in the multipliers map (hidden)", () => {+ expect(+ formatRelativeMultiplier("BUSINESS", { BASIC: 1, PRO: 5 }),+ ).toBeNull();+ });++ it("ignores the baseline from hidden tiers so visible-tier deltas stay honest", () => {+ // BASIC hidden but PRO/MAX visible — PRO becomes the baseline, MAX is 4×.+ expect(formatRelativeMultiplier("MAX", { PRO: 5, MAX: 20 })).toBe(+ "4.0x rate limits",+ );+ expect(formatRelativeMultiplier("PRO", { PRO: 5, MAX: 20 })).toBeNull();+ });++ it("handles fractional LD-provided multipliers cleanly", () => {+ // LD override can set e.g. PRO=7.5×; the relative display still computes+ // correctly against a non-integer minimum.+ expect(formatRelativeMultiplier("PRO", { BASIC: 1.5, PRO: 7.5 })).toBe(+ "5.0x rate limits",+ );+ });++ it("returns null for every tier when all visible multipliers are equal", () => {+ // Edge case: if LD sets every tier to the same value, none are "above"+ // the baseline — the UI shouldn't label any of them.+ expect(formatRelativeMultiplier("PRO", { PRO: 5, MAX: 5 })).toBeNull();+ expect(formatRelativeMultiplier("MAX", { PRO: 5, MAX: 5 })).toBeNull();+ });++ it("returns null when the tier's own multiplier is zero or negative", () => {+ // Defensive: a misconfigured LD value leaking through shouldn't render as+ // "0.0x rate limits" — hide the badge entirely.+ expect(formatRelativeMultiplier("BASIC", { BASIC: 0, PRO: 5 })).toBeNull();+ expect(formatRelativeMultiplier("BASIC", { BASIC: -1, PRO: 5 })).toBeNull();+ });++ it("rounds 8.533... to '8.5x rate limits' (not 8.53 or 9)", () => {+ // Price-ratio-derived multiplier from the real $320/$50 → 6.4, or from+ // limit-ratio 26.67/3.13 → ~8.53. The display rule is one decimal place.+ expect(formatRelativeMultiplier("MAX", { PRO: 3, MAX: 25.6 })).toBe(+ "8.5x rate limits",+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.tsindex 9d576f53ab..ab10abe4f9 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts@@ -1,7 +1,6 @@export interface TierInfo {key: string;label: string;- multiplier: string;description: string;}@@ -9,26 +8,22 @@ export const TIERS: TierInfo[] = [{key: "BASIC",label: "Basic",- multiplier: "1x",description: "Base AutoPilot capacity with standard rate limits",},{key: "PRO",label: "Pro",- multiplier: "5x",- description: "5x AutoPilot capacity — run 5× more tasks per day/week",+ description: "AutoPilot capacity for running more tasks per day/week",},{key: "MAX",label: "Max",- multiplier: "20x",- description: "20x AutoPilot capacity — ideal for power users",+ description: "Expanded AutoPilot capacity — ideal for power users",},{key: "BUSINESS",label: "Business",- multiplier: "60x",- description: "60x AutoPilot capacity — ideal for teams and heavy workloads",+ description: "AutoPilot capacity for teams and heavy workloads",},];@@ -58,3 +53,24 @@ export function formatPendingDate(value: Date | string): string {day: "numeric",});}++// Render a tier's rate-limit badge *relative* to the lowest visible tier so the+// UI doesn't have to hard-code the backend multiplier defaults. Returns `null`+// for the lowest tier (it's the baseline — no badge) and for tiers absent from+// the payload (hidden, e.g. BUSINESS before its LD price is set).+export function formatRelativeMultiplier(+ tierKey: string,+ tierMultipliers: Record<string, number>,+): string | null {+ const mine = tierMultipliers[tierKey];+ if (mine === undefined || mine <= 0) return null;+ const visible = Object.values(tierMultipliers).filter((v) => v > 0);+ if (visible.length === 0) return null;+ const min = Math.min(...visible);+ const label = (mine / min).toFixed(1);+ // Post-rounding equality — floats that are mathematically equal but differ+ // in the last bits (e.g. 5.0 vs 5.0000000001) still collapse to the same+ // displayed ratio, so treat "1.0" as baseline regardless of raw values.+ if (label === "1.0") return null;+ return `${label}x rate limits`;+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 450c22e4b3..ea1faed38d 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15996,6 +15996,12 @@"type": "object","title": "Tier Costs"},+ "tier_multipliers": {+ "additionalProperties": { "type": "number" },+ "type": "object",+ "title": "Tier Multipliers",+ "description": "Tier → rate-limit multiplier. Covers the same tiers listed in ``tier_costs`` so the frontend can render rate-limit badges relative to the lowest visible tier without knowing backend defaults."+ },"proration_credit_cents": {"type": "integer","title": "Proration Credit Cents"