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(copilot): real OpenRouter cost + cost-based rate limits (percent-only public API) (#12864)
Zamil Majdy01f1289aac2e
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.pyindex 379b9e9257..3b9c762f21 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@@ -32,10 +32,10 @@ router = APIRouter(class UserRateLimitResponse(BaseModel):user_id: struser_email: Optional[str] = None- daily_token_limit: int- weekly_token_limit: int- daily_tokens_used: int- weekly_tokens_used: int+ daily_cost_limit_microdollars: int+ weekly_cost_limit_microdollars: int+ daily_cost_used_microdollars: int+ weekly_cost_used_microdollars: inttier: SubscriptionTier@@ -101,17 +101,19 @@ async def get_user_rate_limit(logger.info("Admin %s checking rate limit for user %s", admin_user_id, resolved_id)daily_limit, weekly_limit, tier = await get_global_rate_limits(- resolved_id, config.daily_token_limit, config.weekly_token_limit+ resolved_id,+ config.daily_cost_limit_microdollars,+ config.weekly_cost_limit_microdollars,)usage = await get_usage_status(resolved_id, daily_limit, weekly_limit, tier=tier)return UserRateLimitResponse(user_id=resolved_id,user_email=resolved_email,- daily_token_limit=daily_limit,- weekly_token_limit=weekly_limit,- daily_tokens_used=usage.daily.used,- weekly_tokens_used=usage.weekly.used,+ daily_cost_limit_microdollars=daily_limit,+ weekly_cost_limit_microdollars=weekly_limit,+ daily_cost_used_microdollars=usage.daily.used,+ weekly_cost_used_microdollars=usage.weekly.used,tier=tier,)@@ -141,7 +143,9 @@ async def reset_user_rate_limit(raise HTTPException(status_code=500, detail="Failed to reset usage") from edaily_limit, weekly_limit, tier = await get_global_rate_limits(- user_id, config.daily_token_limit, config.weekly_token_limit+ user_id,+ config.daily_cost_limit_microdollars,+ config.weekly_cost_limit_microdollars,)usage = await get_usage_status(user_id, daily_limit, weekly_limit, tier=tier)@@ -154,10 +158,10 @@ async def reset_user_rate_limit(return UserRateLimitResponse(user_id=user_id,user_email=resolved_email,- daily_token_limit=daily_limit,- weekly_token_limit=weekly_limit,- daily_tokens_used=usage.daily.used,- weekly_tokens_used=usage.weekly.used,+ daily_cost_limit_microdollars=daily_limit,+ weekly_cost_limit_microdollars=weekly_limit,+ daily_cost_used_microdollars=usage.daily.used,+ weekly_cost_used_microdollars=usage.weekly.used,tier=tier,)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.pyindex 77e4a656fb..c6c920829d 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@@ -85,10 +85,10 @@ def test_get_rate_limit(data = response.json()assert data["user_id"] == target_user_idassert data["user_email"] == _TARGET_EMAIL- assert data["daily_token_limit"] == 2_500_000- assert data["weekly_token_limit"] == 12_500_000- assert data["daily_tokens_used"] == 500_000- assert data["weekly_tokens_used"] == 3_000_000+ assert data["daily_cost_limit_microdollars"] == 2_500_000+ assert data["weekly_cost_limit_microdollars"] == 12_500_000+ assert data["daily_cost_used_microdollars"] == 500_000+ assert data["weekly_cost_used_microdollars"] == 3_000_000assert data["tier"] == "FREE"configured_snapshot.assert_match(@@ -117,7 +117,7 @@ def test_get_rate_limit_by_email(data = response.json()assert data["user_id"] == target_user_idassert data["user_email"] == _TARGET_EMAIL- assert data["daily_token_limit"] == 2_500_000+ assert data["daily_cost_limit_microdollars"] == 2_500_000def test_get_rate_limit_by_email_not_found(@@ -160,9 +160,9 @@ def test_reset_user_usage_daily_only(assert response.status_code == 200data = response.json()- assert data["daily_tokens_used"] == 0+ assert data["daily_cost_used_microdollars"] == 0# Weekly is untouched- assert data["weekly_tokens_used"] == 3_000_000+ assert data["weekly_cost_used_microdollars"] == 3_000_000assert data["tier"] == "FREE"mock_reset.assert_awaited_once_with(target_user_id, reset_weekly=False)@@ -192,8 +192,8 @@ def test_reset_user_usage_daily_and_weekly(assert response.status_code == 200data = response.json()- assert data["daily_tokens_used"] == 0- assert data["weekly_tokens_used"] == 0+ assert data["daily_cost_used_microdollars"] == 0+ assert data["weekly_cost_used_microdollars"] == 0assert data["tier"] == "FREE"mock_reset.assert_awaited_once_with(target_user_id, reset_weekly=True)diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex eceedb828c..6ef15f0999 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -34,7 +34,7 @@ from backend.copilot.pending_message_helpers import ()from backend.copilot.pending_messages import peek_pending_messagesfrom backend.copilot.rate_limit import (- CoPilotUsageStatus,+ CoPilotUsagePublic,RateLimitExceeded,acquire_reset_lock,check_rate_limit,@@ -536,23 +536,27 @@ async def get_session()async def get_copilot_usage(user_id: Annotated[str, Security(auth.get_user_id)],-) -> CoPilotUsageStatus:+) -> CoPilotUsagePublic:"""Get CoPilot usage status for the authenticated user.- Returns current token usage vs limits for daily and weekly windows.- Global defaults sourced from LaunchDarkly (falling back to config).- Includes the user's rate-limit tier.+ Returns the percentage of the daily/weekly allowance used — not the+ raw spend or cap — so clients cannot derive per-turn cost or platform+ margins. Global defaults sourced from LaunchDarkly (falling back to+ config). Includes the user's rate-limit tier."""daily_limit, weekly_limit, tier = await get_global_rate_limits(- user_id, config.daily_token_limit, config.weekly_token_limit+ user_id,+ config.daily_cost_limit_microdollars,+ config.weekly_cost_limit_microdollars,)- return await get_usage_status(+ status = await get_usage_status(user_id=user_id,- daily_token_limit=daily_limit,- weekly_token_limit=weekly_limit,+ daily_cost_limit=daily_limit,+ weekly_cost_limit=weekly_limit,rate_limit_reset_cost=config.rate_limit_reset_cost,tier=tier,)+ return CoPilotUsagePublic.from_status(status)class RateLimitResetResponse(BaseModel):@@ -561,7 +565,9 @@ class RateLimitResetResponse(BaseModel):success: boolcredits_charged: int = Field(description="Credits charged (in cents)")remaining_balance: int = Field(description="Credit balance after charge (in cents)")- usage: CoPilotUsageStatus = Field(description="Updated usage status after reset")+ usage: CoPilotUsagePublic = Field(+ description="Updated usage status after reset (percentages only)"+ )@router.post(@@ -585,7 +591,7 @@ async def reset_copilot_usage() -> RateLimitResetResponse:"""Reset the daily CoPilot rate limit by spending credits.- Allows users who have hit their daily token limit to spend credits+ Allows users who have hit their daily cost limit to spend creditsto reset their daily usage counter and continue working.Returns 400 if the feature is disabled or the user is not over the limit.Returns 402 if the user has insufficient credits.@@ -604,7 +610,9 @@ async def reset_copilot_usage()daily_limit, weekly_limit, tier = await get_global_rate_limits(- user_id, config.daily_token_limit, config.weekly_token_limit+ user_id,+ config.daily_cost_limit_microdollars,+ config.weekly_cost_limit_microdollars,)if daily_limit <= 0:@@ -641,8 +649,8 @@ async def reset_copilot_usage(# used for limit checks, not returned to the client.)usage_status = await get_usage_status(user_id=user_id,- daily_token_limit=daily_limit,- weekly_token_limit=weekly_limit,+ daily_cost_limit=daily_limit,+ weekly_cost_limit=weekly_limit,tier=tier,)if daily_limit > 0 and usage_status.daily.used < daily_limit:@@ -677,7 +685,7 @@ 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_token_limit=daily_limit):+ if not await reset_daily_usage(user_id, daily_cost_limit=daily_limit):# Compensate: refund the charged credits.refunded = Falsetry:@@ -713,11 +721,11 @@ async def reset_copilot_usage(finally:await release_reset_lock(user_id)- # Return updated usage status.+ # Return updated usage status (public schema — percentages only).updated_usage = await get_usage_status(user_id=user_id,- daily_token_limit=daily_limit,- weekly_token_limit=weekly_limit,+ daily_cost_limit=daily_limit,+ weekly_cost_limit=weekly_limit,rate_limit_reset_cost=config.rate_limit_reset_cost,tier=tier,)@@ -726,7 +734,7 @@ async def reset_copilot_usage(success=True,credits_charged=cost,remaining_balance=remaining,- usage=updated_usage,+ usage=CoPilotUsagePublic.from_status(updated_usage),)@@ -787,7 +795,7 @@ async def cancel_session_task(),},404: {"description": "Session not found or access denied"},- 429: {"description": "Token rate-limit or call-frequency cap exceeded"},+ 429: {"description": "Cost rate-limit or call-frequency cap exceeded"},},)async def stream_chat_post(@@ -861,18 +869,20 @@ async def stream_chat_post(},)- # Pre-turn rate limit check (token-based).+ # Pre-turn rate limit check (cost-based, microdollars).# check_rate_limit short-circuits internally when both limits are 0.# Global defaults sourced from LaunchDarkly, falling back to config.if user_id:try:daily_limit, weekly_limit, _ = await get_global_rate_limits(- user_id, config.daily_token_limit, config.weekly_token_limit+ user_id,+ config.daily_cost_limit_microdollars,+ config.weekly_cost_limit_microdollars,)await check_rate_limit(user_id=user_id,- daily_token_limit=daily_limit,- weekly_token_limit=weekly_limit,+ daily_cost_limit=daily_limit,+ weekly_cost_limit=weekly_limit,)except RateLimitExceeded as e:raise HTTPException(status_code=429, detail=str(e)) from ediff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 4dc6547515..88c4ef5f14 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -296,8 +296,8 @@ def test_stream_chat_returns_429_on_daily_rate_limit(mocker: pytest_mock.MockerF_mock_stream_internals(mocker)# Ensure the rate-limit branch is entered by setting a non-zero limit.- mocker.patch.object(chat_routes.config, "daily_token_limit", 10000)- mocker.patch.object(chat_routes.config, "weekly_token_limit", 50000)+ mocker.patch.object(chat_routes.config, "daily_cost_limit_microdollars", 10000)+ mocker.patch.object(chat_routes.config, "weekly_cost_limit_microdollars", 50000)mocker.patch("backend.api.features.chat.routes.check_rate_limit",side_effect=RateLimitExceeded("daily", datetime.now(UTC) + timedelta(hours=1)),@@ -318,8 +318,8 @@ def test_stream_chat_returns_429_on_weekly_rate_limit(from backend.copilot.rate_limit import RateLimitExceeded_mock_stream_internals(mocker)- mocker.patch.object(chat_routes.config, "daily_token_limit", 10000)- mocker.patch.object(chat_routes.config, "weekly_token_limit", 50000)+ mocker.patch.object(chat_routes.config, "daily_cost_limit_microdollars", 10000)+ mocker.patch.object(chat_routes.config, "weekly_cost_limit_microdollars", 50000)resets_at = datetime.now(UTC) + timedelta(days=3)mocker.patch("backend.api.features.chat.routes.check_rate_limit",@@ -341,8 +341,8 @@ def test_stream_chat_429_includes_reset_time(mocker: pytest_mock.MockerFixture):from backend.copilot.rate_limit import RateLimitExceeded_mock_stream_internals(mocker)- mocker.patch.object(chat_routes.config, "daily_token_limit", 10000)- mocker.patch.object(chat_routes.config, "weekly_token_limit", 50000)+ mocker.patch.object(chat_routes.config, "daily_cost_limit_microdollars", 10000)+ mocker.patch.object(chat_routes.config, "weekly_cost_limit_microdollars", 50000)mocker.patch("backend.api.features.chat.routes.check_rate_limit",side_effect=RateLimitExceeded(@@ -402,23 +402,33 @@ def test_usage_returns_daily_and_weekly(mocker: pytest_mock.MockerFixture,test_user_id: str,) -> None:- """GET /usage returns daily and weekly usage."""+ """GET /usage returns percentages for daily and weekly windows only.++ The raw used/limit microdollar values MUST NOT leak — clients should not+ be able to derive per-turn cost or platform margins from the public API.+ """mock_get = _mock_usage(mocker, daily_used=500, weekly_used=2000)- mocker.patch.object(chat_routes.config, "daily_token_limit", 10000)- mocker.patch.object(chat_routes.config, "weekly_token_limit", 50000)+ mocker.patch.object(chat_routes.config, "daily_cost_limit_microdollars", 10000)+ mocker.patch.object(chat_routes.config, "weekly_cost_limit_microdollars", 50000)response = client.get("/usage")assert response.status_code == 200data = response.json()- assert data["daily"]["used"] == 500- assert data["weekly"]["used"] == 2000+ # 500 / 10000 = 5%, 2000 / 50000 = 4%+ assert data["daily"]["percent_used"] == 5.0+ assert data["weekly"]["percent_used"] == 4.0+ # Raw spend/limit must not be exposed.+ assert "used" not in data["daily"]+ assert "limit" not in data["daily"]+ assert "used" not in data["weekly"]+ assert "limit" not in data["weekly"]mock_get.assert_called_once_with(user_id=test_user_id,- daily_token_limit=10000,- weekly_token_limit=50000,+ daily_cost_limit=10000,+ weekly_cost_limit=50000,rate_limit_reset_cost=chat_routes.config.rate_limit_reset_cost,tier=SubscriptionTier.FREE,)@@ -438,8 +448,8 @@ def test_usage_uses_config_limits(assert response.status_code == 200mock_get.assert_called_once_with(user_id=test_user_id,- daily_token_limit=99999,- weekly_token_limit=77777,+ daily_cost_limit=99999,+ weekly_cost_limit=77777,rate_limit_reset_cost=500,tier=SubscriptionTier.FREE,)diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.pyindex 7d27beac8b..8a26002e25 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py@@ -22,7 +22,9 @@ from typing import TYPE_CHECKING, Any, castimport orjsonfrom langfuse import propagate_attributes+from openai.types import CompletionUsagefrom openai.types.chat import ChatCompletionMessageParam, ChatCompletionToolParam+from openai.types.completion_usage import PromptTokensDetailsfrom opentelemetry import trace as otel_tracefrom backend.copilot.config import CopilotLlmModel, CopilotMode@@ -126,6 +128,53 @@ _MAX_INLINE_IMAGE_BYTES = 20 * 1024 * 1024# Matches characters unsafe for filenames._UNSAFE_FILENAME = re.compile(r"[^\w.\-]")+# OpenRouter-specific extra_body flag that embeds the real generation cost+# into the final usage chunk. Module-level constant so we don't reallocate+# an identical dict on every streaming call.+_OPENROUTER_INCLUDE_USAGE_COST = {"usage": {"include": True}}+++def _extract_usage_cost(usage: CompletionUsage) -> float | None:+ """Return the provider-reported USD cost on a streaming usage chunk.++ OpenRouter piggybacks a ``cost`` field on the OpenAI-compatible usage+ object when the request body includes ``usage: {"include": True}``.+ The OpenAI SDK's typed ``CompletionUsage`` does not declare it, so we+ read it off ``model_extra`` (the pydantic v2 container for extras) to+ keep the access fully typed — no ``getattr``.++ Returns ``None`` when the field is absent, explicitly null,+ non-numeric, non-finite, or negative. Invalid values (including+ present-but-null) are logged here — they indicate a provider bug+ worth chasing; plain absences are silent so the caller can dedupe+ the "missing cost" warning per stream.+ """+ extras = usage.model_extra or {}+ if "cost" not in extras:+ return None+ raw = extras["cost"]+ if raw is None:+ logger.error("[Baseline] usage.cost is present but null")+ return None+ try:+ val = float(raw)+ except (TypeError, ValueError):+ logger.error("[Baseline] usage.cost is not numeric: %r", raw)+ return None+ if not math.isfinite(val) or val < 0:+ logger.error("[Baseline] usage.cost is non-finite or negative: %r", val)+ return None+ return val+++def _extract_cache_creation_tokens(ptd: PromptTokensDetails) -> int:+ """Read Anthropic's ``cache_creation_input_tokens`` off an OpenAI+ ``PromptTokensDetails`` — it's a provider-specific extra, not in the+ typed model, so we read it via ``model_extra`` rather than+ ``getattr``.+ """+ return int((ptd.model_extra or {}).get("cache_creation_input_tokens") or 0)+async def _prepare_baseline_attachments(file_ids: list[str],@@ -267,6 +316,10 @@ class _BaselineStreamState:turn_cache_read_tokens: int = 0turn_cache_creation_tokens: int = 0cost_usd: float | None = None+ # Tracks whether we've already warned about a missing `cost` field in+ # the usage chunk this stream, so non-OpenRouter providers don't+ # generate one warning per streaming call.+ cost_missing_logged: bool = Falsethinking_stripper: _ThinkingStripper = field(default_factory=_ThinkingStripper)session_messages: list[ChatMessage] = field(default_factory=list)# Tracks how much of ``assistant_text`` has already been flushed to@@ -292,10 +345,12 @@ async def _baseline_llm_caller(state.thinking_stripper = _ThinkingStripper()round_text = ""- response = None # initialized before try so finally block can access ittry:client = _get_openai_client()typed_messages = cast(list[ChatCompletionMessageParam], messages)+ # extra_body `usage.include=true` asks OpenRouter to embed the real+ # generation cost into the final usage chunk. Without this we only get+ # token counts and have no authoritative cost for rate limiting.if tools:typed_tools = cast(list[ChatCompletionToolParam], tools)response = await client.chat.completions.create(@@ -304,6 +359,7 @@ async def _baseline_llm_caller(tools=typed_tools,stream=True,stream_options={"include_usage": True},+ extra_body=_OPENROUTER_INCLUDE_USAGE_COST,)else:response = await client.chat.completions.create(@@ -311,6 +367,7 @@ async def _baseline_llm_caller(messages=typed_messages,stream=True,stream_options={"include_usage": True},+ extra_body=_OPENROUTER_INCLUDE_USAGE_COST,)tool_calls_by_index: dict[int, dict[str, str]] = {}@@ -323,18 +380,33 @@ async def _baseline_llm_caller(if chunk.usage:state.turn_prompt_tokens += chunk.usage.prompt_tokens or 0state.turn_completion_tokens += chunk.usage.completion_tokens or 0- # Extract cache token details when available (OpenAI /- # OpenRouter include these in prompt_tokens_details).- ptd = getattr(chunk.usage, "prompt_tokens_details", None)+ ptd = chunk.usage.prompt_tokens_detailsif ptd:- state.turn_cache_read_tokens += (- getattr(ptd, "cached_tokens", 0) or 0- )- # cache_creation_input_tokens is reported by some providers- # (e.g. Anthropic native) but not standard OpenAI streaming.+ state.turn_cache_read_tokens += ptd.cached_tokens or 0state.turn_cache_creation_tokens += (- getattr(ptd, "cache_creation_input_tokens", 0) or 0+ _extract_cache_creation_tokens(ptd))+ cost = _extract_usage_cost(chunk.usage)+ if cost is not None:+ state.cost_usd = (state.cost_usd or 0.0) + cost+ elif (+ "cost" not in (chunk.usage.model_extra or {})+ and not state.cost_missing_logged+ ):+ # Field absent (non-OpenRouter route, or OpenRouter+ # misconfigured) — warn once per stream so error+ # monitoring picks up persistent misses without+ # flooding. Invalid values already logged inside+ # _extract_usage_cost, so no duplicate warning here.+ logger.warning(+ "[Baseline] usage chunk missing cost (model=%s, "+ "prompt=%s, completion=%s) — rate-limit will "+ "skip this call",+ state.model,+ chunk.usage.prompt_tokens,+ chunk.usage.completion_tokens,+ )+ state.cost_missing_logged = Truedelta = chunk.choices[0].delta if chunk.choices else Noneif not delta:@@ -394,20 +466,6 @@ async def _baseline_llm_caller(state.text_started = Falsestate.text_block_id = str(uuid.uuid4())finally:- # Extract OpenRouter cost from response headers (in finally so we- # capture cost even when the stream errors mid-way — we already paid).- # Accumulate across multi-round tool-calling turns.- try:- # Access undocumented _response attribute — same pattern as- # extract_openrouter_cost() in blocks/llm.py.- cost_header = response._response.headers.get("x-total-cost") # type: ignore[attr-defined]- if cost_header:- cost = float(cost_header)- if math.isfinite(cost) and cost >= 0:- state.cost_usd = (state.cost_usd or 0.0) + cost- except (AttributeError, ValueError):- pass-# Always persist partial text so the session history stays consistent,# even when the stream is interrupted by an exception.state.assistant_text += round_textdiff --git a/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py b/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.pyindex a0e55d843f..e21618c367 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py@@ -11,6 +11,7 @@ from openai.types.chat import ChatCompletionToolParamfrom backend.copilot.baseline.service import (_baseline_conversation_updater,+ _baseline_llm_caller,_BaselineStreamState,_compress_session_messages,)@@ -574,37 +575,80 @@ class TestPrepareBaselineAttachments:assert blocks == []-class TestBaselineCostExtraction:- """Tests for x-total-cost header extraction in _baseline_llm_caller."""+_COST_MISSING = object()- @pytest.mark.asyncio- async def test_cost_usd_extracted_from_response_header(self):- """state.cost_usd is set from x-total-cost header when present."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )- state = _BaselineStreamState(model="gpt-4o-mini")+def _make_usage_chunk(+ *,+ prompt_tokens: int = 0,+ completion_tokens: int = 0,+ cost: float | str | None | object = _COST_MISSING,+ cached_tokens: int | None = None,+ cache_creation_input_tokens: int | None = None,+):+ """Build a mock streaming chunk carrying usage (and optionally cost).- # Build a mock raw httpx response with the cost header- mock_raw_response = MagicMock()- mock_raw_response.headers = {"x-total-cost": "0.0123"}+ Provider-specific fields (``cost`` on usage, ``cache_creation_input_tokens``+ on prompt_tokens_details) are set on ``model_extra`` because that's where+ the baseline helper reads them from (typed ``CompletionUsage.model_extra``+ rather than ``getattr``). Pass ``cost=None`` to emit an explicit-null cost+ key; omit ``cost`` entirely to leave the key absent.+ """+ chunk = MagicMock()+ chunk.choices = []+ chunk.usage = MagicMock()+ chunk.usage.prompt_tokens = prompt_tokens+ chunk.usage.completion_tokens = completion_tokens+ usage_extras: dict[str, float | str | None] = {}+ if cost is not _COST_MISSING:+ usage_extras["cost"] = cost # type: ignore[assignment]+ chunk.usage.model_extra = usage_extras++ if cached_tokens is not None or cache_creation_input_tokens is not None:+ ptd = MagicMock()+ ptd.cached_tokens = cached_tokens or 0+ ptd.model_extra = {+ "cache_creation_input_tokens": cache_creation_input_tokens or 0+ }+ chunk.usage.prompt_tokens_details = ptd+ else:+ chunk.usage.prompt_tokens_details = None- # Build a mock async streaming response that yields no chunks but has- # a _response attribute pointing to the mock httpx response- mock_stream_response = MagicMock()- mock_stream_response._response = mock_raw_response+ return chunk- async def empty_aiter():- return- yield # make it an async generator- mock_stream_response.__aiter__ = lambda self: empty_aiter()+def _make_stream_mock(*chunks):+ """Build an async streaming response mock that yields *chunks* in order."""+ stream = MagicMock()+ stream.close = AsyncMock()++ async def aiter():+ for c in chunks:+ yield c++ stream.__aiter__ = lambda self: aiter()+ return stream+++class TestBaselineCostExtraction:+ """Tests for ``usage.cost`` extraction in ``_baseline_llm_caller``.++ Cost is read from the OpenRouter ``usage.cost`` field on the final+ streaming chunk when the request body includes ``usage: {include: true}``+ (handled by the baseline service via ``extra_body``).+ """++ @pytest.mark.asyncio+ async def test_cost_usd_extracted_from_usage_chunk(self):+ """state.cost_usd is set from chunk.usage.cost when present."""+ state = _BaselineStreamState(model="gpt-4o-mini")+ chunk = _make_usage_chunk(+ prompt_tokens=1000, completion_tokens=200, cost=0.0123+ )mock_client = MagicMock()mock_client.chat.completions.create = AsyncMock(- return_value=mock_stream_response+ return_value=_make_stream_mock(chunk))with patch(@@ -622,29 +666,14 @@ class TestBaselineCostExtraction:@pytest.mark.asyncioasync def test_cost_usd_accumulates_across_calls(self):"""cost_usd accumulates when _baseline_llm_caller is called multiple times."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-state = _BaselineStreamState(model="gpt-4o-mini")- def make_stream_mock(cost: str) -> MagicMock:- mock_raw = MagicMock()- mock_raw.headers = {"x-total-cost": cost}- mock_stream = MagicMock()- mock_stream._response = mock_raw-- async def empty_aiter():- return- yield-- mock_stream.__aiter__ = lambda self: empty_aiter()- return mock_stream-mock_client = MagicMock()mock_client.chat.completions.create = AsyncMock(- side_effect=[make_stream_mock("0.01"), make_stream_mock("0.02")]+ side_effect=[+ _make_stream_mock(_make_usage_chunk(prompt_tokens=500, cost=0.01)),+ _make_stream_mock(_make_usage_chunk(prompt_tokens=600, cost=0.02)),+ ])with patch(@@ -665,28 +694,38 @@ class TestBaselineCostExtraction:assert state.cost_usd == pytest.approx(0.03)@pytest.mark.asyncio- async def test_no_cost_when_header_absent(self):- """state.cost_usd remains None when response has no x-total-cost header."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-+ async def test_cost_usd_accepts_string_value(self):+ """OpenRouter may emit cost as a string — it should still parse."""state = _BaselineStreamState(model="gpt-4o-mini")+ chunk = _make_usage_chunk(prompt_tokens=10, cost="0.005")- mock_raw = MagicMock()- mock_raw.headers = {}- mock_stream = MagicMock()- mock_stream._response = mock_raw+ mock_client = MagicMock()+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk)+ )- async def empty_aiter():- return- yield+ with patch(+ "backend.copilot.baseline.service._get_openai_client",+ return_value=mock_client,+ ):+ await _baseline_llm_caller(+ messages=[{"role": "user", "content": "hi"}],+ tools=[],+ state=state,+ )- mock_stream.__aiter__ = lambda self: empty_aiter()+ assert state.cost_usd == pytest.approx(0.005)++ @pytest.mark.asyncio+ async def test_cost_usd_none_when_usage_cost_missing(self):+ """state.cost_usd stays None when the usage chunk lacks a cost field."""+ state = _BaselineStreamState(model="anthropic/claude-sonnet-4")+ chunk = _make_usage_chunk(prompt_tokens=1000, completion_tokens=500)mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(return_value=mock_stream)+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk)+ )with patch("backend.copilot.baseline.service._get_openai_client",@@ -699,37 +738,73 @@ class TestBaselineCostExtraction:)assert state.cost_usd is None+ # Token accumulators are still populated so the caller can log them.+ assert state.turn_prompt_tokens == 1000+ assert state.turn_completion_tokens == 500@pytest.mark.asyncio- async def test_cost_extracted_even_when_stream_raises(self):- """cost_usd is captured in the finally block even when streaming fails."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,+ async def test_invalid_cost_string_leaves_cost_none(self):+ """A non-numeric cost value is rejected without raising."""+ state = _BaselineStreamState(model="gpt-4o-mini")+ chunk = _make_usage_chunk(prompt_tokens=10, cost="not-a-number")++ mock_client = MagicMock()+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk))+ with patch(+ "backend.copilot.baseline.service._get_openai_client",+ return_value=mock_client,+ ):+ await _baseline_llm_caller(+ messages=[{"role": "user", "content": "hi"}],+ tools=[],+ state=state,+ )++ assert state.cost_usd is None++ @pytest.mark.asyncio+ async def test_negative_cost_is_ignored(self):+ """Guard against negative cost values (shouldn't happen but be safe)."""state = _BaselineStreamState(model="gpt-4o-mini")+ chunk = _make_usage_chunk(prompt_tokens=10, cost=-0.01)- mock_raw = MagicMock()- mock_raw.headers = {"x-total-cost": "0.005"}- mock_stream = MagicMock()- mock_stream._response = mock_raw+ mock_client = MagicMock()+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk)+ )- async def failing_aiter():- raise RuntimeError("stream error")- yield # make it an async generator+ with patch(+ "backend.copilot.baseline.service._get_openai_client",+ return_value=mock_client,+ ):+ await _baseline_llm_caller(+ messages=[{"role": "user", "content": "hi"}],+ tools=[],+ state=state,+ )- mock_stream.__aiter__ = lambda self: failing_aiter()+ assert state.cost_usd is None++ @pytest.mark.asyncio+ async def test_explicit_null_cost_is_logged_and_ignored(self, caplog):+ """`{"cost": null}` is rejected and logged (not silently dropped)."""+ state = _BaselineStreamState(model="openrouter/auto")+ chunk = _make_usage_chunk(prompt_tokens=10, cost=None)mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(return_value=mock_stream)+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk)+ )with (patch("backend.copilot.baseline.service._get_openai_client",return_value=mock_client,),- pytest.raises(RuntimeError, match="stream error"),+ caplog.at_level("ERROR", logger="backend.copilot.baseline.service"),):await _baseline_llm_caller(messages=[{"role": "user", "content": "hi"}],@@ -737,29 +812,34 @@ class TestBaselineCostExtraction:state=state,)- assert state.cost_usd == pytest.approx(0.005)-- @pytest.mark.asyncio- async def test_no_cost_when_api_call_raises_before_stream(self):- """finally block is safe when response is None (API call failed before yielding)."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,+ assert state.cost_usd is None+ assert any(+ "usage.cost is present but null" in rec.message for rec in caplog.records)+ @pytest.mark.asyncio+ async def test_cost_not_captured_when_stream_raises_mid_chunk(self):+ """If the stream aborts before emitting the usage chunk there is no cost."""state = _BaselineStreamState(model="gpt-4o-mini")+ stream = MagicMock()+ stream.close = AsyncMock()++ async def failing_aiter():+ raise RuntimeError("stream error")+ yield # make it an async generator++ stream.__aiter__ = lambda self: failing_aiter()+mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(- side_effect=RuntimeError("connection refused")- )+ mock_client.chat.completions.create = AsyncMock(return_value=stream)with (patch("backend.copilot.baseline.service._get_openai_client",return_value=mock_client,),- pytest.raises(RuntimeError, match="connection refused"),+ pytest.raises(RuntimeError, match="stream error"),):await _baseline_llm_caller(messages=[{"role": "user", "content": "hi"}],@@ -767,42 +847,25 @@ class TestBaselineCostExtraction:state=state,)- # response was never assigned so cost extraction must not raise+ # Stream aborted before yielding the usage chunk — cost stays None.assert state.cost_usd is None@pytest.mark.asyncio- async def test_no_cost_when_header_missing(self):- """cost_usd remains None when x-total-cost is absent."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-- state = _BaselineStreamState(model="anthropic/claude-sonnet-4")-- mock_raw = MagicMock()- mock_raw.headers = {} # no x-total-cost- mock_stream = MagicMock()- mock_stream._response = mock_raw-- mock_chunk = MagicMock()- mock_chunk.usage = MagicMock()- mock_chunk.usage.prompt_tokens = 1000- mock_chunk.usage.completion_tokens = 500- mock_chunk.usage.prompt_tokens_details = None- mock_chunk.choices = []-- async def chunk_aiter():- yield mock_chunk-- mock_stream.__aiter__ = lambda self: chunk_aiter()+ async def test_no_cost_when_api_call_raises_before_stream(self):+ """The helper is safe when the create() call itself raises."""+ state = _BaselineStreamState(model="gpt-4o-mini")mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(return_value=mock_stream)+ mock_client.chat.completions.create = AsyncMock(+ side_effect=RuntimeError("connection refused")+ )- with patch(- "backend.copilot.baseline.service._get_openai_client",- return_value=mock_client,+ with (+ patch(+ "backend.copilot.baseline.service._get_openai_client",+ return_value=mock_client,+ ),+ pytest.raises(RuntimeError, match="connection refused"),):await _baseline_llm_caller(messages=[{"role": "user", "content": "hi"}],@@ -815,36 +878,18 @@ class TestBaselineCostExtraction:@pytest.mark.asyncioasync def test_cache_tokens_extracted_from_usage_details(self):"""cache tokens are extracted from prompt_tokens_details.cached_tokens."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-state = _BaselineStreamState(model="openai/gpt-4o")-- mock_raw = MagicMock()- mock_raw.headers = {"x-total-cost": "0.01"}- mock_stream = MagicMock()- mock_stream._response = mock_raw-- # Create a chunk with prompt_tokens_details- mock_ptd = MagicMock()- mock_ptd.cached_tokens = 800-- mock_chunk = MagicMock()- mock_chunk.usage = MagicMock()- mock_chunk.usage.prompt_tokens = 1000- mock_chunk.usage.completion_tokens = 200- mock_chunk.usage.prompt_tokens_details = mock_ptd- mock_chunk.choices = []-- async def chunk_aiter():- yield mock_chunk-- mock_stream.__aiter__ = lambda self: chunk_aiter()+ chunk = _make_usage_chunk(+ prompt_tokens=1000,+ completion_tokens=200,+ cost=0.01,+ cached_tokens=800,+ )mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(return_value=mock_stream)+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk)+ )with patch("backend.copilot.baseline.service._get_openai_client",@@ -861,37 +906,20 @@ class TestBaselineCostExtraction:@pytest.mark.asyncioasync def test_cache_creation_tokens_extracted_from_usage_details(self):- """cache_creation_tokens are extracted from prompt_tokens_details."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-+ """cache_creation_input_tokens is extracted from prompt_tokens_details."""state = _BaselineStreamState(model="openai/gpt-4o")-- mock_raw = MagicMock()- mock_raw.headers = {"x-total-cost": "0.01"}- mock_stream = MagicMock()- mock_stream._response = mock_raw-- mock_ptd = MagicMock()- mock_ptd.cached_tokens = 0- mock_ptd.cache_creation_input_tokens = 500-- mock_chunk = MagicMock()- mock_chunk.usage = MagicMock()- mock_chunk.usage.prompt_tokens = 1000- mock_chunk.usage.completion_tokens = 200- mock_chunk.usage.prompt_tokens_details = mock_ptd- mock_chunk.choices = []-- async def chunk_aiter():- yield mock_chunk-- mock_stream.__aiter__ = lambda self: chunk_aiter()+ chunk = _make_usage_chunk(+ prompt_tokens=1000,+ completion_tokens=200,+ cost=0.01,+ cached_tokens=0,+ cache_creation_input_tokens=500,+ )mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(return_value=mock_stream)+ mock_client.chat.completions.create = AsyncMock(+ return_value=_make_stream_mock(chunk)+ )with patch("backend.copilot.baseline.service._get_openai_client",@@ -908,37 +936,17 @@ class TestBaselineCostExtraction:@pytest.mark.asyncioasync def test_token_accumulators_track_across_multiple_calls(self):"""Token accumulators grow correctly across multiple _baseline_llm_caller calls."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-state = _BaselineStreamState(model="anthropic/claude-sonnet-4")- def make_stream(prompt_tokens: int, completion_tokens: int):- mock_raw = MagicMock()- mock_raw.headers = {} # no x-total-cost- mock_stream = MagicMock()- mock_stream._response = mock_raw-- mock_chunk = MagicMock()- mock_chunk.usage = MagicMock()- mock_chunk.usage.prompt_tokens = prompt_tokens- mock_chunk.usage.completion_tokens = completion_tokens- mock_chunk.usage.prompt_tokens_details = None- mock_chunk.choices = []-- async def chunk_aiter():- yield mock_chunk-- mock_stream.__aiter__ = lambda self: chunk_aiter()- return mock_stream-mock_client = MagicMock()mock_client.chat.completions.create = AsyncMock(side_effect=[- make_stream(1000, 200),- make_stream(1100, 300),+ _make_stream_mock(+ _make_usage_chunk(prompt_tokens=1000, completion_tokens=200)+ ),+ _make_stream_mock(+ _make_usage_chunk(prompt_tokens=1100, completion_tokens=300)+ ),])@@ -957,45 +965,33 @@ class TestBaselineCostExtraction:state=state,)- # No x-total-cost header and empty pricing table -- cost_usd remains None+ # No usage.cost on either chunk → cost stays None, tokens still accumulate.assert state.cost_usd is None- # Accumulators hold all tokens across both turnsassert state.turn_prompt_tokens == 2100assert state.turn_completion_tokens == 500+ @pytest.mark.parametrize(+ "tools",+ [+ pytest.param([], id="no_tools"),+ pytest.param([_make_tool("search")], id="with_tools"),+ ],+ )@pytest.mark.asyncio- async def test_cost_usd_remains_none_when_header_missing(self):- """cost_usd stays None when x-total-cost header is absent.-- Token counts are still tracked; persist_and_record_usage handles- the None cost by falling back to tracking_type='tokens'.+ async def test_baseline_requests_usage_include_extra_body(+ self, tools: list[ChatCompletionToolParam]+ ):+ """The baseline call must pass extra_body={'usage': {'include': True}}.++ This guards the contract with OpenRouter that triggers inclusion of+ the authoritative cost on the final usage chunk. Without it the+ rate-limit counter stays at zero. Exercise both the no-tools and+ tool-calling branches so a regression in either path trips the test."""- from backend.copilot.baseline.service import (- _baseline_llm_caller,- _BaselineStreamState,- )-- state = _BaselineStreamState(model="anthropic/claude-sonnet-4")-- mock_raw = MagicMock()- mock_raw.headers = {} # no x-total-cost- mock_stream = MagicMock()- mock_stream._response = mock_raw-- mock_chunk = MagicMock()- mock_chunk.usage = MagicMock()- mock_chunk.usage.prompt_tokens = 1000- mock_chunk.usage.completion_tokens = 500- mock_chunk.usage.prompt_tokens_details = None- mock_chunk.choices = []-- async def chunk_aiter():- yield mock_chunk-- mock_stream.__aiter__ = lambda self: chunk_aiter()-+ state = _BaselineStreamState(model="gpt-4o-mini")+ create_mock = AsyncMock(return_value=_make_stream_mock())mock_client = MagicMock()- mock_client.chat.completions.create = AsyncMock(return_value=mock_stream)+ mock_client.chat.completions.create = create_mockwith patch("backend.copilot.baseline.service._get_openai_client",@@ -1003,13 +999,15 @@ class TestBaselineCostExtraction:):await _baseline_llm_caller(messages=[{"role": "user", "content": "hi"}],- tools=[],+ tools=tools,state=state,)- assert state.cost_usd is None- assert state.turn_prompt_tokens == 1000- assert state.turn_completion_tokens == 500+ create_mock.assert_awaited_once()+ await_args = create_mock.await_args+ assert await_args is not None+ assert await_args.kwargs["extra_body"] == {"usage": {"include": True}}+ assert await_args.kwargs["stream_options"] == {"include_usage": True}class TestMidLoopPendingFlushOrdering:diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.pyindex ee4c717dbe..3277854172 100644--- a/autogpt_platform/backend/backend/copilot/config.py+++ b/autogpt_platform/backend/backend/copilot/config.py@@ -101,25 +101,31 @@ class ChatConfig(BaseSettings):description="Cache TTL in seconds for Langfuse prompt (0 to disable caching)",)- # Rate limiting — token-based limits per day and per week.- # Per-turn token cost varies with context size: ~10-15K for early turns,- # ~30-50K mid-session, up to ~100K pre-compaction. Average across a- # session with compaction cycles is ~25-35K tokens/turn, so 2.5M daily- # allows ~70-100 turns/day.+ # Rate limiting — cost-based limits per day and per week, stored in+ # microdollars (1 USD = 1_000_000). The counter tracks the real+ # generation cost reported by the provider (OpenRouter ``usage.cost``+ # or Claude Agent SDK ``total_cost_usd``), so cache discounts and+ # cross-model price differences are already reflected — no token+ # weighting or model multiplier is applied on top.# Checked at the HTTP layer (routes.py) before each turn.#- # These are base limits for the FREE tier. Higher tiers (PRO, BUSINESS,+ # These are base limits for the FREE tier. Higher tiers (PRO, BUSINESS,# ENTERPRISE) multiply these by their tier multiplier (see- # rate_limit.TIER_MULTIPLIERS). User tier is stored in the+ # rate_limit.TIER_MULTIPLIERS). User tier is stored in the# User.subscriptionTier DB column and resolved inside# get_global_rate_limits().- daily_token_limit: int = Field(- default=2_500_000,- description="Max tokens per day, resets at midnight UTC (0 = unlimited)",- )- weekly_token_limit: int = Field(- default=12_500_000,- description="Max tokens per week, resets Monday 00:00 UTC (0 = unlimited)",+ #+ # These defaults act as the ceiling when LaunchDarkly is unreachable;+ # the live per-tier values come from the COPILOT_*_COST_LIMIT flags.+ daily_cost_limit_microdollars: int = Field(+ default=1_000_000,+ description="Max cost per day in microdollars, resets at midnight UTC "+ "(0 = unlimited).",+ )+ weekly_cost_limit_microdollars: int = Field(+ default=5_000_000,+ description="Max cost per week in microdollars, resets Monday 00:00 UTC "+ "(0 = unlimited).",)# Cost (in credits / cents) to reset the daily rate limit using credits.diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.pyindex c08cb1b3a8..472ddf79b0 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py@@ -1,9 +1,16 @@-"""CoPilot rate limiting based on token usage.--Uses Redis fixed-window counters to track per-user token consumption-with configurable daily and weekly limits. Daily windows reset at-midnight UTC; weekly windows reset at ISO week boundary (Monday 00:00-UTC). Fails open when Redis is unavailable to avoid blocking users.+"""CoPilot rate limiting based on generation cost.++Uses Redis fixed-window counters to track per-user USD spend (stored as+microdollars, matching ``PlatformCostLog.cost_microdollars``) with+configurable daily and weekly limits. Daily windows reset at midnight UTC;+weekly windows reset at ISO week boundary (Monday 00:00 UTC). Fails open+when Redis is unavailable to avoid blocking users.++Storing microdollars rather than tokens means the counter already reflects+real model pricing (including cache discounts and provider surcharges), so+this module carries no pricing table — the cost comes from OpenRouter's+``usage.cost`` field (baseline) or the Claude Agent SDK's reported total+cost (SDK path)."""import asyncio@@ -22,8 +29,10 @@ from backend.util.cache import cachedlogger = logging.getLogger(__name__)-# Redis key prefixes-_USAGE_KEY_PREFIX = "copilot:usage"+# Redis key prefixes. Bumped from "copilot:usage" (token-based) to+# "copilot:cost" on the token→cost migration so stale counters do not+# get misinterpreted as microdollars (which would dramatically under-count).+_USAGE_KEY_PREFIX = "copilot:cost"# ---------------------------------------------------------------------------@@ -32,7 +41,7 @@ _USAGE_KEY_PREFIX = "copilot:usage"class SubscriptionTier(str, Enum):- """Subscription tiers with increasing token allowances.+ """Subscription tiers with increasing cost allowances.Mirrors the ``SubscriptionTier`` enum in ``schema.prisma``.Once ``prisma generate`` is run, this can be replaced with::@@ -46,9 +55,9 @@ class SubscriptionTier(str, Enum):ENTERPRISE = "ENTERPRISE"-# Multiplier applied to the base limits (from LD / config) for each tier.-# Intentionally int (not float): keeps limits as whole token counts and avoids-# floating-point rounding. If fractional multipliers are ever needed, change+# 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().TIER_MULTIPLIERS: dict[SubscriptionTier, int] = {SubscriptionTier.FREE: 1,@@ -61,17 +70,27 @@ DEFAULT_TIER = SubscriptionTier.FREEclass UsageWindow(BaseModel):- """Usage within a single time window."""+ """Usage within a single time window.++ ``used`` and ``limit`` are in microdollars (1 USD = 1_000_000).+ """used: intlimit: int = Field(- description="Maximum tokens allowed in this window. 0 means unlimited."+ description="Maximum microdollars of spend allowed in this window. "+ "0 means unlimited.")resets_at: datetimeclass CoPilotUsageStatus(BaseModel):- """Current usage status for a user across all windows."""+ """Current usage status for a user across all windows.++ Internal representation used by server-side code that needs to compare+ usage against limits (e.g. the reset-credits endpoint). The public API+ returns ``CoPilotUsagePublic`` instead so that raw spend and limit+ figures never leak to clients.+ """daily: UsageWindowweekly: UsageWindow@@ -82,6 +101,68 @@ class CoPilotUsageStatus(BaseModel):)+class UsageWindowPublic(BaseModel):+ """Public view of a usage window — only the percentage and reset time.++ Hides the raw spend and the cap so clients cannot derive per-turn cost+ or reverse-engineer platform margins. ``percent_used`` is capped at 100.+ """++ percent_used: float = Field(+ ge=0.0,+ le=100.0,+ description="Percentage of the window's allowance used (0-100). "+ "Clamped at 100 when over the cap.",+ )+ resets_at: datetime+++class CoPilotUsagePublic(BaseModel):+ """Current usage status for a user — public (client-safe) shape."""++ daily: UsageWindowPublic | None = Field(+ default=None,+ description="Null when no daily cap is configured (unlimited).",+ )+ weekly: UsageWindowPublic | None = Field(+ default=None,+ description="Null when no weekly cap is configured (unlimited).",+ )+ tier: SubscriptionTier = DEFAULT_TIER+ reset_cost: int = Field(+ default=0,+ description="Credit cost (in cents) to reset the daily limit. 0 = feature disabled.",+ )++ @classmethod+ def from_status(cls, status: CoPilotUsageStatus) -> "CoPilotUsagePublic":+ """Project the internal status onto the client-safe schema."""++ def window(w: UsageWindow) -> UsageWindowPublic | None:+ if w.limit <= 0:+ return None+ # When at/over the cap, snap to exactly 100.0 so the UI's+ # rounded display and its exhaustion check (`percent_used >= 100`)+ # agree. Without this, e.g. 99.95% would render as "100% used"+ # via Math.round but fail the exhaustion check, leaving the+ # reset button hidden while the bar appears full.+ if w.used >= w.limit:+ pct = 100.0+ else:+ pct = round(100.0 * w.used / w.limit, 1)+ return UsageWindowPublic(+ percent_used=pct,+ resets_at=w.resets_at,+ )++ return cls(+ daily=window(status.daily),+ weekly=window(status.weekly),+ tier=status.tier,+ reset_cost=status.reset_cost,+ )++class RateLimitExceeded(Exception):"""Raised when a user exceeds their CoPilot usage limit."""@@ -103,8 +184,8 @@ class RateLimitExceeded(Exception):async def get_usage_status(user_id: str,- daily_token_limit: int,- weekly_token_limit: int,+ daily_cost_limit: int,+ weekly_cost_limit: int,rate_limit_reset_cost: int = 0,tier: SubscriptionTier = DEFAULT_TIER,) -> CoPilotUsageStatus:@@ -112,13 +193,13 @@ async def get_usage_status(Args:user_id: The user's ID.- daily_token_limit: Max tokens per day (0 = unlimited).- weekly_token_limit: Max tokens per week (0 = unlimited).+ daily_cost_limit: Max microdollars of spend per day (0 = unlimited).+ weekly_cost_limit: Max microdollars of spend per week (0 = unlimited).rate_limit_reset_cost: Credit cost (cents) to reset daily limit (0 = disabled).tier: The user's rate-limit tier (included in the response).Returns:- CoPilotUsageStatus with current usage and limits.+ CoPilotUsageStatus with current usage and limits in microdollars."""now = datetime.now(UTC)daily_used = 0@@ -137,12 +218,12 @@ async def get_usage_status(return CoPilotUsageStatus(daily=UsageWindow(used=daily_used,- limit=daily_token_limit,+ limit=daily_cost_limit,resets_at=_daily_reset_time(now=now),),weekly=UsageWindow(used=weekly_used,- limit=weekly_token_limit,+ limit=weekly_cost_limit,resets_at=_weekly_reset_time(now=now),),tier=tier,@@ -152,22 +233,22 @@ async def get_usage_status(async def check_rate_limit(user_id: str,- daily_token_limit: int,- weekly_token_limit: int,+ daily_cost_limit: int,+ weekly_cost_limit: int,) -> None:"""Check if user is within rate limits. Raises RateLimitExceeded if not.This is a pre-turn soft check. The authoritative usage counter is updated- by ``record_token_usage()`` after the turn completes. Under concurrency,+ by ``record_cost_usage()`` after the turn completes. Under concurrency,two parallel turns may both pass this check against the same snapshot.- This is acceptable because token-based limits are approximate by nature- (the exact token count is unknown until after generation).+ This is acceptable because cost-based limits are approximate by nature+ (the exact cost is unknown until after generation).Fails open: if Redis is unavailable, allows the request."""# Short-circuit: when both limits are 0 (unlimited) skip the Redis# round-trip entirely.- if daily_token_limit <= 0 and weekly_token_limit <= 0:+ if daily_cost_limit <= 0 and weekly_cost_limit <= 0:returnnow = datetime.now(UTC)@@ -183,26 +264,25 @@ async def check_rate_limit(logger.warning("Redis unavailable for rate limit check, allowing request")return- # Worst-case overshoot: N concurrent requests × ~15K tokens each.- if daily_token_limit > 0 and daily_used >= daily_token_limit:+ if daily_cost_limit > 0 and daily_used >= daily_cost_limit:raise RateLimitExceeded("daily", _daily_reset_time(now=now))- if weekly_token_limit > 0 and weekly_used >= weekly_token_limit:+ if weekly_cost_limit > 0 and weekly_used >= weekly_cost_limit:raise RateLimitExceeded("weekly", _weekly_reset_time(now=now))-async def reset_daily_usage(user_id: str, daily_token_limit: int = 0) -> bool:- """Reset a user's daily token usage counter in Redis.+async def reset_daily_usage(user_id: str, daily_cost_limit: int = 0) -> bool:+ """Reset a user's daily cost usage counter in Redis.Called after a user pays credits to extend their daily limit.- Also reduces the weekly usage counter by ``daily_token_limit`` tokens+ Also reduces the weekly usage counter by ``daily_cost_limit`` microdollars(clamped to 0) so the user effectively gets one extra day's worth ofweekly capacity.Args:user_id: The user's ID.- daily_token_limit: The configured daily token limit. When positive,- the weekly counter is reduced by this amount.+ daily_cost_limit: The configured daily cost limit in microdollars.+ When positive, the weekly counter is reduced by this amount.Returns False if Redis is unavailable so the caller can handlecompensation (fail-closed for billed operations, unlike the read-only@@ -218,12 +298,12 @@ async def reset_daily_usage(user_id: str, daily_token_limit: int = 0) -> bool:# counter is not decremented — which would let the caller refund# credits even though the daily limit was already reset.d_key = _daily_key(user_id, now=now)- w_key = _weekly_key(user_id, now=now) if daily_token_limit > 0 else None+ w_key = _weekly_key(user_id, now=now) if daily_cost_limit > 0 else Nonepipe = redis.pipeline(transaction=True)pipe.delete(d_key)if w_key is not None:- pipe.decrby(w_key, daily_token_limit)+ pipe.decrby(w_key, daily_cost_limit)results = await pipe.execute()# Clamp negative weekly counter to 0 (best-effort; not critical).@@ -296,84 +376,40 @@ async def increment_daily_reset_count(user_id: str) -> None:logger.warning("Redis unavailable for tracking reset count")-async def record_token_usage(+async def record_cost_usage(user_id: str,- prompt_tokens: int,- completion_tokens: int,- *,- cache_read_tokens: int = 0,- cache_creation_tokens: int = 0,- model_cost_multiplier: float = 1.0,+ cost_microdollars: int,) -> None:- """Record token usage for a user across all windows.-- Uses cost-weighted counting so cached tokens don't unfairly penalise- multi-turn conversations. Anthropic's pricing:- - uncached input: 100%- - cache creation: 25%- - cache read: 10%- - output: 100%-- ``prompt_tokens`` should be the *uncached* input count (``input_tokens``- from the API response). Cache counts are passed separately.+ """Record a user's generation spend against daily and weekly counters.- ``model_cost_multiplier`` scales the final weighted total to reflect- relative model cost. Use 5.0 for Opus (5× more expensive than Sonnet)- so that Opus turns deplete the rate limit faster, proportional to cost.+ ``cost_microdollars`` is the real generation cost reported by the+ provider (OpenRouter's ``usage.cost`` or the Claude Agent SDK's+ ``total_cost_usd`` converted to microdollars). Because the provider+ cost already reflects model pricing and cache discounts, this function+ carries no pricing table or weighting — it just increments counters.Args:user_id: The user's ID.- prompt_tokens: Uncached input tokens.- completion_tokens: Output tokens.- cache_read_tokens: Tokens served from prompt cache (10% cost).- cache_creation_tokens: Tokens written to prompt cache (25% cost).- model_cost_multiplier: Relative model cost factor (1.0 = Sonnet, 5.0 = Opus).+ cost_microdollars: Spend to record in microdollars (1 USD = 1_000_000).+ Non-positive values are ignored."""- prompt_tokens = max(0, prompt_tokens)- completion_tokens = max(0, completion_tokens)- cache_read_tokens = max(0, cache_read_tokens)- cache_creation_tokens = max(0, cache_creation_tokens)-- weighted_input = (- prompt_tokens- + round(cache_creation_tokens * 0.25)- + round(cache_read_tokens * 0.1)- )- total = round(- (weighted_input + completion_tokens) * max(1.0, model_cost_multiplier)- )- if total <= 0:+ cost_microdollars = max(0, cost_microdollars)+ if cost_microdollars <= 0:return- raw_total = (- prompt_tokens + cache_read_tokens + cache_creation_tokens + completion_tokens- )- logger.info(- "Recording token usage for %s: raw=%d, weighted=%d, multiplier=%.1fx "- "(uncached=%d, cache_read=%d@10%%, cache_create=%d@25%%, output=%d)",- user_id[:8],- raw_total,- total,- model_cost_multiplier,- prompt_tokens,- cache_read_tokens,- cache_creation_tokens,- completion_tokens,- )+ logger.info("Recording copilot spend: %d microdollars", cost_microdollars)now = datetime.now(UTC)try:redis = await get_redis_async()- # transaction=False: these are independent INCRBY+EXPIRE pairs on- # separate keys — no cross-key atomicity needed. Skipping- # MULTI/EXEC avoids the overhead. If the connection drops between- # INCRBY and EXPIRE the key survives until the next date-based key- # rotation (daily/weekly), so the memory-leak risk is negligible.- pipe = redis.pipeline(transaction=False)+ # Use MULTI/EXEC so each INCRBY/EXPIRE pair is atomic — guarantees+ # the TTL is set even if the connection drops mid-pipeline, so+ # counters can never survive past their date-based rotation window.+ pipe = redis.pipeline(transaction=True)# Daily counter (expires at next midnight UTC)d_key = _daily_key(user_id, now=now)- pipe.incrby(d_key, total)+ pipe.incrby(d_key, cost_microdollars)seconds_until_daily_reset = int((_daily_reset_time(now=now) - now).total_seconds())@@ -381,7 +417,7 @@ async def record_token_usage(# Weekly counter (expires end of week)w_key = _weekly_key(user_id, now=now)- pipe.incrby(w_key, total)+ pipe.incrby(w_key, cost_microdollars)seconds_until_weekly_reset = int((_weekly_reset_time(now=now) - now).total_seconds())@@ -390,8 +426,8 @@ async def record_token_usage(await pipe.execute()except (RedisError, ConnectionError, OSError):logger.warning(- "Redis unavailable for recording token usage (tokens=%d)",- total,+ "Redis unavailable for recording cost usage (microdollars=%d)",+ cost_microdollars,)@@ -598,37 +634,41 @@ async def get_global_rate_limits() -> tuple[int, int, SubscriptionTier]:"""Resolve global rate limits from LaunchDarkly, falling back to config.- The base limits (from LD or config) are multiplied by the user's- tier multiplier so that higher tiers receive proportionally larger- allowances.+ Values are microdollars. The base limits (from LD or config) are+ multiplied by the user's tier multiplier so that higher tiers receive+ proportionally larger allowances.Args:user_id: User ID for LD flag evaluation context.- config_daily: Fallback daily limit from ChatConfig.- config_weekly: Fallback weekly limit from ChatConfig.+ config_daily: Fallback daily cost limit (microdollars) from ChatConfig.+ config_weekly: Fallback weekly cost limit (microdollars) from ChatConfig.Returns:- (daily_token_limit, weekly_token_limit, tier) 3-tuple.+ (daily_cost_limit, weekly_cost_limit, tier) — limits in microdollars."""# Lazy import to avoid circular dependency:# rate_limit -> feature_flag -> settings -> ... -> rate_limitfrom backend.util.feature_flag import Flag, get_feature_flag_value- daily_raw = await get_feature_flag_value(- Flag.COPILOT_DAILY_TOKEN_LIMIT.value, user_id, config_daily- )- weekly_raw = await get_feature_flag_value(- Flag.COPILOT_WEEKLY_TOKEN_LIMIT.value, user_id, config_weekly+ # Fetch daily + weekly flags in parallel — each LD evaluation is an+ # independent network round-trip, so gather cuts latency roughly in half.+ daily_raw, weekly_raw = await asyncio.gather(+ get_feature_flag_value(+ Flag.COPILOT_DAILY_COST_LIMIT.value, user_id, config_daily+ ),+ get_feature_flag_value(+ Flag.COPILOT_WEEKLY_COST_LIMIT.value, user_id, config_weekly+ ),)try:daily = max(0, int(daily_raw))except (TypeError, ValueError):- logger.warning("Invalid LD value for daily token limit: %r", daily_raw)+ logger.warning("Invalid LD value for daily cost limit: %r", daily_raw)daily = config_dailytry:weekly = max(0, int(weekly_raw))except (TypeError, ValueError):- logger.warning("Invalid LD value for weekly token limit: %r", weekly_raw)+ logger.warning("Invalid LD value for weekly cost limit: %r", weekly_raw)weekly = config_weekly# Apply tier multiplierdiff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.pyindex 577093c752..3787796c17 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py@@ -24,7 +24,7 @@ from .rate_limit import (get_usage_status,get_user_tier,increment_daily_reset_count,- record_token_usage,+ record_cost_usage,release_reset_lock,reset_daily_usage,reset_user_usage,@@ -82,7 +82,7 @@ class TestGetUsageStatus:return_value=mock_redis,):status = await get_usage_status(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)assert isinstance(status, CoPilotUsageStatus)@@ -98,7 +98,7 @@ class TestGetUsageStatus:side_effect=ConnectionError("Redis down"),):status = await get_usage_status(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)assert status.daily.used == 0@@ -115,7 +115,7 @@ class TestGetUsageStatus:return_value=mock_redis,):status = await get_usage_status(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)assert status.daily.used == 0@@ -132,7 +132,7 @@ class TestGetUsageStatus:return_value=mock_redis,):status = await get_usage_status(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)assert status.daily.used == 500@@ -148,7 +148,7 @@ class TestGetUsageStatus:return_value=mock_redis,):status = await get_usage_status(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)now = datetime.now(UTC)@@ -174,7 +174,7 @@ class TestCheckRateLimit:):# Should not raiseawait check_rate_limit(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)@pytest.mark.asyncio@@ -188,7 +188,7 @@ class TestCheckRateLimit:):with pytest.raises(RateLimitExceeded) as exc_info:await check_rate_limit(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)assert exc_info.value.window == "daily"@@ -203,7 +203,7 @@ class TestCheckRateLimit:):with pytest.raises(RateLimitExceeded) as exc_info:await check_rate_limit(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)assert exc_info.value.window == "weekly"@@ -216,7 +216,7 @@ class TestCheckRateLimit:):# Should not raiseawait check_rate_limit(- _USER, daily_token_limit=10000, weekly_token_limit=50000+ _USER, daily_cost_limit=10000, weekly_cost_limit=50000)@pytest.mark.asyncio@@ -229,15 +229,15 @@ class TestCheckRateLimit:return_value=mock_redis,):# Should not raise — limits of 0 mean unlimited- await check_rate_limit(_USER, daily_token_limit=0, weekly_token_limit=0)+ await check_rate_limit(_USER, daily_cost_limit=0, weekly_cost_limit=0)# ----------------------------------------------------------------------------# record_token_usage+# record_cost_usage# ----------------------------------------------------------------------------class TestRecordTokenUsage:+class TestRecordCostUsage:@staticmethoddef _make_pipeline_mock() -> MagicMock:"""Create a pipeline mock with sync methods and async execute."""@@ -255,27 +255,40 @@ class TestRecordTokenUsage:"backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- await record_token_usage(_USER, prompt_tokens=100, completion_tokens=50)+ await record_cost_usage(_USER, cost_microdollars=123_456)- # Should call incrby twice (daily + weekly) with total=150+ # Should call incrby twice (daily + weekly) with the same costincrby_calls = mock_pipe.incrby.call_args_listassert len(incrby_calls) == 2- assert incrby_calls[0].args[1] == 150 # daily- assert incrby_calls[1].args[1] == 150 # weekly+ assert incrby_calls[0].args[1] == 123_456 # daily+ assert incrby_calls[1].args[1] == 123_456 # weekly@pytest.mark.asyncio- async def test_skips_when_zero_tokens(self):+ async def test_skips_when_cost_is_zero(self):mock_redis = AsyncMock()with patch("backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- await record_token_usage(_USER, prompt_tokens=0, completion_tokens=0)+ await record_cost_usage(_USER, cost_microdollars=0)# Should not call pipeline at allmock_redis.pipeline.assert_not_called()+ @pytest.mark.asyncio+ async def test_skips_when_cost_is_negative(self):+ """Negative costs are clamped to zero and skip the pipeline."""+ mock_redis = AsyncMock()++ with patch(+ "backend.copilot.rate_limit.get_redis_async",+ return_value=mock_redis,+ ):+ await record_cost_usage(_USER, cost_microdollars=-10)++ mock_redis.pipeline.assert_not_called()+@pytest.mark.asyncioasync def test_sets_expire_on_both_keys(self):"""Pipeline should call expire for both daily and weekly keys."""@@ -287,7 +300,7 @@ class TestRecordTokenUsage:"backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- await record_token_usage(_USER, prompt_tokens=100, completion_tokens=50)+ await record_cost_usage(_USER, cost_microdollars=5_000)expire_calls = mock_pipe.expire.call_args_listassert len(expire_calls) == 2@@ -308,32 +321,7 @@ class TestRecordTokenUsage:side_effect=ConnectionError("Redis down"),):# Should not raise- await record_token_usage(_USER, prompt_tokens=100, completion_tokens=50)-- @pytest.mark.asyncio- async def test_cost_weighted_counting(self):- """Cached tokens should be weighted: cache_read=10%, cache_create=25%."""- mock_pipe = self._make_pipeline_mock()- mock_redis = AsyncMock()- mock_redis.pipeline = lambda **_kw: mock_pipe-- with patch(- "backend.copilot.rate_limit.get_redis_async",- return_value=mock_redis,- ):- await record_token_usage(- _USER,- prompt_tokens=100, # uncached → 100- completion_tokens=50, # output → 50- cache_read_tokens=10000, # 10% → 1000- cache_creation_tokens=400, # 25% → 100- )-- # Expected weighted total: 100 + 1000 + 100 + 50 = 1250- incrby_calls = mock_pipe.incrby.call_args_list- assert len(incrby_calls) == 2- assert incrby_calls[0].args[1] == 1250 # daily- assert incrby_calls[1].args[1] == 1250 # weekly+ await record_cost_usage(_USER, cost_microdollars=5_000)@pytest.mark.asyncioasync def test_handles_redis_error_during_pipeline_execute(self):@@ -348,7 +336,7 @@ class TestRecordTokenUsage:return_value=mock_redis,):# Should not raise — fail-open- await record_token_usage(_USER, prompt_tokens=100, completion_tokens=50)+ await record_cost_usage(_USER, cost_microdollars=5_000)# ---------------------------------------------------------------------------@@ -819,7 +807,7 @@ class TestTierLimitsRespected:assert tier == SubscriptionTier.PRO# Should NOT raise — 3M < 12.5Mawait check_rate_limit(- _USER, daily_token_limit=daily, weekly_token_limit=weekly+ _USER, daily_cost_limit=daily, weekly_cost_limit=weekly)@pytest.mark.asyncio@@ -853,7 +841,7 @@ class TestTierLimitsRespected:# Should raise — 2.5M >= 2.5Mwith pytest.raises(RateLimitExceeded):await check_rate_limit(- _USER, daily_token_limit=daily, weekly_token_limit=weekly+ _USER, daily_cost_limit=daily, weekly_cost_limit=weekly)@pytest.mark.asyncio@@ -885,7 +873,7 @@ class TestTierLimitsRespected:assert tier == SubscriptionTier.ENTERPRISE# Should NOT raise — 100M < 150Mawait check_rate_limit(- _USER, daily_token_limit=daily, weekly_token_limit=weekly+ _USER, daily_cost_limit=daily, weekly_cost_limit=weekly)@@ -912,7 +900,7 @@ class TestResetDailyUsage:"backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- result = await reset_daily_usage(_USER, daily_token_limit=10000)+ result = await reset_daily_usage(_USER, daily_cost_limit=10000)assert result is Truemock_pipe.delete.assert_called_once()@@ -928,7 +916,7 @@ class TestResetDailyUsage:"backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- await reset_daily_usage(_USER, daily_token_limit=10000)+ await reset_daily_usage(_USER, daily_cost_limit=10000)mock_pipe.decrby.assert_called_once()mock_redis.set.assert_not_called() # 35000 > 0, no clamp needed@@ -944,14 +932,14 @@ class TestResetDailyUsage:"backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- await reset_daily_usage(_USER, daily_token_limit=10000)+ await reset_daily_usage(_USER, daily_cost_limit=10000)mock_pipe.decrby.assert_called_once()mock_redis.set.assert_called_once()@pytest.mark.asyncioasync def test_no_weekly_reduction_when_daily_limit_zero(self):- """When daily_token_limit is 0, weekly counter should not be touched."""+ """When daily_cost_limit is 0, weekly counter should not be touched."""mock_pipe = self._make_pipeline_mock()mock_pipe.execute = AsyncMock(return_value=[1]) # only delete resultmock_redis = AsyncMock()@@ -961,7 +949,7 @@ class TestResetDailyUsage:"backend.copilot.rate_limit.get_redis_async",return_value=mock_redis,):- await reset_daily_usage(_USER, daily_token_limit=0)+ await reset_daily_usage(_USER, daily_cost_limit=0)mock_pipe.delete.assert_called_once()mock_pipe.decrby.assert_not_called()@@ -972,7 +960,7 @@ class TestResetDailyUsage:"backend.copilot.rate_limit.get_redis_async",side_effect=ConnectionError("Redis down"),):- result = await reset_daily_usage(_USER, daily_token_limit=10000)+ result = await reset_daily_usage(_USER, daily_cost_limit=10000)assert result is Falsediff --git a/autogpt_platform/backend/backend/copilot/reset_usage_test.py b/autogpt_platform/backend/backend/copilot/reset_usage_test.pyindex cbbf714df0..d5b4ee140e 100644--- a/autogpt_platform/backend/backend/copilot/reset_usage_test.py+++ b/autogpt_platform/backend/backend/copilot/reset_usage_test.py@@ -16,14 +16,14 @@ from backend.util.exceptions import InsufficientBalanceError# Minimal config mock matching ChatConfig fields used by the endpoint.def _make_config(rate_limit_reset_cost: int = 500,- daily_token_limit: int = 2_500_000,- weekly_token_limit: int = 12_500_000,+ daily_cost_limit_microdollars: int = 10_000_000,+ weekly_cost_limit_microdollars: int = 50_000_000,max_daily_resets: int = 5,):cfg = MagicMock()cfg.rate_limit_reset_cost = rate_limit_reset_cost- cfg.daily_token_limit = daily_token_limit- cfg.weekly_token_limit = weekly_token_limit+ cfg.daily_cost_limit_microdollars = daily_cost_limit_microdollars+ cfg.weekly_cost_limit_microdollars = weekly_cost_limit_microdollarscfg.max_daily_resets = max_daily_resetsreturn cfg@@ -77,10 +77,10 @@ class TestResetCopilotUsage:assert "not available" in exc_info.value.detailasync def test_no_daily_limit_returns_400(self):- """When daily_token_limit=0 (unlimited), endpoint returns 400."""+ """When daily_cost_limit=0 (unlimited), endpoint returns 400."""with (- patch(f"{_MODULE}.config", _make_config(daily_token_limit=0)),+ patch(f"{_MODULE}.config", _make_config(daily_cost_limit_microdollars=0)),patch(f"{_MODULE}.settings", _mock_settings()),_mock_rate_limits(daily=0),):diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex ea0a135559..e4f29a2b65 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -165,11 +165,6 @@ _MAX_STREAM_ATTEMPTS = 3# self-correct. The limit is generous to allow recovery attempts._EMPTY_TOOL_CALL_LIMIT = 5-# Cost multiplier for Opus model turns — Opus is ~5× more expensive than Sonnet-# ($15/$75 vs $3/$15 per M tokens). Applied to rate-limit counters so Opus-# turns deplete quota proportionally faster.-_OPUS_COST_MULTIPLIER = 5.0-# User-facing error shown when the empty-tool-call circuit breaker trips._CIRCUIT_BREAKER_ERROR_MSG = ("AutoPilot was unable to complete the tool call "@@ -725,22 +720,20 @@ def _resolve_fallback_model() -> str | None:return _normalize_model_name(raw)-async def _resolve_model_and_multiplier(+async def _resolve_sdk_model_for_request(model: "CopilotLlmModel | None",session_id: str,-) -> tuple[str | None, float]:- """Resolve the SDK model string and rate-limit cost multiplier for a turn.+) -> str | None:+ """Resolve the SDK model string for a turn.Priority (highest first):1. Explicit per-request ``model`` tier from the frontend toggle.2. Global config default (``_resolve_sdk_model()``).- Returns a ``(sdk_model, cost_multiplier)`` pair.- ``sdk_model`` is ``None`` when the Claude Code subscription default applies.- ``cost_multiplier`` is 5.0 for Opus, 1.0 otherwise.+ Returns ``None`` when the Claude Code subscription default applies.+ Rate-limit accounting no longer applies a multiplier — the real turn+ cost (reported by the SDK) already reflects model-pricing differences."""- sdk_model = _resolve_sdk_model()-if model == "advanced":sdk_model = _normalize_model_name(config.advanced_model)logger.info(@@ -748,7 +741,7 @@ async def _resolve_model_and_multiplier(session_id[:12] if session_id else "?",sdk_model,)- return sdk_model, _OPUS_COST_MULTIPLIER+ return sdk_modelif model == "standard":# Reset to config default — respects subscription mode (None = CLI default).@@ -758,13 +751,9 @@ async def _resolve_model_and_multiplier(session_id[:12] if session_id else "?",sdk_model or "subscription-default",)- return sdk_model, 1.0+ return sdk_model- # No per-request override; derive multiplier from final resolved model.- cost_multiplier = (- _OPUS_COST_MULTIPLIER if sdk_model and "opus" in sdk_model else 1.0- )- return sdk_model, cost_multiplier+ return _resolve_sdk_model()_MAX_TRANSIENT_BACKOFF_SECONDS = 30@@ -2895,7 +2884,6 @@ async def stream_chat_completion_sdk(# Defaults ensure the finally block can always reference these safely even when# an early return (e.g. sdk_cwd error) skips their normal assignment below.sdk_model: str | None = None- model_cost_multiplier: float = 1.0# Make sure there is no more code between the lock acquisition and try-block.try:@@ -3012,10 +3000,8 @@ async def stream_chat_completion_sdk(mcp_server = create_copilot_mcp_server(use_e2b=use_e2b)- # Resolve model and cost multiplier (request tier → config default).- sdk_model, model_cost_multiplier = await _resolve_model_and_multiplier(- model, session_id- )+ # Resolve model (request tier → config default).+ sdk_model = await _resolve_sdk_model_for_request(model, session_id)# Track SDK-internal compaction (PreCompact hook → start, next msg → end)compaction = CompactionTracker()@@ -3813,7 +3799,6 @@ async def stream_chat_completion_sdk(cost_usd=turn_cost_usd,model=sdk_model or config.model,provider="anthropic",- model_cost_multiplier=model_cost_multiplier,)# --- Persist session messages ---diff --git a/autogpt_platform/backend/backend/copilot/token_tracking.py b/autogpt_platform/backend/backend/copilot/token_tracking.pyindex 19406ced93..f5ace5e749 100644--- a/autogpt_platform/backend/backend/copilot/token_tracking.py+++ b/autogpt_platform/backend/backend/copilot/token_tracking.py@@ -1,9 +1,9 @@-"""Shared token-usage persistence and rate-limit recording.+"""Shared usage persistence and rate-limit recording.Both the baseline (OpenRouter) and SDK (Anthropic) service layers need to:1. Append a ``Usage`` record to the session.- 2. Log the turn's token counts.- 3. Record weighted usage in Redis for rate-limiting.+ 2. Log the turn's token counts and cost.+ 3. Record the real generation cost in Redis for rate-limiting.4. Write a PlatformCostLog entry for admin cost tracking.This module extracts that common logic so both paths stay in sync.@@ -19,7 +19,7 @@ from backend.data.db_accessors import platform_cost_dbfrom backend.data.platform_cost import PlatformCostEntry, usd_to_microdollarsfrom .model import ChatSession, Usage-from .rate_limit import record_token_usage+from .rate_limit import record_cost_usagelogger = logging.getLogger(__name__)@@ -96,9 +96,14 @@ async def persist_and_record_usage(cost_usd: float | str | None = None,model: str | None = None,provider: str = "open_router",- model_cost_multiplier: float = 1.0,) -> int:- """Persist token usage to session and record for rate limiting.+ """Persist token usage to session and record generation cost for rate limiting.++ Rate-limit counters are charged in microdollars against the provider's+ reported cost (``cost_usd``), so cache discounts and cross-model pricing+ differences are already reflected. When cost is unknown the turn is+ logged but the rate-limit counter is left alone — the caller logs an+ error at the point the absence is detected.Args:session: The chat session to append usage to (may be None on error).@@ -108,11 +113,11 @@ async def persist_and_record_usage(cache_read_tokens: Tokens served from prompt cache (Anthropic only).cache_creation_tokens: Tokens written to prompt cache (Anthropic only).log_prefix: Prefix for log messages (e.g. "[SDK]", "[Baseline]").- cost_usd: Optional cost for logging (float from SDK, str otherwise).+ cost_usd: Real generation cost for the turn (float from SDK or parsed+ from OpenRouter usage.cost). ``None`` means the provider did not+ report a cost and rate limiting is skipped for this turn.+ model: Model identifier for cost log attribution.provider: Cost provider name (e.g. "anthropic", "open_router").- model_cost_multiplier: Relative model cost factor for rate limiting- (1.0 = Sonnet/default, 5.0 = Opus). Scales the token counter so- more expensive models deplete the rate limit proportionally faster.Returns:The computed total_tokens (prompt + completion; cache excluded).@@ -156,37 +161,51 @@ async def persist_and_record_usage(else:logger.info(f"{log_prefix} Turn usage: prompt={prompt_tokens}, completion={completion_tokens},"- f" total={total_tokens}"+ f" total={total_tokens}, cost_usd={cost_usd}")- if user_id:+ cost_float: float | None = None+ if cost_usd is not None:try:- await record_token_usage(- user_id=user_id,- prompt_tokens=prompt_tokens,- completion_tokens=completion_tokens,- cache_read_tokens=cache_read_tokens,- cache_creation_tokens=cache_creation_tokens,- model_cost_multiplier=model_cost_multiplier,+ val = float(cost_usd)+ except (ValueError, TypeError):+ logger.error(+ "%s cost_usd is not numeric: %r — rate limit skipped",+ log_prefix,+ cost_usd,)- except Exception as usage_err:- logger.warning("%s Failed to record token usage: %s", log_prefix, usage_err)+ else:+ if not math.isfinite(val):+ logger.error(+ "%s cost_usd is non-finite: %r — rate limit skipped",+ log_prefix,+ val,+ )+ elif val < 0:+ logger.warning(+ "%s cost_usd %s is negative — skipping rate-limit + cost log",+ log_prefix,+ val,+ )+ else:+ cost_float = val++ cost_microdollars = usd_to_microdollars(cost_float)++ if user_id and cost_microdollars is not None and cost_microdollars > 0:+ # record_cost_usage() owns its fail-open handling for Redis/network+ # errors. Don't wrap with a broad except here — unexpected accounting+ # bugs should surface instead of being silently logged as warnings.+ await record_cost_usage(+ user_id=user_id,+ cost_microdollars=cost_microdollars,+ )# Log to PlatformCostLog for admin cost dashboard.# Include entries where cost_usd is set even if token count is 0# (e.g. fully-cached Anthropic responses where only cache tokens# accumulate a charge without incrementing total_tokens).- if user_id and (total_tokens > 0 or cost_usd is not None):- cost_float = None- if cost_usd is not None:- try:- val = float(cost_usd)- if math.isfinite(val) and val >= 0:- cost_float = val- except (ValueError, TypeError):- pass-- cost_microdollars = usd_to_microdollars(cost_float)+ if user_id and (total_tokens > 0 or cost_float is not None):session_id = session.session_id if session else Noneif cost_float is not None:diff --git a/autogpt_platform/backend/backend/copilot/token_tracking_test.py b/autogpt_platform/backend/backend/copilot/token_tracking_test.pyindex 11757ce541..ff5957e1f5 100644--- a/autogpt_platform/backend/backend/copilot/token_tracking_test.py+++ b/autogpt_platform/backend/backend/copilot/token_tracking_test.py@@ -37,7 +37,7 @@ class TestTotalTokens:async def test_returns_prompt_plus_completion(self):"""total_tokens = prompt + completion (cache excluded from total)."""with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):total = await persist_and_record_usage(@@ -63,7 +63,7 @@ class TestTotalTokens:async def test_cache_tokens_excluded_from_total(self):"""Cache tokens are stored separately and not added to total_tokens."""with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):total = await persist_and_record_usage(@@ -81,7 +81,7 @@ class TestTotalTokens:async def test_baseline_path_no_cache(self):"""Baseline (OpenRouter) path passes no cache tokens; total = prompt + completion."""with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):total = await persist_and_record_usage(@@ -97,7 +97,7 @@ class TestTotalTokens:async def test_sdk_path_with_cache(self):"""SDK (Anthropic) path passes cache tokens; total still = prompt + completion."""with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):total = await persist_and_record_usage(@@ -123,7 +123,7 @@ class TestSessionPersistence:async def test_appends_usage_to_session(self):session = _make_session()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):await persist_and_record_usage(@@ -144,7 +144,7 @@ class TestSessionPersistence:async def test_appends_cache_breakdown_to_session(self):session = _make_session()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):await persist_and_record_usage(@@ -163,7 +163,7 @@ class TestSessionPersistence:async def test_multiple_turns_append_multiple_records(self):session = _make_session()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):await persist_and_record_usage(@@ -178,7 +178,7 @@ class TestSessionPersistence:async def test_none_session_does_not_raise(self):"""When session is None (e.g. error path), no exception should be raised."""with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,):total = await persist_and_record_usage(@@ -210,10 +210,11 @@ class TestSessionPersistence:class TestRateLimitRecording:@pytest.mark.asyncio- async def test_calls_record_token_usage_when_user_id_present(self):+ async def test_calls_record_cost_usage_when_cost_and_user_id_present(self):+ """Rate-limit counter is charged with the real provider cost (microdollars)."""mock_record = AsyncMock()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new=mock_record,):await persist_and_record_usage(@@ -223,55 +224,74 @@ class TestRateLimitRecording:completion_tokens=50,cache_read_tokens=1000,cache_creation_tokens=200,+ cost_usd=0.0123,)mock_record.assert_awaited_once_with(user_id="user-abc",- prompt_tokens=100,- completion_tokens=50,- cache_read_tokens=1000,- cache_creation_tokens=200,- model_cost_multiplier=1.0,+ cost_microdollars=12_300,)@pytest.mark.asyncio- async def test_skips_record_when_user_id_is_none(self):- """Anonymous sessions should not create Redis keys."""+ async def test_skips_record_when_cost_is_missing(self):+ """Without a provider cost we have no authoritative figure to charge."""mock_record = AsyncMock()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new=mock_record,):await persist_and_record_usage(session=None,- user_id=None,+ user_id="user-abc",prompt_tokens=100,completion_tokens=50,)mock_record.assert_not_awaited()@pytest.mark.asyncio- async def test_record_failure_does_not_raise(self):- """A Redis error in record_token_usage should be swallowed (fail-open)."""- mock_record = AsyncMock(side_effect=ConnectionError("Redis down"))+ async def test_skips_record_when_user_id_is_none(self):+ """Anonymous sessions should not create Redis keys."""+ mock_record = AsyncMock()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new=mock_record,):- # Should not raise- total = await persist_and_record_usage(+ await persist_and_record_usage(session=None,- user_id="user-xyz",+ user_id=None,prompt_tokens=100,completion_tokens=50,+ cost_usd=0.001,)- assert total == 150+ mock_record.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_record_usage_bubbles_unexpected_error(self):+ """Unexpected errors from record_cost_usage must propagate.++ record_cost_usage() owns its own (RedisError, ConnectionError, OSError)+ fail-open handling. Anything else is a real accounting bug and+ should not be silently swallowed at this layer.+ """+ mock_record = AsyncMock(side_effect=RuntimeError("boom"))+ with patch(+ "backend.copilot.token_tracking.record_cost_usage",+ new=mock_record,+ ):+ with pytest.raises(RuntimeError, match="boom"):+ await persist_and_record_usage(+ session=None,+ user_id="user-xyz",+ prompt_tokens=100,+ completion_tokens=50,+ cost_usd=0.002,+ )@pytest.mark.asyncio- async def test_skips_record_when_zero_tokens(self):- """Returns 0 before calling record_token_usage when tokens are zero."""+ async def test_skips_record_when_zero_tokens_and_no_cost(self):+ """Returns 0 before calling record_cost_usage when there is nothing to record."""mock_record = AsyncMock()with patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new=mock_record,):await persist_and_record_usage(@@ -295,7 +315,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -336,7 +356,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -369,7 +389,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -394,7 +414,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -423,7 +443,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -452,7 +472,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -479,7 +499,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -509,7 +529,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(@@ -545,7 +565,7 @@ class TestPlatformCostLogging:mock_log = AsyncMock()with (patch(- "backend.copilot.token_tracking.record_token_usage",+ "backend.copilot.token_tracking.record_cost_usage",new_callable=AsyncMock,),patch(diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex c341666cdb..1e29ff4102 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -42,8 +42,8 @@ class Flag(str, Enum):CHAT = "chat"CHAT_MODE_OPTION = "chat-mode-option"COPILOT_SDK = "copilot-sdk"- COPILOT_DAILY_TOKEN_LIMIT = "copilot-daily-token-limit"- COPILOT_WEEKLY_TOKEN_LIMIT = "copilot-weekly-token-limit"+ COPILOT_DAILY_COST_LIMIT = "copilot-daily-cost-limit-microdollars"+ COPILOT_WEEKLY_COST_LIMIT = "copilot-weekly-cost-limit-microdollars"STRIPE_PRICE_PRO = "stripe-price-id-pro"STRIPE_PRICE_BUSINESS = "stripe-price-id-business"GRAPHITI_MEMORY = "graphiti-memory"diff --git a/autogpt_platform/backend/snapshots/get_rate_limit b/autogpt_platform/backend/snapshots/get_rate_limitindex 5bae448ba2..3ac1b94222 100644--- a/autogpt_platform/backend/snapshots/get_rate_limit+++ b/autogpt_platform/backend/snapshots/get_rate_limit@@ -1,9 +1,9 @@{- "daily_token_limit": 2500000,- "daily_tokens_used": 500000,+ "daily_cost_limit_microdollars": 2500000,+ "daily_cost_used_microdollars": 500000,"tier": "FREE","user_email": "[email protected]","user_id": "5e53486c-cf57-477e-ba2a-cb02dc828e1c",- "weekly_token_limit": 12500000,- "weekly_tokens_used": 3000000+ "weekly_cost_limit_microdollars": 12500000,+ "weekly_cost_used_microdollars": 3000000}diff --git a/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly b/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weeklyindex c73be30be5..b5361be34a 100644--- a/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly+++ b/autogpt_platform/backend/snapshots/reset_user_usage_daily_and_weekly@@ -1,9 +1,9 @@{- "daily_token_limit": 2500000,- "daily_tokens_used": 0,+ "daily_cost_limit_microdollars": 2500000,+ "daily_cost_used_microdollars": 0,"tier": "FREE","user_email": "[email protected]","user_id": "5e53486c-cf57-477e-ba2a-cb02dc828e1c",- "weekly_token_limit": 12500000,- "weekly_tokens_used": 0+ "weekly_cost_limit_microdollars": 12500000,+ "weekly_cost_used_microdollars": 0}diff --git a/autogpt_platform/backend/snapshots/reset_user_usage_daily_only b/autogpt_platform/backend/snapshots/reset_user_usage_daily_onlyindex 5b205a8bfb..256d8e893d 100644--- a/autogpt_platform/backend/snapshots/reset_user_usage_daily_only+++ b/autogpt_platform/backend/snapshots/reset_user_usage_daily_only@@ -1,9 +1,9 @@{- "daily_token_limit": 2500000,- "daily_tokens_used": 0,+ "daily_cost_limit_microdollars": 2500000,+ "daily_cost_used_microdollars": 0,"tier": "FREE","user_email": "[email protected]","user_id": "5e53486c-cf57-477e-ba2a-cb02dc828e1c",- "weekly_token_limit": 12500000,- "weekly_tokens_used": 3000000+ "weekly_cost_limit_microdollars": 12500000,+ "weekly_cost_used_microdollars": 3000000}diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/UsageBar.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/UsageBar.tsxindex de95cf0e47..442ebf43bc 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/UsageBar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/UsageBar.tsx@@ -1,10 +1,6 @@"use client";-export function formatTokens(tokens: number): string {- if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;- if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(0)}K`;- return tokens.toString();-}+import { formatMicrodollarsAsUsd } from "@/app/(platform)/copilot/components/usageHelpers";export function UsageBar({ used, limit }: { used: number; limit: number }) {if (limit === 0) {@@ -17,8 +13,8 @@ export function UsageBar({ used, limit }: { used: number; limit: number }) {return (<div className="space-y-1"><div className="flex justify-between text-sm">- <span>{formatTokens(used)} used</span>- <span>{formatTokens(limit)} limit</span>+ <span>{formatMicrodollarsAsUsd(used)} spent</span>+ <span>{formatMicrodollarsAsUsd(limit)} limit</span></div><div className="h-2 w-full rounded-full bg-gray-200"><divdiff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/UsageBar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/UsageBar.test.tsxnew file mode 100644index 0000000000..bf03d69221--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/UsageBar.test.tsx@@ -0,0 +1,31 @@+import { render, screen } from "@/tests/integrations/test-utils";+import { describe, expect, it } from "vitest";+import { UsageBar } from "../UsageBar";++describe("UsageBar", () => {+ it('renders "Unlimited" when limit is 0', () => {+ render(<UsageBar used={100} limit={0} />);+ expect(screen.getByText("Unlimited")).toBeDefined();+ });++ it("renders spent + limit in USD", () => {+ render(<UsageBar used={1_500_000} limit={10_000_000} />);+ expect(screen.getByText("$1.50 spent")).toBeDefined();+ expect(screen.getByText("$10.00 limit")).toBeDefined();+ });++ it("renders the computed percentage", () => {+ render(<UsageBar used={500_000} limit={1_000_000} />);+ expect(screen.getByText("50.0% used")).toBeDefined();+ });++ it("clamps percentage at 100% when over limit", () => {+ render(<UsageBar used={2_000_000} limit={1_000_000} />);+ expect(screen.getByText("100.0% used")).toBeDefined();+ });++ it("clamps percentage at 0% for negative used", () => {+ render(<UsageBar used={-100} limit={1_000_000} />);+ expect(screen.getByText("0.0% used")).toBeDefined();+ });+});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.tsxindex b216745c35..024b819699 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@@ -88,8 +88,9 @@ export function RateLimitDisplay({}const nothingToReset = resetWeekly- ? data.daily_tokens_used === 0 && data.weekly_tokens_used === 0- : data.daily_tokens_used === 0;+ ? data.daily_cost_used_microdollars === 0 &&+ data.weekly_cost_used_microdollars === 0+ : data.daily_cost_used_microdollars === 0;return (<div className={className ?? "rounded-md border bg-white p-6"}>@@ -133,17 +134,17 @@ export function RateLimitDisplay({<div className="grid grid-cols-2 gap-6"><div className="space-y-2">- <h3 className="text-sm font-medium text-gray-700">Daily Usage</h3>+ <h3 className="text-sm font-medium text-gray-700">Daily Spend</h3><UsageBar- used={data.daily_tokens_used}- limit={data.daily_token_limit}+ used={data.daily_cost_used_microdollars}+ limit={data.daily_cost_limit_microdollars}/></div><div className="space-y-2">- <h3 className="text-sm font-medium text-gray-700">Weekly Usage</h3>+ <h3 className="text-sm font-medium text-gray-700">Weekly Spend</h3><UsageBar- used={data.weekly_tokens_used}- limit={data.weekly_token_limit}+ used={data.weekly_cost_used_microdollars}+ limit={data.weekly_cost_limit_microdollars}/></div></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.tsxindex 5425a14ff2..08b5db312b 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@@ -30,10 +30,10 @@ function makeData(return {user_id: "user-abc-123",user_email: "[email protected]",- daily_token_limit: 10000,- weekly_token_limit: 50000,- daily_tokens_used: 2500,- weekly_tokens_used: 10000,+ daily_cost_limit_microdollars: 10_000_000,+ weekly_cost_limit_microdollars: 50_000_000,+ daily_cost_used_microdollars: 2_500_000,+ weekly_cost_used_microdollars: 10_000_000,tier: "FREE",...overrides,};@@ -113,8 +113,8 @@ describe("RateLimitDisplay", () => {it("renders daily and weekly usage sections", () => {render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);- expect(screen.getByText("Daily Usage")).toBeDefined();- expect(screen.getByText("Weekly Usage")).toBeDefined();+ expect(screen.getByText("Daily Spend")).toBeDefined();+ expect(screen.getByText("Weekly Spend")).toBeDefined();});it("renders reset scope dropdown and reset button", () => {@@ -126,7 +126,7 @@ describe("RateLimitDisplay", () => {it("disables reset button when nothing to reset", () => {render(<RateLimitDisplay- data={makeData({ daily_tokens_used: 0 })}+ data={makeData({ daily_cost_used_microdollars: 0 })}onReset={vi.fn()}/>,);@@ -137,7 +137,7 @@ describe("RateLimitDisplay", () => {it("enables reset button when there is usage to reset", () => {render(<RateLimitDisplay- data={makeData({ daily_tokens_used: 100 })}+ data={makeData({ daily_cost_used_microdollars: 100_000 })}onReset={vi.fn()}/>,);@@ -174,7 +174,7 @@ describe("RateLimitDisplay", () => {render(<RateLimitDisplay- data={makeData({ weekly_tokens_used: 100 })}+ data={makeData({ weekly_cost_used_microdollars: 100_000 })}onReset={onReset}/>,);diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsxindex ab996748f1..8435e6dc6d 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx@@ -174,10 +174,10 @@ describe("RateLimitManager", () => {rateLimitData: {user_id: "user-123",user_email: "[email protected]",- daily_token_limit: 10000,- weekly_token_limit: 50000,- daily_tokens_used: 2500,- weekly_tokens_used: 10000,+ daily_cost_limit_microdollars: 10_000_000,+ weekly_cost_limit_microdollars: 50_000_000,+ daily_cost_used_microdollars: 2_500_000,+ weekly_cost_used_microdollars: 10_000_000,tier: "FREE",},});@@ -197,10 +197,10 @@ describe("RateLimitManager", () => {rateLimitData: {user_id: "user-123",user_email: "[email protected]",- daily_token_limit: 10000,- weekly_token_limit: 50000,- daily_tokens_used: 2500,- weekly_tokens_used: 10000,+ daily_cost_limit_microdollars: 10_000_000,+ weekly_cost_limit_microdollars: 50_000_000,+ daily_cost_used_microdollars: 2_500_000,+ weekly_cost_used_microdollars: 10_000_000,tier: "FREE",},});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.tsindex d09a74b507..523af7514b 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.ts@@ -28,10 +28,10 @@ function makeRateLimitResponse(overrides = {}) {return {user_id: "user-123",user_email: "[email protected]",- daily_token_limit: 10000,- weekly_token_limit: 50000,- daily_tokens_used: 2500,- weekly_tokens_used: 10000,+ daily_cost_limit_microdollars: 10_000_000,+ weekly_cost_limit_microdollars: 50_000_000,+ daily_cost_used_microdollars: 2_500_000,+ weekly_cost_used_microdollars: 10_000_000,tier: "FREE",...overrides,};@@ -229,8 +229,12 @@ describe("useRateLimitManager", () => {});it("handleReset calls reset endpoint and updates data", async () => {- const initial = makeRateLimitResponse({ daily_tokens_used: 5000 });- const after = makeRateLimitResponse({ daily_tokens_used: 0 });+ const initial = makeRateLimitResponse({+ daily_cost_used_microdollars: 5_000_000,+ });+ const after = makeRateLimitResponse({+ daily_cost_used_microdollars: 0,+ });mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data: initial });mockPostV2ResetUserRateLimitUsage.mockResolvedValue({status: 200,@@ -338,7 +342,9 @@ describe("useRateLimitManager", () => {});it("handleReset throws when endpoint returns non-200 status", async () => {- const initial = makeRateLimitResponse({ daily_tokens_used: 5000 });+ const initial = makeRateLimitResponse({+ daily_cost_used_microdollars: 5_000_000,+ });mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data: initial });mockPostV2ResetUserRateLimitUsage.mockResolvedValue({ status: 500 });diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsxindex 158d0b2392..c3ac603073 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx@@ -1,6 +1,6 @@"use client";-import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";import { toast } from "@/components/molecules/Toast/use-toast";import useCredits from "@/hooks/useCredits";@@ -125,7 +125,7 @@ export function CopilotPage() {isError: usageError,} = useGetV2GetCopilotUsage({query: {- select: (res) => res.data as CoPilotUsageStatus,+ select: (res) => res.data as CoPilotUsagePublic,refetchInterval: 30000,staleTime: 10000,},@@ -258,9 +258,7 @@ export function CopilotPage() {resetCost={resetCost ?? 0}resetMessage={rateLimitMessage ?? ""}isWeeklyExhausted={- hasUsage &&- usage.weekly.limit > 0 &&- usage.weekly.used >= usage.weekly.limit+ hasUsage && !!usage.weekly && usage.weekly.percent_used >= 100}hasInsufficientCredits={hasInsufficientCredits}isBillingEnabled={isBillingEnabled}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsxindex 71791b5694..bef9a2a848 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx@@ -39,13 +39,23 @@ vi.mock("@/components/ui/sidebar", () => ({),}));-// Mock hooks that hit the network+// Mock hooks that hit the network. Exercise the `select` callback so its+// line counts as covered alongside the rest of the options.vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useGetV2GetCopilotUsage: () => ({- data: undefined,- isSuccess: false,- isError: false,- }),+ useGetV2GetCopilotUsage: (opts: {+ query?: { select?: (r: { data: unknown }) => unknown };+ }) => {+ const data = {+ daily: null,+ weekly: null,+ tier: "FREE",+ reset_cost: 0,+ };+ if (typeof opts?.query?.select === "function") {+ opts.query.select({ data });+ }+ return { data: undefined, isSuccess: false, isError: false };+ },}));vi.mock("@/hooks/useCredits", () => ({default: () => ({ credits: null, fetchCredits: vi.fn() }),diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimits.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimits.tsxindex 1420e626b3..711c36c26e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimits.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimits.tsx@@ -1,4 +1,4 @@-import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";import useCredits from "@/hooks/useCredits";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";@@ -14,9 +14,9 @@ import { UsagePanelContent } from "./UsagePanelContent";export { UsagePanelContent, formatResetTime } from "./UsagePanelContent";export function UsageLimits() {- const { data: usage, isLoading } = useGetV2GetCopilotUsage({+ const { data: usage, isSuccess } = useGetV2GetCopilotUsage({query: {- select: (res) => res.data as CoPilotUsageStatus,+ select: (res) => res.data as CoPilotUsagePublic,refetchInterval: 30000,staleTime: 10000,},@@ -28,8 +28,8 @@ export function UsageLimits() {const hasInsufficientCredits =credits !== null && resetCost != null && credits < resetCost;- if (isLoading || !usage?.daily || !usage?.weekly) return null;- if (usage.daily.limit <= 0 && usage.weekly.limit <= 0) return null;+ if (!isSuccess || !usage) return null;+ if (!usage.daily && !usage.weekly) return null;return (<Popover>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsxindex 91187816da..9a1c0d1c87 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx@@ -1,4 +1,4 @@-import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import { Button } from "@/components/atoms/Button/Button";import Link from "next/link";import { formatCents, formatResetTime } from "../usageHelpers";@@ -8,22 +8,17 @@ export { formatResetTime };function UsageBar({label,- used,- limit,+ percentUsed,resetsAt,}: {label: string;- used: number;- limit: number;+ percentUsed: number;resetsAt: Date | string;}) {- if (limit <= 0) return null;-- const rawPercent = (used / limit) * 100;- const percent = Math.min(100, Math.round(rawPercent));+ const percent = Math.min(100, Math.max(0, Math.round(percentUsed)));const isHigh = percent >= 80;const percentLabel =- used > 0 && percent === 0 ? "<1% used" : `${percent}% used`;+ percentUsed > 0 && percent === 0 ? "<1% used" : `${percent}% used`;return (<div className="flex flex-col gap-1">@@ -38,10 +33,15 @@ function UsageBar({</div><div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200"><div+ role="progressbar"+ aria-label={`${label} usage`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={percent}className={`h-full rounded-full transition-[width] duration-300 ease-out ${isHigh ? "bg-orange-500" : "bg-blue-500"}`}- style={{ width: `${Math.max(used > 0 ? 1 : 0, percent)}%` }}+ style={{ width: `${Math.max(percent > 0 ? 1 : 0, percent)}%` }}/></div></div>@@ -79,21 +79,19 @@ export function UsagePanelContent({isBillingEnabled = false,onCreditChange,}: {- usage: CoPilotUsageStatus;+ usage: CoPilotUsagePublic;showBillingLink?: boolean;hasInsufficientCredits?: boolean;isBillingEnabled?: boolean;onCreditChange?: () => void;}) {- const hasDailyLimit = usage.daily.limit > 0;- const hasWeeklyLimit = usage.weekly.limit > 0;- const isDailyExhausted =- hasDailyLimit && usage.daily.used >= usage.daily.limit;- const isWeeklyExhausted =- hasWeeklyLimit && usage.weekly.used >= usage.weekly.limit;+ const daily = usage.daily;+ const weekly = usage.weekly;+ const isDailyExhausted = !!daily && daily.percent_used >= 100;+ const isWeeklyExhausted = !!weekly && weekly.percent_used >= 100;const resetCost = usage.reset_cost ?? 0;- if (!hasDailyLimit && !hasWeeklyLimit) {+ if (!daily && !weekly) {return (<div className="text-xs text-neutral-500">No usage limits configured</div>);@@ -113,20 +111,18 @@ export function UsagePanelContent({<span className="text-[11px] text-neutral-500">{tierLabel} plan</span>)}</div>- {hasDailyLimit && (+ {daily && (<UsageBarlabel="Today"- used={usage.daily.used}- limit={usage.daily.limit}- resetsAt={usage.daily.resets_at}+ percentUsed={daily.percent_used}+ resetsAt={daily.resets_at}/>)}- {hasWeeklyLimit && (+ {weekly && (<UsageBarlabel="This week"- used={usage.weekly.used}- limit={usage.weekly.limit}- resetsAt={usage.weekly.resets_at}+ percentUsed={weekly.percent_used}+ resetsAt={weekly.resets_at}/>)}{isDailyExhausted &&diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsageLimits.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsageLimits.test.tsxindex 9c7a78599f..67595dceec 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsageLimits.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsageLimits.test.tsx@@ -2,10 +2,19 @@ import { render, screen, cleanup } from "@/tests/integrations/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import { UsageLimits } from "../UsageLimits";-// Mock the generated Orval hook+// Mock the generated Orval hook, exercising the `select` callback so its+// line counts as covered alongside the rest of the options.const mockUseGetV2GetCopilotUsage = vi.fn();vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useGetV2GetCopilotUsage: (opts: unknown) => mockUseGetV2GetCopilotUsage(opts),+ useGetV2GetCopilotUsage: (opts: {+ query?: { select?: (r: { data: unknown }) => unknown };+ }) => {+ const ret = mockUseGetV2GetCopilotUsage(opts) as { data?: unknown };+ if (ret?.data !== undefined && typeof opts?.query?.select === "function") {+ opts.query.select({ data: ret.data });+ }+ return ret;+ },}));// Mock Popover to render children directly (Radix portals don't work in happy-dom)@@ -27,22 +36,24 @@ afterEach(() => {});function makeUsage({- dailyUsed = 500,- dailyLimit = 10000,- weeklyUsed = 2000,- weeklyLimit = 50000,+ dailyPercent = 5,+ weeklyPercent = 4,tier = "FREE",}: {- dailyUsed?: number;- dailyLimit?: number;- weeklyUsed?: number;- weeklyLimit?: number;+ dailyPercent?: number | null;+ weeklyPercent?: number | null;tier?: string;} = {}) {- const future = new Date(Date.now() + 3600 * 1000); // 1h from now+ const future = new Date(Date.now() + 3600 * 1000).toISOString();return {- daily: { used: dailyUsed, limit: dailyLimit, resets_at: future },- weekly: { used: weeklyUsed, limit: weeklyLimit, resets_at: future },+ daily:+ dailyPercent === null+ ? null+ : { percent_used: dailyPercent, resets_at: future },+ weekly:+ weeklyPercent === null+ ? null+ : { percent_used: weeklyPercent, resets_at: future },tier,};}@@ -51,7 +62,7 @@ describe("UsageLimits", () => {it("renders nothing while loading", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({data: undefined,- isLoading: true,+ isSuccess: false,});const { container } = render(<UsageLimits />);expect(container.innerHTML).toBe("");@@ -59,8 +70,8 @@ describe("UsageLimits", () => {it("renders nothing when no limits are configured", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({- data: makeUsage({ dailyLimit: 0, weeklyLimit: 0 }),- isLoading: false,+ data: makeUsage({ dailyPercent: null, weeklyPercent: null }),+ isSuccess: true,});const { container } = render(<UsageLimits />);expect(container.innerHTML).toBe("");@@ -69,16 +80,16 @@ describe("UsageLimits", () => {it("renders the usage button when limits exist", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({data: makeUsage(),- isLoading: false,+ isSuccess: true,});render(<UsageLimits />);expect(screen.getByRole("button", { name: /usage limits/i })).toBeDefined();});- it("displays daily and weekly usage percentages", () => {+ it("displays daily and weekly percentage", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({- data: makeUsage({ dailyUsed: 5000, dailyLimit: 10000 }),- isLoading: false,+ data: makeUsage({ dailyPercent: 50, weeklyPercent: 4 }),+ isSuccess: true,});render(<UsageLimits />);@@ -88,14 +99,10 @@ describe("UsageLimits", () => {expect(screen.getByText("Usage limits")).toBeDefined();});- it("shows only weekly bar when daily limit is 0", () => {+ it("shows only weekly bar when daily is null", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({- data: makeUsage({- dailyLimit: 0,- weeklyUsed: 25000,- weeklyLimit: 50000,- }),- isLoading: false,+ data: makeUsage({ dailyPercent: null, weeklyPercent: 50 }),+ isSuccess: true,});render(<UsageLimits />);@@ -103,20 +110,22 @@ describe("UsageLimits", () => {expect(screen.queryByText("Today")).toBeNull();});- it("caps percentage at 100% when over limit", () => {+ it("caps bar width at 100% when over limit", () => {+ // 150% exercises the clamp — 100% exactly is merely exhausted, not over.mockUseGetV2GetCopilotUsage.mockReturnValue({- data: makeUsage({ dailyUsed: 15000, dailyLimit: 10000 }),- isLoading: false,+ data: makeUsage({ dailyPercent: 150 }),+ isSuccess: true,});render(<UsageLimits />);- expect(screen.getByText("100% used")).toBeDefined();+ const dailyBar = screen.getByRole("progressbar", { name: /today usage/i });+ expect(dailyBar.getAttribute("aria-valuenow")).toBe("100");});it("displays the user tier label", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({data: makeUsage({ tier: "PRO" }),- isLoading: false,+ isSuccess: true,});render(<UsageLimits />);@@ -126,7 +135,7 @@ describe("UsageLimits", () => {it("shows learn more link to credits page", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({data: makeUsage(),- isLoading: false,+ isSuccess: true,});render(<UsageLimits />);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsagePanelContentRender.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsagePanelContentRender.test.tsxindex 9230663381..db2d4241a8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsagePanelContentRender.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/__tests__/UsagePanelContentRender.test.tsx@@ -6,7 +6,7 @@ import {} from "@/tests/integrations/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import { UsagePanelContent } from "../UsagePanelContent";-import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";const mockResetUsage = vi.fn();vi.mock("../../../hooks/useResetRateLimit", () => ({@@ -20,36 +20,38 @@ afterEach(() => {function makeUsage(overrides: Partial<{- dailyUsed: number;- dailyLimit: number;- weeklyUsed: number;- weeklyLimit: number;+ dailyPercent: number | null;+ weeklyPercent: number | null;tier: string;resetCost: number;}> = {},-): CoPilotUsageStatus {+): CoPilotUsagePublic {const {- dailyUsed = 500,- dailyLimit = 10000,- weeklyUsed = 2000,- weeklyLimit = 50000,+ dailyPercent = 5,+ weeklyPercent = 4,tier = "FREE",resetCost = 100,} = overrides;- const future = new Date(Date.now() + 3600 * 1000);+ const future = new Date(Date.now() + 3600 * 1000).toISOString();return {- daily: { used: dailyUsed, limit: dailyLimit, resets_at: future },- weekly: { used: weeklyUsed, limit: weeklyLimit, resets_at: future },+ daily:+ dailyPercent === null+ ? null+ : { percent_used: dailyPercent, resets_at: future },+ weekly:+ weeklyPercent === null+ ? null+ : { percent_used: weeklyPercent, resets_at: future },tier,reset_cost: resetCost,- } as CoPilotUsageStatus;+ } as CoPilotUsagePublic;}describe("UsagePanelContent", () => {- it("renders 'No usage limits configured' when both limits are zero", () => {+ it("renders 'No usage limits configured' when both windows are null", () => {render(<UsagePanelContent- usage={makeUsage({ dailyLimit: 0, weeklyLimit: 0 })}+ usage={makeUsage({ dailyPercent: null, weeklyPercent: null })}/>,);expect(screen.getByText("No usage limits configured")).toBeDefined();@@ -58,11 +60,7 @@ describe("UsagePanelContent", () => {it("renders the reset button when daily limit is exhausted", () => {render(<UsagePanelContent- usage={makeUsage({- dailyUsed: 10000,- dailyLimit: 10000,- resetCost: 50,- })}+ usage={makeUsage({ dailyPercent: 100, resetCost: 50 })}/>,);expect(screen.getByText(/Reset daily limit/)).toBeDefined();@@ -72,10 +70,8 @@ describe("UsagePanelContent", () => {render(<UsagePanelContentusage={makeUsage({- dailyUsed: 10000,- dailyLimit: 10000,- weeklyUsed: 50000,- weeklyLimit: 50000,+ dailyPercent: 100,+ weeklyPercent: 100,resetCost: 50,})}/>,@@ -86,11 +82,7 @@ describe("UsagePanelContent", () => {it("calls resetUsage when the reset button is clicked", () => {render(<UsagePanelContent- usage={makeUsage({- dailyUsed: 10000,- dailyLimit: 10000,- resetCost: 50,- })}+ usage={makeUsage({ dailyPercent: 100, resetCost: 50 })}/>,);fireEvent.click(screen.getByText(/Reset daily limit/));@@ -100,15 +92,21 @@ describe("UsagePanelContent", () => {it("renders 'Add credits' link when insufficient credits", () => {render(<UsagePanelContent- usage={makeUsage({- dailyUsed: 10000,- dailyLimit: 10000,- resetCost: 50,- })}+ usage={makeUsage({ dailyPercent: 100, resetCost: 50 })}hasInsufficientCredits={true}isBillingEnabled={true}/>,);expect(screen.getByText("Add credits to reset")).toBeDefined();});++ it("renders percent used in the usage bar", () => {+ render(<UsagePanelContent usage={makeUsage({ dailyPercent: 25 })} />);+ expect(screen.getByText("25% used")).toBeDefined();+ });++ it("renders '<1% used' when usage is greater than 0 but rounds to 0", () => {+ render(<UsagePanelContent usage={makeUsage({ dailyPercent: 0.3 })} />);+ expect(screen.getByText("<1% used")).toBeDefined();+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/__tests__/usageHelpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/__tests__/usageHelpers.test.tsnew file mode 100644index 0000000000..eecdb70245--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/__tests__/usageHelpers.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";+import {+ formatCents,+ formatMicrodollarsAsUsd,+ formatResetTime,+} from "../usageHelpers";++describe("formatCents", () => {+ it("formats whole dollars", () => {+ expect(formatCents(500)).toBe("$5.00");+ });++ it("formats zero", () => {+ expect(formatCents(0)).toBe("$0.00");+ });++ it("formats fractional cents", () => {+ expect(formatCents(1999)).toBe("$19.99");+ });+});++describe("formatMicrodollarsAsUsd", () => {+ it("formats zero as $0.00", () => {+ expect(formatMicrodollarsAsUsd(0)).toBe("$0.00");+ });++ it("formats whole dollar amounts", () => {+ expect(formatMicrodollarsAsUsd(1_500_000)).toBe("$1.50");+ });++ it("formats amounts that round to $0.00 but are > 0 as <$0.01", () => {+ expect(formatMicrodollarsAsUsd(999)).toBe("<$0.01");+ });++ it("formats exactly one cent as $0.01", () => {+ expect(formatMicrodollarsAsUsd(10_000)).toBe("$0.01");+ });++ it("formats negative input with toFixed semantics (no special case)", () => {+ // Negative should never come from the backend, but the helper is+ // safe — it simply passes through `toFixed`.+ expect(formatMicrodollarsAsUsd(-1_500_000)).toBe("$-1.50");+ });++ it("formats very large values without truncating", () => {+ expect(formatMicrodollarsAsUsd(1_234_567_890)).toBe("$1234.57");+ });+});++describe("formatResetTime", () => {+ it("returns 'now' when reset time is in the past", () => {+ const now = new Date("2026-04-21T12:00:00Z");+ const past = new Date("2026-04-21T11:59:00Z");+ expect(formatResetTime(past, now)).toBe("now");+ });++ it("renders sub-hour resets as minutes", () => {+ const now = new Date("2026-04-21T12:00:00Z");+ const future = new Date("2026-04-21T12:15:00Z");+ expect(formatResetTime(future, now)).toBe("in 15m");+ });++ it("renders same-day resets as 'Xh Ym'", () => {+ const now = new Date("2026-04-21T12:00:00Z");+ const future = new Date("2026-04-21T14:30:00Z");+ expect(formatResetTime(future, now)).toBe("in 2h 30m");+ });++ it("renders future-day resets as a localized date string", () => {+ const now = new Date("2026-04-21T12:00:00Z");+ const future = new Date("2026-04-24T12:00:00Z");+ // Not asserting exact format (localized), just that it's not the+ // minute/hour form.+ expect(formatResetTime(future, now)).not.toMatch(/^in \d/);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.tsindex 599442075f..f25df85e9b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts@@ -2,6 +2,12 @@ export function formatCents(cents: number): string {return `$${(cents / 100).toFixed(2)}`;}+export function formatMicrodollarsAsUsd(microdollars: number): string {+ const dollars = microdollars / 1_000_000;+ if (microdollars > 0 && dollars < 0.01) return "<$0.01";+ return `$${dollars.toFixed(2)}`;+}+export function formatResetTime(resetsAt: Date | string,now: Date = new Date(),diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsxindex 939ec5403f..fc6e26424d 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx@@ -1,6 +1,6 @@"use client";-import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";import {@@ -42,9 +42,9 @@ export function BriefingTabContent({ activeTab, agents }: Props) {}function UsageSection() {- const { data: usage } = useGetV2GetCopilotUsage({+ const { data: usage, isSuccess } = useGetV2GetCopilotUsage({query: {- select: (res) => res.data as CoPilotUsageStatus,+ select: (res) => res.data as CoPilotUsagePublic,refetchInterval: 30000,staleTime: 10000,},@@ -56,7 +56,8 @@ function UsageSection() {const hasInsufficientCredits =credits !== null && resetCost != null && credits < resetCost;- if (!usage?.daily || !usage?.weekly) return null;+ if (!isSuccess || !usage) return null;+ if (!usage.daily && !usage.weekly) return null;return (<div className="py-2">@@ -80,19 +81,17 @@ function UsageSection() {)}</div><div className="mt-4 grid grid-cols-1 gap-6 sm:grid-cols-2">- {usage.daily.limit > 0 && (+ {usage.daily && (<UsageMeterlabel="Today"- used={usage.daily.used}- limit={usage.daily.limit}+ percentUsed={usage.daily.percent_used}resetsAt={usage.daily.resets_at}/>)}- {usage.weekly.limit > 0 && (+ {usage.weekly && (<UsageMeterlabel="This week"- used={usage.weekly.used}- limit={usage.weekly.limit}+ percentUsed={usage.weekly.percent_used}resetsAt={usage.weekly.resets_at}/>)}@@ -244,14 +243,12 @@ function UsageFooter({hasInsufficientCredits,onCreditChange,}: {- usage: CoPilotUsageStatus;+ usage: CoPilotUsagePublic;hasInsufficientCredits: boolean;onCreditChange?: () => void;}) {- const isDailyExhausted =- usage.daily.limit > 0 && usage.daily.used >= usage.daily.limit;- const isWeeklyExhausted =- usage.weekly.limit > 0 && usage.weekly.used >= usage.weekly.limit;+ const isDailyExhausted = !!usage.daily && usage.daily.percent_used >= 100;+ const isWeeklyExhausted = !!usage.weekly && usage.weekly.percent_used >= 100;const resetCost = usage.reset_cost ?? 0;const { resetUsage, isPending } = useResetRateLimit({ onCreditChange });@@ -294,22 +291,17 @@ function UsageFooter({function UsageMeter({label,- used,- limit,+ percentUsed,resetsAt,}: {label: string;- used: number;- limit: number;+ percentUsed: number;resetsAt: Date | string;}) {- if (limit <= 0) return null;-- const rawPercent = (used / limit) * 100;- const percent = Math.min(100, Math.round(rawPercent));+ const percent = Math.min(100, Math.max(0, Math.round(percentUsed)));const isHigh = percent >= 80;const percentLabel =- used > 0 && percent === 0 ? "<1% used" : `${percent}% used`;+ percentUsed > 0 && percent === 0 ? "<1% used" : `${percent}% used`;return (<div className="flex flex-col gap-2">@@ -323,20 +315,20 @@ function UsageMeter({</div><div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200"><div+ role="progressbar"+ aria-label={`${label} usage`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={percent}className={`h-full rounded-full transition-[width] duration-300 ease-out ${isHigh ? "bg-orange-500" : "bg-blue-500"}`}- style={{ width: `${Math.max(used > 0 ? 1 : 0, percent)}%` }}+ style={{ width: `${Math.max(percent > 0 ? 1 : 0, percent)}%` }}/></div>- <div className="flex items-baseline justify-between">- <Text variant="small" className="tabular-nums text-neutral-500">- {used.toLocaleString()} / {limit.toLocaleString()}- </Text>- <Text variant="small" className="text-neutral-400">- Resets {formatResetTime(resetsAt)}- </Text>- </div>+ <Text variant="small" className="text-neutral-400">+ Resets {formatResetTime(resetsAt)}+ </Text></div>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsxnew file mode 100644index 0000000000..5dbb3bab17--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsx@@ -0,0 +1,212 @@+import { render, screen, cleanup } from "@/tests/integrations/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";+import { BriefingTabContent } from "../BriefingTabContent";++const mockUseGetV2GetCopilotUsage = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ useGetV2GetCopilotUsage: (opts: {+ query?: { select?: (r: { data: unknown }) => unknown };+ }) => {+ const ret = mockUseGetV2GetCopilotUsage(opts) as { data?: unknown };+ // Exercise the `select` callback so its line counts as covered.+ if (ret?.data !== undefined && typeof opts?.query?.select === "function") {+ opts.query.select({ data: ret.data });+ }+ return ret;+ },+}));++const mockUseGetFlag = vi.fn();+vi.mock("@/services/feature-flags/use-get-flag", async () => {+ const actual = await vi.importActual<+ typeof import("@/services/feature-flags/use-get-flag")+ >("@/services/feature-flags/use-get-flag");+ return {+ ...actual,+ useGetFlag: (flag: unknown) => mockUseGetFlag(flag),+ };+});++const mockUseCredits = vi.fn();+vi.mock("@/hooks/useCredits", () => ({+ default: (opts: unknown) => mockUseCredits(opts),+}));++const mockResetUsage = vi.fn();+vi.mock("@/app/(platform)/copilot/hooks/useResetRateLimit", () => ({+ useResetRateLimit: () => ({+ resetUsage: mockResetUsage,+ isPending: false,+ }),+}));++afterEach(() => {+ cleanup();+ mockUseGetV2GetCopilotUsage.mockReset();+ mockUseGetFlag.mockReset();+ mockUseCredits.mockReset();+ mockResetUsage.mockReset();+});++function makeUsage({+ dailyPercent = 5,+ weeklyPercent = 4,+ tier = "FREE",+ resetCost = 500,+}: {+ dailyPercent?: number | null;+ weeklyPercent?: number | null;+ tier?: string;+ resetCost?: number;+} = {}) {+ const future = new Date(Date.now() + 3600 * 1000).toISOString();+ return {+ daily:+ dailyPercent === null+ ? null+ : { percent_used: dailyPercent, resets_at: future },+ weekly:+ weeklyPercent === null+ ? null+ : { percent_used: weeklyPercent, resets_at: future },+ tier,+ reset_cost: resetCost,+ };+}++describe("BriefingTabContent — UsageSection", () => {+ it("renders nothing when usage fetch has not succeeded", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ });+ mockUseGetFlag.mockReturnValue(false);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });+ const { container } = render(+ <BriefingTabContent activeTab="all" agents={[]} />,+ );+ expect(container.innerHTML).toBe("");+ });++ it("renders nothing when both windows are null (no limits configured)", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: makeUsage({ dailyPercent: null, weeklyPercent: null }),+ isSuccess: true,+ });+ mockUseGetFlag.mockReturnValue(false);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });+ const { container } = render(+ <BriefingTabContent activeTab="all" agents={[]} />,+ );+ expect(container.innerHTML).toBe("");+ });++ it("renders tier badge + daily+weekly meters at normal usage", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: makeUsage({ dailyPercent: 12, weeklyPercent: 4, tier: "PRO" }),+ isSuccess: true,+ });+ mockUseGetFlag.mockReturnValue(true);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });+ render(<BriefingTabContent activeTab="all" agents={[]} />);++ expect(screen.getByText("Usage limits")).toBeDefined();+ expect(screen.getByText("Pro plan")).toBeDefined();+ expect(screen.getByText("12% used")).toBeDefined();+ expect(screen.getByText("4% used")).toBeDefined();+ expect(screen.getByText("Today")).toBeDefined();+ expect(screen.getByText("This week")).toBeDefined();+ expect(screen.getByText("Manage billing")).toBeDefined();+ });++ it("shows reset button when daily limit is exhausted and user has credits", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: makeUsage({ dailyPercent: 100, weeklyPercent: 40, resetCost: 500 }),+ isSuccess: true,+ });+ mockUseGetFlag.mockReturnValue(true);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });+ render(<BriefingTabContent activeTab="all" agents={[]} />);++ expect(screen.getByText(/Reset daily limit/)).toBeDefined();+ });++ it("shows 'Add credits' CTA when daily exhausted but user lacks credits", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: makeUsage({ dailyPercent: 100, weeklyPercent: 40, resetCost: 500 }),+ isSuccess: true,+ });+ mockUseGetFlag.mockReturnValue(true);+ mockUseCredits.mockReturnValue({ credits: 10, fetchCredits: vi.fn() });+ render(<BriefingTabContent activeTab="all" agents={[]} />);++ expect(screen.getByText("Add credits to reset")).toBeDefined();+ expect(screen.queryByText(/Reset daily limit/)).toBeNull();+ });++ it("hides reset CTAs when the weekly limit is also exhausted", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: makeUsage({+ dailyPercent: 100,+ weeklyPercent: 100,+ resetCost: 500,+ }),+ isSuccess: true,+ });+ mockUseGetFlag.mockReturnValue(true);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });+ render(<BriefingTabContent activeTab="all" agents={[]} />);++ expect(screen.queryByText(/Reset daily limit/)).toBeNull();+ expect(screen.queryByText("Add credits to reset")).toBeNull();+ });++ it("renders <1% used when percent is >0 but rounds to 0", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: makeUsage({ dailyPercent: 0.4, weeklyPercent: 0 }),+ isSuccess: true,+ });+ mockUseGetFlag.mockReturnValue(false);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });+ render(<BriefingTabContent activeTab="all" agents={[]} />);++ expect(screen.getByText("<1% used")).toBeDefined();+ });++ it("dispatches to ExecutionListSection for running/attention/completed tabs", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ });+ mockUseGetFlag.mockReturnValue(false);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });++ for (const tab of ["running", "attention", "completed"] as const) {+ const { unmount } = render(+ <BriefingTabContent activeTab={tab} agents={[]} />,+ );+ // Empty list -> EmptyMessage renders for each of the execution tabs.+ expect(+ screen.getByText(/No agents|No recently completed/i),+ ).toBeDefined();+ unmount();+ }+ });++ it("dispatches to AgentListSection for listening/scheduled/idle tabs", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ });+ mockUseGetFlag.mockReturnValue(false);+ mockUseCredits.mockReturnValue({ credits: 1000, fetchCredits: vi.fn() });++ for (const tab of ["listening", "scheduled", "idle"] as const) {+ const { unmount } = render(+ <BriefingTabContent activeTab={tab} agents={[]} />,+ );+ expect(screen.getByText(/No/i)).toBeDefined();+ unmount();+ }+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsxindex fb565c048b..f6f9398721 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx@@ -13,7 +13,7 @@ import { RefundModal } from "./RefundModal";import { SubscriptionTierSection } from "./components/SubscriptionTierSection/SubscriptionTierSection";import { CreditTransaction } from "@/lib/autogpt-server-api";import { UsagePanelContent } from "@/app/(platform)/copilot/components/UsageLimits/UsageLimits";-import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";import {@@ -27,16 +27,16 @@ import {function CoPilotUsageSection() {const router = useRouter();- const { data: usage, isLoading } = useGetV2GetCopilotUsage({+ const { data: usage, isSuccess } = useGetV2GetCopilotUsage({query: {- select: (res) => res.data as CoPilotUsageStatus,+ select: (res) => res.data as CoPilotUsagePublic,refetchInterval: 30000,staleTime: 10000,},});- if (isLoading || !usage?.daily || !usage?.weekly) return null;- if (usage.daily.limit <= 0 && usage.weekly.limit <= 0) return null;+ if (!isSuccess || !usage) return null;+ if (!usage.daily && !usage.weekly) return null;return (<div className="my-6 space-y-4">diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex f20f34a805..9103d6f475 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -1793,7 +1793,7 @@}},"429": {- "description": "Token rate-limit or call-frequency cap exceeded"+ "description": "Cost rate-limit or call-frequency cap exceeded"}}}@@ -1879,14 +1879,14 @@"get": {"tags": ["v2", "chat", "chat"],"summary": "Get Copilot Usage",- "description": "Get CoPilot usage status for the authenticated user.\n\nReturns current token usage vs limits for daily and weekly windows.\nGlobal defaults sourced from LaunchDarkly (falling back to config).\nIncludes the user's rate-limit tier.",+ "description": "Get CoPilot usage status for the authenticated user.\n\nReturns the percentage of the daily/weekly allowance used — not the\nraw spend or cap — so clients cannot derive per-turn cost or platform\nmargins. Global defaults sourced from LaunchDarkly (falling back to\nconfig). Includes the user's rate-limit tier.","operationId": "getV2GetCopilotUsage","responses": {"200": {"description": "Successful Response","content": {"application/json": {- "schema": { "$ref": "#/components/schemas/CoPilotUsageStatus" }+ "schema": { "$ref": "#/components/schemas/CoPilotUsagePublic" }}}},@@ -1901,7 +1901,7 @@"post": {"tags": ["v2", "chat", "chat"],"summary": "Reset Copilot Usage",- "description": "Reset the daily CoPilot rate limit by spending credits.\n\nAllows users who have hit their daily token limit to spend credits\nto reset their daily usage counter and continue working.\nReturns 400 if the feature is disabled or the user is not over the limit.\nReturns 402 if the user has insufficient credits.",+ "description": "Reset the daily CoPilot rate limit by spending credits.\n\nAllows users who have hit their daily cost limit to spend credits\nto reset their daily usage counter and continue working.\nReturns 400 if the feature is disabled or the user is not over the limit.\nReturns 402 if the user has insufficient credits.","operationId": "postV2ResetCopilotUsage","responses": {"200": {@@ -9211,10 +9211,22 @@"title": "ClarifyingQuestion","description": "A question that needs user clarification."},- "CoPilotUsageStatus": {+ "CoPilotUsagePublic": {"properties": {- "daily": { "$ref": "#/components/schemas/UsageWindow" },- "weekly": { "$ref": "#/components/schemas/UsageWindow" },+ "daily": {+ "anyOf": [+ { "$ref": "#/components/schemas/UsageWindowPublic" },+ { "type": "null" }+ ],+ "description": "Null when no daily cap is configured (unlimited)."+ },+ "weekly": {+ "anyOf": [+ { "$ref": "#/components/schemas/UsageWindowPublic" },+ { "type": "null" }+ ],+ "description": "Null when no weekly cap is configured (unlimited)."+ },"tier": {"$ref": "#/components/schemas/SubscriptionTier","default": "FREE"@@ -9227,9 +9239,8 @@}},"type": "object",- "required": ["daily", "weekly"],- "title": "CoPilotUsageStatus",- "description": "Current usage status for a user across all windows."+ "title": "CoPilotUsagePublic",+ "description": "Current usage status for a user — public (client-safe) shape."},"ContentType": {"type": "string",@@ -12997,8 +13008,8 @@"description": "Credit balance after charge (in cents)"},"usage": {- "$ref": "#/components/schemas/CoPilotUsageStatus",- "description": "Updated usage status after reset"+ "$ref": "#/components/schemas/CoPilotUsagePublic",+ "description": "Updated usage status after reset (percentages only)"}},"type": "object",@@ -14259,7 +14270,7 @@"type": "string","enum": ["FREE", "PRO", "BUSINESS", "ENTERPRISE"],"title": "SubscriptionTier",- "description": "Subscription tiers with increasing token 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"+ "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"},"SubscriptionTierRequest": {"properties": {@@ -15886,13 +15897,14 @@"required": ["timezone"],"title": "UpdateTimezoneRequest"},- "UsageWindow": {+ "UsageWindowPublic": {"properties": {- "used": { "type": "integer", "title": "Used" },- "limit": {- "type": "integer",- "title": "Limit",- "description": "Maximum tokens allowed in this window. 0 means unlimited."+ "percent_used": {+ "type": "number",+ "maximum": 100.0,+ "minimum": 0.0,+ "title": "Percent Used",+ "description": "Percentage of the window's allowance used (0-100). Clamped at 100 when over the cap."},"resets_at": {"type": "string",@@ -15901,9 +15913,9 @@}},"type": "object",- "required": ["used", "limit", "resets_at"],- "title": "UsageWindow",- "description": "Usage within a single time window."+ "required": ["percent_used", "resets_at"],+ "title": "UsageWindowPublic",+ "description": "Public view of a usage window — only the percentage and reset time.\n\nHides the raw spend and the cap so clients cannot derive per-turn cost\nor reverse-engineer platform margins. ``percent_used`` is capped at 100."},"UserCostSummary": {"properties": {@@ -16144,31 +16156,31 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "User Email"},- "daily_token_limit": {+ "daily_cost_limit_microdollars": {"type": "integer",- "title": "Daily Token Limit"+ "title": "Daily Cost Limit Microdollars"},- "weekly_token_limit": {+ "weekly_cost_limit_microdollars": {"type": "integer",- "title": "Weekly Token Limit"+ "title": "Weekly Cost Limit Microdollars"},- "daily_tokens_used": {+ "daily_cost_used_microdollars": {"type": "integer",- "title": "Daily Tokens Used"+ "title": "Daily Cost Used Microdollars"},- "weekly_tokens_used": {+ "weekly_cost_used_microdollars": {"type": "integer",- "title": "Weekly Tokens Used"+ "title": "Weekly Cost Used Microdollars"},"tier": { "$ref": "#/components/schemas/SubscriptionTier" }},"type": "object","required": ["user_id",- "daily_token_limit",- "weekly_token_limit",- "daily_tokens_used",- "weekly_tokens_used",+ "daily_cost_limit_microdollars",+ "weekly_cost_limit_microdollars",+ "daily_cost_used_microdollars",+ "weekly_cost_used_microdollars","tier"],"title": "UserRateLimitResponse"