Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(models): value subscription usage at API price (#2189)

Call White6b2ad93b21eb
diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.py
new file mode 100644
index 000000000..4c6ca8dcd
--- /dev/null
+++ b/core/handlers/model_hub/pricing.py
@@ -0,0 +1,499 @@
+"""List-API-price valuation of metered usage, and subscription fees to compare it with.
+
+A valuation, never a bill: it answers "what would this usage have cost at the
+vendor's published API price", so a subscriber can see whether the plan pays for
+itself. Nothing in resolution, admission, or cooldown reads it.
+
+Prices come from two places, highest precedence first: the user's hand-edited
+override file (`<state dir>/model_hub_prices.json`), then the models.dev catalog
+Avibe already caches for the model picker, read from the model's first-party
+provider only. Every day is priced at the current table — the page says which
+table that is — because the table is what we have, not what was in force then.
+
+A model with no price is never priced as zero: it is left out and its tokens are
+counted, so a total can say how much it does not cover.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import math
+import re
+from dataclasses import dataclass
+from datetime import date, datetime, timedelta
+from pathlib import Path
+from typing import Any, Callable, Final, Mapping, Optional
+
+logger = logging.getLogger(__name__)
+
+PRICE_OVERRIDE_FILENAME: Final = "model_hub_prices.json"
+CURRENCY: Final = "USD"
+# A price is USD per million tokens. Anything past this is a typo or a hostile
+# file, not a price; the entry is ignored rather than dominating every total.
+_MAX_PRICE_PER_MTOK: Final = 100_000.0
+_MAX_FEE_USD: Final = 100_000.0
+_MAX_KEY_CHARS: Final = 128
+# An alias may point at another alias, but not forever.
+_MAX_ALIAS_HOPS: Final = 4
+# One-hour cache writes cost twice the input price where the table says nothing.
+_CACHE_WRITE_1H_INPUT_MULTIPLE: Final = 2.0
+
+# Model IDs the agents send that models.dev does not list under that name.
+# Keys are already normalized (lowercase, no date or bracket suffix).
+MODEL_ALIASES: Final[Mapping[str, str]] = {
+ # Claude Code ships a model before models.dev lists it; the predecessor's
+ # price is the closest published figure, and the override file can correct it.
+ "claude-opus-5-5": "claude-opus-5",
+ # Codex CLI names.
+ "gpt-5-codex": "gpt-5",
+ "gpt-5.1-codex": "gpt-5.1",
+ "gpt-5.1-codex-max": "gpt-5.1",
+ "gpt-5.1-codex-mini": "gpt-5-mini",
+ "gpt-5.2-codex": "gpt-5.2",
+ "codex-mini-latest": "gpt-5-mini",
+ # Claude Code short names.
+ "opus": "claude-opus-5",
+ "sonnet": "claude-sonnet-5",
+ "haiku": "claude-haiku-4-5",
+}
+
+# Monthly fee per plan, USD. Keys are what `plan_key` publishes.
+PLAN_FEES_USD: Final[Mapping[str, float]] = {
+ "claude_pro": 20.0,
+ "claude_max_5x": 100.0,
+ "claude_max_20x": 200.0,
+ "chatgpt_plus": 20.0,
+ "chatgpt_pro": 200.0,
+}
+
+# (vendor family, normalized reported plan) → fee-table key.
+_PLAN_KEYS: Final[Mapping[tuple[str, str], str]] = {
+ ("anthropic", "pro"): "claude_pro",
+ ("anthropic", "claude_pro"): "claude_pro",
+ ("anthropic", "max_5x"): "claude_max_5x",
+ ("anthropic", "claude_max_5x"): "claude_max_5x",
+ ("anthropic", "max_20x"): "claude_max_20x",
+ ("anthropic", "claude_max_20x"): "claude_max_20x",
+ ("openai", "plus"): "chatgpt_plus",
+ ("openai", "chatgpt_plus"): "chatgpt_plus",
+ ("openai", "pro"): "chatgpt_pro",
+ ("openai", "chatgpt_pro"): "chatgpt_pro",
+}
+
+# Vendors whose subscriptions have built-in plan names. Any other vendor's plan
+# resolves only through a fee key the override file names outright.
+_PLAN_FAMILIES: Final[Mapping[str, str]] = {"anthropic": "anthropic", "openai": "openai", "codex": "openai"}
+
+_DATE_SUFFIX: Final = re.compile(r"(?:-\d{8}|-\d{4}-\d{2}-\d{2}|@[^/]*)$")
+_BRACKET_SUFFIX: Final = re.compile(r"\[[^\]]*\]$")
+
+
+@dataclass(frozen=True)
+class ModelPrice:
+ """USD per million tokens."""
+
+ input: float
+ output: float
+ cache_read: float
+ cache_write: float
+ cache_write_1h: float
+ # Whether the table lists a cache write above input. The one-hour figure
+ # counts only when listed: its default is a multiple of input for every
+ # model, so a defaulted one says nothing about the vendor.
+ charges_cache_writes: bool = False
+
+
+def _price(value: object) -> Optional[float]:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ number = float(value)
+ if not math.isfinite(number) or number < 0 or number > _MAX_PRICE_PER_MTOK:
+ return None
+ return number
+
+
+def model_price(cost: object) -> Optional[ModelPrice]:
+ """Read one models.dev-shaped `cost` object, or None when it has no usable price.
+
+ Input and output are required. A missing cache member falls back to what the
+ tokens are otherwise: a cache read or write is input.
+ """
+
+ if not isinstance(cost, Mapping):
+ return None
+ input_price = _price(cost.get("input"))
+ output_price = _price(cost.get("output"))
+ if input_price is None or output_price is None:
+ return None
+ cache_read = _price(cost.get("cache_read"))
+ cache_write = _price(cost.get("cache_write"))
+ cache_write_1h = _price(cost.get("cache_write_1h"))
+ return ModelPrice(
+ input=input_price,
+ output=output_price,
+ cache_read=input_price if cache_read is None else cache_read,
+ cache_write=input_price if cache_write is None else cache_write,
+ cache_write_1h=(
+ input_price * _CACHE_WRITE_1H_INPUT_MULTIPLE if cache_write_1h is None else cache_write_1h
+ ),
+ charges_cache_writes=any(price is not None and price > input_price for price in (cache_write, cache_write_1h)),
+ )
+
+
+def normalize_model_id(model_id: str) -> str:
+ """Fold the spellings agents send onto the one a price table lists.
+
+ `anthropic/claude-opus-5[1m]` and `claude-opus-4-5-20251101` become
+ `claude-opus-5` and `claude-opus-4-5`: the context-window tag, the snapshot
+ date, and a provider prefix do not change a list price.
+ """
+
+ text = model_id.strip().lower()
+ text = text.rsplit("/", 1)[-1]
+ text = _BRACKET_SUFFIX.sub("", text)
+ text = _DATE_SUFFIX.sub("", text)
+ return text.strip()
+
+
+def _first_party(model_id: str, vendor_map: Mapping[str, Any]) -> Optional[str]:
+ families = vendor_map.get("families")
+ if not isinstance(families, list):
+ return None
+ matches = [
+ item
+ for item in families
+ if isinstance(item, Mapping)
+ and isinstance(item.get("prefix"), str)
+ and isinstance(item.get("vendor_id"), str)
+ and model_id.startswith(item["prefix"])
+ ]
+ if not matches:
+ return None
+ return max(matches, key=lambda item: len(item["prefix"]))["vendor_id"]
+
+
+def plan_key(vendor: str, plan: Optional[str]) -> Optional[str]:
+ """Resolve a reported plan to a fee-table key, or None when it is not a known plan."""
+
+ if not plan:
+ return None
+ family = _PLAN_FAMILIES.get(vendor.strip().lower())
+ if family is None:
+ return None
+ normalized = re.sub(r"[\s-]+", "_", plan.strip().lower())
+ return _PLAN_KEYS.get((family, normalized))
+
+
+def _local_day(epoch: object) -> Optional[str]:
+ if isinstance(epoch, bool) or not isinstance(epoch, (int, float)) or not math.isfinite(epoch):
+ return None
+ try:
+ return datetime.fromtimestamp(float(epoch)).date().isoformat()
+ except (OverflowError, OSError, ValueError):
+ return None
+
+
+@dataclass(frozen=True)
+class SourcePlan:
+ plan: Optional[str] = None
+ renewal_day: Optional[int] = None
+
+
+class PriceTable:
+ """One consistent view of prices, fees, and per-Source plan settings."""
+
+ def __init__(
+ self,
+ *,
+ catalog: Mapping[str, Any],
+ vendor_map: Mapping[str, Any],
+ overrides: Mapping[str, Any],
+ price_table_date: Optional[str],
+ ):
+ self.price_table_date = price_table_date
+ self._catalog = catalog
+ self._vendor_map = vendor_map
+ self._model_overrides: dict[str, Mapping[str, Any]] = {}
+ models = overrides.get("models")
+ if isinstance(models, Mapping):
+ for key, entry in models.items():
+ if isinstance(key, str) and len(key) <= _MAX_KEY_CHARS and isinstance(entry, Mapping):
+ self._model_overrides[normalize_model_id(key)] = entry
+ self._fees = dict(PLAN_FEES_USD)
+ plans = overrides.get("plans")
+ if isinstance(plans, Mapping):
+ for key, entry in plans.items():
+ fee = entry.get("fee_usd") if isinstance(entry, Mapping) else None
+ if (
+ isinstance(key, str)
+ and 0 < len(key) <= 64
+ and not isinstance(fee, bool)
+ and isinstance(fee, (int, float))
+ and math.isfinite(fee)
+ and 0 <= fee <= _MAX_FEE_USD
+ ):
+ self._fees[key] = float(fee)
+ self._sources: dict[str, SourcePlan] = {}
+ sources = overrides.get("sources")
+ if isinstance(sources, Mapping):
+ for source_id, entry in sources.items():
+ if not isinstance(source_id, str) or not isinstance(entry, Mapping):
+ continue
+ plan = entry.get("plan")
+ day = entry.get("renewal_day")
+ self._sources[source_id] = SourcePlan(
+ plan=plan[:64] if isinstance(plan, str) and plan.strip() else None,
+ renewal_day=(
+ day
+ if isinstance(day, int) and not isinstance(day, bool) and 1 <= day <= 31
+ else None
+ ),
+ )
+ self._memo: dict[str, Optional[ModelPrice]] = {}
+
+ def price(self, model_id: str) -> Optional[ModelPrice]:
+ key = normalize_model_id(model_id)
+ if key not in self._memo:
+ self._memo[key] = self._resolve(key, hops=0)
+ return self._memo[key]
+
+ def _resolve(self, key: str, *, hops: int) -> Optional[ModelPrice]:
+ if hops > _MAX_ALIAS_HOPS or not key:
+ return None
+ override = self._model_overrides.get(key)
+ if override is not None:
+ alias = override.get("alias")
+ if isinstance(alias, str) and alias.strip():
+ return self._resolve(normalize_model_id(alias), hops=hops + 1)
+ price = model_price(override)
+ if price is not None:
+ return price
+ price = self._catalog_price(key)
+ if price is not None:
+ return price
+ alias = MODEL_ALIASES.get(key)
+ if alias is not None:
+ return self._resolve(alias, hops=hops + 1)
+ return None
+
+ def _catalog_price(self, key: str) -> Optional[ModelPrice]:
+ vendor = _first_party(key, self._vendor_map)
+ if vendor is None:
+ return None
+ provider = self._catalog.get(vendor)
+ models = provider.get("models") if isinstance(provider, Mapping) else None
+ if not isinstance(models, Mapping):
+ return None
+ entry = models.get(key)
+ if not isinstance(entry, Mapping):
+ return None
+ return model_price(entry.get("cost"))
+
+ def source_plan(self, source_id: str) -> SourcePlan:
+ return self._sources.get(source_id, SourcePlan())
+
+ def fee(self, key: Optional[str]) -> Optional[float]:
+ return None if key is None else self._fees.get(key)
+
+ def resolve_plan_key(self, source_id: str, vendor: str, reported: Optional[str]) -> Optional[str]:
+ """The override's plan wins over what the vendor reported."""
+
+ configured = self.source_plan(source_id).plan
+ if configured is not None:
+ if configured in self._fees:
+ return configured
+ return plan_key(vendor, configured)
+ return plan_key(vendor, reported)
+
+
+@dataclass
+class Cost:
+ """Priced usage of one aggregate."""
+
+ api_cost_usd: float = 0.0
+ excluded_tokens: int = 0
+ api_cost_lower_bound: bool = False
+
+ def add(self, other: "Cost") -> None:
+ self.api_cost_usd += other.api_cost_usd
+ self.excluded_tokens += other.excluded_tokens
+ self.api_cost_lower_bound = self.api_cost_lower_bound or other.api_cost_lower_bound
+
+ def fields(self) -> dict[str, Any]:
+ return {
+ "api_cost_usd": round(self.api_cost_usd, 6),
+ "excluded_tokens": self.excluded_tokens,
+ # Anything left unpriced makes the priced figure a floor, not the value.
+ "api_cost_lower_bound": self.api_cost_lower_bound or self.excluded_tokens > 0,
+ }
+
+
+def row_cost(row: Mapping[str, Any], price: Optional[ModelPrice]) -> Cost:
+ """Price one ledger row's counters at one model's price."""
+
+ input_tokens = int(row.get("input_tokens") or 0)
+ output_tokens = int(row.get("output_tokens") or 0)
+ # A request without a token report has usage of unknown size, never zero,
+ # whether or not its model has a price.
+ unreported = int(row.get("requests") or 0) > int(row.get("token_reports") or 0)
+ if price is None:
+ return Cost(excluded_tokens=input_tokens + output_tokens, api_cost_lower_bound=unreported)
+ cache_read = min(int(row.get("cached_input_tokens") or 0), input_tokens)
+ cache_write = min(int(row.get("cache_write_input_tokens") or 0), input_tokens - cache_read)
+ cache_write_1h = min(int(row.get("cache_write_1h_input_tokens") or 0), cache_write)
+ fresh = input_tokens - cache_read - cache_write
+ usd = (
+ fresh * price.input
+ + cache_read * price.cache_read
+ + (cache_write - cache_write_1h) * price.cache_write
+ + cache_write_1h * price.cache_write_1h
+ + output_tokens * price.output
+ ) / 1_000_000
+ uncaptured = int(row.get("cache_write_uncaptured_reports") or 0) > 0
+ return Cost(
+ api_cost_usd=usd,
+ api_cost_lower_bound=unreported or (uncaptured and price.charges_cache_writes),
+ )
+
+
+def billing_period(today: date, renewal_day: Optional[int]) -> tuple[str, date, Optional[date]]:
+ """(basis, first day, next renewal) of the period ending today."""
+
+ if renewal_day is None:
+ return "rolling_30d", today - timedelta(days=29), None
+
+ def on(year: int, month: int) -> date:
+ # A renewal on the 31st lands on the month's last day in shorter months.
+ next_first = date(year + (month == 12), month % 12 + 1, 1)
+ last = (next_first - timedelta(days=1)).day
+ return date(year, month, min(renewal_day, last))
+
+ this_month = on(today.year, today.month)
+ if today >= this_month:
+ start = this_month
+ renews = on(today.year + (today.month == 12), today.month % 12 + 1)
+ else:
+ previous_year, previous_month = (today.year - 1, 12) if today.month == 1 else (today.year, today.month - 1)
+ start = on(previous_year, previous_month)
+ renews = this_month
+ return "billing_cycle", start, renews
+
+
+def _read_overrides(path: Path) -> dict[str, Any]:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return {}
+ except (OSError, ValueError, RecursionError) as exc:
+ logger.warning("Model Hub price override file %s is unreadable: %s", path, exc)
+ return {}
+ if not isinstance(payload, dict):
+ logger.warning("Model Hub price override file %s is not an object", path)
+ return {}
+ return payload
+
+
+def load_price_table(
+ state_dir: Path,
+ *,
+ catalog_loader: Optional[Callable[[], tuple[Mapping[str, Any], Optional[float]]]] = None,
+ vendor_map_loader: Optional[Callable[[], Mapping[str, Any]]] = None,
+) -> PriceTable:
+ """Build the current table. A missing catalog leaves only the overrides to price with."""
+
+ if catalog_loader is None or vendor_map_loader is None:
+ from vibe import models_dev_catalog
+
+ catalog_loader = catalog_loader or models_dev_catalog.load_models_dev_catalog_with_date
+ vendor_map_loader = vendor_map_loader or models_dev_catalog.load_model_vendor_map
+ try:
+ catalog, fetched_at = catalog_loader()
+ except Exception as exc: # noqa: BLE001 - an optional valuation never fails a read
+ logger.info("Model Hub pricing has no models.dev catalog: %s", type(exc).__name__)
+ catalog, fetched_at = {}, None
+ try:
+ vendor_map = vendor_map_loader()
+ except Exception: # noqa: BLE001
+ vendor_map = {}
+ return PriceTable(
+ catalog=catalog if isinstance(catalog, Mapping) else {},
+ vendor_map=vendor_map if isinstance(vendor_map, Mapping) else {},
+ overrides=_read_overrides(state_dir / PRICE_OVERRIDE_FILENAME),
+ price_table_date=_local_day(fetched_at) if catalog else None,
+ )
+
+
+# The longest span `quota_values` sums: a billing cycle is at most 31 days.
+VALUE_WINDOW_DAYS: Final = 31
+_WEEK_DAYS: Final = 7
+
+
+def _span(days: Mapping[str, Cost], first: date, last: date) -> Cost:
+ total = Cost()
+ for day, cost in days.items():
+ if first.isoformat() <= day <= last.isoformat():
+ total.add(cost)
+ return total
+
+
+def quota_values(
+ sources: list[dict[str, Any]],
+ *,
+ daily_costs: Mapping[str, Mapping[str, Cost]],
+ prices: PriceTable,
+ today: date,
+) -> dict[str, Any]:
+ """Add each quota Source's `value` block in place and return the root totals.
+
+ `sources` are quota-summary Source payloads; their reported `plan` is what the
+ override file's plan, if any, replaces.
+ """
+
+ week_total = Cost()
+ period_total = Cost()
+ period_fee = 0.0
+ period_sources = 0
+ for source in sources:
+ days = daily_costs.get(source["source_id"], {})
+ basis, start, renews = billing_period(today, prices.source_plan(source["source_id"]).renewal_day)
+ week = _span(days, today - timedelta(days=_WEEK_DAYS - 1), today)
+ period = _span(days, start, today)
+ key = prices.resolve_plan_key(source["source_id"], source["vendor"], source.get("plan"))
+ fee = prices.fee(key)
+ multiple = round(period.api_cost_usd / fee, 4) if fee else None
+ source["value"] = {
+ "currency": CURRENCY,
+ "price_table_date": prices.price_table_date,
+ "plan_key": key,
+ "fee_usd": fee,
+ "multiple": multiple,
+ "week": week.fields(),
+ "period": {
+ "basis": basis,
+ "from_day": start.isoformat(),
+ "to_day": today.isoformat(),
+ "renews_on": renews.isoformat() if renews is not None else None,
+ **period.fields(),
+ },
+ }
+ week_total.add(week)
+ if fee:
+ period_total.add(period)
+ period_fee += fee
+ period_sources += 1
+ return {
+ "currency": CURRENCY,
+ "price_table_date": prices.price_table_date,
+ "week": week_total.fields(),
+ "period": (
+ {
+ "sources": period_sources,
+ "fee_usd": round(period_fee, 6),
+ "multiple": round(period_total.api_cost_usd / period_fee, 4),
+ **period_total.fields(),
+ }
+ if period_sources
+ else None
+ ),
+ }
diff --git a/core/handlers/model_hub/quota.py b/core/handlers/model_hub/quota.py
index cf185472e..2e05bedcf 100644
--- a/core/handlers/model_hub/quota.py
+++ b/core/handlers/model_hub/quota.py
@@ -267,6 +267,42 @@ def parse_claude_quota(body: object) -> dict[str, Any]:
return {"plan": None, "windows": _ordered(windows)}
+# Claude's usage report names no plan; its OAuth profile's organization does.
+# Claude Code CLI 2.1.280 reads the same profile: `organization_type` names the
+# product (claude_max / claude_pro / claude_team / claude_enterprise) and
+# `rate_limit_tier` separates the Max tiers. Team seats can carry a Max tier, so
+# the tier counts only on a claude_max organization.
+_CLAUDE_MAX_TIER_PLANS: Final[Mapping[str, str]] = {
+ "default_claude_max_20x": "max_20x",
+ "default_claude_max_5x": "max_5x",
+}
+
+
+def parse_claude_plan(body: object) -> Optional[str]:
+ """Read the plan from `GET https://api.anthropic.com/api/oauth/profile`, or None.
+
+ Best effort by design: the plan only prices a fee comparison, so a body we
+ cannot read, or a product without a built-in fee (Team, Enterprise, an
+ unknown Max tier), yields no plan rather than a failure.
+ """
+
+ try:
+ payload = _load_object(body)
+ except SubscriptionQuotaError:
+ return None
+ organization = payload.get("organization")
+ if not isinstance(organization, dict):
+ return None
+ kind = organization.get("organization_type")
+ kind = kind.strip().lower() if isinstance(kind, str) else ""
+ if kind == "claude_pro":
+ return "pro"
+ if kind != "claude_max":
+ return None
+ tier = organization.get("rate_limit_tier")
+ return _CLAUDE_MAX_TIER_PLANS.get(tier.strip().lower()) if isinstance(tier, str) else None
+
+
def _codex_kind(seconds: Optional[int]) -> QuotaWindowKind:
if seconds is None:
return "other"
@@ -393,6 +429,8 @@ QUOTA_READ_DEADLINE_SECONDS: Final = 12.0
# queue here instead of all reaching the engine at once.
QUOTA_MAX_CONCURRENT_FETCHES: Final = 4
QUOTA_FETCH_TIMEOUT_SECONDS: Final = 10.0
+# The plan read follows the quota read inside the same deadline; it is optional.
+CLAUDE_PLAN_FETCH_TIMEOUT_SECONDS: Final = 5.0
_RATE_LIMIT_COOLDOWN_FLOOR: Final = timedelta(minutes=5)
_RATE_LIMIT_COOLDOWN_CEILING: Final = timedelta(hours=1)
@@ -456,10 +494,21 @@ class SubscriptionQuotaCache:
# A slow vendor must not hold the page: whatever has not answered by
# the deadline keeps running and lands in the next read.
await asyncio.wait(pending, timeout=QUOTA_READ_DEADLINE_SECONDS)
- return {
+ payload: dict[str, Any] = {
"refresh_interval_seconds": int(QUOTA_REFRESH_INTERVAL.total_seconds()),
"sources": [self._payload(source) for source in sources],
}
+ # Named so the page can re-read shortly instead of showing a gap as a failure.
+ still_reading = [
+ source.source_id
+ for source in sources
+ if (entry := self._entries.get(source.source_id)) is not None
+ and entry.task is not None
+ and not entry.task.done()
+ ]
+ if still_reading:
+ payload["pending"] = still_reading
+ return payload
def forget(self, source_id: str) -> None:
"""Drop a Source's snapshot, failure, and throttle, e.g. after re-authentication.
@@ -519,7 +568,11 @@ class SubscriptionQuotaCache:
entry.failure = "unavailable"
logger.warning("Model Hub quota read failed for %s", source.source_id, exc_info=False)
return
- entry.snapshot = {"plan": parsed.get("plan"), "windows": windows}
+ plan = parsed.get("plan")
+ if plan is None and entry.snapshot is not None:
+ # The plan is a best-effort second read; one miss must not blank it.
+ plan = entry.snapshot["plan"]
+ entry.snapshot = {"plan": plan, "windows": windows}
entry.fetched_at = self._now()
entry.failure = None
entry.cooldown_until = None
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index ebaa00470..2517c0f78 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -115,6 +115,7 @@ from .oauth import (
OAuthFlowRegistry,
UnavailableNativeOAuthAdapter,
)
+from .pricing import VALUE_WINDOW_DAYS, PriceTable, load_price_table, quota_values
from .quota import QuotaSourceRef, SubscriptionQuotaCache, SubscriptionQuotaError
from .provenance import (
BoundedProvenanceStore,
@@ -151,6 +152,7 @@ from .usage import (
BoundedUsageLedger,
SourceIdentity,
UsageWriter,
+ local_usage_day,
)
CONTRACT_VERSION = 10
@@ -898,6 +900,7 @@ class ModelHubService:
] = None,
now: Callable[[], datetime] = _utc_now,
recovery: RecoveryPolicy | None = None,
+ price_table: Callable[[], PriceTable] | None = None,
):
self.store = store
self.adapter = adapter
@@ -960,6 +963,10 @@ class ModelHubService:
self._builtin_snapshot_cache: dict[BackendName, list[dict[str, Any]]] = {}
self._pending_builtin_catalog_refresh: set[BackendName] = set()
self.quota = SubscriptionQuotaCache(self._fetch_subscription_quota, now=lambda: self.now())
+ # Read per report: the override file is hand-edited and the catalog refreshes itself.
+ self.price_table: Callable[[], PriceTable] = price_table or (
+ lambda: load_price_table(paths.get_state_dir())
+ )
@staticmethod
@asynccontextmanager
@@ -5486,12 +5493,14 @@ class ModelHubService:
for source in config.sources
]
now = self.now()
+ prices = self.price_table()
if window is not None:
- return self.usage.report(window=window, now=now, identities=identities)
+ return self.usage.report(window=window, now=now, identities=identities, prices=prices)
return self.usage.summary(
days=USAGE_DEFAULT_WINDOW_DAYS if days is None else days,
now=now,
identities=identities,
+ prices=prices,
)
async def _fetch_subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> Mapping[str, Any]:
@@ -5536,7 +5545,40 @@ class ModelHubService:
"""
sources = await asyncio.to_thread(self._quota_sources)
- return await self.quota.summary(sources, force=force)
+ summary = await self.quota.summary(sources, force=force)
+ try:
+ summary["value"] = await asyncio.to_thread(self._quota_values, summary["sources"])
+ except Exception: # noqa: BLE001 - the valuation is optional; the windows are not
+ logger.warning("Model Hub quota valuation failed", exc_info=True)
+ for source in summary["sources"]:
+ source.pop("value", None)
+ return summary
+
+ def _quota_values(self, sources: list[dict[str, Any]]) -> dict[str, Any]:
+ config = self.store.load()
+ wanted = {source["source_id"] for source in sources}
+ identities = [
+ SourceIdentity(
+ source_id=source.id,
+ label=source.display_name,
+ model_ids=[model.id for model in source.models],
+ )
+ for source in config.sources
+ if source.id in wanted
+ ]
+ prices = self.price_table()
+ now = self.now()
+ return quota_values(
+ sources,
+ daily_costs=self.usage.daily_costs(
+ days=VALUE_WINDOW_DAYS,
+ now=now,
+ identities=identities,
+ prices=prices,
+ ),
+ prices=prices,
+ today=local_usage_day(now),
+ )
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
events = self.events.list(limit=limit, before=before)
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 282bf3bb6..de9e8f61e 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -394,6 +394,10 @@ class ProtocolUsageReport:
input_tokens: int = 0
cached_input_tokens: int = 0
output_tokens: int = 0
+ # Input written to the prompt cache: a subset of input disjoint from cached
+ # input, and the part of it written with the one-hour lifetime.
+ cache_write_input_tokens: int = 0
+ cache_write_1h_input_tokens: int = 0
@classmethod
def of(
@@ -402,6 +406,8 @@ class ProtocolUsageReport:
input_tokens: int,
cached_input_tokens: int,
output_tokens: int,
+ cache_write_input_tokens: int = 0,
+ cache_write_1h_input_tokens: int = 0,
) -> "ProtocolUsageReport":
"""Build one report with the cached-input subset invariant enforced.
@@ -410,13 +416,18 @@ class ProtocolUsageReport:
by. Both numbers come from the same upstream, so the only bound worth
trusting is the input count this module normalized itself — never a
total the response declares. Cached input reported without a readable
- input count is a subset of nothing, so it clamps to zero.
+ input count is a subset of nothing, so it clamps to zero. Cache writes are
+ the input left after cache reads, and one-hour writes are part of them.
"""
+ cached = min(cached_input_tokens, input_tokens)
+ cache_write = min(cache_write_input_tokens, input_tokens - cached)
return cls(
input_tokens=input_tokens,
- cached_input_tokens=min(cached_input_tokens, input_tokens),
+ cached_input_tokens=cached,
output_tokens=output_tokens,
+ cache_write_input_tokens=cache_write,
+ cache_write_1h_input_tokens=min(cache_write_1h_input_tokens, cache_write),
)
def merge(self, other: "ProtocolUsageReport") -> "ProtocolUsageReport":
@@ -431,6 +442,10 @@ class ProtocolUsageReport:
input_tokens=max(self.input_tokens, other.input_tokens),
cached_input_tokens=max(self.cached_input_tokens, other.cached_input_tokens),
output_tokens=max(self.output_tokens, other.output_tokens),
+ cache_write_input_tokens=max(self.cache_write_input_tokens, other.cache_write_input_tokens),
+ cache_write_1h_input_tokens=max(
+ self.cache_write_1h_input_tokens, other.cache_write_1h_input_tokens
+ ),
)
@@ -484,6 +499,9 @@ class ProtocolUsageTaxonomy:
input_paths: tuple[tuple[str, ...], ...]
cached_input_paths: tuple[tuple[str, ...], ...]
output_paths: tuple[tuple[str, ...], ...]
+ # Protocols that report no cache writes leave these empty.
+ cache_write_paths: tuple[tuple[str, ...], ...] = ()
+ cache_write_1h_paths: tuple[tuple[str, ...], ...] = ()
@dataclass(frozen=True)
@@ -558,6 +576,10 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {
),
cached_input_paths=(("cache_read_input_tokens",),),
output_paths=(("output_tokens",),),
+ # Cache writes are priced apart from fresh input; the one-hour
+ # lifetime is split out under `cache_creation`.
+ cache_write_paths=(("cache_creation_input_tokens",),),
+ cache_write_1h_paths=(("cache_creation", "ephemeral_1h_input_tokens"),),
),
),
"openai_responses": ProtocolStreamTaxonomy(
@@ -822,6 +844,8 @@ def extract_protocol_usage(
input_tokens=input_tokens or 0,
cached_input_tokens=cached_input_tokens or 0,
output_tokens=output_tokens or 0,
+ cache_write_input_tokens=_usage_sum(container, taxonomy.cache_write_paths) or 0,
+ cache_write_1h_input_tokens=_usage_sum(container, taxonomy.cache_write_1h_paths) or 0,
)
report = candidate if report is None else report.merge(candidate)
return report
@@ -856,6 +880,8 @@ def _usage_from_scalar_paths(
input_tokens=input_tokens or 0,
cached_input_tokens=cached_input_tokens or 0,
output_tokens=output_tokens or 0,
+ cache_write_input_tokens=usage_sum(taxonomy.cache_write_paths) or 0,
+ cache_write_1h_input_tokens=usage_sum(taxonomy.cache_write_1h_paths) or 0,
)
report = candidate if report is None else report.merge(candidate)
return report
@@ -885,6 +911,8 @@ def _protocol_projection_paths(protocol: str) -> frozenset[JSONPath]:
taxonomy.usage.input_paths,
taxonomy.usage.cached_input_paths,
taxonomy.usage.output_paths,
+ taxonomy.usage.cache_write_paths,
+ taxonomy.usage.cache_write_1h_paths,
):
paths.update((*container_path, *leaf_path) for leaf_path in leaf_paths)
return frozenset(paths)
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index ac4b1988a..778d91266 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -40,6 +40,7 @@ from pathlib import Path
from typing import Callable, Final, Mapping, Optional, Sequence
from .identifiers import persisted_ledger_key, usage_ledger_key
+from .pricing import CURRENCY, Cost, ModelPrice, PriceTable, row_cost
from .state_file import write_state_document
from .stream_wire import ProtocolUsageReport
@@ -113,17 +114,56 @@ _COUNTER_KEYS: Final = (
"input_tokens",
"cached_input_tokens",
"output_tokens",
+ "cache_write_input_tokens",
+ "cache_write_1h_input_tokens",
+ "cache_write_uncaptured_reports",
+)
+# Counters added after files were already written. A released row lacks them, and
+# what it lacks is knowledge, not usage: its cache writes are inside its input but
+# were never split out, so every token report it carries counts as uncaptured.
+# Additive only — no stored row is rewritten to acquire them.
+_CACHE_WRITE_KEYS: Final = (
+ "cache_write_input_tokens",
+ "cache_write_1h_input_tokens",
+ "cache_write_uncaptured_reports",
)
# The cross-field guarantees the read contract makes, as (subset, superset).
# Each one is repaired on read, so a corrupt or hand-edited file degrades into a
# smaller true statement instead of publishing an impossible one: a coverage
-# figure above 100% is more misleading than a conservative one.
+# figure above 100% is more misleading than a conservative one. Order matters:
+# a superset is repaired before the subsets that are read against it.
_COUNTER_SUBSETS: Final = (
("cached_input_tokens", "input_tokens"),
("token_reports", "requests"),
+ ("cache_write_uncaptured_reports", "token_reports"),
+ ("cache_write_1h_input_tokens", "cache_write_input_tokens"),
)
+def _released_cache_write_counters(value: dict) -> dict[str, int]:
+ """What a counter set written before cache writes were metered stands for."""
+
+ reports = value.get("token_reports")
+ uncaptured = reports if isinstance(reports, int) and not isinstance(reports, bool) else 0
+ return {
+ "cache_write_input_tokens": 0,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": max(0, uncaptured),
+ }
+
+
+def _repair_cache_writes(counters: dict) -> None:
+ """Keep cache writes inside the input that cache reads did not already claim."""
+
+ counters["cache_write_input_tokens"] = min(
+ counters["cache_write_input_tokens"],
+ max(0, counters["input_tokens"] - counters["cached_input_tokens"]),
+ )
+ counters["cache_write_1h_input_tokens"] = min(
+ counters["cache_write_1h_input_tokens"], counters["cache_write_input_tokens"]
+ )
+
+
def _utc_now() -> datetime:
return datetime.now(timezone.utc)
@@ -553,6 +593,8 @@ def _normalize_hourly_totals(value: object) -> Optional[dict]:
if not isinstance(value, dict):
return None
+ if all(key not in value for key in _CACHE_WRITE_KEYS):
+ value = {**_released_cache_write_counters(value), **value}
totals: dict[str, int] = {}
for key in _COUNTER_KEYS:
counter = value.get(key)
@@ -564,6 +606,8 @@ def _normalize_hourly_totals(value: object) -> Optional[dict]:
for subset, superset in _COUNTER_SUBSETS:
if totals[subset] > totals[superset]:
return None
+ if totals["cache_write_input_tokens"] + totals["cached_input_tokens"] > totals["input_tokens"]:
+ return None
if totals["token_reports"] == 0 and any(
totals[key] for key in ("input_tokens", "cached_input_tokens", "output_tokens")
):
@@ -595,6 +639,8 @@ def _normalize_row(row: object) -> Optional[dict]:
calendar_day = _calendar_day(day)
if calendar_day is None:
return None
+ if all(key not in row for key in _CACHE_WRITE_KEYS):
+ row = {**_released_cache_write_counters(row), **row}
counters: dict[str, int] = {}
for key in _COUNTER_KEYS:
counter = _counter(row.get(key))
@@ -613,6 +659,8 @@ def _normalize_row(row: object) -> Optional[dict]:
normalized["history_degraded"] = True
for subset, superset in _COUNTER_SUBSETS:
normalized[subset] = min(normalized[subset], normalized[superset])
+ _repair_cache_writes(normalized)
+ counters = {key: normalized[key] for key in _COUNTER_KEYS}
normalized["last_metered_at"] = _timestamp(row.get("last_metered_at"))
raw_hours = row.get("hours")
if isinstance(raw_hours, list):
@@ -738,6 +786,29 @@ def _keyed_identities(
return sources, models
+def _row_price(
+ row: Mapping, prices: PriceTable, keyed_model_labels: Mapping[tuple[str, str], str]
+) -> Optional[ModelPrice]:
+ """Price a row by the identity it was metered under; a folded key is not a model name."""
+
+ return prices.price(keyed_model_labels.get((row["source_id"], row["model_id"]), row["model_id"]))
+
+
+def _priced_bucket_row(
+ row: dict,
+ prices: Optional[PriceTable],
+ keyed_model_labels: Mapping[tuple[str, str], str],
+ *,
+ degraded: bool = False,
+) -> dict:
+ if prices is None:
+ return row
+ cost = row_cost(row, _row_price(row, prices, keyed_model_labels))
+ # A degraded read lost rows of unknown size, so no figure from it is exact.
+ cost.api_cost_lower_bound = cost.api_cost_lower_bound or degraded
+ return {**row, **cost.fields()}
+
+
def _recency(
row: dict, ceiling: datetime, *, utc_owner_days: bool = False,
) -> tuple[str, datetime]:
@@ -794,6 +865,14 @@ def _recency(
return (row["day"], metered)
+def _cache_write_increment(usage: Optional[ProtocolUsageReport]) -> dict[str, int]:
+ return {
+ "cache_write_input_tokens": usage.cache_write_input_tokens if usage else 0,
+ "cache_write_1h_input_tokens": usage.cache_write_1h_input_tokens if usage else 0,
+ "cache_write_uncaptured_reports": 0,
+ }
+
+
def _row_key(row: dict) -> tuple[str, str, str]:
return (row["day"], row["source_id"], row["model_id"])
@@ -1201,6 +1280,7 @@ class BoundedUsageLedger:
"input_tokens": usage.input_tokens if usage else 0,
"cached_input_tokens": usage.cached_input_tokens if usage else 0,
"output_tokens": usage.output_tokens if usage else 0,
+ **_cache_write_increment(usage),
"last_metered_at": metered_at.isoformat(),
"hours": [
{
@@ -1210,6 +1290,7 @@ class BoundedUsageLedger:
"input_tokens": usage.input_tokens if usage else 0,
"cached_input_tokens": usage.cached_input_tokens if usage else 0,
"output_tokens": usage.output_tokens if usage else 0,
+ **_cache_write_increment(usage),
"last_metered_at": metered_at.isoformat(),
}
],
@@ -1324,6 +1405,43 @@ class BoundedUsageLedger:
rows, _degraded = self._window_rows(days=days, now=now)
return rows
+ def daily_costs(
+ self,
+ *,
+ days: int,
+ now: datetime,
+ identities: Sequence[SourceIdentity],
+ prices: PriceTable,
+ ) -> dict[str, dict[str, Cost]]:
+ """Price the window's rows per Source and local day, keyed by config Source ID.
+
+ The quota page compares spans the ledger does not know (a billing cycle, a
+ week), so it gets days to sum rather than one total. Only the given
+ identities are answered for; a row keyed to anything else is not theirs.
+ """
+
+ keyed_sources = {
+ key: identity.source_id
+ for identity in identities
+ if (key := usage_ledger_key(identity.source_id)) is not None
+ }
+ _labels, keyed_model_labels = _keyed_identities(identities)
+ rows, degraded = self._window_rows(days=days, now=now)
+ costs: dict[str, dict[str, Cost]] = {}
+ for row in rows:
+ source_id = keyed_sources.get(row["source_id"])
+ if source_id is None:
+ continue
+ cost = row_cost(row, _row_price(row, prices, keyed_model_labels))
+ costs.setdefault(source_id, {}).setdefault(row["day"], Cost()).add(cost)
+ if degraded:
+ # Rows of unknown size were lost, so every Source's value is a floor:
+ # today lies in every span the quota page sums.
+ today = local_usage_day(now).isoformat()
+ for source_id in keyed_sources.values():
+ costs.setdefault(source_id, {}).setdefault(today, Cost()).add(Cost(api_cost_lower_bound=True))
+ return costs
+
def _hourly_rows(
self,
*,
@@ -1384,6 +1502,7 @@ class BoundedUsageLedger:
days: int = USAGE_DEFAULT_WINDOW_DAYS,
now: datetime,
identities: Optional[Sequence[SourceIdentity]] = None,
+ prices: Optional[PriceTable] = None,
) -> dict:
"""Aggregate the window into the read shape the settings page consumes.
@@ -1409,13 +1528,15 @@ class BoundedUsageLedger:
bounded_days = max(1, min(int(days), self.retention_days))
today = local_usage_day(now)
- rows, _degraded = self._window_rows(days=bounded_days, now=now)
+ rows, degraded = self._window_rows(days=bounded_days, now=now)
return self._summary_from_rows(
rows,
window_days=bounded_days,
from_day=(today - timedelta(days=bounded_days - 1)).isoformat(),
to_day=today.isoformat(),
identities=identities,
+ prices=prices,
+ degraded=degraded,
)
def _summary_from_rows(
@@ -1426,16 +1547,42 @@ class BoundedUsageLedger:
from_day: str,
to_day: str,
identities: Optional[Sequence[SourceIdentity]],
+ prices: Optional[PriceTable] = None,
+ degraded: bool = False,
) -> dict:
- """Aggregate one exact set of daily or hourly rows."""
+ """Aggregate one exact set of daily or hourly rows.
+
+ With a price table, every aggregate also carries its API-price valuation,
+ summed from the same rows so a total always equals the sum of its parts.
+ A `degraded` read lost rows of unknown size, so every valuation is a floor.
+ """
keyed_source_labels, keyed_model_labels = _keyed_identities(identities)
+ costs: dict[int, Cost] = {}
+
+ def priced(target: dict, cost: Optional[Cost]) -> None:
+ if cost is not None:
+ costs.setdefault(id(target), Cost()).add(cost)
+
+ def with_cost(target: dict, *, omit: str = "") -> dict:
+ published = {key: value for key, value in target.items() if key != omit}
+ if prices is None:
+ return published
+ cost = costs.get(id(target), Cost())
+ cost.api_cost_lower_bound = cost.api_cost_lower_bound or degraded
+ return {**published, **cost.fields()}
totals = _empty_totals()
sources: dict[str, dict] = {}
by_day: dict[str, dict] = {}
for row in rows:
_accumulate(totals, row)
+ cost = (
+ None
+ if prices is None
+ else row_cost(row, _row_price(row, prices, keyed_model_labels))
+ )
+ priced(totals, cost)
source = sources.setdefault(
row["source_id"],
@@ -1448,6 +1595,7 @@ class BoundedUsageLedger:
},
)
_accumulate(source, row)
+ priced(source, cost)
source["last_metered_at"] = _newer_timestamp(
source["last_metered_at"],
row["last_metered_at"],
@@ -1461,30 +1609,40 @@ class BoundedUsageLedger:
},
)
_accumulate(model, row)
+ priced(model, cost)
+ if prices is not None:
+ model["priced"] = _row_price(row, prices, keyed_model_labels) is not None
day = by_day.setdefault(row["day"], {"day": row["day"], **_empty_totals()})
_accumulate(day, row)
+ priced(day, cost)
- return {
+ summary = {
"window_days": window_days,
"from_day": from_day,
"to_day": to_day,
- "totals": totals,
+ "totals": with_cost(totals),
"sources": [
{
- **{key: value for key, value in source.items() if key != "models"},
- "models": sorted(
- source["models"].values(),
- key=lambda model: (-model["requests"], model["model_id"]),
- ),
+ **with_cost(source, omit="models"),
+ "models": [
+ with_cost(model)
+ for model in sorted(
+ source["models"].values(),
+ key=lambda model: (-model["requests"], model["model_id"]),
+ )
+ ],
}
for source in sorted(
sources.values(),
key=lambda source: (-source["requests"], source["source_id"]),
)
],
- "days": [by_day[day] for day in sorted(by_day)],
+ "days": [with_cost(by_day[day]) for day in sorted(by_day)],
}
+ if prices is not None:
+ summary["pricing"] = {"currency": CURRENCY, "price_table_date": prices.price_table_date}
+ return summary
def report(
self,
@@ -1492,13 +1650,14 @@ class BoundedUsageLedger:
window: str,
now: datetime,
identities: Optional[Sequence[SourceIdentity]] = None,
+ prices: Optional[PriceTable] = None,
) -> dict:
"""Build one modern dense report without reallocating daily history."""
if window not in USAGE_WINDOW_KEYS:
raise ValueError(f"unsupported usage window: {window!r}")
if window == "24h":
- return self._hourly_report(now=now, identities=identities)
+ return self._hourly_report(now=now, identities=identities, prices=prices)
days = int(window[:-1])
bounded_days = max(1, min(days, self.retention_days))
report_local = _local(now)
@@ -1511,7 +1670,10 @@ class BoundedUsageLedger:
from_day=from_day.isoformat(),
to_day=today.isoformat(),
identities=identities,
+ prices=prices,
+ degraded=read_degraded,
)
+ _source_labels, keyed_model_labels = _keyed_identities(identities)
by_day = {
row["day"]: []
for row in rows
@@ -1520,11 +1682,16 @@ class BoundedUsageLedger:
for row in rows:
if row["day"] in by_day:
by_day[row["day"]].append(
- {
- "source_id": row["source_id"],
- "model_id": row["model_id"],
- **{key: row[key] for key in _COUNTER_KEYS},
- }
+ _priced_bucket_row(
+ {
+ "source_id": row["source_id"],
+ "model_id": row["model_id"],
+ **{key: row[key] for key in _COUNTER_KEYS},
+ },
+ prices,
+ keyed_model_labels,
+ degraded=read_degraded,
+ )
)
buckets = []
for index in range(bounded_days):
@@ -1561,9 +1728,12 @@ class BoundedUsageLedger:
*,
now: datetime,
identities: Optional[Sequence[SourceIdentity]],
+ prices: Optional[PriceTable] = None,
) -> dict:
"""Project only measured nested slices onto 24 actual consecutive hours."""
+ _source_labels, keyed_model_labels = _keyed_identities(identities)
+
report_instant = _aware(now)
starts = _hour_starts(now)
interval_by_instant = {
@@ -1648,11 +1818,17 @@ class BoundedUsageLedger:
start_local = start.astimezone()
end_local = end.astimezone()
projected_rows = [
- {
- "source_id": row["source_id"],
- "model_id": row["model_id"],
- **{counter: row[counter] for counter in _COUNTER_KEYS},
- }
+ _priced_bucket_row(
+ {
+ "source_id": row["source_id"],
+ "model_id": row["model_id"],
+ **{counter: row[counter] for counter in _COUNTER_KEYS},
+ },
+ prices,
+ keyed_model_labels,
+ # An incomplete hour holds usage it cannot place, so its cost is a floor.
+ degraded=index in incomplete,
+ )
for row in sorted(
measured_by_bucket[index].values(),
key=lambda row: (row["source_id"], row["model_id"]),
@@ -1679,6 +1855,8 @@ class BoundedUsageLedger:
from_day=days[0],
to_day=days[-1],
identities=identities,
+ prices=prices,
+ degraded=bool(incomplete),
)
return {
**summary,
@@ -1827,6 +2005,10 @@ class UsageCall:
input_tokens=sum(report.input_tokens for report in reports),
cached_input_tokens=sum(report.cached_input_tokens for report in reports),
output_tokens=sum(report.output_tokens for report in reports),
+ cache_write_input_tokens=sum(report.cache_write_input_tokens for report in reports),
+ cache_write_1h_input_tokens=sum(
+ report.cache_write_1h_input_tokens for report in reports
+ ),
)
return replace(
self,
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 081c42124..3d211f555 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -230,8 +230,8 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `source-probe-result.schema.json` | Explicit API-key Source/model test, without Agent routing, fallback or provider-wide health mutation. |
| `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, protocol-establishment, and inventory observation. |
| `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. The one versioned object persisted to disk, so it accepts every released version. |
-| `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns. A report only: no consumer may feed it back into resolution, admission, or cooldown. |
-| `quota-summary.schema.json` | Rate-limit windows of hub-held subscriptions, parsed from each vendor's own usage report. A report only; carries no grant, raw body, or monetary field. |
+| `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns, with its list-API-price valuation. A report only: no consumer may feed it back into resolution, admission, or cooldown. |
+| `quota-summary.schema.json` | Rate-limit windows of hub-held subscriptions, parsed from each vendor's own usage report, and the API-price value of each subscription's metered usage against its monthly fee. A report only; carries no grant or raw body. |
| `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. |
| `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. |
| `migration-scan.schema.json` | Server-owned custody-takeover scan of existing native CLI/provider configuration; not an internal contract migration. |
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 80e0fd53a..cbeb51130 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -62,7 +62,7 @@ remain readable; ephemeral envelopes use only the terminal version.
| GET `/api/models/agents/<backend>/provenance?model=<id>` | → `{provenance: TurnProvenance \| null}` | On-demand read of the most recently persisted retained record for this exact backend and canonical catalog model, regardless of outcome. Validates backend/model; absent history is null. Uses only the existing bounded store and never starts or syncs the engine. No history field is added to AgentChain. |
| GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. |
| GET `/api/models/usage?days=<n>` | → `{usage: UsageSummary \| UsageReport}` | The released `days` selector remains supported and is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. The exclusive modern `window=24h\|7d\|30d\|60d` selector returns the dense temporal report; sending both selectors or an invalid `window` returns `400 invalid_parameter`. |
-| GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline. Never starts the engine. |
+| GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report, plus each Source's API-price `value` (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline, and a Source still being read is listed in `pending`. Never starts the engine. |
| POST `/api/models/quota/refresh` | → `{quota: QuotaSummary}` | Forced re-read. Rate-limited per Source to one vendor call every 30 seconds and suppressed while a Source cools down after a vendor 429; a suppressed Source returns its cached snapshot. |
| POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |
| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. |
@@ -1395,9 +1395,41 @@ failure keeps the last good windows and reports `stale`; a 401/403 reports
`auth_expired`; a Source with no good read yet reports `error`. A
re-authenticated Source is a different grant and starts with no snapshot.
-`quota-summary.schema.json` reserves no monetary field. A later contract version
-may add an optional `value` block per Source; consumers must treat its absence as
-"not reported", never as zero.
+A read waits for in-flight Source reads only up to a 12-second deadline; a read
+that misses it keeps running and lands in the cache. Those Sources are listed in
+the root `pending` array, and the settings page re-reads after about five seconds,
+with a bounded number of retries, showing them as loading rather than unavailable.
+It stops re-reading once `pending` is empty or absent.
+
+### Subscription value
+
+Each hub-held subscription Source carries an optional `value` block, and the root carries `value` totals. They price the Source's own
+usage-ledger rows at list API prices (see API-price valuation under Usage
+metering) so the page can compare that with what the subscription costs. A
+valuation only, never an amount charged; consumers must treat an absent `value`
+as "not reported", never as zero.
+
+- `week` is the trailing seven local days ending today.
+- `period` is the current billing cycle when the local override file sets a
+ renewal day for the Source (`basis: billing_cycle`, with `renews_on`), else the
+ trailing 30 local days (`basis: rolling_30d`). The page labels which it is.
+- `fee_usd` is the plan's monthly fee. The plan comes from what the vendor's usage
+ report says (`plan`) or from the override file's per-Source `plan`, and resolves
+ to a fee-table key (`plan_key`). Built-in plan names resolve for `anthropic`
+ and `openai` / `codex` Sources only; any other vendor needs the override to
+ name a fee key outright. Claude's plan is read from the OAuth profile the
+ Claude Code CLI also reads: `organization.organization_type` `claude_pro` is
+ Pro, and `claude_max` with `rate_limit_tier` `default_claude_max_5x` or
+ `default_claude_max_20x` is Max 5x or 20x; Team, Enterprise, and unknown tiers
+ are no plan. Built-in fees: `claude_pro` 20, `claude_max_5x`
+ 100, `claude_max_20x` 200, `chatgpt_plus` 20, `chatgpt_pro` 200 (USD / month). An
+ unknown plan leaves `plan_key`, `fee_usd`, and `multiple` null: the page still
+ shows the API value but no payback figure.
+- `multiple` is `period.api_cost_usd / fee_usd`. When `period.api_cost_lower_bound`
+ is true the multiple is a floor: the page may say the fee is paid back, marked
+ 「≥」, but never names a shortfall.
+- Root `value.period` sums only the Sources with a known fee, so its multiple
+ compares like with like; root `value.week` sums every valued Source.
## Usage metering
@@ -1436,6 +1468,75 @@ publishing an impossible one.
`source_id` and `model_id` are reported in the canonical form configuration admitted,
so one model is one row rather than one row per spelling.
+Cache writes are metered separately from input served from cache.
+`cache_write_input_tokens` is the subset of `input_tokens` written to the prompt
+cache (Anthropic `cache_creation_input_tokens`), disjoint from
+`cached_input_tokens`, and `cache_write_1h_input_tokens` is the part of it written
+with the one-hour lifetime (`cache_creation.ephemeral_1h_input_tokens`). OpenAI
+protocols report no cache writes, so both are zero there. The fields are additive:
+a ledger row written before they existed reads them as zero and counts its token
+reports in `cache_write_uncaptured_reports`, so a consumer can tell "no cache
+writes" from "cache writes not captured". No stored row is rewritten.
+
+### API-price valuation
+
+When a price table can be read, every usage document carries `pricing`
+(`currency: "USD"`, `price_table_date`) and each aggregate carries
+`api_cost_usd`, `excluded_tokens`, and `api_cost_lower_bound`; each model row
+also carries `priced`. `api_cost_usd` is what the same usage would cost at the
+vendor's list API price. It is a valuation for comparing subscriptions, never an
+amount charged, and every day is priced at the current table, not the price in
+force when the call ran; `price_table_date` says which table that is.
+
+Prices come from two places, highest precedence first:
+
+1. The local override file `<state dir>/model_hub_prices.json` (by default
+ `~/.avibe/state/model_hub_prices.json`), which the user edits by hand.
+2. The models.dev catalog Avibe already caches for the model picker
+ (`<state dir>/models_dev_catalog.json`, refreshed at most daily), read from
+ the model's first-party provider (`anthropic`, `openai`, `xai`, …) only.
+
+Before lookup a ledger model ID is normalized: a `[1m]` or other bracketed
+suffix, a trailing `-YYYYMMDD` or `@…` date, and a `provider/` prefix are removed,
+and a built-in alias map covers IDs models.dev does not list under the name Claude
+Code or Codex sends. Prices are USD per million tokens with members `input`,
+`output`, `cache_read`, `cache_write` (five-minute lifetime) and optional
+`cache_write_1h`. A missing `cache_read` prices cache reads as input; a missing
+`cache_write` prices cache writes as input; a missing `cache_write_1h` prices
+one-hour writes at twice `input`. Only the base tier is used.
+
+Cost of one row = fresh input × `input` + `cached_input_tokens` × `cache_read` +
+five-minute writes × `cache_write` + one-hour writes × `cache_write_1h` +
+`output_tokens` × `output`, where fresh input is `input_tokens` minus cache reads
+and cache writes. A model with no price is left out: its `input_tokens +
+output_tokens` are added to `excluded_tokens` and the page shows it as having no
+price, never as free. `api_cost_lower_bound` is true when `api_cost_usd` is only a
+floor: some tokens are excluded, some requests have no token report
+(`requests > token_reports`), or priced usage includes reports from before cache
+writes were captured on a model that lists a cache-write price (five-minute or
+one-hour) above its input price. It is also true for every aggregate of a read
+that could not see all usage: a degraded ledger read (rows dropped), or an hourly
+bucket, and the 24-hour totals over it, whose `history_complete` is false.
+
+The override file is optional and read on every summary; an unreadable file is
+ignored with a warning. Every member is optional:
+
+```json
+{
+ "models": {
+ "claude-opus-5-5": {"input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25},
+ "relay-model": {"alias": "claude-sonnet-5"}
+ },
+ "plans": {"claude_max_20x": {"fee_usd": 200}, "team": {"fee_usd": 30}},
+ "sources": {"src_abc123": {"plan": "claude_max_20x", "renewal_day": 14}}
+}
+```
+
+`models` entries either give prices or alias another model ID. `plans` sets or
+adds a monthly fee per fee-table key. `sources` sets a Source's plan when the
+vendor does not report one (Claude's usage report does not) and its billing-cycle
+renewal day of month (1–31, clamped to the month's length).
+
Days are local-calendar days on the Avibe host. `from_day` and `to_day` bound the
requested window even when no turn fell inside it; `days[]` contains only days that
carry a metered turn (grouped by bucket start date for hourly reports, as described
diff --git a/docs/plans/model-hub-contracts/quota-summary.schema.json b/docs/plans/model-hub-contracts/quota-summary.schema.json
index 630463bfa..44aae61f9 100644
--- a/docs/plans/model-hub-contracts/quota-summary.schema.json
+++ b/docs/plans/model-hub-contracts/quota-summary.schema.json
@@ -2,9 +2,12 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/quota-summary.schema.json",
"title": "Model Hub subscription quota",
- "description": "Rate-limit windows of every hub-held subscription Source, parsed from the vendor's own model-free usage report that the engine reads with the bound grant. A report only: no consumer may feed it back into resolution, admission, or cooldown. It carries parsed fields only, never a grant, token, or raw upstream body. Quota only: a monetary `value` block is reserved for a later contract version and is absent here.",
+ "description": "Rate-limit windows of every hub-held subscription Source, parsed from the vendor's own model-free usage report that the engine reads with the bound grant. A report only: no consumer may feed it back into resolution, admission, or cooldown. It carries parsed fields only, never a grant, token, or raw upstream body. The optional `value` blocks price the Source's own metered usage at list API prices for comparison with the subscription fee; they are a valuation, never an amount charged, and their absence means not reported, never zero.",
"type": "object",
- "required": ["refresh_interval_seconds", "sources"],
+ "required": [
+ "refresh_interval_seconds",
+ "sources"
+ ],
"additionalProperties": false,
"properties": {
"refresh_interval_seconds": {
@@ -15,32 +18,80 @@
"sources": {
"description": "One entry per hub-held subscription Source, in Source order.",
"type": "array",
- "items": { "$ref": "#/definitions/SourceQuota" }
+ "items": {
+ "$ref": "#/definitions/SourceQuota"
+ }
+ },
+ "pending": {
+ "description": "Source IDs whose quota read was still in flight when this response was built. The read keeps running and lands in the cache; a client may re-read shortly instead of presenting those Sources as unavailable. Absent from documents produced before this field existed; read absence as empty.",
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "value": {
+ "$ref": "#/definitions/ValueTotals"
}
},
"definitions": {
"SourceQuota": {
"type": "object",
- "required": ["source_id", "vendor", "display_name", "account_label", "plan", "fetched_at", "state", "windows"],
+ "required": [
+ "source_id",
+ "vendor",
+ "display_name",
+ "account_label",
+ "plan",
+ "fetched_at",
+ "state",
+ "windows"
+ ],
"additionalProperties": false,
"properties": {
- "source_id": { "type": "string", "minLength": 1 },
- "vendor": { "type": "string", "minLength": 1 },
- "display_name": { "type": "string" },
- "account_label": { "type": ["string", "null"] },
+ "source_id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "vendor": {
+ "type": "string",
+ "minLength": 1
+ },
+ "display_name": {
+ "type": "string"
+ },
+ "account_label": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
"plan": {
"description": "Plan name the vendor reported, when it reports one.",
- "type": ["string", "null"],
+ "type": [
+ "string",
+ "null"
+ ],
"maxLength": 64
},
"fetched_at": {
"description": "When `windows` was read. Null until the first good read.",
- "type": ["string", "null"],
+ "type": [
+ "string",
+ "null"
+ ],
"format": "date-time"
},
"state": {
"description": "ok: fresh windows. stale: the latest read failed and `windows` is the last good snapshot. auth_expired: the vendor refused the grant; `windows` may be the last good snapshot. unsupported: this vendor has no quota report. error: no good read exists yet.",
- "enum": ["ok", "stale", "auth_expired", "unsupported", "error"]
+ "enum": [
+ "ok",
+ "stale",
+ "auth_expired",
+ "unsupported",
+ "error"
+ ]
},
"error_key": {
"description": "Present exactly when `state` is not ok.",
@@ -55,22 +106,59 @@
"windows": {
"type": "array",
"maxItems": 16,
- "items": { "$ref": "#/definitions/QuotaWindow" }
+ "items": {
+ "$ref": "#/definitions/QuotaWindow"
+ }
+ },
+ "value": {
+ "$ref": "#/definitions/SourceValue"
+ }
+ },
+ "if": {
+ "properties": {
+ "state": {
+ "const": "ok"
+ }
+ }
+ },
+ "then": {
+ "not": {
+ "required": [
+ "error_key"
+ ]
}
},
- "if": { "properties": { "state": { "const": "ok" } } },
- "then": { "not": { "required": ["error_key"] } },
- "else": { "required": ["error_key"] }
+ "else": {
+ "required": [
+ "error_key"
+ ]
+ }
},
"QuotaWindow": {
"type": "object",
- "required": ["id", "kind", "label", "used_pct", "window_seconds", "resets_at"],
+ "required": [
+ "id",
+ "kind",
+ "label",
+ "used_pct",
+ "window_seconds",
+ "resets_at"
+ ],
"additionalProperties": false,
"properties": {
- "id": { "type": "string", "minLength": 1, "maxLength": 128 },
+ "id": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128
+ },
"kind": {
"description": "session: the shared short window. weekly: the shared weekly window. model_weekly: a weekly window only one model draws on, named by `scope_model`. other: any window the server does not recognise, rendered from `label`.",
- "enum": ["session", "weekly", "model_weekly", "other"]
+ "enum": [
+ "session",
+ "weekly",
+ "model_weekly",
+ "other"
+ ]
},
"label": {
"description": "Upstream name, whitespace-collapsed and bounded. Display copy for `other`; the UI composes its own copy for the known kinds.",
@@ -84,13 +172,276 @@
"minLength": 1,
"maxLength": 64
},
- "used_pct": { "type": "number", "minimum": 0, "maximum": 100 },
- "window_seconds": { "type": ["integer", "null"], "minimum": 1 },
- "resets_at": { "type": ["string", "null"], "format": "date-time" }
+ "used_pct": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 100
+ },
+ "window_seconds": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "minimum": 1
+ },
+ "resets_at": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time"
+ }
},
- "if": { "properties": { "kind": { "const": "model_weekly" } } },
- "then": { "required": ["scope_model"] },
- "else": { "not": { "required": ["scope_model"] } }
+ "if": {
+ "properties": {
+ "kind": {
+ "const": "model_weekly"
+ }
+ }
+ },
+ "then": {
+ "required": [
+ "scope_model"
+ ]
+ },
+ "else": {
+ "not": {
+ "required": [
+ "scope_model"
+ ]
+ }
+ }
+ },
+ "Money": {
+ "description": "USD amount, never negative.",
+ "type": "number",
+ "minimum": 0
+ },
+ "Tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "LocalDay": {
+ "type": "string",
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
+ },
+ "PricedUsage": {
+ "description": "API-price valuation of one span of metered usage, at the current price table.",
+ "type": "object",
+ "required": [
+ "api_cost_usd",
+ "excluded_tokens",
+ "api_cost_lower_bound"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "api_cost_usd": {
+ "$ref": "#/definitions/Money",
+ "description": "Sum over priced usage only."
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Tokens",
+ "description": "input + output tokens of usage whose model has no known price, left out of api_cost_usd."
+ },
+ "api_cost_lower_bound": {
+ "type": "boolean",
+ "description": "True when api_cost_usd is only a floor: some tokens are excluded, some requests have no token report, or some usage was metered before cache writes were captured on a model that lists a cache-write price above input. A floor can show a payback but never a shortfall."
+ }
+ }
+ },
+ "Period": {
+ "type": "object",
+ "required": [
+ "basis",
+ "from_day",
+ "to_day",
+ "renews_on",
+ "api_cost_usd",
+ "excluded_tokens",
+ "api_cost_lower_bound"
+ ],
+ "properties": {
+ "basis": {
+ "description": "billing_cycle: the current cycle from the configured renewal day. rolling_30d: no cycle is known, so the trailing 30 local days ending today.",
+ "enum": [
+ "billing_cycle",
+ "rolling_30d"
+ ]
+ },
+ "from_day": {
+ "$ref": "#/definitions/LocalDay"
+ },
+ "to_day": {
+ "$ref": "#/definitions/LocalDay",
+ "description": "Today; usage after today does not exist yet."
+ },
+ "renews_on": {
+ "description": "Next renewal day, present exactly for billing_cycle.",
+ "oneOf": [
+ {
+ "$ref": "#/definitions/LocalDay"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "api_cost_usd": {
+ "$ref": "#/definitions/Money",
+ "description": "Sum over priced usage only."
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Tokens",
+ "description": "input + output tokens of usage whose model has no known price, left out of api_cost_usd."
+ },
+ "api_cost_lower_bound": {
+ "type": "boolean",
+ "description": "True when api_cost_usd is only a floor: some tokens are excluded, some requests have no token report, or some usage was metered before cache writes were captured on a model that lists a cache-write price above input. A floor can show a payback but never a shortfall."
+ }
+ },
+ "additionalProperties": false,
+ "description": "The span `multiple` compares with the monthly fee, and its valuation (same members as PricedUsage)."
+ },
+ "SourceValue": {
+ "description": "This Source's metered usage priced at list API prices, and how it compares with the plan's monthly fee.",
+ "type": "object",
+ "required": [
+ "currency",
+ "price_table_date",
+ "plan_key",
+ "fee_usd",
+ "multiple",
+ "week",
+ "period"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "currency": {
+ "const": "USD"
+ },
+ "price_table_date": {
+ "description": "Local date the models.dev price table was fetched; null when only local overrides priced anything.",
+ "oneOf": [
+ {
+ "$ref": "#/definitions/LocalDay"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "plan_key": {
+ "description": "Fee-table key the plan resolved to (built-in: claude_pro, claude_max_5x, claude_max_20x, chatgpt_plus, chatgpt_pro; or a key the local override file defines), or null when the plan is unknown.",
+ "type": [
+ "string",
+ "null"
+ ],
+ "maxLength": 64
+ },
+ "fee_usd": {
+ "description": "Monthly fee of the plan, from the built-in table or the local override file. Null when the plan or its fee is unknown; the page then shows no payback.",
+ "oneOf": [
+ {
+ "$ref": "#/definitions/Money"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "multiple": {
+ "description": "period.api_cost_usd / fee_usd, present exactly when fee_usd is positive.",
+ "oneOf": [
+ {
+ "type": "number",
+ "minimum": 0
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "week": {
+ "$ref": "#/definitions/PricedUsage",
+ "description": "The trailing 7 local days ending today."
+ },
+ "period": {
+ "$ref": "#/definitions/Period"
+ }
+ }
+ },
+ "ValueTotals": {
+ "description": "Sums across every Source that carries a `value` block.",
+ "type": "object",
+ "required": [
+ "currency",
+ "price_table_date",
+ "week",
+ "period"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "currency": {
+ "const": "USD"
+ },
+ "price_table_date": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/LocalDay"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "week": {
+ "$ref": "#/definitions/PricedUsage",
+ "description": "Every valued Source."
+ },
+ "period": {
+ "description": "Only the Sources with a known fee, so the multiple compares like with like. Null when no Source has a known fee.",
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "type": "object",
+ "required": [
+ "sources",
+ "fee_usd",
+ "multiple",
+ "api_cost_usd",
+ "excluded_tokens",
+ "api_cost_lower_bound"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "sources": {
+ "type": "integer",
+ "minimum": 1,
+ "description": "How many Sources the period totals cover."
+ },
+ "fee_usd": {
+ "$ref": "#/definitions/Money"
+ },
+ "multiple": {
+ "type": "number",
+ "minimum": 0
+ },
+ "api_cost_usd": {
+ "$ref": "#/definitions/Money"
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Tokens"
+ },
+ "api_cost_lower_bound": {
+ "type": "boolean"
+ }
+ }
+ }
+ ]
+ }
+ }
}
}
}
diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.json
index b2ef261dc..83c14ad30 100644
--- a/docs/plans/model-hub-contracts/usage-summary.schema.json
+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json
@@ -16,11 +16,31 @@
{
"not": {
"anyOf": [
- {"required": ["window_key"]},
- {"required": ["granularity"]},
- {"required": ["from_at"]},
- {"required": ["to_at"]},
- {"required": ["buckets"]}
+ {
+ "required": [
+ "window_key"
+ ]
+ },
+ {
+ "required": [
+ "granularity"
+ ]
+ },
+ {
+ "required": [
+ "from_at"
+ ]
+ },
+ {
+ "required": [
+ "to_at"
+ ]
+ },
+ {
+ "required": [
+ "buckets"
+ ]
+ }
]
}
},
@@ -69,11 +89,19 @@
},
"window_key": {
"description": "Modern report selector served by the API.",
- "enum": ["24h", "7d", "30d", "60d"]
+ "enum": [
+ "24h",
+ "7d",
+ "30d",
+ "60d"
+ ]
},
"granularity": {
"description": "Temporal granularity of the dense bucket matrix.",
- "enum": ["hour", "day"]
+ "enum": [
+ "hour",
+ "day"
+ ]
},
"from_at": {
"description": "RFC3339 start of the first dense bucket, with the server-local UTC offset.",
@@ -92,6 +120,9 @@
"items": {
"$ref": "#/definitions/UsageBucket"
}
+ },
+ "pricing": {
+ "$ref": "#/definitions/Pricing"
}
},
"definitions": {
@@ -134,6 +165,31 @@
},
"output_tokens": {
"$ref": "#/definitions/Count"
+ },
+ "cache_write_input_tokens": {
+ "$ref": "#/definitions/Count",
+ "description": "Subset of input_tokens written to the prompt cache (Anthropic `cache_creation_input_tokens`), disjoint from cached_input_tokens. Zero for protocols that report no cache writes. Absent from documents produced before cache writes were metered; read absence as zero."
+ },
+ "cache_write_1h_input_tokens": {
+ "$ref": "#/definitions/Count",
+ "description": "Subset of cache_write_input_tokens written with the one-hour cache lifetime (Anthropic `cache_creation.ephemeral_1h_input_tokens`); the rest used the five-minute lifetime."
+ },
+ "cache_write_uncaptured_reports": {
+ "$ref": "#/definitions/Count",
+ "description": "Subset of token_reports metered before cache writes were captured. Their cache writes, if any, are inside input_tokens but not in cache_write_input_tokens."
+ },
+ "api_cost_usd": {
+ "description": "What this usage would cost at the vendor's list API price, in `pricing.currency`, at the current price table — never the price in force when the call ran. A valuation for comparison, never an amount charged. Present exactly when `pricing` is. Usage whose model has no price is left out and counted in excluded_tokens, never priced as zero.",
+ "type": "number",
+ "minimum": 0
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Count",
+ "description": "input_tokens + output_tokens of the usage whose model has no known price, which api_cost_usd therefore leaves out. Present exactly when `pricing` is."
+ },
+ "api_cost_lower_bound": {
+ "description": "True when api_cost_usd is only a floor: some tokens are excluded, some requests have no token report, or some priced usage was metered before cache writes were captured on a model that lists a cache-write price above input, or the read could not see all usage (a degraded ledger read, or an incomplete hourly bucket). Present exactly when `pricing` is.",
+ "type": "boolean"
}
}
},
@@ -172,6 +228,24 @@
},
"output_tokens": {
"$ref": "#/definitions/Count"
+ },
+ "cache_write_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_input_tokens"
+ },
+ "cache_write_1h_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_1h_input_tokens"
+ },
+ "cache_write_uncaptured_reports": {
+ "$ref": "#/definitions/Counters/properties/cache_write_uncaptured_reports"
+ },
+ "api_cost_usd": {
+ "$ref": "#/definitions/Counters/properties/api_cost_usd"
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Counters/properties/excluded_tokens"
+ },
+ "api_cost_lower_bound": {
+ "$ref": "#/definitions/Counters/properties/api_cost_lower_bound"
}
}
},
@@ -233,7 +307,10 @@
},
"label": {
"description": "Joined from current Source config; null once the Source is gone.",
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
},
"requests": {
"$ref": "#/definitions/Count"
@@ -252,7 +329,10 @@
},
"last_metered_at": {
"description": "When this Source last had a call metered, served or billed-and-failed.",
- "type": ["string", "null"],
+ "type": [
+ "string",
+ "null"
+ ],
"format": "date-time"
},
"models": {
@@ -261,6 +341,24 @@
"items": {
"$ref": "#/definitions/ModelUsage"
}
+ },
+ "cache_write_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_input_tokens"
+ },
+ "cache_write_1h_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_1h_input_tokens"
+ },
+ "cache_write_uncaptured_reports": {
+ "$ref": "#/definitions/Counters/properties/cache_write_uncaptured_reports"
+ },
+ "api_cost_usd": {
+ "$ref": "#/definitions/Counters/properties/api_cost_usd"
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Counters/properties/excluded_tokens"
+ },
+ "api_cost_lower_bound": {
+ "$ref": "#/definitions/Counters/properties/api_cost_lower_bound"
}
}
},
@@ -284,7 +382,10 @@
},
"label": {
"description": "The model identity this row was metered under, joined from current Source config; null once the model is gone.",
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
},
"requests": {
"$ref": "#/definitions/Count"
@@ -300,6 +401,28 @@
},
"output_tokens": {
"$ref": "#/definitions/Count"
+ },
+ "cache_write_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_input_tokens"
+ },
+ "cache_write_1h_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_1h_input_tokens"
+ },
+ "cache_write_uncaptured_reports": {
+ "$ref": "#/definitions/Counters/properties/cache_write_uncaptured_reports"
+ },
+ "api_cost_usd": {
+ "$ref": "#/definitions/Counters/properties/api_cost_usd"
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Counters/properties/excluded_tokens"
+ },
+ "api_cost_lower_bound": {
+ "$ref": "#/definitions/Counters/properties/api_cost_lower_bound"
+ },
+ "priced": {
+ "description": "Whether a price was found for this model. Present exactly when `pricing` is; false means the UI shows no price for it and its tokens are in excluded_tokens.",
+ "type": "boolean"
}
}
},
@@ -332,6 +455,49 @@
},
"output_tokens": {
"$ref": "#/definitions/Count"
+ },
+ "cache_write_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_input_tokens"
+ },
+ "cache_write_1h_input_tokens": {
+ "$ref": "#/definitions/Counters/properties/cache_write_1h_input_tokens"
+ },
+ "cache_write_uncaptured_reports": {
+ "$ref": "#/definitions/Counters/properties/cache_write_uncaptured_reports"
+ },
+ "api_cost_usd": {
+ "$ref": "#/definitions/Counters/properties/api_cost_usd"
+ },
+ "excluded_tokens": {
+ "$ref": "#/definitions/Counters/properties/excluded_tokens"
+ },
+ "api_cost_lower_bound": {
+ "$ref": "#/definitions/Counters/properties/api_cost_lower_bound"
+ }
+ }
+ },
+ "Pricing": {
+ "description": "The price table the cost fields were computed from: models.dev list prices under the local override file. Absent from documents produced before API-price valuation existed, and whenever no price table could be read; the cost fields are then absent too.",
+ "type": "object",
+ "required": [
+ "currency",
+ "price_table_date"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "currency": {
+ "const": "USD"
+ },
+ "price_table_date": {
+ "description": "Local date the models.dev price table was last fetched; null when none has been fetched and only local overrides priced anything.",
+ "oneOf": [
+ {
+ "$ref": "#/definitions/LocalDay"
+ },
+ {
+ "type": "null"
+ }
+ ]
}
}
}
@@ -346,7 +512,13 @@
"token_reports": 9,
"input_tokens": 148230,
"cached_input_tokens": 96010,
- "output_tokens": 4120
+ "output_tokens": 4120,
+ "cache_write_input_tokens": 20100,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": 0,
+ "api_cost_usd": 0.43723,
+ "excluded_tokens": 0,
+ "api_cost_lower_bound": false
},
"sources": [
{
@@ -366,9 +538,22 @@
"token_reports": 9,
"input_tokens": 148230,
"cached_input_tokens": 96010,
- "output_tokens": 4120
+ "output_tokens": 4120,
+ "cache_write_input_tokens": 20100,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": 0,
+ "api_cost_usd": 0.43723,
+ "excluded_tokens": 0,
+ "api_cost_lower_bound": false,
+ "priced": true
}
- ]
+ ],
+ "cache_write_input_tokens": 20100,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": 0,
+ "api_cost_usd": 0.43723,
+ "excluded_tokens": 0,
+ "api_cost_lower_bound": false
}
],
"days": [
@@ -378,9 +563,19 @@
"token_reports": 9,
"input_tokens": 148230,
"cached_input_tokens": 96010,
- "output_tokens": 4120
+ "output_tokens": 4120,
+ "cache_write_input_tokens": 20100,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": 0,
+ "api_cost_usd": 0.43723,
+ "excluded_tokens": 0,
+ "api_cost_lower_bound": false
}
- ]
+ ],
+ "pricing": {
+ "currency": "USD",
+ "price_table_date": "2026-08-18"
+ }
}
]
}
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 1a23f6ca8..c77ea8d25 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -31,6 +31,7 @@ capabilities:
- tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
+ - tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
- tests/e2e/test_model_hub_guards.py
- tests/e2e/test_model_hub_migration.py
- tests/e2e/test_model_hub_migration_persisted.py
@@ -75,11 +76,14 @@ capabilities:
- tests/test_model_hub_usage.py
- tests/test_ui_server_fastapi.py
- tests/test_model_hub_quota.py
+ - tests/test_model_hub_pricing.py
- tests/test_local_deps.py
- tests/test_opencode_server.py
- tests/test_runtime_activation.py
- ui/src/components/settings/models/UsageTab.test.tsx
- ui/src/components/settings/models/QuotaTab.test.tsx
+ - ui/src/components/settings/models/usageProjection.test.ts
+ - ui/src/components/settings/models/format.test.ts
- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
- ui/src/components/settings/models/RouteChainDialog.test.tsx
- ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 6d76fced2..e8e58d7fa 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -25,7 +25,10 @@ capability:
- tests/test_model_hub_usage.py
- tests/test_ui_server_fastapi.py
- tests/test_model_hub_quota.py
+ - tests/test_model_hub_pricing.py
- ui/src/components/settings/models/QuotaTab.test.tsx
+ - ui/src/components/settings/models/usageProjection.test.ts
+ - ui/src/components/settings/models/format.test.ts
- tests/test_local_deps.py
- tests/test_opencode_server.py
- tests/test_runtime_activation.py
@@ -52,6 +55,7 @@ capability:
- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
- tests/test_model_hub_persisted_migration.py
- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
+ - tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
- tests/e2e/test_model_hub_guards.py
- tests/e2e/test_model_hub_migration.py
- tests/e2e/test_model_hub_migration_persisted.py
@@ -681,6 +685,43 @@ scenarios:
kind: observation
layer: unit
test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-027
+ - id: MH-USAGE-028
+ name: API price sums only across rows that all carry one and renders as dollars with a sub-cent floor
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/usageProjection.test.ts::MH-USAGE-028
+ related_tests:
+ - ui/src/components/settings/models/format.test.ts::MH-USAGE-028
+ - id: MH-USAGE-029
+ name: The usage report states API price as not a charge and names unpriced tokens and the price table
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-029
+ related_tests:
+ - ui/e2e/model-catalog/usage.spec.ts
+ - id: MH-USAGE-030
+ name: The usage report offers the API-price metric only when the server priced the report
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-030
+ - id: MH-USAGE-031
+ name: The Chinese usage report reads API price as a conversion, never a charge
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-031
+ - id: MH-USAGE-032
+ name: A floor API price reads 「≥」 in the chart legend and bucket detail, a floor of zero included
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-032
+ related_tests:
+ - ui/src/components/settings/models/format.test.ts::MH-USAGE-032
+ - ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-024
- id: MH-USAGE-BACKEND-001
name: Modern usage reports keep dense hourly buckets and distinct Unicode Source/model identities
status: covered
@@ -853,6 +894,148 @@ scenarios:
kind: recovery
layer: unit
test: tests/test_model_hub_retry_policy.py::test_routing_blocker_drops_the_blocked_grants_quota_reading
+ - id: MH-QUOTA-019
+ name: The Claude plan is read best-effort from the OAuth profile and a missed read keeps the last known plan
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_claude_plan_is_read_from_the_oauth_profile_organization
+ related_tests:
+ - tests/test_model_hub_quota.py::test_claude_plan_ignores_an_unreadable_profile
+ - tests/test_model_hub_quota.py::test_adapter_adds_the_claude_plan_from_the_profile_and_never_fails_on_it
+ - tests/test_model_hub_quota.py::test_a_missing_plan_on_one_read_keeps_the_last_known_plan
+ - id: MH-QUOTA-020
+ name: A quota read past the page deadline is named pending, and the page re-reads it soon a bounded number of times until it lands
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_summary_names_the_sources_still_being_read
+ related_tests:
+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-QUOTA-020
+ - id: MH-QUOTA-021
+ name: Payback reads as paid at 1.1x and over, just even from 1x, and short below the fee
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-021
+ - id: MH-QUOTA-022
+ name: The quota tab states week and period value at API price against the fee, with the price table date
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-022
+ - id: MH-QUOTA-023
+ name: A subscription short of its fee says by how much, and an unknown plan hides payback but keeps the value
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-023
+ - id: MH-QUOTA-024
+ name: A model with no price reads as no price and is counted, never priced as zero
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-024
+ - id: MH-QUOTA-025
+ name: A Source still being read shows a loading line instead of an unavailable reading
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-025
+ - id: MH-QUOTA-026
+ name: The quota value copy renders in English through the same keys
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-026
+ - id: MH-PRICE-001
+ name: A models.dev price fills a missing cache price from input and a one-hour cache write from twice input
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_model_price_reads_models_dev_cost_and_fills_missing_cache_prices
+ - id: MH-PRICE-002
+ name: Context tags, snapshot dates, provider prefixes, and case do not change the list price a model ID resolves to
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_model_ids_normalize_to_the_price_table_spelling
+ - id: MH-PRICE-003
+ name: Real ledger model IDs price from their first-party provider, directly or through the alias map
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_real_ledger_model_ids_resolve_through_the_alias_map
+ - id: MH-PRICE-004
+ name: The local price override file wins over models.dev, and an unreadable one falls back to it
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_override_file_wins_over_models_dev_and_can_alias
+ related_tests:
+ - tests/test_model_hub_pricing.py::test_price_table_reads_the_override_file_and_survives_a_bad_one
+ - id: MH-PRICE-005
+ name: Each token class takes its own price, a model with no price is excluded and counted, and any unknown part (excluded tokens, unreported requests, uncaptured cache writes) makes a lower bound
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_row_cost_prices_each_token_class_and_excludes_unknown_models
+ related_tests:
+ - tests/test_model_hub_pricing.py::test_usage_metered_before_cache_writes_were_captured_is_a_lower_bound
+ - tests/test_model_hub_pricing.py::test_priced_usage_with_unknown_parts_is_a_floor
+ - id: MH-PRICE-006
+ name: Every priced usage total is the sum of its rows, with unpriced tokens counted apart
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_usage_report_prices_totals_as_the_sum_of_their_rows
+ - id: MH-PRICE-007
+ name: A ledger row written before cache-write capture reads as zero writes and uncaptured, without a rewrite
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_rows_written_before_cache_writes_read_as_uncaptured
+ - id: MH-PRICE-008
+ name: Reported and configured plans resolve to the built-in or overridden monthly fee
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_reported_plans_resolve_to_fee_table_keys
+ related_tests:
+ - tests/test_model_hub_pricing.py::test_override_file_sets_a_sources_plan_fee_and_renewal_day
+ - id: MH-PRICE-009
+ name: The value period is the current billing cycle when a renewal day is known, else the trailing 30 days
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_billing_period_is_the_current_cycle_or_the_trailing_30_days
+ - id: MH-PRICE-010
+ name: Each subscription's week and period value is compared with its plan fee, and payback totals count only known fees
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_quota_values_compare_each_period_with_its_plan_fee
+ related_tests:
+ - tests/test_model_hub_pricing.py::test_daily_costs_answer_only_for_the_given_sources
+ - tests/test_model_hub_api.py::test_quota_endpoints_serve_hub_subscriptions_and_rate_limit_forced_refresh
+ - id: MH-PRICE-011
+ name: Priced daily and hourly usage reads stay inside the usage-summary contract
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_priced_usage_reads_match_the_usage_summary_contract
+ - id: MH-PRICE-SCENARIO-001
+ name: A metered stream's cache writes and an unreported call reach the served usage and quota value at API price, as a floor
+ status: covered
+ kind: happy_path
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py::test_mh_price_scenario_001_a_metered_stream_is_valued_through_usage_and_quota
+ - id: MH-PRICE-012
+ name: Any unpriced, unreported, or uncaptured part reaches every usage aggregate and quota value above it as a floor
+ status: covered
+ kind: safety
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_no_aggregate_over_an_unknown_part_is_published_as_exact
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py b/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
new file mode 100644
index 000000000..650f4a00a
--- /dev/null
+++ b/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
@@ -0,0 +1,126 @@
+"""Model Hub API-price valuation, closed loop: metered wire to served usage and quota value.
+
+One upstream response travels the production path: protocol usage extraction,
+the shared usage writer, the persisted ledger, the service's price lookup, and the
+usage and quota reads the Web UI renders. The unit suites pin each layer; this
+proves the layers are wired to each other.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+from jsonschema import Draft7Validator, FormatChecker
+from referencing import Registry, Resource
+
+from core.handlers.model_hub.pricing import PriceTable
+from core.handlers.model_hub.stream_wire import extract_protocol_usage
+from tests.scenario_harness.model_hub import (
+ MemoryModelHubStore,
+ ModelHubScenarioAdapter,
+ config_with_sources,
+ service_for,
+ source,
+)
+
+
+CONTRACTS = Path("docs/plans/model-hub-contracts")
+NOW = datetime(2026, 9, 25, 4, 0, tzinfo=timezone.utc)
+CATALOG = {
+ "anthropic": {
+ "models": {"claude-opus-5": {"cost": {"input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25}}}
+ }
+}
+VENDOR_MAP = {"families": [{"prefix": "claude-", "vendor_id": "anthropic"}]}
+# An Anthropic message_start as the upstream streams it: fresh input, a cache read,
+# and a cache write split into its five-minute and one-hour lifetimes.
+MESSAGE_START = {
+ "type": "message_start",
+ "message": {
+ "usage": {
+ "input_tokens": 100_000,
+ "cache_read_input_tokens": 600_000,
+ "cache_creation_input_tokens": 300_000,
+ "cache_creation": {"ephemeral_5m_input_tokens": 200_000, "ephemeral_1h_input_tokens": 100_000},
+ "output_tokens": 0,
+ }
+ },
+}
+MESSAGE_DELTA = {"type": "message_delta", "usage": {"output_tokens": 100_000}}
+# fresh 100k × 5 + read 600k × 0.5 + 5m 200k × 6.25 + 1h 100k × 10 + out 100k × 25
+EXPECTED_USD = 0.5 + 0.3 + 1.25 + 1.0 + 2.5
+
+
[email protected](autouse=True)
+def _enable_model_hub(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
+def _assert_valid(name: str, payload: dict) -> None:
+ registry = Registry()
+ for path in sorted(CONTRACTS.glob("*.schema.json")):
+ schema = json.loads(path.read_text(encoding="utf-8"))
+ registry = registry.with_resource(schema["$id"], Resource.from_contents(schema))
+ schema = json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
+ errors = list(Draft7Validator(schema, registry=registry, format_checker=FormatChecker()).iter_errors(payload))
+ assert not errors, [error.message for error in errors]
+
+
+class QuotaAdapter(ModelHubScenarioAdapter):
+ async def subscription_quota(self, source_id, vendor, credential_ref):
+ return {"plan": "max_20x", "windows": [{
+ "id": "five_hour", "kind": "session", "label": "five_hour", "used_pct": 12.0,
+ "window_seconds": 18000, "resets_at": "2026-09-25T08:00:00Z",
+ }]}
+
+
+def _service(tmp_path: Path):
+ config = config_with_sources([source("src_max", ["claude-opus-5"], kind="subscription")])
+ service = service_for(tmp_path, MemoryModelHubStore(config), QuotaAdapter(), now=lambda: NOW)
+ service.price_table = lambda: PriceTable(
+ catalog=CATALOG, vendor_map=VENDOR_MAP, overrides={}, price_table_date="2026-09-23"
+ )
+ return service
+
+
+def test_mh_price_scenario_001_a_metered_stream_is_valued_through_usage_and_quota(tmp_path):
+ """MH-PRICE-SCENARIO-001: A metered stream's cache writes reach the served usage and quota value at API price."""
+
+ service = _service(tmp_path)
+ report = extract_protocol_usage("anthropic", MESSAGE_START).merge(
+ extract_protocol_usage("anthropic", MESSAGE_DELTA)
+ )
+
+ async def meter() -> None:
+ service.usage_writer.record(source_id="src_max", model_id="claude-opus-5", usage=report, at=NOW)
+ # A second call whose stream ended without a usage report.
+ service.usage_writer.record(source_id="src_max", model_id="claude-opus-5", usage=None, at=NOW)
+ assert await service.usage_writer.drain(timeout=5) == 0
+
+ asyncio.run(meter())
+
+ for window in ("24h", "7d"):
+ usage = service.usage_summary(window=window)
+ _assert_valid("usage-summary.schema.json", usage)
+ totals = usage["totals"]
+ assert totals["cache_write_input_tokens"] == 300_000
+ assert totals["cache_write_1h_input_tokens"] == 100_000
+ assert totals["api_cost_usd"] == pytest.approx(EXPECTED_USD)
+ # The unreported call makes every figure above it a floor, never exact.
+ assert totals["api_cost_lower_bound"] is True
+ assert usage["pricing"]["price_table_date"] == "2026-09-23"
+
+ quota = asyncio.run(service.quota_summary())
+ _assert_valid("quota-summary.schema.json", quota)
+ value = quota["sources"][0]["value"]
+ assert value["plan_key"] == "claude_max_20x"
+ assert value["fee_usd"] == 200
+ assert value["week"]["api_cost_usd"] == pytest.approx(EXPECTED_USD)
+ assert value["week"]["api_cost_lower_bound"] is True
+ assert value["period"]["api_cost_lower_bound"] is True
+ assert quota["value"]["period"]["api_cost_lower_bound"] is True
+ assert "cred_" not in json.dumps(quota)
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index d8ad0ea57..a41ee8514 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -47,6 +47,7 @@ from core.handlers.model_hub.adapter import (
)
from core.handlers.model_hub.catalog_admission import admissible_backend_model
from core.handlers.model_hub.errors import ModelDiscoveryError
+from core.handlers.model_hub.pricing import PriceTable
from core.handlers.model_hub.identifiers import canonical_model_id, usage_ledger_key
from core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent
from core.handlers.model_hub.oauth import (
@@ -403,6 +404,16 @@ class FakeAdapter:
)
+_PRICE_TABLE = PriceTable(
+ catalog={"anthropic": {"models": {"claude-opus-5": {"cost": {
+ "input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25,
+ }}}}},
+ vendor_map={"families": [{"prefix": "claude-", "vendor_id": "anthropic"}]},
+ overrides={},
+ price_table_date="2026-07-22",
+)
+
+
def _service(tmp_path, adapter=None):
store = MemoryStore()
adapter = adapter or FakeAdapter()
@@ -424,6 +435,7 @@ def _service(tmp_path, adapter=None):
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
requested_model_override=lambda backend: store.requested_model(backend),
migration_home=tmp_path / "native-home",
+ price_table=lambda: _PRICE_TABLE,
)
return service, store, adapter
@@ -9629,6 +9641,14 @@ def test_quota_endpoints_serve_hub_subscriptions_and_rate_limit_forced_refresh(m
assert "cred_" not in json.dumps(body)
assert sorted(calls) == ["src_codexsub01", "src_subscribe01"]
+ # Each subscription carries its API-price value; an unknown plan hides only the payback.
+ assert sources["src_subscribe01"]["value"]["plan_key"] is None
+ assert sources["src_subscribe01"]["value"]["multiple"] is None
+ assert sources["src_subscribe01"]["value"]["period"]["basis"] == "rolling_30d"
+ assert body["quota"]["value"]["price_table_date"] == "2026-07-22"
+ assert body["quota"]["value"]["period"] is None
+ assert "pending" not in body["quota"]
+
headers = csrf_headers(client, origin)
refreshed = client.post("/api/models/quota/refresh", headers=headers, base_url=origin)
assert refreshed.status_code == 200
diff --git a/tests/test_model_hub_pricing.py b/tests/test_model_hub_pricing.py
new file mode 100644
index 000000000..8817bd352
--- /dev/null
+++ b/tests/test_model_hub_pricing.py
@@ -0,0 +1,517 @@
+"""Model Hub API-price valuation: price resolution, cost math, and subscription value.
+
+A valuation is a report, never a bill. The properties under test are that a price
+comes from the right place (override file, then models.dev's first-party
+provider, then an alias), that a model without a price is excluded and counted
+rather than priced as zero, and that every total is the sum of its rows.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import date, datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+
+from core.handlers.model_hub.pricing import (
+ PRICE_OVERRIDE_FILENAME,
+ Cost,
+ ModelPrice,
+ PriceTable,
+ billing_period,
+ load_price_table,
+ model_price,
+ normalize_model_id,
+ plan_key,
+ quota_values,
+ row_cost,
+)
+from core.handlers.model_hub.stream_wire import ProtocolUsageReport
+from core.handlers.model_hub.usage import BoundedUsageLedger, SourceIdentity, UsageCall
+
+# Shapes as models.dev publishes them (USD per million tokens), at 2026-09 prices.
+CATALOG = {
+ "anthropic": {
+ "models": {
+ "claude-opus-5": {"cost": {"input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25}},
+ "claude-fable-5-1": {"cost": {"input": 10, "output": 50, "cache_read": 0.25, "cache_write": 12.5}},
+ "claude-haiku-4-5": {"cost": {"input": 1, "output": 5, "cache_read": 0.1, "cache_write": 1.25}},
+ }
+ },
+ "openai": {
+ "models": {
+ "gpt-5": {"cost": {"input": 1.25, "output": 10, "cache_read": 0.125}},
+ "gpt-5.5": {"cost": {"input": 5, "output": 30, "cache_read": 0.5}},
+ "gpt-5.6-sol": {"cost": {"input": 4, "output": 20, "cache_read": 0.4, "cache_write": 5}},
+ "gpt-5.6-luna": {"cost": {"input": 0.2, "output": 1.2, "cache_read": 0.02, "cache_write": 0.25}},
+ "gpt-6-astra": {"cost": {"input": 10, "output": 50, "cache_read": 1, "cache_write": 12.5}},
+ }
+ },
+ "xai": {"models": {"grok-4.6": {"cost": {"input": 2, "output": 6, "cache_read": 0.5}}}},
+ # An aggregator relisting a first-party model at its own price is never read.
+ "openrouter": {"models": {"claude-opus-5": {"cost": {"input": 99, "output": 99}}}},
+}
+VENDOR_MAP = {
+ "families": [
+ {"prefix": "claude-", "vendor_id": "anthropic"},
+ {"prefix": "gpt-", "vendor_id": "openai"},
+ {"prefix": "grok-", "vendor_id": "xai"},
+ ]
+}
+FETCHED_AT = datetime(2026, 9, 23, 12, 0).timestamp()
+
+
+def _table(overrides=None) -> PriceTable:
+ return PriceTable(catalog=CATALOG, vendor_map=VENDOR_MAP, overrides=overrides or {}, price_table_date="2026-09-23")
+
+
+def test_model_price_reads_models_dev_cost_and_fills_missing_cache_prices():
+ """MH-PRICE-001: A missing cache price is input; a one-hour cache write is twice input unless listed."""
+
+ assert model_price({"input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25}) == ModelPrice(
+ input=5, output=25, cache_read=0.5, cache_write=6.25, cache_write_1h=10, charges_cache_writes=True
+ )
+ assert model_price({"input": 2, "output": 6}) == ModelPrice(
+ input=2, output=6, cache_read=2, cache_write=2, cache_write_1h=4
+ )
+ assert model_price({"input": 2, "output": 6, "cache_write_1h": 3}).cache_write_1h == 3
+ for bad in (None, {}, {"input": 1}, {"input": -1, "output": 1}, {"input": True, "output": 1},
+ {"input": float("nan"), "output": 1}, {"input": 1e9, "output": 1}):
+ assert model_price(bad) is None
+
+
+ ("reported", "normalized"),
+ [
+ ("claude-opus-5[1m]", "claude-opus-5"),
+ ("anthropic/claude-opus-5", "claude-opus-5"),
+ ("claude-haiku-4-5-20251001", "claude-haiku-4-5"),
+ ("claude-opus-4-1@20250805", "claude-opus-4-1"),
+ ("gpt-5-2025-08-07", "gpt-5"),
+ (" GPT-5.5 ", "gpt-5.5"),
+ ],
+)
+def test_model_ids_normalize_to_the_price_table_spelling(reported, normalized):
+ """MH-PRICE-002: Context tags, snapshot dates, provider prefixes, and case do not change a list price."""
+
+ assert normalize_model_id(reported) == normalized
+
+
+ ("ledger_model_id", "input_price"),
+ [
+ # Every model ID found in a real usage ledger, and the price it resolves to.
+ ("gpt-5.6-sol", 4),
+ ("gpt-6-astra", 10),
+ ("grok-4.6", 2),
+ ("claude-fable-5-1", 10),
+ ("claude-opus-5", 5),
+ ("claude-opus-5-5", 5), # not yet on models.dev: aliased to its predecessor
+ ("gpt-5.5", 5),
+ ("gpt-5.6-luna", 0.2),
+ ("relay-model", None), # a relay's own name has no list price
+ # Names Claude Code and Codex send.
+ ("claude-opus-5[1m]", 5),
+ ("claude-haiku-4-5-20251001", 1),
+ ("opus", 5),
+ ("haiku", 1),
+ ("gpt-5-codex", 1.25),
+ ("gpt-5.1-codex-max", None), # alias target gpt-5.1 is not in this fixture
+ ],
+)
+def test_real_ledger_model_ids_resolve_through_the_alias_map(ledger_model_id, input_price):
+ """MH-PRICE-003: Real ledger IDs price from the first-party provider, directly or through an alias."""
+
+ price = _table().price(ledger_model_id)
+ assert (price.input if price else None) == input_price
+
+
+def test_override_file_wins_over_models_dev_and_can_alias():
+ """MH-PRICE-004: An override price or alias wins; an unusable override falls through to models.dev."""
+
+ table = _table({
+ "models": {
+ "claude-opus-5": {"input": 1, "output": 2},
+ "relay-model": {"alias": "claude-fable-5-1"},
+ "grok-4.6": {"input": "free"},
+ "loop-a": {"alias": "loop-b"},
+ "loop-b": {"alias": "loop-a"},
+ }
+ })
+ assert table.price("claude-opus-5[1m]").input == 1
+ # The alias from the built-in map now lands on the override too.
+ assert table.price("claude-opus-5-5").input == 1
+ assert table.price("relay-model").input == 10
+ assert table.price("grok-4.6").input == 2
+ assert table.price("loop-a") is None
+
+
+def test_price_table_reads_the_override_file_and_survives_a_bad_one(tmp_path):
+ """MH-PRICE-004: The state-dir override file is read per table; an unreadable one prices from models.dev."""
+
+ def load():
+ return load_price_table(
+ tmp_path,
+ catalog_loader=lambda: (CATALOG, FETCHED_AT),
+ vendor_map_loader=lambda: VENDOR_MAP,
+ )
+
+ assert load().price("claude-opus-5").input == 5
+ assert load().price_table_date == "2026-09-23"
+ (tmp_path / PRICE_OVERRIDE_FILENAME).write_text(
+ json.dumps({"models": {"claude-opus-5": {"input": 3, "output": 4}}}), encoding="utf-8"
+ )
+ assert load().price("claude-opus-5").input == 3
+ (tmp_path / PRICE_OVERRIDE_FILENAME).write_text("{not json", encoding="utf-8")
+ assert load().price("claude-opus-5").input == 5
+
+ def broken():
+ raise OSError("offline")
+
+ bare = load_price_table(tmp_path, catalog_loader=broken, vendor_map_loader=lambda: VENDOR_MAP)
+ assert bare.price("claude-opus-5") is None
+ assert bare.price_table_date is None
+
+
+def test_row_cost_prices_each_token_class_and_excludes_unknown_models():
+ """MH-PRICE-005: Fresh, cache-read, 5m and 1h cache-write, and output tokens each take their own price."""
+
+ opus = _table().price("claude-opus-5")
+ row = {
+ "input_tokens": 1_000_000,
+ "cached_input_tokens": 600_000,
+ "cache_write_input_tokens": 300_000,
+ "cache_write_1h_input_tokens": 100_000,
+ "output_tokens": 100_000,
+ }
+ # fresh 100k × 5 + read 600k × 0.5 + 5m 200k × 6.25 + 1h 100k × 10 + out 100k × 25
+ assert row_cost(row, opus) == Cost(api_cost_usd=0.5 + 0.3 + 1.25 + 1.0 + 2.5)
+ unknown = row_cost(row, None)
+ assert unknown == Cost(api_cost_usd=0, excluded_tokens=1_100_000)
+
+
+def test_usage_metered_before_cache_writes_were_captured_is_a_lower_bound():
+ """MH-PRICE-005: Uncaptured reports make a total a lower bound only where cache writes cost extra."""
+
+ row = {"input_tokens": 1000, "output_tokens": 10, "cache_write_uncaptured_reports": 1}
+ assert row_cost(row, _table().price("claude-opus-5")).api_cost_lower_bound is True
+ assert row_cost(row, _table().price("grok-4.6")).api_cost_lower_bound is False
+ # A listed one-hour premium counts even when the five-minute write is priced as input.
+ assert row_cost(row, model_price({"input": 2, "output": 6, "cache_write_1h": 4})).api_cost_lower_bound is True
+ assert row_cost(row, model_price({"input": 2, "output": 6})).api_cost_lower_bound is False
+
+
+def test_priced_usage_with_unknown_parts_is_a_floor():
+ """MH-PRICE-005: Requests without a token report, or tokens with no price, make the priced figure a lower bound."""
+
+ grok = _table().price("grok-4.6")
+ reported = {"requests": 2, "token_reports": 2, "input_tokens": 1000, "output_tokens": 10}
+ assert row_cost(reported, grok).api_cost_lower_bound is False
+ unreported = {**reported, "requests": 3}
+ assert row_cost(unreported, grok).api_cost_lower_bound is True
+ # An unpriced model's unreported request is a floor too, not $0 exact.
+ silent = {"requests": 1, "token_reports": 0}
+ assert row_cost(silent, None).fields() == {"api_cost_usd": 0, "excluded_tokens": 0, "api_cost_lower_bound": True}
+ assert Cost(1.0, excluded_tokens=5).fields()["api_cost_lower_bound"] is True
+ assert Cost(1.0).fields()["api_cost_lower_bound"] is False
+
+
+def test_usage_report_prices_totals_as_the_sum_of_their_rows(tmp_path):
+ """MH-PRICE-006: A fixture with a known total: every level sums its rows, unknown models are counted apart."""
+
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(tmp_path / "usage.json", now=lambda: now)
+ anthropic = ProtocolUsageReport.of(
+ input_tokens=1_000_000, cached_input_tokens=600_000, output_tokens=100_000,
+ cache_write_input_tokens=300_000, cache_write_1h_input_tokens=100_000,
+ )
+ ledger.record_many([
+ UsageCall(source_id="src_claude", model_id="claude-opus-5[1m]", usage=anthropic, at=now),
+ UsageCall(source_id="src_codex", model_id="gpt-5.5",
+ usage=ProtocolUsageReport.of(input_tokens=2_000_000, cached_input_tokens=1_000_000,
+ output_tokens=100_000), at=now),
+ UsageCall(source_id="src_relay", model_id="relay-model",
+ usage=ProtocolUsageReport.of(input_tokens=700, cached_input_tokens=0, output_tokens=300), at=now),
+ ])
+ summary = ledger.summary(days=7, now=now, identities=[
+ SourceIdentity("src_claude", "Claude", ["claude-opus-5[1m]"]),
+ SourceIdentity("src_codex", "Codex", ["gpt-5.5"]),
+ SourceIdentity("src_relay", "Relay", ["relay-model"]),
+ ], prices=_table())
+ # claude 5.55; codex 1M × 5 + 1M × 0.5 + 100k × 30 = 5 + 0.5 + 3 = 8.5
+ assert summary["totals"]["api_cost_usd"] == pytest.approx(14.05)
+ assert summary["totals"]["excluded_tokens"] == 1000
+ assert summary["totals"]["cache_write_input_tokens"] == 300_000
+ assert summary["pricing"] == {"currency": "USD", "price_table_date": "2026-09-23"}
+ by_source = {source["source_id"]: source for source in summary["sources"]}
+ assert by_source["src_claude"]["api_cost_usd"] == pytest.approx(5.55)
+ assert by_source["src_relay"]["models"][0]["priced"] is False
+ assert by_source["src_relay"]["api_cost_usd"] == 0
+ assert sum(day["api_cost_usd"] for day in summary["days"]) == pytest.approx(14.05)
+ # Without a table nothing is priced and the shape is the released one.
+ assert "api_cost_usd" not in ledger.summary(days=7, now=now)["totals"]
+
+
+def test_rows_written_before_cache_writes_read_as_uncaptured(tmp_path):
+ """MH-PRICE-007: A released row has no cache-write counters; it reads as zero writes, all reports uncaptured."""
+
+ path = tmp_path / "usage.json"
+ path.write_text(json.dumps([{
+ "day": "2026-09-25", "source_id": "src_claude", "model_id": "claude-opus-5",
+ "requests": 2, "token_reports": 2, "input_tokens": 1_000_000, "cached_input_tokens": 0,
+ "output_tokens": 0, "last_metered_at": "2026-09-25T10:00:00+00:00",
+ }]), encoding="utf-8")
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(path, now=lambda: now)
+ before = path.read_bytes()
+ summary = ledger.summary(days=1, now=now, prices=_table())
+ assert path.read_bytes() == before
+ assert summary["totals"]["cache_write_input_tokens"] == 0
+ assert summary["totals"]["cache_write_uncaptured_reports"] == 2
+ assert summary["totals"]["api_cost_usd"] == pytest.approx(5.0)
+ assert summary["totals"]["api_cost_lower_bound"] is True
+
+
+ ("vendor", "reported", "key"),
+ [
+ ("anthropic", "max_20x", "claude_max_20x"),
+ ("anthropic", "Max 5x", "claude_max_5x"),
+ ("anthropic", "pro", "claude_pro"),
+ ("openai", "plus", "chatgpt_plus"),
+ ("openai", "pro", "chatgpt_pro"),
+ ("openai", "team", None),
+ ("codex", "pro", "chatgpt_pro"),
+ ("gemini", "pro", None),
+ ("xai", "plus", None),
+ ("anthropic", None, None),
+ ],
+)
+def test_reported_plans_resolve_to_fee_table_keys(vendor, reported, key):
+ """MH-PRICE-008: Known plans resolve to the built-in fee table; anything else is no plan."""
+
+ assert plan_key(vendor, reported) == key
+
+
+def test_override_file_sets_a_sources_plan_fee_and_renewal_day():
+ """MH-PRICE-008: A per-Source plan wins over the reported one, and an override fee wins over the table."""
+
+ table = _table({
+ "plans": {"chatgpt_pro": {"fee_usd": 229}, "team_seat": {"fee_usd": 30}, "bad": {"fee_usd": -1}},
+ "sources": {"src_a": {"plan": "team_seat", "renewal_day": 31}, "src_b": {"plan": "max 20x"}},
+ })
+ assert table.resolve_plan_key("src_a", "openai", "plus") == "team_seat"
+ assert table.fee("team_seat") == 30
+ assert table.fee("chatgpt_pro") == 229
+ assert table.fee("bad") is None
+ assert table.resolve_plan_key("src_b", "anthropic", None) == "claude_max_20x"
+ assert table.resolve_plan_key("src_c", "openai", "plus") == "chatgpt_plus"
+ assert table.source_plan("src_a").renewal_day == 31
+
+
+ ("today", "renewal_day", "expected"),
+ [
+ (date(2026, 9, 25), None, ("rolling_30d", date(2026, 8, 27), None)),
+ (date(2026, 9, 25), 10, ("billing_cycle", date(2026, 9, 10), date(2026, 10, 10))),
+ (date(2026, 9, 5), 10, ("billing_cycle", date(2026, 8, 10), date(2026, 9, 10))),
+ (date(2026, 9, 10), 10, ("billing_cycle", date(2026, 9, 10), date(2026, 10, 10))),
+ (date(2026, 2, 28), 31, ("billing_cycle", date(2026, 2, 28), date(2026, 3, 31))),
+ (date(2026, 3, 15), 31, ("billing_cycle", date(2026, 2, 28), date(2026, 3, 31))),
+ (date(2026, 1, 3), 5, ("billing_cycle", date(2025, 12, 5), date(2026, 1, 5))),
+ (date(2026, 12, 20), 5, ("billing_cycle", date(2026, 12, 5), date(2027, 1, 5))),
+ ],
+)
+def test_billing_period_is_the_current_cycle_or_the_trailing_30_days(today, renewal_day, expected):
+ """MH-PRICE-009: A renewal day gives the current cycle, clamped to short months; none gives 30 days."""
+
+ assert billing_period(today, renewal_day) == expected
+
+
+def test_quota_values_compare_each_period_with_its_plan_fee():
+ """MH-PRICE-010: Each Source gets week and period value; totals count only known-fee Sources for payback."""
+
+ today = date(2026, 9, 25)
+ sources = [
+ {"source_id": "src_max", "vendor": "anthropic", "plan": "max_20x"},
+ {"source_id": "src_plus", "vendor": "openai", "plan": "plus"},
+ {"source_id": "src_team", "vendor": "openai", "plan": "team"},
+ ]
+ days = {
+ "src_max": {"2026-09-25": Cost(300.0), "2026-09-10": Cost(100.0), "2026-08-01": Cost(999.0)},
+ "src_plus": {"2026-09-20": Cost(10.0, excluded_tokens=5, api_cost_lower_bound=True)},
+ "src_team": {"2026-09-24": Cost(40.0)},
+ }
+ table = _table({"sources": {"src_max": {"renewal_day": 5}}})
+ totals = quota_values(sources, daily_costs=days, prices=table, today=today)
+
+ max_value = sources[0]["value"]
+ assert max_value["plan_key"] == "claude_max_20x" and max_value["fee_usd"] == 200
+ assert max_value["week"]["api_cost_usd"] == 300
+ assert max_value["period"] == {
+ "basis": "billing_cycle", "from_day": "2026-09-05", "to_day": "2026-09-25", "renews_on": "2026-10-05",
+ "api_cost_usd": 400.0, "excluded_tokens": 0, "api_cost_lower_bound": False,
+ }
+ assert max_value["multiple"] == 2.0
+ plus_value = sources[1]["value"]
+ assert plus_value["period"]["basis"] == "rolling_30d" and plus_value["period"]["renews_on"] is None
+ assert plus_value["multiple"] == 0.5
+ team_value = sources[2]["value"]
+ assert (team_value["plan_key"], team_value["fee_usd"], team_value["multiple"]) == (None, None, None)
+ assert team_value["week"]["api_cost_usd"] == 40
+
+ assert totals["week"] == {"api_cost_usd": 350.0, "excluded_tokens": 5, "api_cost_lower_bound": True}
+ assert totals["period"] == {
+ "sources": 2, "fee_usd": 220.0, "multiple": round(410 / 220, 4),
+ "api_cost_usd": 410.0, "excluded_tokens": 5, "api_cost_lower_bound": True,
+ }
+ assert totals["price_table_date"] == "2026-09-23"
+ no_fee = [{"source_id": "src_team", "vendor": "openai", "plan": None}]
+ assert quota_values(no_fee, daily_costs=days, prices=table, today=today)["period"] is None
+
+
+def test_daily_costs_answer_only_for_the_given_sources(tmp_path):
+ """MH-PRICE-010: The ledger prices each configured Source's days by its config model ID."""
+
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(tmp_path / "usage.json", now=lambda: now)
+ report = ProtocolUsageReport.of(input_tokens=1_000_000, cached_input_tokens=0, output_tokens=0)
+ ledger.record_many([
+ UsageCall(source_id="src_claude", model_id="claude-opus-5", usage=report, at=now),
+ UsageCall(source_id="src_claude", model_id="claude-opus-5", usage=report, at=now - timedelta(days=3)),
+ UsageCall(source_id="src_other", model_id="claude-opus-5", usage=report, at=now),
+ ])
+ costs = ledger.daily_costs(
+ days=31, now=now, identities=[SourceIdentity("src_claude", "Claude", ["claude-opus-5"])], prices=_table()
+ )
+ assert set(costs) == {"src_claude"}
+ assert sum(cost.api_cost_usd for cost in costs["src_claude"].values()) == pytest.approx(10.0)
+ assert len(costs["src_claude"]) == 2
+
+
+def _assert_valid(name: str, payload: dict) -> None:
+ from jsonschema import Draft7Validator, FormatChecker
+
+ schema = json.loads(
+ (Path(__file__).parents[1] / "docs" / "plans" / "model-hub-contracts" / name).read_text(encoding="utf-8")
+ )
+ errors = [error.message for error in Draft7Validator(schema, format_checker=FormatChecker()).iter_errors(payload)]
+ assert not errors, errors
+
+
+def test_priced_usage_reads_match_the_usage_summary_contract(tmp_path):
+ """MH-PRICE-011: Daily and hourly priced reads, with unknown and uncaptured rows, stay inside the schema."""
+
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(tmp_path / "usage.json", now=lambda: now)
+ ledger.record_many([
+ UsageCall(source_id="src_claude", model_id="claude-opus-5", at=now, usage=ProtocolUsageReport.of(
+ input_tokens=5000, cached_input_tokens=1000, output_tokens=200,
+ cache_write_input_tokens=800, cache_write_1h_input_tokens=300)),
+ UsageCall(source_id="src_relay", model_id="relay-model", at=now,
+ usage=ProtocolUsageReport.of(input_tokens=10, cached_input_tokens=0, output_tokens=1)),
+ UsageCall(source_id="src_relay", model_id="relay-model", at=now, usage=None),
+ ])
+ identities = [SourceIdentity("src_claude", "Claude", ["claude-opus-5"])]
+ _assert_valid("usage-summary.schema.json", ledger.summary(days=30, now=now, identities=identities, prices=_table()))
+ for window in ("24h", "7d"):
+ report = ledger.report(window=window, now=now, identities=identities, prices=_table())
+ _assert_valid("usage-summary.schema.json", report)
+ assert report["totals"]["excluded_tokens"] == 11
+
+
+def _priced_aggregates(document: dict):
+ """Every priced aggregate a usage read publishes: totals, sources, models, days, buckets, rows."""
+
+ yield document["totals"]
+ for source in document.get("sources", []):
+ yield source
+ yield from source.get("models", [])
+ yield from document.get("days", [])
+ for bucket in document.get("buckets", []):
+ yield from bucket.get("rows", [])
+
+
+ ("model_id", "usage"),
+ [
+ # Unpriced: the model has no price anywhere.
+ ("relay-model", ProtocolUsageReport.of(input_tokens=1000, cached_input_tokens=0, output_tokens=10)),
+ # Unreported: the call happened, its size is unknown.
+ ("grok-4.6", None),
+ ("relay-model", None),
+ # Uncaptured write: a row metered before cache writes were counted, on a model that charges for them.
+ ("claude-opus-5", "uncaptured"),
+ ],
+ ids=["unpriced", "unreported-priced", "unreported-unpriced", "uncaptured-write"],
+)
+def test_no_aggregate_over_an_unknown_part_is_published_as_exact(tmp_path, model_id, usage):
+ """MH-PRICE-012: Any unknown part reaches every aggregate and quota value above it as a floor."""
+
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ path = tmp_path / "usage.json"
+ if usage == "uncaptured":
+ path.write_text(json.dumps([{
+ "day": "2026-09-25", "source_id": "src_a", "model_id": model_id,
+ "requests": 1, "token_reports": 1, "input_tokens": 1000, "cached_input_tokens": 0,
+ "output_tokens": 10, "last_metered_at": "2026-09-25T10:00:00+00:00",
+ }]), encoding="utf-8")
+ ledger = BoundedUsageLedger(path, now=lambda: now)
+ known = ProtocolUsageReport.of(input_tokens=1_000_000, cached_input_tokens=0, output_tokens=0)
+ calls = [UsageCall(source_id="src_a", model_id="grok-4.6", usage=known, at=now)]
+ if usage != "uncaptured":
+ calls.append(UsageCall(source_id="src_a", model_id=model_id, usage=usage, at=now))
+ ledger.record_many(calls)
+ identities = [SourceIdentity("src_a", "A", ["grok-4.6", model_id])]
+ documents = [ledger.summary(days=7, now=now, identities=identities, prices=_table())]
+ documents += [ledger.report(window=w, now=now, identities=identities, prices=_table()) for w in ("7d",)]
+ hourly = ledger.report(window="24h", now=now, identities=identities, prices=_table())
+ if usage == "uncaptured":
+ # A legacy daily row has no hours to place, so the 24 hours it overlaps are
+ # incomplete and their valuation is a floor even though the row is not in them.
+ assert hourly["totals"]["api_cost_lower_bound"] is True
+ else:
+ documents.append(hourly)
+ for document in documents:
+ covering = [
+ aggregate for aggregate in _priced_aggregates(document)
+ if aggregate.get("model_id", model_id) == model_id and aggregate.get("requests", 1) > 0
+ ]
+ assert covering
+ assert all(aggregate["api_cost_lower_bound"] is True for aggregate in covering), covering
+
+ costs = ledger.daily_costs(days=31, now=now, identities=identities, prices=_table())
+ sources = [{"source_id": "src_a", "vendor": "xai", "plan": None}]
+ table = _table({"plans": {"xai_seat": {"fee_usd": 1000}}, "sources": {"src_a": {"plan": "xai_seat"}}})
+ totals = quota_values(sources, daily_costs=costs, prices=table, today=date(2026, 9, 25))
+ value = sources[0]["value"]
+ assert value["multiple"] is not None
+ assert value["week"]["api_cost_lower_bound"] is True
+ assert value["period"]["api_cost_lower_bound"] is True
+ assert totals["week"]["api_cost_lower_bound"] is True
+ assert totals["period"]["api_cost_lower_bound"] is True
+
+
+def test_a_degraded_ledger_read_values_nothing_as_exact(tmp_path):
+ """MH-PRICE-012: Rows a ledger read had to drop are unknown usage, so every valuation over the read is a floor."""
+
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ path = tmp_path / "usage.json"
+ path.write_text("{not json", encoding="utf-8")
+ ledger = BoundedUsageLedger(path, now=lambda: now)
+ identities = [SourceIdentity("src_a", "A", ["claude-opus-5"])]
+ documents = [ledger.summary(days=7, now=now, identities=identities, prices=_table())]
+ documents += [ledger.report(window=w, now=now, identities=identities, prices=_table()) for w in ("24h", "7d")]
+ for document in documents:
+ assert document["totals"]["api_cost_usd"] == 0
+ assert document["totals"]["api_cost_lower_bound"] is True
+
+ costs = ledger.daily_costs(days=31, now=now, identities=identities, prices=_table())
+ sources = [{"source_id": "src_a", "vendor": "anthropic", "plan": "max_20x"}]
+ totals = quota_values(sources, daily_costs=costs, prices=_table(), today=date(2026, 9, 25))
+ value = sources[0]["value"]
+ assert value["fee_usd"] == 200
+ assert value["week"]["api_cost_lower_bound"] is True
+ assert value["period"]["api_cost_lower_bound"] is True
+ assert totals["period"]["api_cost_lower_bound"] is True
diff --git a/tests/test_model_hub_quota.py b/tests/test_model_hub_quota.py
index 9c7f09e11..85316e8fe 100644
--- a/tests/test_model_hub_quota.py
+++ b/tests/test_model_hub_quota.py
@@ -493,6 +493,32 @@ async def test_quota_cache_does_not_hold_the_page_on_a_slow_vendor(monkeypatch):
assert [source["state"] for source in (await cache.summary([_CLAUDE, _CODEX]))["sources"]] == ["ok", "ok"]
+async def test_quota_summary_names_the_sources_still_being_read(monkeypatch):
+ """MH-QUOTA-020: A read past the deadline is named `pending` until it lands, then the hint is gone."""
+
+ from core.handlers.model_hub import quota
+
+ monkeypatch.setattr(quota, "QUOTA_READ_DEADLINE_SECONDS", 0.05)
+ release = asyncio.Event()
+
+ async def fetch(source_id, vendor, credential_ref):
+ if source_id == "src_codex":
+ await release.wait()
+ return {"plan": None, "windows": [_WINDOW]}
+
+ cache = SubscriptionQuotaCache(fetch, now=_Clock())
+ first = await cache.summary([_CLAUDE, _CODEX])
+ assert first["pending"] == ["src_codex"]
+ # A re-read while the vendor is still slow says so again, without a second fetch.
+ assert (await cache.summary([_CLAUDE, _CODEX]))["pending"] == ["src_codex"]
+ release.set()
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ settled = await cache.summary([_CLAUDE, _CODEX])
+ assert "pending" not in settled
+ assert [source["state"] for source in settled["sources"]] == ["ok", "ok"]
+
+
class _Supervisor:
def __init__(self, client):
self._client = client
@@ -505,8 +531,9 @@ class _Supervisor:
class _EngineClient:
- def __init__(self, response):
+ def __init__(self, response, by_url=None):
self.response = response
+ self.by_url = by_url or {}
self.calls = []
def management_request(self, method, path, *, query=None, payload=None, timeout=None):
@@ -517,7 +544,10 @@ class _EngineClient:
{"auth_index": "8", "id": "codex-b.json", "name": "codex-b.json", "provider": "codex",
"id_token": {"chatgpt_account_id": "acct_123"}},
]}
- return self.response
+ answer = self.by_url.get((payload or {}).get("url"), self.response)
+ if isinstance(answer, Exception):
+ raise answer
+ return answer
class _StateStore:
@@ -528,11 +558,11 @@ class _StateStore:
return self.metadata[credential_ref]
-def _adapter(response, metadata):
+def _adapter(response, metadata, by_url=None):
from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
adapter = CLIProxyEngineAdapter.__new__(CLIProxyEngineAdapter)
- client = _EngineClient(response)
+ client = _EngineClient(response, by_url)
adapter.supervisor = _Supervisor(client)
adapter.state_store = _StateStore(metadata)
return adapter, client
@@ -547,10 +577,15 @@ _METADATA = {
async def test_adapter_reads_quota_through_the_engine_without_exposing_the_grant():
"""MH-QUOTA-011: The engine makes the usage call with `$TOKEN$`, the witness headers, and Claude's OAuth beta; only parsed windows return."""
- adapter, client = _adapter({"status_code": 200, "header": {}, "body": json.dumps(CLAUDE_LEGACY)}, _METADATA)
+ adapter, client = _adapter(
+ {"status_code": 200, "header": {}, "body": json.dumps(CLAUDE_LEGACY)},
+ _METADATA,
+ {_PROFILE_URL: {"status_code": 200, "body": "{}"}},
+ )
parsed = await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
assert set(parsed) == {"plan", "windows"}
- method, path, payload = client.calls[-1]
+ usage_calls = [call for call in client.calls if (call[2] or {}).get("url") != _PROFILE_URL]
+ method, path, payload = usage_calls[-1]
assert (method, path) == ("POST", "/api-call")
assert payload["auth_index"] == "7"
assert payload["url"] == "https://api.anthropic.com/api/oauth/usage"
@@ -568,6 +603,98 @@ async def test_adapter_reads_quota_through_the_engine_without_exposing_the_grant
assert "anthropic-beta" not in payload["header"]
+_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile"
+
+
+# The profile shape the Claude Code CLI (2.1.280) reads: `organization_type`
+# names the product and `rate_limit_tier` the Max tier; identifiers are fake.
+CLAUDE_PROFILE = {
+ "account": {
+ "uuid": "00000000-0000-4000-8000-000000000001",
+ "email": "[email protected]",
+ "full_name": "Someone",
+ "display_name": "Someone",
+ "has_claude_max": True,
+ "has_claude_pro": False,
+ },
+ "organization": {
+ "uuid": "00000000-0000-4000-8000-000000000002",
+ "name": "[email protected]'s Organization",
+ "organization_type": "claude_max",
+ "billing_type": "stripe_subscription",
+ "rate_limit_tier": "default_claude_max_20x",
+ "seat_tier": None,
+ "has_extra_usage_enabled": False,
+ },
+}
+
+
+ ("organization", "plan"),
+ [
+ ({}, "max_20x"),
+ ({"rate_limit_tier": "default_claude_max_5x"}, "max_5x"),
+ ({"organization_type": "claude_pro", "rate_limit_tier": "default_claude_ai"}, "pro"),
+ ({"organization_type": "claude_team", "rate_limit_tier": "default_claude_max_5x"}, None),
+ ({"organization_type": "claude_enterprise", "rate_limit_tier": "default_claude_max_20x"}, None),
+ ({"rate_limit_tier": "something_new"}, None),
+ ({"rate_limit_tier": None}, None),
+ ],
+)
+def test_claude_plan_is_read_from_the_oauth_profile_organization(organization, plan):
+ """MH-QUOTA-019: The product comes from organization_type, the Max tier from rate_limit_tier; anything else is no plan."""
+
+ from core.handlers.model_hub.quota import parse_claude_plan
+
+ body = {**CLAUDE_PROFILE, "organization": {**CLAUDE_PROFILE["organization"], **organization}}
+ assert parse_claude_plan(json.dumps(body)) == plan
+
+
+def test_claude_plan_ignores_an_unreadable_profile():
+ """MH-QUOTA-019: A body that is not a profile yields no plan, never an error."""
+
+ from core.handlers.model_hub.quota import parse_claude_plan
+
+ assert parse_claude_plan("<html>") is None
+ assert parse_claude_plan(json.dumps({"account": {}, "organization": "not an object"})) is None
+
+
+async def test_adapter_adds_the_claude_plan_from_the_profile_and_never_fails_on_it():
+ """MH-QUOTA-019: The plan is a second, best-effort read with the witness headers; its failure leaves windows intact."""
+
+ usage = {"status_code": 200, "header": {}, "body": json.dumps(CLAUDE_LEGACY)}
+ body = {**CLAUDE_PROFILE, "organization": {**CLAUDE_PROFILE["organization"], "rate_limit_tier": "default_claude_max_5x"}}
+ profile = {"status_code": 200, "body": json.dumps(body)}
+ adapter, client = _adapter(usage, _METADATA, {_PROFILE_URL: profile})
+ parsed = await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
+ assert parsed["plan"] == "max_5x" and parsed["windows"]
+ profile_call = client.calls[-1][2]
+ assert profile_call["url"] == _PROFILE_URL
+ assert profile_call["header"]["Authorization"] == "Bearer $TOKEN$"
+
+ from vibe.model_hub_runtime.client import EngineClientError
+
+ for failure in ({"status_code": 500, "body": "{}"}, {"status_code": 200, "body": "<html>"}, EngineClientError("down")):
+ adapter, _client = _adapter(usage, _METADATA, {_PROFILE_URL: failure})
+ parsed = await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
+ assert parsed["plan"] is None and parsed["windows"]
+
+
+async def test_a_missing_plan_on_one_read_keeps_the_last_known_plan():
+ """MH-QUOTA-019: A plan read that misses once does not blank the plan the page prices against."""
+
+ plans = iter(["max_20x", None])
+ moment = [datetime(2026, 9, 1, tzinfo=timezone.utc)]
+
+ async def fetch(source_id, vendor, credential_ref):
+ return {"plan": next(plans), "windows": []}
+
+ cache = SubscriptionQuotaCache(fetch, now=lambda: moment[0])
+ assert (await cache.summary([_CLAUDE]))["sources"][0]["plan"] == "max_20x"
+ moment[0] += timedelta(minutes=6)
+ assert (await cache.summary([_CLAUDE]))["sources"][0]["plan"] == "max_20x"
+
+
@pytest.mark.parametrize(
("response", "reason", "retry_after"),
[
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index ab57e237f..65584aa4c 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -57,7 +57,9 @@ INVOKE_CONTRACT = ROOT / "core/handlers/model_hub/adapter.py"
# forbid reaching it the easy way for one reason -- the read blocks on the lock
# the writers hold across an fsync -- so the rule is declared once here instead
# of restated in each loop's scan, where a second reader would escape both.
-LEDGER_READ_NAMES = frozenset({"usage_summary"})
+# `_quota_values` prices the quota page from the same ledger; it is reached only
+# through `asyncio.to_thread` inside the service, which the guard below checks.
+LEDGER_READ_NAMES = frozenset({"usage_summary", "_quota_values"})
LEDGER_TOUCH_NAMES = LEDGER_READ_NAMES | {"usage"}
PRODUCT_PACKAGES = ("core", "config", "modules", "vibe")
FIXTURES = Path(__file__).parent / "fixtures" / "model_hub"
@@ -921,6 +923,15 @@ def test_the_ledger_read_is_the_whole_of_what_both_loops_are_told_to_watch() ->
name for name, fn in _functions(_tree(SERVICE)).items() if any(map(_reaches_the_ledger, ast.walk(fn)))
}
assert readers == set(LEDGER_READ_NAMES)
+ # The quota valuation is a service-internal reader: every reference to it is
+ # handed to `to_thread`, never called on the loop.
+ tree = _tree(SERVICE)
+ parents = _parents(tree)
+ uses = [node for node in ast.walk(tree) if isinstance(node, ast.Attribute) and node.attr == "_quota_values"]
+ assert uses
+ for use in uses:
+ call = parents.get(use)
+ assert isinstance(call, ast.Call) and _call_name(call) == "to_thread" and use in call.args
def test_the_ledger_read_reaches_the_web_ui_awaited_and_off_the_compat_surface() -> None:
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
index fdd0ede7b..13a4b80a7 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -62,6 +62,17 @@ from core.handlers.model_hub.usage import (
NOW = datetime(2026, 7, 23, 12, 0, tzinfo=timezone.utc)
+def _as_released(counts: dict) -> dict:
+ """Totals of rows written before cache writes were metered: every report uncaptured."""
+
+ return {
+ **counts,
+ "cache_write_input_tokens": 0,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": counts["token_reports"],
+ }
+
+
def _frame(document: dict) -> bytes:
"""Render one SSE frame the way the protocols that name events do.
@@ -110,7 +121,12 @@ def test_every_observed_protocol_declares_a_usage_location() -> None:
"cache_creation_input_tokens": 2,
"output_tokens": 7,
},
- ProtocolUsageReport(input_tokens=17, cached_input_tokens=3, output_tokens=7),
+ ProtocolUsageReport(
+ input_tokens=17,
+ cached_input_tokens=3,
+ output_tokens=7,
+ cache_write_input_tokens=2,
+ ),
),
(
"openai_responses",
@@ -168,6 +184,7 @@ def test_anthropic_input_total_sums_the_cache_members() -> None:
input_tokens=1000,
cached_input_tokens=900,
output_tokens=40,
+ cache_write_input_tokens=88,
)
@@ -617,6 +634,9 @@ def test_modern_hourly_report_is_dense_and_keeps_source_model_identity(
"input_tokens": 112,
"cached_input_tokens": 40,
"output_tokens": 10,
+ "cache_write_input_tokens": 0,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": 0,
}
measured = {
(row["source_id"], row["model_id"]): row
@@ -876,7 +896,7 @@ def test_future_hourly_evidence_is_incomplete_on_read_and_after_a_write(
bucket["history_complete"] == (bucket["start_at"][:10] != owner_day)
for bucket in report["buckets"]
)
- assert ledger.summary(days=1, now=now)["totals"] == counts
+ assert ledger.summary(days=1, now=now)["totals"] == _as_released(counts)
else:
assert all(not bucket["history_complete"] for bucket in report["buckets"])
assert ledger.summary(days=1, now=now)["totals"]["requests"] == 0
@@ -1141,7 +1161,7 @@ def test_recent_usage_without_its_hour_cannot_claim_complete_hourly_history(
assert report["totals"]["requests"] == 0
assert any(not bucket["history_complete"] for bucket in report["buckets"])
- assert ledger.summary(days=1, now=now)["totals"] == counts
+ assert ledger.summary(days=1, now=now)["totals"] == _as_released(counts)
finally:
if previous_tz is None:
os.environ.pop("TZ", None)
@@ -1205,7 +1225,7 @@ def test_missing_in_horizon_hour_cannot_be_hidden_by_a_present_latest_hour(
for row in bucket["rows"]
)
assert any(not bucket["history_complete"] for bucket in report["buckets"])
- assert ledger.summary(days=1, now=now)["totals"] == counts
+ assert ledger.summary(days=1, now=now)["totals"] == _as_released(counts)
finally:
if previous_tz is None:
os.environ.pop("TZ", None)
@@ -3201,6 +3221,11 @@ def test_a_persisted_report_count_above_its_requests_is_repaired_on_read(
"input_tokens": 120,
"cached_input_tokens": 8,
"output_tokens": 4,
+ # A released row: its reports are repaired first, then all count as
+ # uncaptured cache-write evidence.
+ "cache_write_input_tokens": 0,
+ "cache_write_1h_input_tokens": 0,
+ "cache_write_uncaptured_reports": 3,
}
@@ -3494,13 +3519,9 @@ def test_a_persisted_counter_past_the_representation_drops_its_row(
)
assert ledger.window(days=30, now=NOW) == []
- assert ledger.summary(days=30, now=NOW)["totals"] == {
- "requests": 0,
- "token_reports": 0,
- "input_tokens": 0,
- "cached_input_tokens": 0,
- "output_tokens": 0,
- }
+ assert ledger.summary(days=30, now=NOW)["totals"] == _as_released(
+ dict.fromkeys(("requests", "token_reports", "input_tokens", "cached_input_tokens", "output_tokens"), 0)
+ )
def test_a_merge_the_file_cannot_hold_is_refused_by_every_surface(
diff --git a/ui/e2e/model-catalog/quota-layout.spec.ts b/ui/e2e/model-catalog/quota-layout.spec.ts
index 4d28677ed..997773122 100644
--- a/ui/e2e/model-catalog/quota-layout.spec.ts
+++ b/ui/e2e/model-catalog/quota-layout.spec.ts
@@ -37,6 +37,32 @@ for (const lang of ['en', 'zh'] as const) {
expect(await fits(title)).toBe(true);
expect(titleBox.height).toBeGreaterThan(20);
+ // Each upcoming-reset chip stays inside the list; a long window name
+ // truncates rather than pushing the chip, or its time, past the edge.
+ const timeline = await box(page.locator('.model-hub-quota-timeline'));
+ for (const chip of await page.locator('.model-hub-quota-chip').all()) {
+ const [chipBox, timeBox] = await Promise.all([box(chip), box(chip.locator('b'))]);
+ expect(chipBox.x + chipBox.width).toBeLessThanOrEqual(timeline.x + timeline.width);
+ expect(timeBox.height).toBeLessThan(24);
+ }
+
+ // The API-price value holds too: two stat cards per row, and each account's
+ // value strip stays inside its card.
+ const stats = page.locator('.model-hub-quota-stats--valued > *');
+ await expect(stats).toHaveCount(4);
+ const statBoxes = await Promise.all((await stats.all()).map(box));
+ expect(Math.abs(statBoxes[0].y - statBoxes[1].y)).toBeLessThanOrEqual(1);
+ expect(statBoxes[2].y).toBeGreaterThanOrEqual(statBoxes[0].y + statBoxes[0].height - 1);
+ for (const stat of statBoxes) expect(stat.x + stat.width).toBeLessThanOrEqual(360);
+ const strips = page.locator('[data-quota-value]');
+ await expect(strips).toHaveCount(2);
+ for (let index = 0; index < 2; index += 1) {
+ const [strip, card] = await Promise.all([box(strips.nth(index)), box(cards.nth(index))]);
+ expect(strip.x + strip.width).toBeLessThanOrEqual(card.x + card.width + 1);
+ expect(await fits(strips.nth(index))).toBe(true);
+ }
+ await expect(page.locator('[data-quota-payback]').first()).toBeVisible();
+
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
await page.screenshot({ path: testInfo.outputPath('quota-layout.png'), fullPage: true });
});
diff --git a/ui/e2e/model-catalog/quotaFixture.tsx b/ui/e2e/model-catalog/quotaFixture.tsx
index 8a414737f..5f9d94f49 100644
--- a/ui/e2e/model-catalog/quotaFixture.tsx
+++ b/ui/e2e/model-catalog/quotaFixture.tsx
@@ -1,6 +1,6 @@
import { QuotaTab } from '../../src/components/settings/models/QuotaTab';
import { readyRegion } from '../../src/components/settings/models/regionRead';
-import type { QuotaWindow, SourceQuota } from '../../src/components/settings/models/types';
+import type { PricedUsage, QuotaValueTotals, QuotaWindow, SourceQuota, SourceQuotaValue } from '../../src/components/settings/models/types';
const NOW = Date.parse('2026-09-25T08:00:00Z');
const HOUR = 3_600_000;
@@ -11,7 +11,19 @@ const limit = (over: Partial<QuotaWindow>): QuotaWindow => ({
});
const weekly = { kind: 'weekly' as const, window_seconds: 604_800, resets_at: iso(NOW + 4 * 24 * HOUR) };
-// Two accounts, one with an unrecognised window whose upstream name is one long word.
+const priced = (api_cost_usd: number, excluded_tokens = 0): PricedUsage => ({
+ api_cost_usd, excluded_tokens, api_cost_lower_bound: false,
+});
+const valued = (over: Partial<SourceQuotaValue>): SourceQuotaValue => ({
+ currency: 'USD', price_table_date: '2026-09-23', plan_key: null, fee_usd: null, multiple: null,
+ week: priced(0),
+ period: { basis: 'rolling_30d', from_day: '2026-08-27', to_day: '2026-09-25', renews_on: null, ...priced(0) },
+ ...over,
+});
+
+// Two accounts, one with an unrecognised window whose upstream name is one long word;
+// one paid off many times over on a known cycle, one short on the trailing 30 days.
+
const sources: SourceQuota[] = [
{
source_id: 'src_claude', vendor: 'anthropic', display_name: 'Claude Max', account_label: '[email protected]',
@@ -21,6 +33,13 @@ const sources: SourceQuota[] = [
limit({ id: 'seven_day', label: 'seven_day', used_pct: 61, ...weekly }),
limit({ ...weekly, id: 'x', kind: 'other', label: 'unrecognised_upstream_limit_name_'.repeat(2), used_pct: 12 }),
],
+ value: valued({
+ plan_key: 'claude_max_20x', fee_usd: 200, multiple: 6.4201, week: priced(412.37),
+ period: {
+ basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05',
+ ...priced(1284.02),
+ },
+ }),
},
{
source_id: 'src_codex', vendor: 'openai', display_name: 'ChatGPT Pro', account_label: null,
@@ -29,11 +48,20 @@ const sources: SourceQuota[] = [
limit({ id: 'primary_window', label: 'primary_window', used_pct: 70, resets_at: iso(NOW + 47 * 60_000) }),
limit({ id: 'secondary_window', label: 'secondary_window', used_pct: 45, ...weekly }),
],
+ value: valued({
+ plan_key: 'chatgpt_pro', fee_usd: 200, multiple: 0.6125, week: priced(38.2, 12_400),
+ period: { basis: 'rolling_30d', from_day: '2026-08-27', to_day: '2026-09-25', renews_on: null, ...priced(122.5, 12_400) },
+ }),
},
];
+const value: QuotaValueTotals = {
+ currency: 'USD', price_table_date: '2026-09-23', week: priced(450.57, 12_400),
+ period: { sources: 2, fee_usd: 400, multiple: 3.5163, ...priced(1406.52, 12_400) },
+};
+
export function QuotaFixture() {
return <main className="model-hub-shell mx-auto min-w-0 max-w-5xl p-4">
- <QuotaTab quota={readyRegion({ refresh_interval_seconds: 300, sources })} now={NOW} />
+ <QuotaTab quota={readyRegion({ refresh_interval_seconds: 300, sources, value })} now={NOW} />
</main>;
}
diff --git a/ui/e2e/model-catalog/usage.spec.ts b/ui/e2e/model-catalog/usage.spec.ts
index aa9b93d90..78b31cabf 100644
--- a/ui/e2e/model-catalog/usage.spec.ts
+++ b/ui/e2e/model-catalog/usage.spec.ts
@@ -1,7 +1,7 @@
import { expect, test, type Locator, type Page } from '@playwright/test';
-const openUsage = async (page: Page, theme: 'light' | 'dark' = 'dark') => {
- await page.goto(`/e2e/model-catalog/fixture.html?view=usage&lang=en&theme=${theme}`);
+const openUsage = async (page: Page, theme: 'light' | 'dark' = 'dark', query = '') => {
+ await page.goto(`/e2e/model-catalog/fixture.html?view=usage&lang=en&theme=${theme}${query}`);
await expect(page.getByRole('heading', { name: 'Usage', level: 2 })).toBeVisible();
};
@@ -137,4 +137,18 @@ test.describe('hermetic UsageTab', () => {
await page.getByRole('heading', { name: 'Exact usage details', level: 3 }).scrollIntoViewIfNeeded();
expect(await scrollOwner.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
});
+
+ test('MH-USAGE-029: the API-price value holds the narrow layout and plots as dollars', async ({ page }) => {
+ await page.setViewportSize({ width: 360, height: 844 });
+ await openUsage(page, 'dark', '&priced=1');
+ const grid = page.locator('.model-hub-usage-stat-grid--priced');
+ await expect(grid.locator('.model-hub-usage-stat-card')).toHaveCount(4);
+ expect(await grid.evaluate((node) => getComputedStyle(node).gridTemplateColumns.split(' ').length)).toBe(1);
+ await expect(grid).toContainText('$4.50');
+ await expect(grid).toContainText('Price table from 2026-09-23');
+ await page.getByRole('combobox', { name: 'Metric' }).selectOption('cost');
+ await expect(page.locator('.model-hub-usage-cost-note')).toHaveText('At published API prices, not a charge');
+ await expect(page.locator('.model-hub-usage-svg')).toContainText('$');
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
+ });
});
diff --git a/ui/e2e/model-catalog/usageFixture.tsx b/ui/e2e/model-catalog/usageFixture.tsx
index 2a81a416a..d837323cf 100644
--- a/ui/e2e/model-catalog/usageFixture.tsx
+++ b/ui/e2e/model-catalog/usageFixture.tsx
@@ -21,6 +21,7 @@ const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({
const row = (over: Partial<UsageBucketRow> = {}): UsageBucketRow => ({
...counters(),
+ ...(params.get('priced') === '1' ? { api_cost_usd: 1.5, excluded_tokens: 0, api_cost_lower_bound: false } : {}),
source_id: 'source-alpha',
model_id: 'model-shared',
...over,
@@ -41,6 +42,11 @@ const rowsFor = (index: number, count: number): UsageBucketRow[] => {
return [];
};
+// `?priced=1` serves the report as a server with API-price valuation does.
+const PRICED = params.get('priced') === '1';
+const cost = (api_cost_usd: number): Partial<UsageCounters> =>
+ (PRICED ? { api_cost_usd, excluded_tokens: 0, api_cost_lower_bound: false } : {});
+
const makeReport = (windowKey: UsageWindowKey): UsageReport => {
const count = windowKey === '24h' ? 24 : Number(windowKey.slice(0, -1));
const granularity = windowKey === '24h' ? 'hour' : 'day';
@@ -68,24 +74,25 @@ const makeReport = (windowKey: UsageWindowKey): UsageReport => {
input_tokens: 360,
cached_input_tokens: 120,
output_tokens: 180,
+ ...cost(4.5),
}),
sources: [
{
source_id: 'source-alpha',
label: 'Same supplier',
last_metered_at: '2026-09-24T18:00:00+08:00',
- ...counters({ requests: 6, token_reports: 6, input_tokens: 240, cached_input_tokens: 80, output_tokens: 120 }),
+ ...counters({ requests: 6, token_reports: 6, input_tokens: 240, cached_input_tokens: 80, output_tokens: 120, ...cost(3) }),
models: [
- { model_id: 'model-shared', label: 'Same model', ...counters() },
- { model_id: 'model-second', label: 'Second model', ...counters() },
+ { model_id: 'model-shared', label: 'Same model', ...counters(cost(1.5)) },
+ { model_id: 'model-second', label: 'Second model', ...counters(cost(1.5)) },
],
},
{
source_id: 'source-beta',
label: 'Same supplier',
last_metered_at: '2026-09-24T10:00:00+08:00',
- ...counters(),
- models: [{ model_id: 'model-shared', label: 'Same model', ...counters() }],
+ ...counters(cost(1.5)),
+ models: [{ model_id: 'model-shared', label: 'Same model', ...counters(cost(1.5)) }],
},
],
days: [],
@@ -94,6 +101,7 @@ const makeReport = (windowKey: UsageWindowKey): UsageReport => {
from_at: localAt(firstStart),
to_at: CURRENT_AT,
buckets,
+ ...(PRICED ? { pricing: { currency: 'USD' as const, price_table_date: '2026-09-23' } } : {}),
};
};
diff --git a/ui/src/components/settings/models/QuotaTab.test.tsx b/ui/src/components/settings/models/QuotaTab.test.tsx
index 7bdcddca7..ed0a9887c 100644
--- a/ui/src/components/settings/models/QuotaTab.test.tsx
+++ b/ui/src/components/settings/models/QuotaTab.test.tsx
@@ -11,8 +11,8 @@ import en from '../../../i18n/en.json';
import zh from '../../../i18n/zh.json';
import { degradedRegion, loadingRegion, readyRegion, type RegionRead } from './regionRead';
import { QuotaTab } from './QuotaTab';
-import { windowLeftPct, windowPace, windowUsedPct } from './quotaProjection';
-import type { QuotaSummary, QuotaWindow, SourceQuota } from './types';
+import { PAYBACK_CLEAR_MULTIPLE, quotaPayback, windowLeftPct, windowPace, windowUsedPct } from './quotaProjection';
+import type { PricedUsage, QuotaSummary, QuotaValueTotals, QuotaWindow, SourceQuota, SourceQuotaValue } from './types';
const i18n = createInstance();
void i18n.use(initReactI18next).init({
@@ -126,7 +126,7 @@ describe('QuotaTab', () => {
expect(screen.getByLabelText('即将重置').textContent).toContain('47 分钟');
expect(screen.getByText('进度条是已用的部分,细竖线是这个周期已经过去的时间:进度条超过竖线,就是用得比时间快。')).toBeTruthy();
- // Money is out of scope: nothing on the tab states a price or a currency.
+ // A server that predates the value block draws the quota alone: no price, no currency.
expect(container.textContent).not.toMatch(/\$|USD|API 价格|回本/);
});
@@ -270,4 +270,177 @@ describe('QuotaTab', () => {
await i18n.changeLanguage('zh');
}
});
+
+ describe('API-price value', () => {
+ const priced = (api_cost_usd: number, over: Partial<PricedUsage> = {}): PricedUsage => ({
+ api_cost_usd, excluded_tokens: 0, api_cost_lower_bound: false, ...over,
+ });
+ const sourceValue = (period: number, fee: number | null, over: Partial<SourceQuotaValue> = {}): SourceQuotaValue => ({
+ currency: 'USD',
+ price_table_date: '2026-09-23',
+ plan_key: fee === null ? null : 'claude_max_20x',
+ fee_usd: fee,
+ multiple: fee === null ? null : period / fee,
+ week: priced(period / 3),
+ period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...priced(period) },
+ ...over,
+ });
+ const totals = (week: number, period: { cost: number; fee: number } | null, over: Partial<QuotaValueTotals> = {}): QuotaValueTotals => ({
+ currency: 'USD',
+ price_table_date: '2026-09-23',
+ week: priced(week),
+ period: period && { sources: 1, fee_usd: period.fee, multiple: period.cost / period.fee, ...priced(period.cost) },
+ ...over,
+ });
+ const valued = (sources: SourceQuota[], value: QuotaValueTotals, pending?: string[]): QuotaSummary => ({
+ ...summary(sources), value, ...(pending ? { pending } : {}),
+ });
+
+ it('MH-QUOTA-021: classifies payback at the 1× and 1.1× thresholds', () => {
+ expect(PAYBACK_CLEAR_MULTIPLE).toBe(1.1);
+ expect(quotaPayback(99, 100)).toMatchObject({ kind: 'short', shortfallUsd: 1 });
+ expect(quotaPayback(100, 100)).toMatchObject({ kind: 'even', surplusUsd: 0 });
+ expect(quotaPayback(109, 100)?.kind).toBe('even');
+ expect(quotaPayback(110, 100)).toMatchObject({ kind: 'paid', surplusUsd: 10 });
+ expect(quotaPayback(50, 0)).toBeNull();
+ expect(quotaPayback(Number.NaN, 20)).toBeNull();
+ // On each account card, in words.
+ const line = (cost: number) => {
+ cleanup();
+ draw(readyRegion(valued([claude({ value: sourceValue(cost, 100) })], totals(cost / 3, { cost, fee: 100 }))));
+ return screen.getByRole('article').querySelector('[data-quota-payback]')!.textContent;
+ };
+ expect(line(99)).toBe('还差 $1.00 回本');
+ expect(line(100)).toBe('刚好回本');
+ expect(line(109)).toBe('刚好回本');
+ expect(line(110)).toBe('回本 1.1 倍');
+ // Rounded down: 1.99× is not claimed as 2.0×.
+ expect(line(199)).toBe('回本 1.9 倍');
+ });
+
+ it('MH-QUOTA-022: states the week and period value against the fee, with the price table date', () => {
+ const { container } = draw(readyRegion(valued(
+ [claude({ value: sourceValue(412.5, 200) }), codex({ value: sourceValue(18, 200, { plan_key: 'chatgpt_pro', week: priced(6) }) })],
+ totals(143.5, { cost: 430.5, fee: 400 }),
+ )));
+ expect(screen.getAllByText('近 7 天按 API 价格').length).toBe(3);
+ const stats = container.querySelector('.model-hub-quota-stats')!;
+ expect(stats.textContent).toContain('$143.50');
+ expect(stats.textContent).toContain('本期回本');
+ expect(stats.textContent).toContain('1.0 倍月费');
+ expect(stats.textContent).toContain('已回本,多薅了 $30.50');
+ const [claudeCard, codexCard] = screen.getAllByRole('article');
+ expect(within(claudeCard).getByText('本期按 API 价格')).toBeTruthy();
+ expect(claudeCard.textContent).toContain('$412.50');
+ expect(claudeCard.textContent).toContain('回本 2.0 倍');
+ // Counted between host-calendar days (2026-09-25 → 2026-10-05), whatever the browser's zone.
+ expect(claudeCard.textContent).toContain('距下次续费10 天');
+ expect(claudeCard.textContent).toContain('2026-10-05');
+ expect(codexCard.textContent).toContain('还差 $182.00 回本');
+ const foot = container.querySelector('.model-hub-quota-foot')!.textContent!;
+ expect(foot).toContain('进度条是已用的部分');
+ expect(foot).toContain('“按 API 价格”指同样的用量按官方 API 标价要花多少钱,用来看订阅值不值,不是实际扣费。');
+ expect(foot).toContain('价格表日期 2026-09-23。');
+ });
+
+ it('MH-QUOTA-023: short of the fee says how much, and an unknown plan hides payback but keeps the value', () => {
+ draw(readyRegion(valued([claude({ value: sourceValue(150, 200) })], totals(50, { cost: 150, fee: 200 }))));
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('还差 $50.00 回本');
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('0.7 倍月费');
+ cleanup();
+
+ const { container } = draw(readyRegion(valued(
+ [claude({ plan: null, value: sourceValue(90, null, { period: { basis: 'rolling_30d', from_day: '2026-08-27', to_day: '2026-09-25', renews_on: null, ...priced(90) } }) })],
+ totals(30, null),
+ )));
+ const card = screen.getByRole('article');
+ expect(card.textContent).toContain('$30.00');
+ expect(within(card).getByText('近 30 天按 API 价格')).toBeTruthy();
+ expect(card.textContent).toContain('$90.00');
+ expect(card.querySelector('[data-quota-payback]')).toBeNull();
+ expect(card.textContent).not.toContain('回本');
+ expect(card.textContent).not.toContain('距下次续费');
+ expect(container.querySelector('.model-hub-quota-stats')!.textContent).toContain('套餐未知,暂不计算回本');
+ });
+
+ it('MH-QUOTA-024: a model with no price says so and is counted, never priced as zero', () => {
+ const unknown = priced(0, { excluded_tokens: 12_000 });
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(0, 200, { week: unknown, period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...unknown } }) })],
+ totals(0, { cost: 0, fee: 200 }, { week: unknown }),
+ )));
+ const card = screen.getByRole('article');
+ expect(within(card).getAllByText('暂无价格').length).toBe(2);
+ expect(card.textContent).toContain('12,000 tokens 暂无价格,未计入');
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('暂无价格');
+ cleanup();
+ // Partly priced: the figure stands and the leftover is named; a lower bound says ≥.
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(40, 200, { week: priced(40, { excluded_tokens: 500, api_cost_lower_bound: true }) }) })],
+ totals(40, { cost: 40, fee: 200 }, { week: priced(40, { excluded_tokens: 500, api_cost_lower_bound: true }) }),
+ )));
+ expect(screen.getByRole('article').textContent).toContain('≥ $40.00');
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('500 tokens 暂无价格,未计入');
+ cleanup();
+ // A floor short of the fee names no shortfall; a floor past it still proves the payback.
+ const floor = (cost: number) => priced(cost, { excluded_tokens: 500, api_cost_lower_bound: true });
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(40, 200, { period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...floor(40) } }) })],
+ totals(40, { cost: 40, fee: 200 }, { period: { sources: 1, fee_usd: 200, multiple: 0.2, ...floor(40) } }),
+ )));
+ expect(document.body.textContent).not.toContain('还差');
+ expect(screen.getByRole('article').textContent).toContain('部分用量暂无价格,差额暂不显示');
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('≥ 0.2 倍');
+ cleanup();
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(400, 200, { period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...floor(400) } }) })],
+ totals(400, { cost: 400, fee: 200 }, { period: { sources: 1, fee_usd: 200, multiple: 2, ...floor(400) } }),
+ )));
+ expect(screen.getByRole('article').textContent).toContain('回本 ≥ 2.0 倍');
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('已回本,多薅了 ≥ $200.00');
+ cleanup();
+ // A floor just past the fee is at least paid back, never 「刚好回本」.
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(210, 200, { period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...floor(210) } }) })],
+ totals(210, { cost: 210, fee: 200 }, { period: { sources: 1, fee_usd: 200, multiple: 1.05, ...floor(210) } }),
+ )));
+ expect(screen.getByRole('article').textContent).not.toContain('刚好回本');
+ expect(screen.getByRole('article').textContent).toContain('回本 ≥ 1.0 倍');
+ cleanup();
+ // A floor of zero (calls whose size went unreported) is still a floor: 「≥ $0.00」, never an exact zero or a shortfall.
+ const zero = priced(0, { api_cost_lower_bound: true });
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(0, 200, { week: zero, period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...zero } }) })],
+ totals(0, { cost: 0, fee: 200 }, { week: zero, period: { sources: 1, fee_usd: 200, multiple: 0, ...zero } }),
+ )));
+ expect(document.body.textContent).toContain('≥ $0.00');
+ expect(document.body.textContent).not.toMatch(/(?<!≥ )\$0\.00/);
+ expect(document.body.textContent).not.toContain('还差');
+ });
+
+ it('MH-QUOTA-025: a Source still being read shows a loading line instead of 「暂时读不到」', () => {
+ const unread = claude({ state: 'error', error_key: 'models.quota.error.unavailable', windows: [], fetched_at: null, plan: null });
+ draw(readyRegion({ ...summary([unread]), pending: ['src_claude'] }));
+ const card = screen.getByRole('article');
+ expect(within(card).getByRole('status').textContent).toBe('正在读取额度…');
+ expect(card.textContent).not.toContain('暂时读不到额度');
+ cleanup();
+ draw(readyRegion(summary([unread])));
+ expect(screen.getByRole('article').textContent).toContain('暂时读不到额度');
+ });
+
+ it('MH-QUOTA-026: renders the value copy in English through the same keys', async () => {
+ await i18n.changeLanguage('en');
+ try {
+ const { container } = draw(readyRegion(valued([claude({ value: sourceValue(412.5, 200) })], totals(137.5, { cost: 412.5, fee: 200 }))));
+ expect(container.querySelector('.model-hub-quota-stats')!.textContent).toContain('Last 7 days at API price');
+ expect(container.textContent).toContain('Paid back 2.0×');
+ expect(container.textContent).toContain('Paid back, $212.50 ahead');
+ expect(container.textContent).toContain('Price table from 2026-09-23.');
+ expect(container.textContent).not.toMatch(/[一-鿿]/);
+ } finally {
+ await i18n.changeLanguage('zh');
+ }
+ });
+ });
});
diff --git a/ui/src/components/settings/models/QuotaTab.tsx b/ui/src/components/settings/models/QuotaTab.tsx
index 1f39ae666..74f9b79e1 100644
--- a/ui/src/components/settings/models/QuotaTab.tsx
+++ b/ui/src/components/settings/models/QuotaTab.tsx
@@ -2,20 +2,22 @@
// (`quota-summary.schema.json`).
//
// Like 用量 it is a report and only a report: nothing here feeds resolution,
-// admission, or cooldown. It states quota only. What the same use would cost at
-// API prices belongs to the usage lane; the contract reserves an optional
-// `value` block for it, so this tab draws nothing where that figure would go.
+// admission, or cooldown. Beside the quota it states what the same use would
+// cost at list API prices (the optional `value` block), against the plan's
+// monthly fee — a valuation to judge whether the plan pays for itself, never a
+// charge. A server that predates the block draws the quota alone.
//
// Drawn after the 订阅额度 design preview. Its geometry follows the usage tab's
// vocabulary (12px card radius, 18px gutter) so the two tabs read as one surface.
import * as React from 'react';
import { useTranslation } from 'react-i18next';
-import { AlertTriangle, Clock3, Gauge, RefreshCw, Sparkles, TimerReset } from 'lucide-react';
+import { AlertTriangle, CircleDollarSign, Clock3, Gauge, LoaderCircle, RefreshCw, Sparkles, TimerReset, TrendingUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
+import { atLeast, formatCost, formatCount, formatUsd } from './format';
import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
-import type { QuotaSummary, QuotaWindow, SourceQuota } from './types';
+import type { PricedUsage, QuotaSummary, QuotaWindow, SourceQuota, SourceQuotaValue } from './types';
import { VendorGlyph } from './vendorGlyph';
import {
DAY_MS,
@@ -25,6 +27,7 @@ import {
quotaDuration,
quotaIsLive,
quotaIsRetained,
+ quotaPayback,
sourceStatus,
tightestWindow,
upcomingResets,
@@ -87,7 +90,18 @@ const useQuotaText = (now: number) => {
default: return t('settings.models.quota.pace.ok') as string;
}
}, [clock, duration, t]);
- return { duration, clock, ago, windowLabel, windowHint, paceText };
+ /** Plain dollars, for a figure only shown when its period is exact (a shortfall). */
+ const dollars = React.useCallback((amount: number) => formatUsd(amount, i18n.language), [i18n.language]);
+ /** A priced figure, 「≥」 whenever the server marks it a floor. */
+ const usd = React.useCallback((value: PricedUsage) => (
+ formatCost(value.api_cost_usd, value.api_cost_lower_bound, i18n.language)
+ ), [i18n.language]);
+ const tokens = React.useCallback((value: number) => formatCount(value, i18n.language), [i18n.language]);
+ /** A multiple to one decimal, rounded down so 0.99× never reads as 「1.0 倍」. */
+ const multiple = React.useCallback((value: number) => new Intl.NumberFormat(i18n.language, {
+ minimumFractionDigits: 1, maximumFractionDigits: 1,
+ }).format(Math.floor(value * 10) / 10), [i18n.language]);
+ return { duration, clock, ago, windowLabel, windowHint, paceText, dollars, usd, tokens, multiple };
};
type QuotaText = ReturnType<typeof useQuotaText>;
@@ -156,12 +170,73 @@ const unreadKey = (source: SourceQuota) => {
return 'settings.models.quota.unread.error' as const;
};
+/** Whole days from one `YYYY-MM-DD` to another. */
+const calendarDaysBetween = (from: string, to: string) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS);
+
+/** Whether every priced token of a span belongs to a model with no price. */
+const unpriced = (value: PricedUsage) => value.api_cost_usd === 0 && value.excluded_tokens > 0;
+
+/** The account's API-price value: its week, its period against the fee, and the renewal. */
+const ValueStrip: React.FC<{ value: SourceQuotaValue; text: QuotaText }> = ({ value, text }) => {
+ const { t } = useTranslation();
+ const payback = value.fee_usd !== null ? quotaPayback(value.period.api_cost_usd, value.fee_usd) : null;
+ // A floor can prove a payback but never size a shortfall.
+ const floor = value.period.api_cost_lower_bound;
+ // Both days are host-calendar days, so count between them, not from the browser's clock.
+ const renewsIn = value.period.renews_on !== null
+ ? calendarDaysBetween(value.period.to_day, value.period.renews_on)
+ : null;
+ const excluded = Math.max(value.week.excluded_tokens, value.period.excluded_tokens);
+ return (
+ <>
+ <div className="model-hub-quota-value" data-quota-value>
+ <div>
+ <span>{t('settings.models.quota.value.week')}</span>
+ <b>{unpriced(value.week) ? t('settings.models.quota.value.noPrice') : text.usd(value.week)}</b>
+ </div>
+ <div>
+ <span>{t(`settings.models.quota.value.period.${value.period.basis}`)}</span>
+ <b>
+ {unpriced(value.period) ? t('settings.models.quota.value.noPrice') : text.usd(value.period)}
+ {payback !== null && (
+ <em className={cn(payback.kind !== 'short' && 'is-good')} data-quota-payback={payback.kind}>
+ {/* 「刚好回本」 sizes the value against the fee; a floor there only proves it is at least paid back. */}
+ {payback.kind === 'paid' || (payback.kind === 'even' && floor)
+ ? t('settings.models.quota.value.paid', { multiple: atLeast(text.multiple(payback.multiple), floor) })
+ : payback.kind === 'even'
+ ? t('settings.models.quota.value.even')
+ : floor
+ ? t('settings.models.quota.value.shortUnknown')
+ : t('settings.models.quota.value.short', { amount: text.dollars(payback.shortfallUsd) })}
+ </em>
+ )}
+ </b>
+ </div>
+ {renewsIn !== null && (
+ <div>
+ <span>{t('settings.models.quota.value.renews')}</span>
+ <b>
+ {t('settings.models.quota.value.renewsIn', { count: Math.max(0, renewsIn) })}
+ <em>{value.period.renews_on}</em>
+ </b>
+ </div>
+ )}
+ </div>
+ {excluded > 0 && (
+ <p className="model-hub-quota-value-note">{t('settings.models.quota.value.excluded', { tokens: text.tokens(excluded) })}</p>
+ )}
+ </>
+ );
+};
+
const AccountCard: React.FC<{
source: SourceQuota;
now: number;
text: QuotaText;
+ /** The read is still running: a gap is loading, not a failure. */
+ pending?: boolean;
onRequestReauth?: (sourceId: string) => void;
-}> = ({ source, now, text, onRequestReauth }) => {
+}> = ({ source, now, text, pending = false, onRequestReauth }) => {
const { t } = useTranslation();
const retained = quotaIsRetained(source);
const status = sourceStatus(source, now);
@@ -205,7 +280,14 @@ const AccountCard: React.FC<{
)}
</div>
)}
- {source.windows.length === 0 || (!retained && !quotaIsLive(source))
+ {source.windows.length === 0 && pending && source.state === 'error'
+ ? (
+ <div className="model-hub-quota-unread flex items-center gap-2" role="status" data-quota-pending>
+ <LoaderCircle className="size-[13px] shrink-0 animate-spin" aria-hidden />
+ <span className="min-w-0 flex-1">{t('settings.models.quota.pending')}</span>
+ </div>
+ )
+ : source.windows.length === 0 || (!retained && !quotaIsLive(source))
? (
<div className="model-hub-quota-unread flex items-center gap-2">
<span className="min-w-0 flex-1">
@@ -231,6 +313,7 @@ const AccountCard: React.FC<{
{scoped.map((window) => <WindowRow key={window.id} window={window} now={now} retained={retained} nested text={text} />)}
</div>
)}
+ {source.value && <ValueStrip value={source.value} text={text} />}
</article>
);
};
@@ -280,6 +363,12 @@ export const QuotaTab: React.FC<{
const tightest = tightestWindow(sources, now);
const exhausted = exhaustedWindows(sources, now);
const upcoming = upcomingResets(sources, now);
+ const pending = new Set(summary?.pending ?? []);
+ const value = summary?.value;
+ const periodPayback = value?.period ? quotaPayback(value.period.api_cost_usd, value.period.fee_usd) : null;
+ const unfeed = sources.filter((source) => source.value && source.value.fee_usd === null).length;
+ // 本期 is each account's billing cycle only where its renewal day is known.
+ const rollingPeriod = sources.some((source) => source.value?.fee_usd != null && source.value.period.basis === 'rolling_30d');
return (
<section className="model-hub-usage" aria-label={t('settings.models.quota.title') as string}>
@@ -310,7 +399,7 @@ export const QuotaTab: React.FC<{
: sources.length === 0
? <p className="model-hub-usage-empty rounded-xl border border-border bg-background text-center text-muted">{t('settings.models.quota.empty')}</p>
: <>
- <div className="model-hub-quota-stats grid gap-4">
+ <div className={cn('model-hub-quota-stats grid gap-4', value && 'model-hub-quota-stats--valued')}>
<StatCard
primary
label={t('settings.models.quota.stat.tightest')}
@@ -344,24 +433,74 @@ export const QuotaTab: React.FC<{
// when every account has a current reading to back it.
: t(sources.every(quotaIsLive) ? 'settings.models.quota.stat.exhaustedNone' : 'settings.models.quota.stat.exhaustedNoneObserved')}
/>
+ {value && (
+ <StatCard
+ label={t('settings.models.quota.stat.weekValue')}
+ icon={<CircleDollarSign className="size-[15px]" aria-hidden />}
+ value={unpriced(value.week)
+ ? t('settings.models.quota.value.noPrice')
+ : <>{text.usd(value.week)}<small className="model-hub-quota-stat-unit">USD</small></>}
+ note={[
+ t('settings.models.quota.stat.weekValueNote'),
+ value.week.excluded_tokens > 0 && !unpriced(value.week)
+ ? t('settings.models.quota.value.excluded', { tokens: text.tokens(value.week.excluded_tokens) })
+ : null,
+ ].filter(Boolean).join(' · ')}
+ />
+ )}
+ {value && (
+ <StatCard
+ label={t('settings.models.quota.stat.payback')}
+ icon={<TrendingUp className="size-[15px]" aria-hidden />}
+ value={value.period && periodPayback
+ ? <>{t('settings.models.quota.stat.paybackMultiple', { multiple: atLeast(text.multiple(periodPayback.multiple), value.period.api_cost_lower_bound) })}<small className="model-hub-quota-stat-unit">{t('settings.models.quota.stat.paybackUnit')}</small></>
+ : '—'}
+ note={value.period && periodPayback
+ ? [
+ periodPayback.kind === 'short'
+ ? value.period.api_cost_lower_bound
+ ? t('settings.models.quota.stat.paybackShortUnknown')
+ : t('settings.models.quota.stat.paybackShort', { amount: text.dollars(periodPayback.shortfallUsd) })
+ : t('settings.models.quota.stat.paybackPaid', { amount: atLeast(text.dollars(periodPayback.surplusUsd), value.period.api_cost_lower_bound) }),
+ rollingPeriod ? t('settings.models.quota.stat.paybackRolling') : null,
+ unfeed > 0 ? t('settings.models.quota.stat.paybackPartial', { count: unfeed }) : null,
+ ].filter(Boolean).join(' · ')
+ : t('settings.models.quota.stat.paybackUnknown')}
+ />
+ )}
</div>
{upcoming.length > 0 && (
<div className="model-hub-quota-timeline flex flex-wrap items-center gap-2 rounded-xl border border-border bg-surface" aria-label={t('settings.models.quota.upcoming') as string}>
<span className="model-hub-quota-timeline-title flex items-center gap-1.5"><TimerReset className="size-[13px]" aria-hidden />{t('settings.models.quota.upcoming')}</span>
{upcoming.map(({ source, window }) => (
- <span key={`${source.source_id}:${window.id}`} className={cn('model-hub-quota-chip flex items-baseline gap-1.5', windowIsExhausted(window, now) && toneClass('danger'))}>
- <b>{text.duration((windowResetAt(window) as number) - now)}</b>
- {source.display_name} · {text.windowLabel(window)}
+ <span key={`${source.source_id}:${window.id}`} className={cn('model-hub-quota-chip flex min-w-0 max-w-full items-baseline gap-1.5', windowIsExhausted(window, now) && toneClass('danger'))}>
+ <b className="shrink-0 whitespace-nowrap">{text.duration((windowResetAt(window) as number) - now)}</b>
+ <span className="min-w-0 truncate" title={`${source.display_name} · ${text.windowLabel(window)}`}>{source.display_name} · {text.windowLabel(window)}</span>
</span>
))}
</div>
)}
<div className="model-hub-quota-grid grid gap-4">
- {sources.map((source) => <AccountCard key={source.source_id} source={source} now={now} text={text} onRequestReauth={onRequestReauth} />)}
+ {sources.map((source) => (
+ <AccountCard
+ key={source.source_id}
+ source={source}
+ now={now}
+ text={text}
+ pending={pending.has(source.source_id)}
+ onRequestReauth={onRequestReauth}
+ />
+ ))}
</div>
<p className="model-hub-quota-foot flex items-start gap-2">
<Clock3 className="mt-px size-[13px] shrink-0" aria-hidden />
- <span>{t('settings.models.quota.footnote')}</span>
+ <span>
+ {t('settings.models.quota.footnote')}
+ {value && <>{' '}{t('settings.models.quota.footnoteValue')}</>}
+ {value && <>{' '}{value.price_table_date
+ ? t('settings.models.quota.priceTableDate', { date: value.price_table_date })
+ : t('settings.models.quota.priceTableUnknown')}</>}
+ </span>
</p>
</>}
</section>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index edf51c933..712bd1923 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -14,7 +14,7 @@ import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';
import { MANAGE_COMMIT_ACTIONS } from './manage';
import type { ModelsSurfaceKind } from './modelHubSurfaceState';
import { ApiCallError, modelsApi } from './modelsApi';
-import { SettingsModelsPage as SettingsModelsRoute } from './SettingsModelsPage';
+import { QUOTA_PENDING_REREADS, QUOTA_PENDING_REREAD_MS, SettingsModelsPage as SettingsModelsRoute } from './SettingsModelsPage';
import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';
import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type QuotaSummary, type Source, type UsageReport } from './types';
@@ -2433,6 +2433,65 @@ describe('SettingsModelsPage quota region', () => {
expect(clear).toHaveBeenCalled();
});
+ // A vendor slower than the page deadline must not read as a failure for a whole
+ // poll: the service names it pending, and the page re-reads soon, a bounded
+ // number of times, until the reading lands.
+ it('MH-QUOTA-020: re-reads a pending Source soon after and stops once nothing is pending', async () => {
+ const timeouts = vi.spyOn(window, 'setTimeout');
+ const slow = {
+ source_id: 'src_slow', vendor: 'anthropic', display_name: 'Slow Claude', account_label: null, plan: null,
+ fetched_at: null, state: 'error' as const, error_key: 'models.quota.error.unavailable', windows: [],
+ };
+ const landed = {
+ ...slow, state: 'ok' as const, error_key: undefined, fetched_at: new Date().toISOString(),
+ windows: [{ id: 'five_hour', kind: 'session' as const, label: 'five_hour', used_pct: 40, window_seconds: 18_000, resets_at: new Date(Date.now() + 3_600_000).toISOString() }],
+ };
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getQuota);
+ read
+ .mockResolvedValueOnce({ refresh_interval_seconds: 300, sources: [slow], pending: ['src_slow'] })
+ .mockResolvedValueOnce({ refresh_interval_seconds: 300, sources: [landed] });
+ await openQuota();
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
+ expect(await screen.findByText(/^Reading quota…$|^正在读取额度…$/)).toBeTruthy();
+ const rereads = () => timeouts.mock.calls.filter(([, delay]) => delay === QUOTA_PENDING_REREAD_MS);
+ await waitFor(() => expect(rereads()).toHaveLength(1));
+ await act(async () => { (rereads()[0][0] as () => void)(); });
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ // The real reading replaces the loading line without a manual refresh.
+ expect((await screen.findAllByText(/^60%$/)).length).toBeGreaterThan(0);
+ expect(screen.queryByText(/^Reading quota…$|^正在读取额度…$/)).toBeNull();
+ // Nothing pending: no further re-read is scheduled.
+ await act(async () => { await Promise.resolve(); });
+ expect(rereads()).toHaveLength(1);
+ });
+
+ it('MH-QUOTA-020: gives up re-reading after a bounded number of tries while a Source stays pending', async () => {
+ const timeouts = vi.spyOn(window, 'setTimeout');
+ const stuck = {
+ refresh_interval_seconds: 300,
+ sources: [{
+ source_id: 'src_slow', vendor: 'anthropic', display_name: 'Slow Claude', account_label: null, plan: null,
+ fetched_at: null, state: 'error' as const, error_key: 'models.quota.error.unavailable', windows: [],
+ }],
+ pending: ['src_slow'],
+ };
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getQuota);
+ read.mockResolvedValue(stuck);
+ await openQuota();
+ const rereads = () => timeouts.mock.calls.filter(([, delay]) => delay === QUOTA_PENDING_REREAD_MS);
+ for (let attempt = 1; attempt <= QUOTA_PENDING_REREADS; attempt += 1) {
+ await waitFor(() => expect(rereads()).toHaveLength(attempt));
+ await act(async () => { (rereads()[attempt - 1][0] as () => void)(); });
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(attempt + 1));
+ }
+ await act(async () => { await Promise.resolve(); });
+ expect(rereads()).toHaveLength(QUOTA_PENDING_REREADS);
+ });
+
// A quota read can be the first to see a refused grant, while the Source row
// itself is still healthy and so offers no repair button. The card's re-login
// must therefore reach the confirmed journey on its own, and the tab must
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 1234c57df..80332c4ec 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -294,6 +294,10 @@ const ModelHubShell: React.FC<{ actions?: React.ReactNode; children: React.React
/** The service refreshes each Source at most this often; polling faster buys nothing. */
const QUOTA_POLL_MS = 5 * 60_000;
+/** A read the service is still running past its page deadline lands soon after;
+ * re-read at this pace, a bounded number of times, rather than wait a whole poll. */
+export const QUOTA_PENDING_REREAD_MS = 5_000;
+export const QUOTA_PENDING_REREADS = 3;
/** Back to the re-login button of a quota card, or to the selected tab once a refresh has removed it. */
const focusQuotaOpener = (opener: HTMLElement) =>
@@ -689,9 +693,14 @@ export const SettingsModelsPage: React.FC = () => {
await refreshUsage(usageWindow);
}, [refreshUsage, usageWindow]);
+ const quotaPendingRereads = React.useRef(0);
+ // Counts settled reads, so a re-read that lands with the same pending set
+ // still re-arms the timer below.
+ const [quotaSettled, setQuotaSettled] = React.useState(0);
const [quotaReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<QuotaSummary>>((incoming) => {
if (!aliveRef.current) return;
setQuotaRead((previous) => settleRegionRead(previous, incoming));
+ setQuotaSettled((count) => count + 1);
}));
const readQuota = React.useCallback(async (force: boolean) => {
@@ -708,12 +717,39 @@ export const SettingsModelsPage: React.FC = () => {
*/
React.useEffect(() => {
if (tab !== 'quota') return undefined;
+ quotaPendingRereads.current = 0;
void readQuota(false);
const timer = window.setInterval(() => { void readQuota(false); }, QUOTA_POLL_MS);
return () => window.clearInterval(timer);
}, [tab, readQuota]);
+ /**
+ * The Sources the service named as still reading: null while no settled
+ * reading is on screen, '' when none is pending. Each settled reading that
+ * still names one re-arms the timer once.
+ */
+ const quotaPendingKey = foldRegionRead<QuotaSummary, string | null>(quotaRead, {
+ loading: () => null,
+ ready: (data) => (data.pending ?? []).join('\u0000'),
+ unread: () => null,
+ degraded: () => null,
+ });
+ React.useEffect(() => {
+ if (tab !== 'quota' || quotaPendingKey === null) return undefined;
+ if (quotaPendingKey === '') {
+ quotaPendingRereads.current = 0;
+ return undefined;
+ }
+ if (quotaPendingRereads.current >= QUOTA_PENDING_REREADS) return undefined;
+ const timer = window.setTimeout(() => {
+ quotaPendingRereads.current += 1;
+ void readQuota(false);
+ }, QUOTA_PENDING_REREAD_MS);
+ return () => window.clearTimeout(timer);
+ }, [tab, quotaPendingKey, quotaSettled, readQuota]);
+
const refreshQuotaNow = React.useCallback(async () => {
+ quotaPendingRereads.current = 0;
setRefreshingQuota(true);
try {
await readQuota(true);
diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsx
index 4c14b3edf..e9ec022d7 100644
--- a/ui/src/components/settings/models/UsageTab.test.tsx
+++ b/ui/src/components/settings/models/UsageTab.test.tsx
@@ -348,6 +348,105 @@ describe('UsageTab', () => {
expect(screen.getAllByRole('button', { name: /Usage bucket/ })).toHaveLength(3);
});
+ // API price is a report beside the token counts: offered only when the server
+ // priced the report, never read as a charge, and never $0 for a model with no
+ // price.
+ const pricedReport = (): UsageReport => {
+ const cost = (usd: number, excluded = 0) => ({ api_cost_usd: usd, excluded_tokens: excluded, api_cost_lower_bound: false });
+ const pricedRow = row(cost(0.5));
+ const unpricedRow = row({ source_id: 'source-b', model_id: 'relay-model', ...cost(0, 140) });
+ return report({
+ totals: counters({ requests: 4, token_reports: 4, input_tokens: 200, cached_input_tokens: 50, output_tokens: 80, ...cost(0.5, 140) }),
+ sources: [
+ { source_id: 'source-a', label: 'Claude', last_metered_at: null, ...counters(cost(0.5)),
+ models: [{ model_id: 'model-a', label: 'Opus', ...counters(cost(0.5)) }] },
+ { source_id: 'source-b', label: 'Relay', last_metered_at: null, ...counters(cost(0, 140)),
+ models: [{ model_id: 'relay-model', label: 'Relay model', ...counters(cost(0, 140)) }] },
+ ],
+ buckets: [bucket('00', [pricedRow, unpricedRow])],
+ pricing: { currency: 'USD', price_table_date: '2026-09-23' },
+ });
+ };
+
+ it('MH-USAGE-030: offers the API-price metric only for a priced report', () => {
+ draw(report());
+ const metric = () => screen.getByRole('combobox', { name: 'Metric' }) as HTMLSelectElement;
+ expect([...metric().options].map((option) => option.value)).not.toContain('cost');
+ cleanup();
+ draw(pricedReport());
+ expect([...metric().options].map((option) => option.value)).toContain('cost');
+ });
+
+ it('MH-USAGE-029: states the API-price value, what it leaves out, and its price table', async () => {
+ const { container } = draw(pricedReport());
+ const stats = container.querySelector('.model-hub-usage-stat-grid--priced');
+ expect(stats).not.toBeNull();
+ expect(stats!.textContent).toContain('At API price');
+ expect(stats!.textContent).toContain('$0.50');
+ expect(stats!.textContent).toContain('At published API prices, not a charge');
+ expect(stats!.textContent).toContain('140 tokens have no price and are left out');
+ expect(stats!.textContent).toContain('Price table from 2026-09-23');
+
+ await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Metric' }), 'cost');
+ expect(container.querySelector('.model-hub-usage-cost-note')?.textContent).toBe('At published API prices, not a charge');
+ expect(container.querySelector('.model-hub-usage-table-scroll')?.textContent).toContain('No price yet');
+ expect(container.querySelector('.model-hub-usage-table-scroll')?.textContent).toContain('$0.50');
+ expect(container.querySelector('.model-hub-usage-table-scroll')?.textContent).not.toContain('≥');
+ expect(container.querySelector('.model-hub-usage-table-scroll tbody')?.textContent).toMatch(/\d%/);
+ cleanup();
+
+ // A floor keeps its 「≥」 in the itemized rows and the table total, not only the card.
+ const floor = pricedReport();
+ const lower = <T extends object>(value: T): T => ({ ...value, api_cost_lower_bound: true });
+ floor.buckets = floor.buckets.map((item) => ({ ...item, rows: item.rows.map((entry, index) => (index === 0 ? lower(entry) : entry)) }));
+ floor.sources = floor.sources.map((source, index) => (index === 0 ? { ...lower(source), models: source.models.map(lower) } : source));
+ floor.totals = lower(floor.totals);
+ const drawn = draw(floor);
+ await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Metric' }), 'cost');
+ const table = drawn.container.querySelector('.model-hub-usage-table-scroll')!;
+ expect(table.querySelector('tbody')!.textContent).toContain('≥ $0.50');
+ expect(table.querySelector('tfoot')!.textContent).toContain('≥ $0.50');
+ // A share of a floor total is not a known fraction.
+ expect(table.querySelector('tbody')!.textContent).not.toMatch(/\d%/);
+ });
+
+ it('MH-USAGE-032: a floor bucket reads 「≥」 in the chart legend and the bucket detail, an exact one does not', async () => {
+ const floor = pricedReport();
+ floor.buckets = [
+ bucket('00', [row({ api_cost_usd: 0.5, excluded_tokens: 0, api_cost_lower_bound: true })]),
+ bucket('01', [row({ api_cost_usd: 0.25, excluded_tokens: 0, api_cost_lower_bound: false })]),
+ ];
+ const { container } = draw(floor);
+ await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Metric' }), 'cost');
+ expect(container.querySelector('.model-hub-usage-legend')!.textContent).toContain('≥ $0.75');
+
+ const buckets = screen.getAllByRole('button', { name: /Usage bucket/ });
+ fireEvent.pointerEnter(buckets[0]);
+ const detail = () => screen.getByRole('dialog', { name: 'Usage bucket details' });
+ expect(detail().querySelector('.model-hub-usage-tooltip-total')!.textContent).toContain('≥ $0.50');
+ expect(detail().querySelector('.model-hub-usage-tooltip-lines')!.textContent).toContain('≥ $0.50');
+ fireEvent.pointerEnter(buckets[1]);
+ await screen.findByText('$0.25', { selector: '.model-hub-usage-tooltip-total strong' });
+ expect(detail().textContent).not.toContain('≥');
+ });
+
+ it('MH-USAGE-031: reads the API-price value in Chinese as a conversion, not a charge', async () => {
+ await i18n.addResourceBundle('zh', 'translation', zh, true, true);
+ await i18n.changeLanguage('zh');
+ try {
+ const { container } = draw(pricedReport());
+ const stats = container.querySelector('.model-hub-usage-stat-grid--priced')!;
+ expect(stats.textContent).toContain('折合 API 价格');
+ expect(stats.textContent).toContain('不是实际扣费');
+ expect(stats.textContent).toContain('价格表日期 2026-09-23');
+ await userEvent.selectOptions(screen.getByRole('combobox', { name: '指标' }), 'cost');
+ expect(container.querySelector('.model-hub-usage-cost-note')?.textContent).toContain('不是实际扣费');
+ expect(container.querySelector('.model-hub-usage-table-scroll')?.textContent).toContain('暂无价格');
+ } finally {
+ await i18n.changeLanguage('en');
+ }
+ });
+
it('renders exact accounting and preserves source/model pair rows', () => {
const second = row({ source_id: 'source-b', model_id: 'model-a' });
const value = report({
diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsx
index 27000788e..3577426b8 100644
--- a/ui/src/components/settings/models/UsageTab.tsx
+++ b/ui/src/components/settings/models/UsageTab.tsx
@@ -20,11 +20,12 @@ import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { SegmentedRadio } from '@/components/ui/segmented';
import { cn } from '@/lib/utils';
-import { formatPercent } from './format';
+import { atLeast, formatCost, formatPercent, formatUsd } from './format';
import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
import type { UsageCounters, UsageReport, UsageWindowKey } from './types';
import {
aggregateCounters,
+ costIsFloor,
filterBucketRows,
filteredRows,
formatBucketAxisLabel,
@@ -34,6 +35,7 @@ import {
modelLabel,
pairKey,
reportHasPartialHistory,
+ reportIsPriced,
reportHasUnknownTokens,
seriesFor,
sourceIdentityLabel,
@@ -41,6 +43,7 @@ import {
usageLabelContext,
usageCachedInputShare,
usageIsEmpty,
+ usageIsPriced,
usageMetricValue,
usageNonCachedInput,
usageReportShortfall,
@@ -68,6 +71,10 @@ type FilterOption = { key: string; label: string; detail?: string };
type UsageTranslate = (key: string, options?: Record<string, unknown>) => string;
const metricKeys: UsageMetric[] = ['tokens', 'input', 'output', 'cache', 'requests'];
+/** 折合 API 价格 is offered only when the server priced the report. */
+const metricKeysFor = (report: UsageReport): UsageMetric[] => (reportIsPriced(report) ? [...metricKeys, 'cost'] : metricKeys);
+/** Metrics with one series only, where 按类型 has nothing to split. */
+const unsplitMetric = (metric: UsageMetric) => metric === 'requests' || metric === 'cost';
const groupKeys: UsageGroup[] = ['total', 'type', 'model', 'source'];
const useUsageTranslation = () => {
@@ -83,6 +90,16 @@ const useCount = () => {
return React.useCallback((value: number) => new Intl.NumberFormat(i18n.language).format(value), [i18n.language]);
};
+/** The formatter for one metric's figures: dollars for 折合 API 价格, a count for the rest. */
+const useMetricFormat = (metric: UsageMetric) => {
+ const { i18n } = useTranslation();
+ const count = useCount();
+ return React.useCallback(
+ (value: number) => (metric === 'cost' ? formatUsd(value, i18n.language) : count(value)),
+ [count, i18n.language, metric],
+ );
+};
+
const tokenText = (
counters: UsageCounters,
metric: UsageMetric,
@@ -93,6 +110,10 @@ const tokenText = (
return value === null ? blank : count(value);
};
+/** Every priced token of these counters belongs to a model with no known price. */
+const usageHasNoPrice = (counters: UsageCounters): boolean =>
+ usageIsPriced(counters) && (counters.excluded_tokens ?? 0) > 0 && (counters.api_cost_usd ?? 0) === 0;
+
const metricLabel = (metric: UsageMetric, t: UsageTranslate): string =>
t(`settings.models.usage.metric.${metric}`);
@@ -227,6 +248,7 @@ const ChartLegend: React.FC<{
{series.map((item) => {
const values = item.values.filter((value): value is number => value !== null);
const total = values.reduce((sum, value) => sum + value, 0);
+ const floor = item.floors.some(Boolean);
const isHidden = hidden.includes(item.key);
return (
<button
@@ -238,7 +260,7 @@ const ChartLegend: React.FC<{
>
<span className="model-hub-usage-legend-swatch" style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />
<span>{labels.get(item.key) ?? item.label}</span>
- <strong>{values.length === 0 ? blank : count(total)}</strong>
+ <strong>{values.length === 0 ? blank : atLeast(count(total), floor)}</strong>
</button>
);
})}
@@ -264,6 +286,7 @@ function UsageChart({
}) {
const { t, i18n } = useUsageTranslation();
const count = useCount();
+ const format = useMetricFormat(metric);
const [hovered, setHovered] = React.useState<number | null>(null);
const [inspected, setInspected] = React.useState<number | null>(null);
const [dismissed, setDismissed] = React.useState(false);
@@ -304,7 +327,9 @@ function UsageChart({
? t('settings.models.usage.series.output')
: item.key === 'requests'
? t('settings.models.usage.series.requests')
- : item.label,
+ : item.key === 'cost'
+ ? metricLabel('cost', t)
+ : item.label,
])), [metric, series, t]);
const visibleSeries = series.filter((item) => !hidden.includes(item.key));
const narrow = width < 560;
@@ -524,7 +549,7 @@ function UsageChart({
hidden={hidden}
onToggle={toggleHidden}
labels={labels}
- count={count}
+ count={format}
blank={t('settings.models.usage.blank') as string}
ariaLabel={t('settings.models.usage.chart.legend') as string}
/>
@@ -546,7 +571,7 @@ function UsageChart({
{[0, 1, 2, 3, 4].map((step) => (
<g key={step}>
<line x1={left} x2={width - right} y1={y(max * step / 4)} y2={y(max * step / 4)} className="model-hub-usage-grid" strokeDasharray={step === 0 ? undefined : '3 5'} />
- <text x={left - 10} y={y(max * step / 4) + 4} textAnchor="end" className="model-hub-usage-tick">{count(max * step / 4)}</text>
+ <text x={left - 10} y={y(max * step / 4) + 4} textAnchor="end" className="model-hub-usage-tick">{format(max * step / 4)}</text>
</g>
))}
{activeIndex !== null && activeIndex >= 0 && (
@@ -693,14 +718,16 @@ function UsageChart({
</div>
</div>
<div className="model-hub-usage-tooltip-total">
- <strong>{activeValue === null ? t('settings.models.usage.blank') : count(activeValue)}</strong>
+ <strong>{activeValue === null ? t('settings.models.usage.blank') : atLeast(format(activeValue), costIsFloor(bucketRows, metric))}</strong>
<span>{metricLabel(metric, t)}</span>
</div>
<div className="model-hub-usage-tooltip-lines">
{visibleSeries.map((item) => (
<div key={item.key}>
<span><i style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />{labels.get(item.key) ?? item.label}</span>
- <b>{item.values[activeIndex as number] === null ? t('settings.models.usage.blank') : count(item.values[activeIndex as number] ?? 0)}</b>
+ <b>{item.values[activeIndex as number] === null
+ ? t('settings.models.usage.blank')
+ : atLeast(format(item.values[activeIndex as number] ?? 0), item.floors[activeIndex as number])}</b>
</div>
))}
</div>
@@ -718,6 +745,7 @@ function UsageChart({
</div>
<div className="model-hub-usage-chart-foot">
<span>{t('settings.models.usage.chart.points', { count: report.buckets.length, granularity: t(`settings.models.usage.granularity.${report.granularity}`) })}</span>
+ {metric === 'cost' && <span className="model-hub-usage-cost-note">{t('settings.models.usage.cost.notBilled')}</span>}
<span>{hidden.length > 0 ? t('settings.models.usage.chart.legendOnly') : t('settings.models.usage.chart.interaction')}</span>
</div>
</div>
@@ -791,6 +819,7 @@ export const UsageTab: React.FC<{
const [sourceIds, setSourceIds] = React.useState<string[]>([]);
const [modelKeys, setModelKeys] = React.useState<string[]>([]);
const [metric, setMetric] = React.useState<UsageMetric>('tokens');
+ const format = useMetricFormat(metric);
const [group, setGroup] = React.useState<UsageGroup>('type');
const [tableGroup, setTableGroup] = React.useState<'model' | 'source'>('model');
const [sortAscending, setSortAscending] = React.useState(false);
@@ -807,6 +836,10 @@ export const UsageTab: React.FC<{
setPinnedKey(null);
}, [scopeKey]);
+ React.useEffect(() => {
+ if (report !== null && metric === 'cost' && !reportIsPriced(report)) setMetric('tokens');
+ }, [report, metric]);
+
React.useEffect(() => {
if (report !== null && pinnedKey !== null && !report.buckets.some((bucket) => bucket.key === pinnedKey)) {
setPinnedKey(null);
@@ -871,8 +904,12 @@ export const UsageTab: React.FC<{
(activePinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === activePinnedKey))
.flatMap((bucket) => filterBucketRows(bucket, filter)),
);
- const metricText = (counters: UsageCounters, selectedMetric = metric) =>
- tokenText(counters, selectedMetric, count, t('settings.models.usage.blank') as string);
+ const metricText = (counters: UsageCounters, selectedMetric = metric) => {
+ const text = tokenText(counters, selectedMetric, selectedMetric === metric ? format : count, t('settings.models.usage.blank') as string);
+ // A cost that is only a floor keeps its 「≥」 wherever it is itemized.
+ return selectedMetric === 'cost' ? atLeast(text, counters.api_cost_lower_bound) : text;
+ };
+ const priced = reportIsPriced(report);
const partialHistoryNote = String(t('settings.models.usage.partialHistory'));
const unknownTokensNote = String(t('settings.models.usage.unknownTokens'));
const allReportedNote = String(t('settings.models.usage.stats.allReported'));
@@ -932,10 +969,10 @@ export const UsageTab: React.FC<{
onChange={(event) => {
const next = event.target.value as UsageMetric;
setMetric(next);
- if (next === 'requests' && group === 'type') setGroup('total');
+ if (unsplitMetric(next) && group === 'type') setGroup('total');
}}
>
- {metricKeys.map((key) => <option value={key} key={key}>{metricLabel(key, t)}</option>)}
+ {metricKeysFor(report).map((key) => <option value={key} key={key}>{metricLabel(key, t)}</option>)}
</select>
<ChevronDown aria-hidden className="size-3" />
</div>
@@ -964,7 +1001,7 @@ export const UsageTab: React.FC<{
<EmptyState kind="filter" onReset={() => { setSourceIds([]); setModelKeys([]); }} />
) : (
<>
- <div className="model-hub-usage-stat-grid">
+ <div className={cn('model-hub-usage-stat-grid', priced && 'model-hub-usage-stat-grid--priced')}>
<StatCard
label={t('settings.models.usage.stats.tokens')}
value={historyOnlyUnknown ? t('settings.models.usage.blank') : metricText(totals, 'tokens')}
@@ -986,6 +1023,25 @@ export const UsageTab: React.FC<{
? t('settings.models.usage.stats.cacheUnknown')
: t('settings.models.usage.stats.cacheSplit', { cached: count(totals.cached_input_tokens), input: count(totals.input_tokens) })}
/>
+ {priced && (
+ <StatCard
+ label={t('settings.models.usage.stats.cost')}
+ value={historyOnlyUnknown || !usageIsPriced(totals)
+ ? t('settings.models.usage.blank')
+ : usageHasNoPrice(totals)
+ ? t('settings.models.usage.cost.noPrice')
+ : formatCost(totals.api_cost_usd ?? 0, totals.api_cost_lower_bound, i18n.language)}
+ note={[
+ t('settings.models.usage.cost.notBilled'),
+ (totals.excluded_tokens ?? 0) > 0 && !usageHasNoPrice(totals)
+ ? t('settings.models.usage.cost.excluded', { count: totals.excluded_tokens ?? 0, tokens: count(totals.excluded_tokens ?? 0) })
+ : null,
+ report.pricing?.price_table_date
+ ? t('settings.models.usage.cost.tableDate', { date: report.pricing.price_table_date })
+ : t('settings.models.usage.cost.tableDateUnknown'),
+ ].filter(Boolean).join(' · ')}
+ />
+ )}
</div>
{(partialHistory || reportHasUnknownTokens(report, filter)) && (
<div className="model-hub-usage-notice" role="status">
@@ -1013,7 +1069,7 @@ export const UsageTab: React.FC<{
type="button"
key={key}
aria-pressed={group === key}
- disabled={key === 'type' && metric === 'requests'}
+ disabled={key === 'type' && unsplitMetric(metric)}
className={cn(group === key && 'is-selected')}
onClick={() => setGroup(key)}
>
@@ -1076,7 +1132,10 @@ export const UsageTab: React.FC<{
{sortedRows.map((row) => {
const value = usageMetricValue(row.counters, metric);
const totalValue = usageMetricValue(tableTotal, metric);
- const share = value === null || totalValue === null || totalValue === 0 ? null : value / totalValue;
+ // A share of a floor or of an unpriced part is not a known fraction.
+ const shareUnknown = metric === 'cost' && (row.counters.api_cost_lower_bound === true
+ || tableTotal.api_cost_lower_bound === true || usageHasNoPrice(row.counters));
+ const share = shareUnknown || value === null || totalValue === null || totalValue === 0 ? null : value / totalValue;
return (
<tr key={row.key}>
<th scope="row">
@@ -1088,7 +1147,9 @@ export const UsageTab: React.FC<{
<td>{usageTokensAreKnown(row.counters) ? count(usageNonCachedInput(row.counters)) : t('settings.models.usage.blank')}</td>
<td>{tokenText(row.counters, 'cache', count, t('settings.models.usage.blank') as string)}</td>
<td>{tokenText(row.counters, 'output', count, t('settings.models.usage.blank') as string)}</td>
- <td className="model-hub-usage-table-total">{value === null ? t('settings.models.usage.blank') : count(value)}</td>
+ <td className="model-hub-usage-table-total">{metric === 'cost' && usageHasNoPrice(row.counters)
+ ? t('settings.models.usage.cost.noPrice')
+ : metricText(row.counters)}</td>
<td>{share === null ? t('settings.models.usage.blank') : formatPercent(share, i18n.language, 1)}</td>
</tr>
);
diff --git a/ui/src/components/settings/models/format.test.ts b/ui/src/components/settings/models/format.test.ts
index ece6f4bf4..d55f363fe 100644
--- a/ui/src/components/settings/models/format.test.ts
+++ b/ui/src/components/settings/models/format.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { cooldownEtaMinutes, formatCount, formatDayTime, formatNameList, formatPercent, formatTokensCompact } from './format';
+import { atLeast, cooldownEtaMinutes, formatCost, formatCount, formatDayTime, formatNameList, formatPercent, formatTokensCompact, formatUsd } from './format';
describe('formatCount', () => {
it('groups so a figure can be read against a vendor console', () => {
@@ -96,3 +96,26 @@ describe('cooldownEtaMinutes', () => {
expect(cooldownEtaMinutes(new Date(Date.now() + 5 * 60_000 + 1_000).toISOString())).toBe(5);
});
});
+
+describe('formatUsd', () => {
+ // A value in dollars is a report, never a bill: two decimals, a sub-cent
+ // figure never reads as free, and a negative one never appears.
+ it('MH-USAGE-028: renders dollars with cents, a floor below one cent, and never a negative', () => {
+ expect(formatUsd(1234.5, 'en-US')).toBe('$1,234.50');
+ expect(formatUsd(1234.5, 'zh-CN')).toBe('$1,234.50');
+ expect(formatUsd(0, 'en-US')).toBe('$0.00');
+ expect(formatUsd(0.001, 'en-US')).toBe('<$0.01');
+ expect(formatUsd(-3, 'en-US')).toBe('$0.00');
+ });
+});
+
+describe('formatCost', () => {
+ it('MH-USAGE-032: marks a floor 「≥」, a floor of zero included, and leaves an exact figure bare', () => {
+ expect(formatCost(0, true, 'en-US')).toBe('≥ $0.00');
+ expect(formatCost(0, false, 'en-US')).toBe('$0.00');
+ expect(formatCost(12.5, true, 'en-US')).toBe('≥ $12.50');
+ expect(formatCost(12.5, undefined, 'en-US')).toBe('$12.50');
+ expect(atLeast('2.0×', true)).toBe('≥ 2.0×');
+ expect(atLeast('2.0×', false)).toBe('2.0×');
+ });
+});
diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.ts
index 947eb8552..705760585 100644
--- a/ui/src/components/settings/models/format.ts
+++ b/ui/src/components/settings/models/format.ts
@@ -54,6 +54,39 @@ export function formatPercent(ratio: number, locale: string, fractionDigits = 0)
}).format(ratio);
}
+/**
+ * A US-dollar figure in the reader's own grouping — 「$1,234.56」.
+ *
+ * Two decimals because an API-price valuation is compared against a monthly fee
+ * quoted in dollars and cents; a sub-cent figure shows as 「<$0.01」 rather than
+ * as a zero that reads as "free".
+ */
+export function formatUsd(value: number, locale: string): string {
+ const format = (amount: number) => new Intl.NumberFormat(locale, {
+ style: 'currency',
+ currency: 'USD',
+ currencyDisplay: 'narrowSymbol',
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }).format(amount);
+ if (value > 0 && value < 0.005) return `<${format(0.01)}`;
+ return format(Math.max(0, value));
+}
+
+/**
+ * A priced figure that may be only a floor. Every $ or multiple the value
+ * surfaces show goes through this with the server's `api_cost_lower_bound`, so a
+ * floor never reads as exact, a floor of zero included (「≥ $0.00」).
+ */
+export function atLeast(text: string, lowerBound: boolean | undefined): string {
+ return lowerBound === true ? `≥ ${text}` : text;
+}
+
+/** `formatUsd` for a figure that carries its lower-bound flag. */
+export function formatCost(value: number, lowerBound: boolean | undefined, locale: string): string {
+ return atLeast(formatUsd(value, locale), lowerBound);
+}
+
/**
* An instant as a short day-and-time in the reader's own zone — 「8/18 03:14」.
*
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 46b030de5..d1db14b22 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -2440,6 +2440,8 @@
gap: 10px;
}
+.model-hub-usage-stat-grid--priced { grid-template-columns: repeat(4, minmax(0, 1fr)); }
+
.model-hub-usage-stat-card {
display: flex;
min-width: 0;
@@ -2876,6 +2878,46 @@
.model-hub-quota-tone--danger { --model-hub-quota-tone: var(--destructive-ink); }
.model-hub-quota-tone--stale { --model-hub-quota-tone: var(--model-hub-ink-73); }
.model-hub-quota-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+.model-hub-quota-stats--valued { grid-template-columns: repeat(4, minmax(0, 1fr)); }
+@media (max-width: 950px) {
+ .model-hub-quota-stats--valued { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+}
+/* What the account's use would cost at API prices, against its monthly fee. */
+.model-hub-quota-value {
+ display: grid;
+ grid-auto-columns: minmax(0, 1fr);
+ grid-auto-flow: column;
+ margin-top: 14px;
+ border: 1px solid var(--border);
+ border-radius: 9px;
+ background: var(--surface);
+}
+.model-hub-quota-value > div { min-width: 0; padding: 10px 12px; }
+.model-hub-quota-value > div + div { border-left: 1px solid var(--border); }
+.model-hub-quota-value span { display: block; color: var(--model-hub-ink-8c); font-size: var(--model-hub-usage-label-size); }
+.model-hub-quota-value b {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 4px 6px;
+ margin-top: 5px;
+ color: var(--foreground);
+ font-size: 14px;
+ font-weight: 550;
+ font-variant-numeric: tabular-nums;
+}
+.model-hub-quota-value em {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-label-size);
+ font-style: normal;
+ font-weight: 400;
+}
+.model-hub-quota-value em.is-good { color: var(--mint-ink); }
+.model-hub-quota-value-note {
+ margin-top: 6px;
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-label-size);
+}
.model-hub-quota-stat--primary { border-color: var(--model-hub-mint-4d); }
.model-hub-quota-stat-unit {
margin-left: 5px;
@@ -3040,6 +3082,11 @@
}
}
+/* Four cost-bearing cards need the full width; between tablet and desktop they pair up. */
+@media (max-width: 1100px) {
+ .model-hub-usage-stat-grid--priced { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+}
+
@media (max-width: 767px) {
.model-hub-source-table-head { display: none; }
.model-hub-source-table-row,
@@ -3054,7 +3101,8 @@
.model-hub-usage-heading { align-items: flex-start; flex-direction: column; }
.model-hub-usage-window { width: 100%; }
.model-hub-usage-filter-context { width: 100%; margin-left: 0; }
- .model-hub-usage-stat-grid { grid-template-columns: 1fr; }
+ .model-hub-usage-stat-grid,
+ .model-hub-usage-stat-grid--priced { grid-template-columns: 1fr; }
.model-hub-usage-card-header { align-items: flex-start; flex-direction: column; }
.model-hub-usage-group-control { width: 100%; align-items: flex-start; flex-direction: column; }
.model-hub-usage-group-control > div { width: 100%; }
@@ -3066,6 +3114,8 @@
.model-hub-quota-row-foot { flex-direction: column; gap: 4px; }
.model-hub-quota-reset { white-space: normal; }
.model-hub-quota-timeline-title { width: 100%; }
+ .model-hub-quota-value > div { padding: 9px 8px; }
+ .model-hub-quota-value b { font-size: 12px; }
}
@media (min-width: 1024px) {
diff --git a/ui/src/components/settings/models/quotaProjection.ts b/ui/src/components/settings/models/quotaProjection.ts
index 1065763f2..8b4c0e74b 100644
--- a/ui/src/components/settings/models/quotaProjection.ts
+++ b/ui/src/components/settings/models/quotaProjection.ts
@@ -153,3 +153,26 @@ export const windowLeftPct = (window: QuotaWindow, now: number): number =>
/** Whole percent used, the complement of `windowLeftPct`: a limit with headroom never reads as 100% used. */
export const windowUsedPct = (window: QuotaWindow, now: number): number => 100 - windowLeftPct(window, now);
+
+/**
+ * How an API-price valuation compares with the plan's monthly fee.
+ *
+ * `multiple` is value ÷ fee. From 1.1× the plan has clearly paid for itself; from
+ * 1× to just under 1.1× it has only just done so, and a multiple that rounds to
+ * 「1.0 倍」 is not a figure worth boasting; below 1× the gap is the dollars
+ * still to go.
+ */
+export type QuotaPayback =
+ | { kind: 'paid'; multiple: number; surplusUsd: number }
+ | { kind: 'even'; multiple: number; surplusUsd: number }
+ | { kind: 'short'; multiple: number; shortfallUsd: number };
+
+export const PAYBACK_CLEAR_MULTIPLE = 1.1;
+
+export function quotaPayback(costUsd: number, feeUsd: number): QuotaPayback | null {
+ if (!(feeUsd > 0) || !Number.isFinite(costUsd)) return null;
+ const multiple = costUsd / feeUsd;
+ if (multiple >= PAYBACK_CLEAR_MULTIPLE) return { kind: 'paid', multiple, surplusUsd: costUsd - feeUsd };
+ if (multiple >= 1) return { kind: 'even', multiple, surplusUsd: costUsd - feeUsd };
+ return { kind: 'short', multiple, shortfallUsd: feeUsd - costUsd };
+}
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 9768866c3..8462d41b3 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -777,9 +777,37 @@ export type UsageCounters = {
/** Subset of `input_tokens` served from cache. */
cached_input_tokens: number;
output_tokens: number;
+ /** Subset of `input_tokens` written to the prompt cache, disjoint from cached
+ * input. Codex reports none. Absent on a server that predates the field. */
+ cache_write_input_tokens?: number;
+ /** Subset of `cache_write_input_tokens` written with the one-hour lifetime. */
+ cache_write_1h_input_tokens?: number;
+ /** Token reports that could not carry cache writes (metered before they were
+ * captured, or on a protocol without them). */
+ cache_write_uncaptured_reports?: number;
+} & Partial<PricedUsage>;
+
+/** API-price valuation of one span: what it would have cost at list API
+ * prices. A valuation, never an amount charged. */
+export type PricedUsage = {
+ api_cost_usd: number;
+ /** input + output tokens of models with no known price, left out of the cost. */
+ excluded_tokens: number;
+ /** True when part of the cost predates cache-write capture on a model that
+ * charges for it, so the figure understates. */
+ api_cost_lower_bound: boolean;
+};
+
+export type UsagePricing = {
+ currency: 'USD';
+ /** Local date the price table was fetched; null when only overrides priced. */
+ price_table_date: string | null;
};
export type UsageByModel = UsageCounters & {
+ /** False when no price is known for the model: its tokens are in
+ * `excluded_tokens`. Present exactly when the report is priced. */
+ priced?: boolean;
/** Ledger key, which for a long identifier is a head plus a digest rather
* than the identifier itself — a string nobody typed. Display `label`,
* never this. `usageProjection.modelIdentity` is the only reader. */
@@ -816,6 +844,8 @@ export type UsageSummary = {
/** One entry per local day carrying a metered turn, oldest first — a trend
* series, so a day with no turn is ABSENT rather than reported as zero. */
days: UsageByDay[];
+ /** Present when the server priced the report. */
+ pricing?: UsagePricing;
};
export type UsageWindowKey = '24h' | '7d' | '30d' | '60d';
@@ -849,9 +879,9 @@ export const USAGE_WINDOW_MAX_DAYS = 62 as const;
export const USAGE_DEFAULT_WINDOW_DAYS = 30 as const;
export const USAGE_DEFAULT_WINDOW: UsageWindowKey = '24h';
-/** `quota-summary.schema.json` — a subscription's own rate-limit windows. A
- * report, like usage: nothing in routing reads it. Money is deliberately absent;
- * the contract reserves an optional `value` block for it. */
+/** `quota-summary.schema.json` — a subscription's own rate-limit windows, and
+ * what its metered usage would have cost at API prices. A report, like usage:
+ * nothing in routing reads it. */
export type QuotaWindowKind = 'session' | 'weekly' | 'model_weekly' | 'other';
export type QuotaWindow = {
@@ -878,11 +908,40 @@ export type SourceQuota = {
state: QuotaSourceState;
error_key?: string;
windows: QuotaWindow[];
+ /** Absent means "not reported", never zero. */
+ value?: SourceQuotaValue;
+};
+
+export type QuotaValuePeriod = PricedUsage & {
+ /** billing_cycle from a configured renewal day, else the trailing 30 days. */
+ basis: 'billing_cycle' | 'rolling_30d';
+ from_day: string;
+ to_day: string;
+ renews_on: string | null;
+};
+
+export type SourceQuotaValue = UsagePricing & {
+ /** Fee-table key; null when the plan is unknown, and then no payback shows. */
+ plan_key: string | null;
+ fee_usd: number | null;
+ /** period.api_cost_usd / fee_usd; null exactly when the fee is unknown. */
+ multiple: number | null;
+ week: PricedUsage;
+ period: QuotaValuePeriod;
+};
+
+export type QuotaValueTotals = UsagePricing & {
+ week: PricedUsage;
+ /** Only the Sources with a known fee; null when none has one. */
+ period: (PricedUsage & { sources: number; fee_usd: number; multiple: number }) | null;
};
export type QuotaSummary = {
refresh_interval_seconds: number;
sources: SourceQuota[];
+ /** Sources whose read is still running past the page deadline; re-read soon. */
+ pending?: string[];
+ value?: QuotaValueTotals;
};
// ── API envelope + request shapes (api.md) ──────────────────────────────
diff --git a/ui/src/components/settings/models/usageProjection.test.ts b/ui/src/components/settings/models/usageProjection.test.ts
index 53dfec9bb..265bbd68e 100644
--- a/ui/src/components/settings/models/usageProjection.test.ts
+++ b/ui/src/components/settings/models/usageProjection.test.ts
@@ -2,15 +2,19 @@ import { describe, expect, it } from 'vitest';
import type { UsageBucket, UsageBucketRow, UsageCounters, UsageReport } from './types';
import {
+ aggregateCounters,
formatBucketAxisLabel,
formatBucketRange,
identityLabel,
pairKey,
reportHasPartialHistory,
+ reportIsPriced,
seriesFor,
sourceIdentityLabel,
usageLabelContext,
usageIsEmpty,
+ usageIsPriced,
+ usageMetricValue,
usageNonCachedInput,
usageTotalTokens,
} from './usageProjection';
@@ -209,4 +213,24 @@ describe('usageProjection', () => {
}, 'en-US')).toBe('Sep 24');
expect(formatBucketRange(hourly, 'en-US')).toContain('Sep 24, 2026');
});
+
+ // A total at API price is the sum of its rows, and it is a price only when
+ // every row was priced: a server that predates valuation must not read as $0.
+ it('MH-USAGE-028: sums API price only across rows that all carry one', () => {
+ const priced = aggregateCounters([
+ counters({ api_cost_usd: 1.25, excluded_tokens: 0, api_cost_lower_bound: false }),
+ counters({ api_cost_usd: 0.5, excluded_tokens: 30, api_cost_lower_bound: true }),
+ ]);
+ expect(priced.api_cost_usd).toBeCloseTo(1.75);
+ expect(priced.excluded_tokens).toBe(30);
+ expect(priced.api_cost_lower_bound).toBe(true);
+ expect(usageMetricValue(priced, 'cost')).toBeCloseTo(1.75);
+
+ const mixed = aggregateCounters([counters({ api_cost_usd: 1 }), counters()]);
+ expect(usageIsPriced(mixed)).toBe(false);
+ expect(usageMetricValue(mixed, 'cost')).toBeNull();
+ expect(usageMetricValue(counters({ requests: 0, token_reports: 0 }), 'cost')).toBe(0);
+ expect(reportIsPriced(reportWith([]))).toBe(false);
+ expect(reportIsPriced({ ...reportWith([]), pricing: { currency: 'USD', price_table_date: null } })).toBe(true);
+ });
});
diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.ts
index a5854d491..f3d878a86 100644
--- a/ui/src/components/settings/models/usageProjection.ts
+++ b/ui/src/components/settings/models/usageProjection.ts
@@ -3,13 +3,14 @@ import type {
UsageBucketRow,
UsageCounters,
UsageReport,
+ UsageSummary,
UsageWindowKey,
} from './types';
export const USAGE_WINDOW_OPTIONS = ['24h', '7d', '30d', '60d'] as const satisfies readonly UsageWindowKey[];
export type UsageWindowOption = UsageWindowKey;
-export type UsageMetric = 'tokens' | 'input' | 'output' | 'cache' | 'requests';
+export type UsageMetric = 'tokens' | 'input' | 'output' | 'cache' | 'requests' | 'cost';
export type UsageGroup = 'total' | 'type' | 'model' | 'source';
export type UsageFilter = {
sourceIds: readonly string[];
@@ -37,6 +38,8 @@ export type UsageSeries = {
label: string;
colorIndex: number;
values: Array<number | null>;
+ /** Per bucket, whether the value is only a floor (`api_cost_lower_bound`); cost only. */
+ floors: boolean[];
};
export const PAIR_SEPARATOR = '\u0000';
@@ -53,15 +56,28 @@ export const emptyCounters = (): UsageCounters => ({
});
export function aggregateCounters(rows: readonly UsageCounters[]): UsageCounters {
- return rows.reduce((total, row) => ({
- requests: total.requests + row.requests,
- token_reports: total.token_reports + row.token_reports,
- input_tokens: total.input_tokens + row.input_tokens,
- cached_input_tokens: total.cached_input_tokens + row.cached_input_tokens,
- output_tokens: total.output_tokens + row.output_tokens,
+ const total = rows.reduce<UsageCounters>((sum, row) => ({
+ requests: sum.requests + row.requests,
+ token_reports: sum.token_reports + row.token_reports,
+ input_tokens: sum.input_tokens + row.input_tokens,
+ cached_input_tokens: sum.cached_input_tokens + row.cached_input_tokens,
+ output_tokens: sum.output_tokens + row.output_tokens,
}), emptyCounters());
+ // A priced row carries its cost; the sum is priced only when every row is.
+ if (rows.length > 0 && rows.every(usageIsPriced)) {
+ total.api_cost_usd = rows.reduce((sum, row) => sum + (row.api_cost_usd ?? 0), 0);
+ total.excluded_tokens = rows.reduce((sum, row) => sum + (row.excluded_tokens ?? 0), 0);
+ total.api_cost_lower_bound = rows.some((row) => row.api_cost_lower_bound === true);
+ }
+ return total;
}
+/** Whether the server priced these counters at API prices. */
+export const usageIsPriced = (counters: UsageCounters): boolean => typeof counters.api_cost_usd === 'number';
+
+/** Whether the report carries API-price value at all: a server that predates it never does. */
+export const reportIsPriced = (report: UsageSummary): boolean => report.pricing !== undefined;
+
export function usageTotalTokens(counters: UsageCounters): number {
return counters.input_tokens + counters.output_tokens;
}
@@ -84,6 +100,8 @@ export function usageTokensAreReported(counters: Pick<UsageCounters, 'token_repo
export function usageMetricValue(counters: UsageCounters, metric: UsageMetric): number | null {
if (metric === 'requests') return counters.requests;
+ // Nothing metered costs nothing, priced or not.
+ if (metric === 'cost') return usageIsPriced(counters) ? counters.api_cost_usd ?? 0 : counters.requests === 0 ? 0 : null;
if (!usageTokensAreKnown(counters)) return null;
if (metric === 'tokens') return usageTotalTokens(counters);
if (metric === 'input') return counters.input_tokens;
@@ -322,6 +340,9 @@ const typeSeries = (
metric: UsageMetric,
historyComplete: boolean,
): Array<[string, number | null]> => {
+ if (metric === 'cost') {
+ return [['cost', !historyComplete && rows.length === 0 ? null : usageMetricValue(aggregateCounters(rows), 'cost')]];
+ }
if (!historyComplete && rows.length === 0) {
if (metric === 'requests') return [['requests', null]];
if (metric === 'output') return [['output', null]];
@@ -348,6 +369,11 @@ const typeSeries = (
];
};
+/** Whether these rows' cost is only a floor, as the server marked it. */
+export const costIsFloor = (rows: readonly UsageCounters[], metric: UsageMetric): boolean => (
+ metric === 'cost' && aggregateCounters(rows).api_cost_lower_bound === true
+);
+
const bucketMetricValue = (
bucket: UsageBucket,
rows: UsageBucketRow[],
@@ -377,12 +403,15 @@ export function seriesFor(
cache: 'Cache reads',
output: 'Output',
requests: 'Requests',
+ cost: 'API price',
};
+ const floors = report.buckets.map((bucket) => costIsFloor(filterBucketRows(bucket, filter), metric));
return [...valuesByKey.entries()].map(([key, values], index) => ({
key,
label: labels[key],
colorIndex: index,
values,
+ floors,
}));
}
@@ -396,6 +425,7 @@ export function seriesFor(
filterBucketRows(bucket, filter),
metric,
)),
+ floors: report.buckets.map((bucket) => costIsFloor(filterBucketRows(bucket, filter), metric)),
}];
}
@@ -410,6 +440,10 @@ export function seriesFor(
const rowsForSource = filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId);
return bucketMetricValue(bucket, rowsForSource, metric);
}),
+ floors: report.buckets.map((bucket) => costIsFloor(
+ filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId),
+ metric,
+ )),
}));
}
@@ -425,6 +459,12 @@ export function seriesFor(
));
return bucketMetricValue(bucket, rowsForIdentity, metric);
}),
+ floors: report.buckets.map((bucket) => costIsFloor(
+ filterBucketRows(bucket, filter).filter((row) => (
+ row.source_id === identity.sourceId && row.model_id === identity.modelId
+ )),
+ metric,
+ )),
}));
}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 5ad1a0343..1048556ed 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1405,10 +1405,42 @@
"exhaustedNone": "Every account is usable",
"exhaustedNoneObserved": "None used up in current readings",
"exhaustedNote": "{{name}} · back {{time}}",
- "resetsIn": "resets in {{duration}}"
+ "resetsIn": "resets in {{duration}}",
+ "weekValue": "Last 7 days at API price",
+ "weekValueNote": "All subscription use, at the vendors’ published API prices",
+ "payback": "Paid back this period",
+ "paybackMultiple": "{{multiple}}×",
+ "paybackUnit": "the monthly fee",
+ "paybackPaid": "Paid back, {{amount}} ahead",
+ "paybackShort": "{{amount}} to pay back",
+ "paybackShortUnknown": "Some usage has no price, so the gap isn’t shown",
+ "paybackRolling": "Accounts without a renewal day use the last 30 days",
+ "paybackPartial_one": "{{count}} account with an unknown plan left out",
+ "paybackPartial_other": "{{count}} accounts with an unknown plan left out",
+ "paybackUnknown": "Plan unknown, so payback isn’t shown"
},
"upcoming": "Resetting soon",
- "footnote": "The bar is the part used; the thin mark is how much of this period has passed. A bar past the mark is spending faster than time."
+ "footnote": "The bar is the part used; the thin mark is how much of this period has passed. A bar past the mark is spending faster than time.",
+ "pending": "Reading quota…",
+ "footnoteValue": "“At API price” is what the same use would cost at the vendor’s published API price — a way to judge the plan, not a charge.",
+ "priceTableDate": "Price table from {{date}}.",
+ "priceTableUnknown": "Price table date unknown.",
+ "value": {
+ "week": "Last 7 days at API price",
+ "period": {
+ "billing_cycle": "This cycle at API price",
+ "rolling_30d": "Last 30 days at API price"
+ },
+ "noPrice": "No price yet",
+ "paid": "Paid back {{multiple}}×",
+ "even": "Just paid back",
+ "short": "{{amount}} to pay back",
+ "shortUnknown": "Not all usage is priced, so the gap isn’t shown",
+ "renews": "Next renewal",
+ "renewsIn_one": "in {{count}} day",
+ "renewsIn_other": "in {{count}} days",
+ "excluded": "{{tokens}} tokens have no price and are left out"
+ }
},
"usage": {
"title": "Usage",
@@ -1422,7 +1454,16 @@
"60d": "60 days"
},
"range": "{{from}} – {{to}} · trailing {{days}} days",
- "empty": "Nothing metered yet. A window fills once a gateway source serves a request.",
+ "empty": {
+ "report": {
+ "title": "No usage in this window",
+ "body": "The gateway has not recorded a request in the selected time range."
+ },
+ "filter": {
+ "title": "No matching usage",
+ "body": "Try another Source or model, or reset the filters."
+ }
+ },
"blank": "—",
"tokens": {
"label": "Tokens",
@@ -1472,7 +1513,8 @@
"input": "Input (including cache)",
"output": "Output",
"cache": "Cache reads",
- "requests": "Requests"
+ "requests": "Requests",
+ "cost": "At API price"
},
"filters": {
"source": "Source",
@@ -1500,7 +1542,8 @@
"shortfall_other": "{{count}} requests have no token report",
"allReported": "Every request reported tokens",
"cacheUnknown": "No measured input available",
- "cacheSplit": "{{cached}} cached of {{input}} input"
+ "cacheSplit": "{{cached}} cached of {{input}} input",
+ "cost": "At API price"
},
"unknownTokens": "Some requests have no token report; token values are unavailable",
"partialHistory": "Some buckets have incomplete history",
@@ -1583,18 +1626,16 @@
"outputTokens": "Output tokens",
"totalTokens": "Total tokens"
},
- "empty": {
- "report": {
- "title": "No usage in this window",
- "body": "The gateway has not recorded a request in the selected time range."
- },
- "filter": {
- "title": "No matching usage",
- "body": "Try another Source or model, or reset the filters."
- }
- },
"failure": "The usage report could not be read.",
- "retry": "Retry"
+ "retry": "Retry",
+ "cost": {
+ "notBilled": "At published API prices, not a charge",
+ "noPrice": "No price yet",
+ "excluded_one": "{{tokens}} token has no price and is left out",
+ "excluded_other": "{{tokens}} tokens have no price and are left out",
+ "tableDate": "Price table from {{date}}",
+ "tableDateUnknown": "Price table date unknown"
+ }
},
"supplyTooltip": {
"label": "Supplies: "
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b4f137ea0..17589d590 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1405,10 +1405,42 @@
"exhaustedNone": "所有账号都能正常使用",
"exhaustedNoneObserved": "已读到的额度都没用完",
"exhaustedNote": "{{name}} · {{time}} 恢复",
- "resetsIn": "{{duration}}后重置"
+ "resetsIn": "{{duration}}后重置",
+ "weekValue": "近 7 天按 API 价格",
+ "weekValueNote": "所有订阅账号的用量,按官方 API 标价计算",
+ "payback": "本期回本",
+ "paybackMultiple": "{{multiple}} 倍",
+ "paybackUnit": "月费",
+ "paybackPaid": "已回本,多薅了 {{amount}}",
+ "paybackShort": "还差 {{amount}} 回本",
+ "paybackShortUnknown": "部分用量暂无价格,差额暂不显示",
+ "paybackRolling": "未设续费日的账号按近 30 天计",
+ "paybackPartial_one": "{{count}} 个账号套餐未知,未计入",
+ "paybackPartial_other": "{{count}} 个账号套餐未知,未计入",
+ "paybackUnknown": "套餐未知,暂不计算回本"
},
"upcoming": "即将重置",
- "footnote": "进度条是已用的部分,细竖线是这个周期已经过去的时间:进度条超过竖线,就是用得比时间快。"
+ "footnote": "进度条是已用的部分,细竖线是这个周期已经过去的时间:进度条超过竖线,就是用得比时间快。",
+ "pending": "正在读取额度…",
+ "footnoteValue": "“按 API 价格”指同样的用量按官方 API 标价要花多少钱,用来看订阅值不值,不是实际扣费。",
+ "priceTableDate": "价格表日期 {{date}}。",
+ "priceTableUnknown": "暂无价格表日期。",
+ "value": {
+ "week": "近 7 天按 API 价格",
+ "period": {
+ "billing_cycle": "本期按 API 价格",
+ "rolling_30d": "近 30 天按 API 价格"
+ },
+ "noPrice": "暂无价格",
+ "paid": "回本 {{multiple}} 倍",
+ "even": "刚好回本",
+ "short": "还差 {{amount}} 回本",
+ "shortUnknown": "部分用量暂无价格,差额暂不显示",
+ "renews": "距下次续费",
+ "renewsIn_one": "{{count}} 天",
+ "renewsIn_other": "{{count}} 天",
+ "excluded": "{{tokens}} tokens 暂无价格,未计入"
+ }
},
"usage": {
"title": "用量",
@@ -1422,7 +1454,16 @@
"60d": "60 天"
},
"range": "{{from}} – {{to}} · 近 {{days}} 天",
- "empty": "还没有计量数据。模型网关完成请求后,这里就会有内容。",
+ "empty": {
+ "report": {
+ "title": "这个区间没有用量",
+ "body": "模型网关在所选时间范围内还没有记录请求。"
+ },
+ "filter": {
+ "title": "没有符合条件的用量",
+ "body": "试试其他供应商或模型,或重置筛选。"
+ }
+ },
"blank": "—",
"tokens": {
"label": "Tokens",
@@ -1472,7 +1513,8 @@
"input": "输入(含缓存)",
"output": "输出",
"cache": "缓存读取",
- "requests": "请求数"
+ "requests": "请求数",
+ "cost": "折合 API 价格"
},
"filters": {
"source": "供应商",
@@ -1500,7 +1542,8 @@
"shortfall_other": "{{count}} 次请求没有回报 token",
"allReported": "每次请求都回报了 token",
"cacheUnknown": "暂无已知输入 token",
- "cacheSplit": "输入 {{input}} 中有 {{cached}} 来自缓存"
+ "cacheSplit": "输入 {{input}} 中有 {{cached}} 来自缓存",
+ "cost": "折合 API 价格"
},
"unknownTokens": "部分请求没有回报 token,相关 token 数值不可用",
"partialHistory": "部分时间桶的历史记录不完整",
@@ -1583,18 +1626,16 @@
"outputTokens": "输出 token",
"totalTokens": "总 token"
},
- "empty": {
- "report": {
- "title": "这个区间没有用量",
- "body": "模型网关在所选时间范围内还没有记录请求。"
- },
- "filter": {
- "title": "没有符合条件的用量",
- "body": "试试其他供应商或模型,或重置筛选。"
- }
- },
"failure": "暂时没能读取用量报表。",
- "retry": "重试"
+ "retry": "重试",
+ "cost": {
+ "notBilled": "按官方 API 标价折算,不是实际扣费",
+ "noPrice": "暂无价格",
+ "excluded_one": "{{tokens}} tokens 暂无价格,未计入",
+ "excluded_other": "{{tokens}} tokens 暂无价格,未计入",
+ "tableDate": "价格表日期 {{date}}",
+ "tableDateUnknown": "暂无价格表日期"
+ }
},
"supplyTooltip": {
"label": "使用:"
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 3045bdcf4..f0c9f42f1 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -40,8 +40,10 @@ from core.handlers.model_hub.adapter import (
from core.handlers.model_hub.errors import ModelDiscoveryError
from core.handlers.model_hub.identifiers import model_id_without_credential_address
from core.handlers.model_hub.quota import (
+ CLAUDE_PLAN_FETCH_TIMEOUT_SECONDS,
QUOTA_FETCH_TIMEOUT_SECONDS,
SubscriptionQuotaError,
+ parse_claude_plan,
parse_subscription_quota,
)
from core.handlers.model_hub.async_owner import run_owned_in_thread
@@ -1239,7 +1241,33 @@ def _fetch_subscription_quota(
)
if not isinstance(status, int) or isinstance(status, bool) or status not in _SUCCESS_STATUSES:
raise SubscriptionQuotaError("unavailable")
- return parse_subscription_quota(vendor, payload.get("body"))
+ parsed = parse_subscription_quota(vendor, payload.get("body"))
+ if vendor == "anthropic" and parsed.get("plan") is None:
+ parsed["plan"] = _fetch_claude_plan(client=client, auth=auth)
+ return parsed
+
+
+def _fetch_claude_plan(*, client: EngineClient, auth: _AuthRecord) -> str | None:
+ """Claude's usage report names no plan; read it from the profile, best effort."""
+
+ try:
+ payload = client.management_request(
+ "POST",
+ "/api-call",
+ payload={
+ "auth_index": auth.auth_index,
+ "method": "GET",
+ "url": _OAUTH_CONTROL_PLANE_URLS["anthropic"],
+ "header": _oauth_account_call_headers(auth, "anthropic"),
+ },
+ timeout=CLAUDE_PLAN_FETCH_TIMEOUT_SECONDS,
+ )
+ except (EngineClientError, OSError):
+ return None
+ status = payload.get("status_code")
+ if not isinstance(status, int) or isinstance(status, bool) or status not in _SUCCESS_STATUSES:
+ return None
+ return parse_claude_plan(payload.get("body"))
def _probe_oauth_control_plane_witness(
diff --git a/vibe/models_dev_catalog.py b/vibe/models_dev_catalog.py
index b71889340..9ea942428 100644
--- a/vibe/models_dev_catalog.py
+++ b/vibe/models_dev_catalog.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import logging
import os
import re
import threading
@@ -20,6 +21,8 @@ from config.v2_config import (
from core.handlers.model_hub.catalog_admission import admissible_backend_model
+logger = logging.getLogger(__name__)
+
MODELS_DEV_URL_ENV = "AVIBE_MODELS_DEV_URL"
DEFAULT_MODELS_DEV_URL = "https://models.dev/api.json"
MODELS_DEV_TIMEOUT_SECONDS = 8.0
@@ -201,6 +204,52 @@ def load_models_dev_catalog() -> dict[str, Any]:
raise RuntimeError("models.dev catalog is unavailable") from None
+_REFRESH_IN_FLIGHT = threading.Event()
+
+
+def _refresh_in_background() -> None:
+ def refresh() -> None:
+ try:
+ # Only the read is locked: request-path readers must not wait on the
+ # network, and the write is atomic on its own.
+ with _CACHE_LOCK:
+ cached = _read_cache()
+ _fetch_catalog(cached)
+ except Exception: # noqa: BLE001 - a background refresh has no one to report to
+ logger.debug("models.dev background refresh failed", exc_info=True)
+ finally:
+ _REFRESH_IN_FLIGHT.clear()
+
+ if _REFRESH_IN_FLIGHT.is_set():
+ return
+ _REFRESH_IN_FLIGHT.set()
+ threading.Thread(target=refresh, name="models-dev-refresh", daemon=True).start()
+
+
+def load_models_dev_catalog_with_date() -> tuple[dict[str, Any], float | None]:
+ """The catalog and when it was fetched, without waiting on the network when a copy exists.
+
+ For readers on a request path, such as usage valuation: a stale cached copy is
+ returned at once and refreshed in the background, since a day-old price table
+ is still the best one there is and the reader shows its date. With no cached
+ copy at all it starts that fetch and returns an empty catalog, so the first
+ read reports nothing as priced rather than holding a page on the network.
+ """
+
+ with _CACHE_LOCK:
+ cached = _read_cache()
+ catalog = _catalog_from_cache(cached) if cached.get("url") == _models_dev_url() else None
+ fetched_at = cached.get("fetched_at")
+ fetched = float(fetched_at) if isinstance(fetched_at, (int, float)) and not isinstance(fetched_at, bool) else None
+ if catalog is not None:
+ age = time.time() - fetched if fetched is not None else None
+ if age is None or not 0 <= age < MODELS_DEV_CACHE_TTL_SECONDS:
+ _refresh_in_background()
+ return catalog, fetched
+ _refresh_in_background()
+ return {}, None
+
+
def _search_tokens(query: str) -> tuple[str, ...]:
lowered = query.strip().lower()
tokens = [lowered]