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(model-hub): subscription quota tab (#2171)

Call White6af1066eb3a1
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index c45660468..0bfc0682b 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -567,6 +567,17 @@ class EngineAdapter(Protocol):
"""
...
+ async def subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> dict[str, Any]:
+ """Read this subscription's rate-limit windows from the vendor's usage report.
+
+ The engine makes the model-free account call with the bound grant; only
+ the parsed ``{plan, windows}`` crosses this boundary, never the grant or
+ the raw body. Raise ``SubscriptionQuotaError`` with a sanitized reason
+ (``auth_expired``, ``rate_limited``, ``unsupported``, ``unavailable`` or
+ ``malformed``) on every failure. A report only: never feeds resolution.
+ """
+ ...
+
async def retarget_api_key_credential(
self,
credential_ref: str,
diff --git a/core/handlers/model_hub/quota.py b/core/handlers/model_hub/quota.py
new file mode 100644
index 000000000..cf185472e
--- /dev/null
+++ b/core/handlers/model_hub/quota.py
@@ -0,0 +1,554 @@
+"""Subscription quota: parse the vendors' own usage reports into rate-limit windows.
+
+A logged-in subscription (Claude, ChatGPT/Codex) exposes how much of each of its
+rate-limit windows is used through a model-free account endpoint. The engine that
+holds the grant makes the call; this module only turns the returned body into the
+`quota-summary.schema.json` window shape. It is a report, like usage metering:
+nothing in resolution, admission, or cooldown reads it.
+
+Parsing is defensive by construction. A vendor may add, rename, or null a window
+at any time, so a window we cannot read is skipped, a window we do not recognise
+is rendered generically from its upstream name, and a body that is not the shape
+at all raises `SubscriptionQuotaError("malformed")` — a per-Source failure, never
+a page failure. Only the parsed fields leave this module; the body does not.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import itertools
+import json
+import logging
+import math
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from typing import Any, Awaitable, Callable, Final, Literal, Mapping, Optional, Sequence
+
+logger = logging.getLogger(__name__)
+
+QuotaWindowKind = Literal["session", "weekly", "model_weekly", "other"]
+QuotaFailure = Literal["auth_expired", "rate_limited", "unsupported", "unavailable", "malformed"]
+
+SESSION_WINDOW_SECONDS: Final = 5 * 3600
+WEEKLY_WINDOW_SECONDS: Final = 7 * 86400
+# Upstream labels are user-visible; bound them so a hostile body cannot flood the page.
+_MAX_LABEL_CHARS: Final = 64
+_MAX_WINDOWS: Final = 16
+# Rows read from any one upstream array or object. A report carries a handful;
+# a hostile or runaway body stops costing work here, before anything is built.
+_MAX_UPSTREAM_ROWS: Final = 64
+# A usage report is a few KiB; refuse anything far larger before decoding it.
+_MAX_BODY_BYTES: Final = 256 * 1024
+
+QUOTA_VENDORS: Final = frozenset({"anthropic", "openai", "codex"})
+
+# Claude's legacy top-level keys. `seven_day_oauth_apps` is an app-surface limit
+# Claude Code itself does not present, so it is deliberately not a window here.
+_CLAUDE_TOP_LEVEL: Final[Mapping[str, tuple[QuotaWindowKind, Optional[str]]]] = {
+ "five_hour": ("session", None),
+ "seven_day": ("weekly", None),
+ "seven_day_opus": ("model_weekly", "Opus"),
+ "seven_day_sonnet": ("model_weekly", "Sonnet"),
+ "seven_day_overage_included": ("model_weekly", "Fable"),
+}
+_CLAUDE_SKIPPED_TOP_LEVEL: Final = frozenset({"seven_day_oauth_apps", "extra_usage", "limits"})
+
+# Codex meters Spark under a feature id rather than a model name.
+_CODEX_FEATURE_LABELS: Final[Mapping[str, str]] = {"codex_bengalfox": "Spark"}
+
+
+class SubscriptionQuotaError(RuntimeError):
+ """A sanitized, per-Source quota failure. Carries no upstream text."""
+
+ def __init__(self, reason: QuotaFailure, *, retry_after_seconds: Optional[float] = None):
+ super().__init__(f"subscription quota {reason}")
+ self.reason: QuotaFailure = reason
+ self.retry_after_seconds = retry_after_seconds
+
+
+def _label(value: object) -> Optional[str]:
+ if not isinstance(value, str):
+ return None
+ text = " ".join(value.split())
+ return text[:_MAX_LABEL_CHARS] or None
+
+
+def _number(value: object) -> Optional[float]:
+ """The one numeric coercion for upstream values: anything unreadable is missing."""
+
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ try:
+ # JSON integers are unbounded; one too large for a float is unreadable, not a crash.
+ number = float(value)
+ except (OverflowError, ValueError):
+ return None
+ return number if math.isfinite(number) else None
+
+
+def _percent(value: object) -> Optional[float]:
+ number = _number(value)
+ if number is None:
+ return None
+ rounded = round(min(100.0, max(0.0, number)), 1)
+ # 100 means spent; rounding must not promote a limit with headroom to it.
+ return 99.9 if rounded >= 100.0 and number < 100.0 else rounded
+
+
+def _seconds(value: object) -> Optional[int]:
+ number = _number(value)
+ if number is None or number < 1:
+ return None
+ return int(number)
+
+
+def _iso(moment: datetime) -> str:
+ return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _iso_timestamp(value: object) -> Optional[str]:
+ if not isinstance(value, str) or not value.strip():
+ return None
+ try:
+ moment = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ if moment.tzinfo is None:
+ moment = moment.replace(tzinfo=timezone.utc)
+ return _iso(moment)
+ except (OverflowError, ValueError):
+ return None
+
+
+def _unix_timestamp(value: object) -> Optional[str]:
+ seconds = _seconds(value)
+ if seconds is None:
+ return None
+ try:
+ return _iso(datetime.fromtimestamp(seconds, tz=timezone.utc))
+ except (OverflowError, OSError, ValueError):
+ return None
+
+
+def _window(
+ *,
+ window_id: str,
+ kind: QuotaWindowKind,
+ label: str,
+ used_pct: float,
+ window_seconds: Optional[int],
+ resets_at: Optional[str],
+ scope_model: Optional[str] = None,
+) -> dict[str, Any]:
+ window: dict[str, Any] = {
+ "id": window_id[:128],
+ "kind": kind,
+ # Labels are composed from upstream parts, so bound the final text here.
+ "label": _label(label) or window_id[:_MAX_LABEL_CHARS],
+ "used_pct": used_pct,
+ "window_seconds": window_seconds,
+ "resets_at": resets_at,
+ }
+ if scope_model is not None:
+ window["scope_model"] = scope_model
+ return window
+
+
+def _load_object(body: object) -> dict[str, Any]:
+ if not isinstance(body, (str, bytes, bytearray)):
+ raise SubscriptionQuotaError("malformed")
+ size = len(body.encode("utf-8", "surrogatepass")) if isinstance(body, str) else len(body)
+ if size > _MAX_BODY_BYTES:
+ raise SubscriptionQuotaError("malformed")
+ try:
+ payload = json.loads(body)
+ except (TypeError, UnicodeDecodeError, ValueError):
+ raise SubscriptionQuotaError("malformed") from None
+ if not isinstance(payload, dict) or "error" in payload:
+ raise SubscriptionQuotaError("malformed")
+ try:
+ # An escaped lone surrogate decodes but cannot be served as UTF-8 JSON.
+ json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ except (UnicodeEncodeError, ValueError):
+ raise SubscriptionQuotaError("malformed") from None
+ return payload
+
+
+def _claude_limit_rows(rows: list[object]) -> list[dict[str, Any]]:
+ windows: list[dict[str, Any]] = []
+ for index, row in enumerate(rows[:_MAX_UPSTREAM_ROWS]):
+ if not isinstance(row, dict):
+ continue
+ used = _percent(row.get("percent"))
+ if used is None:
+ continue
+ upstream_kind = row.get("kind")
+ scope = row.get("scope") if isinstance(row.get("scope"), dict) else {}
+ model = scope.get("model") if isinstance(scope.get("model"), dict) else {}
+ scope_model = _label(model.get("display_name"))
+ resets_at = _iso_timestamp(row.get("resets_at"))
+ # Classify on the server's `kind`, never on its display text.
+ if upstream_kind == "session":
+ kind: QuotaWindowKind = "session"
+ seconds: Optional[int] = SESSION_WINDOW_SECONDS
+ label = "session"
+ elif upstream_kind == "weekly_all":
+ kind, seconds, label = "weekly", WEEKLY_WINDOW_SECONDS, "weekly"
+ elif upstream_kind == "weekly_scoped" and scope_model:
+ kind, seconds, label = "model_weekly", WEEKLY_WINDOW_SECONDS, scope_model
+ else:
+ surface = scope.get("surface") if isinstance(scope.get("surface"), dict) else {}
+ generic = scope_model or _label(surface.get("display_name")) or _label(upstream_kind)
+ if generic is None:
+ continue
+ kind = "other"
+ seconds = WEEKLY_WINDOW_SECONDS if row.get("group") == "weekly" else None
+ label = generic
+ windows.append(
+ _window(
+ window_id=f"limit:{upstream_kind if isinstance(upstream_kind, str) else index}:{scope_model or index}",
+ kind=kind,
+ label=label,
+ used_pct=used,
+ window_seconds=seconds,
+ resets_at=resets_at,
+ scope_model=scope_model if kind == "model_weekly" else None,
+ )
+ )
+ return windows
+
+
+def _claude_top_level(payload: Mapping[str, Any]) -> list[dict[str, Any]]:
+ windows: list[dict[str, Any]] = []
+ # The fixed keys are always read; only unknown keys count against the row cap.
+ fixed = [(key, payload[key]) for key in _CLAUDE_TOP_LEVEL if key in payload]
+ unknown = ((key, value) for key, value in payload.items() if key not in _CLAUDE_TOP_LEVEL)
+ for key, value in itertools.chain(fixed, itertools.islice(unknown, _MAX_UPSTREAM_ROWS)):
+ if key in _CLAUDE_SKIPPED_TOP_LEVEL or not isinstance(value, dict) or "utilization" not in value:
+ continue
+ used = _percent(value.get("utilization"))
+ if used is None:
+ continue
+ kind, scope_model = _CLAUDE_TOP_LEVEL.get(key, ("other", None))
+ seconds = {
+ "session": SESSION_WINDOW_SECONDS,
+ "weekly": WEEKLY_WINDOW_SECONDS,
+ "model_weekly": WEEKLY_WINDOW_SECONDS,
+ }.get(kind)
+ label = scope_model or _label(key)
+ if label is None:
+ continue
+ windows.append(
+ _window(
+ window_id=key,
+ kind=kind,
+ label=label,
+ used_pct=used,
+ window_seconds=seconds,
+ resets_at=_iso_timestamp(value.get("resets_at")),
+ scope_model=scope_model,
+ )
+ )
+ return windows
+
+
+def parse_claude_quota(body: object) -> dict[str, Any]:
+ """Parse `GET https://api.anthropic.com/api/oauth/usage`.
+
+ Prefer the server's `limits[]` rows when present: they carry the server's own
+ model names. Otherwise fall back to the fixed top-level window keys.
+ """
+
+ payload = _load_object(body)
+ rows = payload.get("limits")
+ windows = _claude_limit_rows(rows) if isinstance(rows, list) and rows else []
+ if not windows:
+ windows = _claude_top_level(payload)
+ if not windows and not any(key in payload for key in (*_CLAUDE_TOP_LEVEL, "limits")):
+ raise SubscriptionQuotaError("malformed")
+ return {"plan": None, "windows": _ordered(windows)}
+
+
+def _codex_kind(seconds: Optional[int]) -> QuotaWindowKind:
+ if seconds is None:
+ return "other"
+ if abs(seconds - SESSION_WINDOW_SECONDS) <= 900:
+ return "session"
+ if abs(seconds - WEEKLY_WINDOW_SECONDS) <= 3 * 3600:
+ return "weekly"
+ return "other"
+
+
+def _codex_window(value: object) -> Optional[tuple[float, Optional[int], Optional[str]]]:
+ if not isinstance(value, dict):
+ return None
+ used = _percent(value.get("used_percent"))
+ if used is None:
+ return None
+ return used, _seconds(value.get("limit_window_seconds")), _unix_timestamp(value.get("reset_at"))
+
+
+def _span_label(seconds: Optional[int]) -> str:
+ """A window length as written: whole days, whole hours, else hours and minutes."""
+ if seconds is None:
+ return ""
+ if seconds % 86400 == 0:
+ return f"{seconds // 86400}d"
+ if seconds % 3600 == 0:
+ return f"{seconds // 3600}h"
+ hours, minutes = divmod(max(1, round(seconds / 60)), 60)
+ if not minutes:
+ return f"{hours}h"
+ return f"{hours}h {minutes}m" if hours else f"{minutes}m"
+
+
+def parse_codex_quota(body: object) -> dict[str, Any]:
+ """Parse `GET https://chatgpt.com/backend-api/wham/usage`."""
+
+ payload = _load_object(body)
+ rate_limit = payload.get("rate_limit")
+ additional = payload.get("additional_rate_limits")
+ if not isinstance(rate_limit, dict) and not isinstance(additional, list) and "plan_type" not in payload:
+ raise SubscriptionQuotaError("malformed")
+ windows: list[dict[str, Any]] = []
+ if isinstance(rate_limit, dict):
+ for slot in ("primary_window", "secondary_window"):
+ parsed = _codex_window(rate_limit.get(slot))
+ if parsed is None:
+ continue
+ used, seconds, resets_at = parsed
+ kind = _codex_kind(seconds)
+ windows.append(
+ _window(
+ window_id=slot,
+ kind=kind,
+ label=slot if kind != "other" else (_span_label(seconds) or slot),
+ used_pct=used,
+ window_seconds=seconds,
+ resets_at=resets_at,
+ )
+ )
+ if isinstance(additional, list):
+ for index, item in enumerate(additional[:_MAX_UPSTREAM_ROWS]):
+ if not isinstance(item, dict) or not isinstance(item.get("rate_limit"), dict):
+ continue
+ feature = item.get("metered_feature")
+ scope_model = (
+ _CODEX_FEATURE_LABELS.get(feature) if isinstance(feature, str) else None
+ ) or _label(item.get("limit_name")) or _label(feature)
+ if scope_model is None:
+ continue
+ for slot in ("primary_window", "secondary_window"):
+ parsed = _codex_window(item["rate_limit"].get(slot))
+ if parsed is None:
+ continue
+ used, seconds, resets_at = parsed
+ weekly = _codex_kind(seconds) == "weekly"
+ span = _span_label(seconds)
+ windows.append(
+ _window(
+ window_id=f"additional:{index}:{slot}",
+ kind="model_weekly" if weekly else "other",
+ label=scope_model if weekly or not span else f"{scope_model} · {span}",
+ used_pct=used,
+ window_seconds=seconds,
+ resets_at=resets_at,
+ scope_model=scope_model if weekly else None,
+ )
+ )
+ plan = _label(payload.get("plan_type"))
+ return {"plan": plan, "windows": _ordered(windows)}
+
+
+_KIND_ORDER: Final = {"session": 0, "weekly": 1, "model_weekly": 2, "other": 3}
+
+
+def _ordered(windows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ seen: set[str] = set()
+ unique = []
+ for window in windows:
+ if window["id"] in seen:
+ continue
+ seen.add(window["id"])
+ unique.append(window)
+ unique.sort(key=lambda window: _KIND_ORDER[window["kind"]])
+ return unique[:_MAX_WINDOWS]
+
+
+def parse_subscription_quota(vendor: str, body: object) -> dict[str, Any]:
+ normalized = vendor.strip().lower()
+ if normalized == "anthropic":
+ return parse_claude_quota(body)
+ if normalized in {"openai", "codex"}:
+ return parse_codex_quota(body)
+ raise SubscriptionQuotaError("unsupported")
+
+
+# ── Service-side cache ──────────────────────────────────────────────────────
+
+QUOTA_REFRESH_INTERVAL: Final = timedelta(minutes=5)
+# A forced refresh re-reads a Source at most this often; a click storm is served
+# the snapshot it just produced instead of reaching the vendor again.
+QUOTA_FORCED_REFRESH_INTERVAL: Final = timedelta(seconds=30)
+QUOTA_READ_DEADLINE_SECONDS: Final = 12.0
+# Each fetch reads the engine's auth inventory and calls a vendor; many Sources
+# queue here instead of all reaching the engine at once.
+QUOTA_MAX_CONCURRENT_FETCHES: Final = 4
+QUOTA_FETCH_TIMEOUT_SECONDS: Final = 10.0
+_RATE_LIMIT_COOLDOWN_FLOOR: Final = timedelta(minutes=5)
+_RATE_LIMIT_COOLDOWN_CEILING: Final = timedelta(hours=1)
+
+QuotaFetch = Callable[[str, str, str], Awaitable[Mapping[str, Any]]]
+
+
+@dataclass(frozen=True)
+class QuotaSourceRef:
+ source_id: str
+ vendor: str
+ credential_ref: str
+ display_name: str
+ account_label: Optional[str]
+
+
+@dataclass
+class _QuotaEntry:
+ credential_ref: str
+ snapshot: Optional[dict[str, Any]] = None
+ fetched_at: Optional[datetime] = None
+ attempted_at: Optional[datetime] = None
+ failure: Optional[QuotaFailure] = None
+ cooldown_until: Optional[datetime] = None
+ task: Optional[asyncio.Task[None]] = None
+
+
+def _cooldown(now: datetime, retry_after_seconds: Optional[float]) -> datetime:
+ # Clamp in seconds first: a hostile Retry-After must not overflow timedelta.
+ floor = _RATE_LIMIT_COOLDOWN_FLOOR.total_seconds()
+ ceiling = _RATE_LIMIT_COOLDOWN_CEILING.total_seconds()
+ seconds = retry_after_seconds if retry_after_seconds and math.isfinite(retry_after_seconds) else floor
+ return now + timedelta(seconds=min(ceiling, max(floor, seconds)))
+
+
+class SubscriptionQuotaCache:
+ """Last-good quota per Source, re-read at most every refresh interval.
+
+ A read re-fetches each Source whose last attempt is older than the interval
+ and is not cooling down after a vendor 429; concurrent reads share one fetch.
+ A failure never discards the last good snapshot: the Source is reported
+ `stale` (or `auth_expired`) with the windows it last had.
+ """
+
+ def __init__(self, fetch: QuotaFetch, *, now: Callable[[], datetime]):
+ self._fetch = fetch
+ self._now = now
+ self._entries: dict[str, _QuotaEntry] = {}
+ self._fetch_slots = asyncio.Semaphore(QUOTA_MAX_CONCURRENT_FETCHES)
+
+ async def summary(self, sources: Sequence[QuotaSourceRef], *, force: bool = False) -> dict[str, Any]:
+ live = {source.source_id for source in sources}
+ for source_id in list(self._entries):
+ if source_id not in live:
+ self._entries.pop(source_id)
+ pending = [
+ task
+ for source in sources
+ if (task := self._schedule(source, force=force)) is not None
+ ]
+ if pending:
+ # 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 {
+ "refresh_interval_seconds": int(QUOTA_REFRESH_INTERVAL.total_seconds()),
+ "sources": [self._payload(source) for source in sources],
+ }
+
+ def forget(self, source_id: str) -> None:
+ """Drop a Source's snapshot, failure, and throttle, e.g. after re-authentication.
+
+ The credential ref alone is not grant identity: re-authentication can keep it.
+ An in-flight read of the old grant lands on the detached entry and is discarded.
+ """
+
+ self._entries.pop(source_id, None)
+
+ def _entry(self, source: QuotaSourceRef) -> _QuotaEntry:
+ entry = self._entries.get(source.source_id)
+ if entry is None or entry.credential_ref != source.credential_ref:
+ # A re-authenticated Source is a different grant; its old windows are not its own.
+ entry = _QuotaEntry(credential_ref=source.credential_ref)
+ self._entries[source.source_id] = entry
+ return entry
+
+ def _schedule(self, source: QuotaSourceRef, *, force: bool) -> Optional[asyncio.Task[None]]:
+ if source.vendor not in QUOTA_VENDORS:
+ return None
+ entry = self._entry(source)
+ if entry.task is not None and not entry.task.done():
+ return entry.task
+ now = self._now()
+ if entry.cooldown_until is not None and now < entry.cooldown_until:
+ return None
+ interval = QUOTA_FORCED_REFRESH_INTERVAL if force else QUOTA_REFRESH_INTERVAL
+ if entry.attempted_at is not None and now - entry.attempted_at < interval:
+ return None
+ entry.task = asyncio.create_task(
+ self._refresh(source, entry),
+ name=f"model-hub-quota-{source.source_id}",
+ )
+ return entry.task
+
+ async def _refresh(self, source: QuotaSourceRef, entry: _QuotaEntry) -> None:
+ try:
+ async with self._fetch_slots:
+ # The throttle counts from the vendor request, not from the queue:
+ # a read that waited for a slot has not yet asked the vendor.
+ entry.attempted_at = self._now()
+ parsed = await self._fetch(source.source_id, source.vendor, source.credential_ref)
+ windows = parsed.get("windows")
+ if not isinstance(windows, list):
+ raise SubscriptionQuotaError("malformed")
+ except SubscriptionQuotaError as exc:
+ entry.failure = exc.reason
+ if exc.reason == "rate_limited":
+ entry.cooldown_until = _cooldown(self._now(), exc.retry_after_seconds)
+ logger.info("Model Hub quota read failed for %s: %s", source.source_id, exc.reason)
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ # Never let one Source's failure become the page's; never log the body.
+ 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}
+ entry.fetched_at = self._now()
+ entry.failure = None
+ entry.cooldown_until = None
+
+ def _payload(self, source: QuotaSourceRef) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "source_id": source.source_id,
+ "vendor": source.vendor,
+ "display_name": source.display_name,
+ "account_label": source.account_label,
+ "plan": None,
+ "fetched_at": None,
+ "windows": [],
+ }
+ if source.vendor not in QUOTA_VENDORS:
+ return {**payload, "state": "unsupported", "error_key": "models.quota.error.unsupported"}
+ entry = self._entries.get(source.source_id)
+ if entry is not None and entry.snapshot is not None:
+ payload.update(
+ plan=entry.snapshot["plan"],
+ windows=entry.snapshot["windows"],
+ fetched_at=_iso(entry.fetched_at) if entry.fetched_at else None,
+ )
+ failure = entry.failure if entry is not None else None
+ if failure is None:
+ if entry is None or entry.snapshot is None:
+ return {**payload, "state": "error", "error_key": "models.quota.error.unavailable"}
+ return {**payload, "state": "ok"}
+ if failure == "auth_expired":
+ return {**payload, "state": "auth_expired", "error_key": "models.quota.error.auth_expired"}
+ state = "stale" if entry is not None and entry.snapshot is not None else "error"
+ return {**payload, "state": state, "error_key": f"models.quota.error.{failure}"}
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 853f54536..34cd64de2 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -203,6 +203,8 @@ async def dispatch_model_hub_rpc(
service.usage_summary,
days=payload.get("days", USAGE_DEFAULT_WINDOW_DAYS),
)
+ if operation == "quota_summary":
+ return await service.quota_summary(force=payload.get("force") is True)
if operation == "get_agent_chain":
return service.agent_chain(payload.get("backend"), payload.get("model_id"))
if operation == "get_agent_chains":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 563598044..be24601ae 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 .quota import QuotaSourceRef, SubscriptionQuotaCache, SubscriptionQuotaError
from .provenance import (
BoundedProvenanceStore,
ENGINE_DOWN_TURN_OUTCOME,
@@ -447,6 +448,9 @@ class UnavailableEngineAdapter:
def subscription_account_label(self, source_id: str, vendor: str, credential_ref: str) -> str | None:
return None
+ async def subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> dict[str, Any]:
+ raise SubscriptionQuotaError("unavailable")
+
async def provision_transient_credential(
self, vendor: str, secret: str, base_url: str | None,
*, auth_scheme: str | None = None, on_reserved: Callable[[str], None] | None = None,
@@ -949,6 +953,7 @@ class ModelHubService:
self._builtin_snapshot_generations: dict[BackendName, str] = {}
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())
@staticmethod
@asynccontextmanager
@@ -1999,6 +2004,7 @@ class ModelHubService:
config,
rollback_on_sync_failure=False,
)
+ self.quota.forget(source_id)
async def _discard_unbound_hub_flow(self, flow: OAuthFlowState) -> None:
if flow.credential_ref:
@@ -2833,6 +2839,7 @@ class ModelHubService:
old_revocation_recorded = True
await self._commit_synced(previous, config)
committed = True
+ self.quota.forget(source.id)
self._record_reasoning_tier_overrides(source, overrides)
self._complete_reauth_flow(
flow_id,
@@ -2972,6 +2979,7 @@ class ModelHubService:
config,
rollback_on_sync_failure=False,
)
+ self.quota.forget(source.id)
return config
async def _materialize_failed_hub_reauth(
@@ -5466,6 +5474,50 @@ class ModelHubService:
],
)
+ async def _fetch_subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> Mapping[str, Any]:
+ reader = getattr(self.adapter, "subscription_quota", None)
+ if not callable(reader):
+ raise SubscriptionQuotaError("unavailable")
+ return await reader(source_id, vendor, credential_ref)
+
+ def _quota_sources(self) -> list[QuotaSourceRef]:
+ config = self.store.load()
+ refs = []
+ for source in config.sources:
+ if source.kind != "subscription" or source.supply_channel != "hub" or not source.credential_ref:
+ continue
+ payload = self._source_account_payload(
+ {
+ "id": source.id,
+ "kind": source.kind,
+ "vendor": source.vendor,
+ "supply_channel": source.supply_channel,
+ "credential_ref": source.credential_ref,
+ "account_label": source.account_label,
+ }
+ )
+ refs.append(
+ QuotaSourceRef(
+ source_id=source.id,
+ vendor=source.vendor.strip().lower(),
+ credential_ref=source.credential_ref,
+ display_name=source.display_name,
+ account_label=payload.get("account_label"),
+ )
+ )
+ return refs
+
+ async def quota_summary(self, *, force: bool = False) -> dict:
+ """Report each hub-held subscription's rate-limit windows.
+
+ A report only, like usage metering: nothing in resolution reads it. The
+ cache re-reads a Source at most every five minutes, or every thirty
+ seconds when forced, and keeps the last good snapshot across failures.
+ """
+
+ sources = await asyncio.to_thread(self._quota_sources)
+ return await self.quota.summary(sources, force=force)
+
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
events = self.events.list(limit=limit, before=before)
for event in events:
@@ -5874,6 +5926,9 @@ class ModelHubService:
detail_key=detail_key,
)
persisted = self._save_runtime_config(previous, config)
+ if persisted:
+ # A blocked grant must not keep reporting the windows it had while usable.
+ self.quota.forget(source.id)
if persisted and emit_event:
self._record_event(
agent=cast(EventAgent, backend),
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 9ecced1d0..081c42124 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -231,6 +231,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `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. |
| `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/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index c45660468..0bfc0682b 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -567,6 +567,17 @@ class EngineAdapter(Protocol):
"""
...
+ async def subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> dict[str, Any]:
+ """Read this subscription's rate-limit windows from the vendor's usage report.
+
+ The engine makes the model-free account call with the bound grant; only
+ the parsed ``{plan, windows}`` crosses this boundary, never the grant or
+ the raw body. Raise ``SubscriptionQuotaError`` with a sanitized reason
+ (``auth_expired``, ``rate_limited``, ``unsupported``, ``unavailable`` or
+ ``malformed``) on every failure. A report only: never feeds resolution.
+ """
+ ...
+
async def retarget_api_key_credential(
self,
credential_ref: str,
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 6b851e734..ac21e8864 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -35,6 +35,8 @@
{"method": "GET", "path": "/api/models/agents/<backend>/provenance?model=<id>", "response_schema": "LatestProvenanceResponse", "exercises": [{"path": "/api/models/agents/claude/provenance?model=claude-opus-4-6", "status": 200}, {"path": "/api/models/agents/claude/provenance?model=claude-sonnet-4-6", "status": 200}]},
{"method": "GET", "path": "/api/models/events?limit=<n>&before=<id>", "response_schema": "EventsResponse", "exercise": {"path": "/api/models/events?limit=20", "status": 200}},
{"method": "GET", "path": "/api/models/usage?days=<n>", "response_schema": "UsageResponse", "exercise": {"path": "/api/models/usage?days=30", "status": 200}},
+ {"method": "GET", "path": "/api/models/quota", "response_schema": "QuotaResponse", "exercise": {"path": "/api/models/quota", "status": 200}},
+ {"method": "POST", "path": "/api/models/quota/refresh", "response_schema": "QuotaResponse", "exercise": {"path": "/api/models/quota/refresh", "status": 200}},
{"method": "POST", "path": "/api/models/oauth/start", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/oauth/start", "status": 200, "json": {"vendor": "anthropic", "channel": "hub"}}},
{"method": "GET", "path": "/api/models/oauth/status/<flow_id>", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/status/oaf_00000001", "status": 200}},
{"method": "POST", "path": "/api/models/oauth/submit", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/submit", "status": 200, "json": {"flow_id": "oaf_00000001", "value": "contract-code"}}},
@@ -485,6 +487,16 @@
"usage": {"$ref": "model-hub/usage-summary.schema.json"}
}
},
+ "QuotaResponse": {
+ "type": "object",
+ "required": ["ok", "contract_version", "quota"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 10},
+ "quota": {"$ref": "model-hub/quota-summary.schema.json"}
+ }
+ },
"OAuthFlowResponse": {
"type": "object",
"required": ["ok", "contract_version", "flow"],
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 6fa7b7739..a66b165c0 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -62,6 +62,8 @@ 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}` | Bounded metered token report over a trailing local-day window. `days` is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. |
+| 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. |
+| 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. |
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A value the provider refuses before writing anything (not a callback address, no `code`) is the non-terminal `422 submission_rejected`: the flow stays `awaiting_action` and accepts another submission until its `expires_at`. |
@@ -1326,6 +1328,46 @@ when emitted.
successful refresh replaced a non-empty user declaration; it contains neither the old
tiers, new tiers, nor credential material.
+## Subscription quota
+
+Quota is a report, never a control input, exactly like usage metering: nothing in
+resolution, admission, or cooldown reads it. It covers hub-held subscription
+Sources (`kind: subscription`, `supply_channel: hub`, bound credential). Native-CLI
+subscriptions and API-key Sources are absent.
+
+The engine that holds the grant makes one model-free account call per Source
+through its management `api-call`, so Avibe never handles the token:
+
+| Vendor | Upstream | Extra header |
+| --- | --- | --- |
+| `anthropic` | `GET https://api.anthropic.com/api/oauth/usage` | `anthropic-beta: oauth-2025-04-20` |
+| `openai` / `codex` | `GET https://chatgpt.com/backend-api/wham/usage` | `ChatGPT-Account-ID` when the grant carries one |
+
+Only parsed fields cross the adapter boundary (`EngineAdapter.subscription_quota`);
+the raw body, headers, and grant never reach the service, a log line, or a
+response. Parsing is defensive: a null or unreadable window is skipped, a window
+the parser does not recognise is returned as `kind: other` with its bounded
+upstream name, and a body that is not the report shape is a per-Source
+`malformed` failure. Claude's `limits[]` rows are classified on `kind`
+(`session`, `weekly_all`, `weekly_scoped` with `scope.model.display_name`) and
+fall back to the fixed top-level keys (`five_hour`, `seven_day`,
+`seven_day_opus`, `seven_day_sonnet`, `seven_day_overage_included`). Codex
+primary/secondary windows are classified by `limit_window_seconds`, and each
+`additional_rate_limits` entry is named by its metered feature (`codex_bengalfox`
+is Spark) or `limit_name`.
+
+The service caches the last good snapshot per Source. A read re-fetches a Source
+whose last attempt is older than `refresh_interval_seconds` (300); a forced
+refresh lowers that to 30 seconds. A vendor 429 starts a cooldown of
+`Retry-After` bounded to 5–60 minutes, after which the next read retries. A
+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.
+
## Usage metering
Usage is a report, never a control input. Nothing in resolution, admission, or
diff --git a/docs/plans/model-hub-contracts/quota-summary.schema.json b/docs/plans/model-hub-contracts/quota-summary.schema.json
new file mode 100644
index 000000000..630463bfa
--- /dev/null
+++ b/docs/plans/model-hub-contracts/quota-summary.schema.json
@@ -0,0 +1,96 @@
+{
+ "$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.",
+ "type": "object",
+ "required": ["refresh_interval_seconds", "sources"],
+ "additionalProperties": false,
+ "properties": {
+ "refresh_interval_seconds": {
+ "description": "How often the server re-reads one Source without a forced refresh.",
+ "type": "integer",
+ "minimum": 1
+ },
+ "sources": {
+ "description": "One entry per hub-held subscription Source, in Source order.",
+ "type": "array",
+ "items": { "$ref": "#/definitions/SourceQuota" }
+ }
+ },
+ "definitions": {
+ "SourceQuota": {
+ "type": "object",
+ "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"] },
+ "plan": {
+ "description": "Plan name the vendor reported, when it reports one.",
+ "type": ["string", "null"],
+ "maxLength": 64
+ },
+ "fetched_at": {
+ "description": "When `windows` was read. Null until the first good read.",
+ "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"]
+ },
+ "error_key": {
+ "description": "Present exactly when `state` is not ok.",
+ "enum": [
+ "models.quota.error.auth_expired",
+ "models.quota.error.rate_limited",
+ "models.quota.error.unsupported",
+ "models.quota.error.unavailable",
+ "models.quota.error.malformed"
+ ]
+ },
+ "windows": {
+ "type": "array",
+ "maxItems": 16,
+ "items": { "$ref": "#/definitions/QuotaWindow" }
+ }
+ },
+ "if": { "properties": { "state": { "const": "ok" } } },
+ "then": { "not": { "required": ["error_key"] } },
+ "else": { "required": ["error_key"] }
+ },
+ "QuotaWindow": {
+ "type": "object",
+ "required": ["id", "kind", "label", "used_pct", "window_seconds", "resets_at"],
+ "additionalProperties": false,
+ "properties": {
+ "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"]
+ },
+ "label": {
+ "description": "Upstream name, whitespace-collapsed and bounded. Display copy for `other`; the UI composes its own copy for the known kinds.",
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64
+ },
+ "scope_model": {
+ "description": "Present exactly for model_weekly: the upstream model name.",
+ "type": "string",
+ "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" }
+ },
+ "if": { "properties": { "kind": { "const": "model_weekly" } } },
+ "then": { "required": ["scope_model"] },
+ "else": { "not": { "required": ["scope_model"] } }
+ }
+ }
+}
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index a6764d6d7..28820ad8f 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -74,10 +74,12 @@ capabilities:
- tests/test_model_hub_request_body_budget.py
- tests/test_model_hub_l3.py
- tests/test_model_hub_usage.py
+ - tests/test_model_hub_quota.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/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/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 26ddef9c0..3826c3fe1 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -334,6 +334,13 @@ scenarios:
layer: scenario
backend: web
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_cloud_pairing_recovery_closed_loop
+ - id: AUTH-SETUP-909
+ name: Quota-card Hub re-auth commits the new grant and the next quota read reaches it at once
+ status: covered
+ kind: recovery
+ layer: scenario
+ backend: shared
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_quota_card_reauth_reaches_a_fresh_quota_reading
- id: AUTH-SETUP-119
name: Runtime manual provider code reaches native persistence and controller-confirmed readiness
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index d8c93962c..a45d1c254 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -1918,6 +1918,70 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent["sources"]["order"], [source.id])
self.assertEqual(agent["supply_status"], "ok")
+ async def test_quota_card_reauth_reaches_a_fresh_quota_reading(self):
+ """Scenario: AUTH-SETUP-909.
+
+ The quota tab is a second entry into Hub re-auth. An expired grant reads
+ `auth_expired`; the same acknowledged re-auth as AUTH-SETUP-109 then
+ commits, and the next quota read reaches the new grant at once instead
+ of waiting out the old failure's refresh interval.
+ """
+ from core.handlers.model_hub.quota import SubscriptionQuotaError
+
+ state_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(state_dir.cleanup)
+ harness = HubOAuthScenarioHarness(Path(state_dir.name))
+ source = ModelHubSourceConfig.from_payload(
+ {
+ "id": "src_hubquota01",
+ "created_at": "2026-07-25T00:00:00+00:00",
+ "last_discovered_at": "2026-07-25T00:00:00+00:00",
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Claude Hub subscription",
+ "protocol": "anthropic",
+ "base_url": None,
+ "supply_channel": "hub",
+ "billing": "monthly",
+ "state": {
+ "status": "needs_action",
+ "retry_at": None,
+ "detail_key": "models.source.needs_action.oauth_expired",
+ },
+ "models": [],
+ "credential_ref": "cred_hubold01",
+ "account_label": None,
+ "masked_credential": None,
+ }
+ )
+ harness.store.config.sources.append(source)
+ reads: list[str] = []
+
+ async def subscription_quota(source_id, vendor, credential_ref):
+ reads.append(credential_ref)
+ if credential_ref == "cred_hubold01":
+ raise SubscriptionQuotaError("auth_expired")
+ return {"plan": "max", "windows": [{
+ "id": "five_hour", "kind": "session", "label": "five_hour", "used_pct": 12.0,
+ "window_seconds": 18000, "resets_at": "2026-07-25T05:00:00Z",
+ }]}
+
+ harness.adapter.subscription_quota = subscription_quota
+ expired = (await harness.service.quota_summary())["sources"][0]
+ self.assertEqual(expired["state"], "auth_expired")
+
+ started = await harness.service.reauth_source(source.id, {"acknowledge_irreversible": True})
+ flow_id = started["flow"]["flow_id"]
+ harness.adapter.complete(flow_id)
+ terminal = await harness.service.oauth_status(flow_id)
+ self.assertEqual(terminal["flow"]["state"], "success")
+
+ # Inside the old failure's five-minute interval, an unforced read still reaches the new grant.
+ fresh = (await harness.service.quota_summary())["sources"][0]
+ self.assertEqual(reads, ["cred_hubold01", "cred_consent01"])
+ self.assertEqual(fresh["state"], "ok")
+ self.assertEqual(fresh["windows"][0]["used_pct"], 12.0)
+
async def test_hub_only_subscription_vendors_start_a_hub_flow_and_refuse_native_custody(self):
"""Scenario: AUTH-SETUP-115, AUTH-SETUP-116.
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 07d14a045..bddc8db0d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -23,6 +23,8 @@ capability:
- tests/test_model_hub_request_body_budget.py
- tests/test_model_hub_l3.py
- tests/test_model_hub_usage.py
+ - tests/test_model_hub_quota.py
+ - ui/src/components/settings/models/QuotaTab.test.tsx
- tests/test_local_deps.py
- tests/test_opencode_server.py
- tests/test_runtime_activation.py
@@ -678,6 +680,116 @@ scenarios:
kind: observation
layer: unit
test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-027
+ - id: MH-QUOTA-001
+ name: Claude's fixed quota windows parse and null or app-only windows are skipped
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_claude_quota_parser_reads_legacy_windows_and_skips_nulls
+ - id: MH-QUOTA-002
+ name: Claude limit rows classify on kind and keep the server's model names, including non-ASCII ones
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_claude_quota_parser_prefers_server_limits_and_keeps_unknown_rows
+ - id: MH-QUOTA-003
+ name: Codex quota windows classify by length and name Spark from its metered feature
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_codex_quota_parser_reads_primary_secondary_and_additional_limits
+ - id: MH-QUOTA-004
+ name: A malformed or hostile quota body is one Source's sanitized failure with bounded values
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_parsers_reject_a_malformed_body_as_one_source_failure
+ - id: MH-QUOTA-005
+ name: Each subscription's quota is re-read at most every five minutes and concurrent reads share one fetch
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_cache_refreshes_each_source_at_most_every_five_minutes
+ - id: MH-QUOTA-006
+ name: A failed quota re-read keeps the last good windows and reports the Source stale
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_cache_keeps_the_last_good_snapshot_as_stale
+ - id: MH-QUOTA-007
+ name: A refused grant reports auth_expired and one Source's failure never fails the page
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_cache_reports_auth_expired_and_never_a_page_failure
+ - id: MH-QUOTA-008
+ name: A forced quota refresh is rate-limited and a vendor 429 cools the Source down
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_cache_forced_refresh_is_rate_limited_and_429_cools_down
+ - id: MH-QUOTA-009
+ name: A re-authenticated subscription does not inherit the old grant's quota
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_cache_forgets_a_reauthenticated_grant
+ - id: MH-QUOTA-010
+ name: A slow vendor quota call does not hold the page
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_quota_cache_does_not_hold_the_page_on_a_slow_vendor
+ - id: MH-QUOTA-011
+ name: The engine reads quota with the bound grant and only parsed windows cross the adapter
+ status: covered
+ kind: observation
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_adapter_reads_quota_through_the_engine_without_exposing_the_grant
+ - id: MH-QUOTA-012
+ name: Quota routes serve hub subscriptions only and a forced refresh inside its interval is served from cache
+ status: covered
+ kind: contract
+ layer: contract
+ test: tests/test_model_hub_api.py::test_quota_endpoints_serve_hub_subscriptions_and_rate_limit_forced_refresh
+ - id: MH-QUOTA-013
+ name: The quota tab shows each window's remaining share, pace, and reset, with scoped models grouped
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-013
+ - id: MH-QUOTA-014
+ name: A stale or expired subscription keeps its last windows under a re-login banner
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-014
+ - id: MH-QUOTA-015
+ name: The quota tab stays within a narrow viewport
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-015
+ related_tests:
+ - ui/e2e/model-catalog/quota-layout.spec.ts
+ - id: MH-QUOTA-016
+ name: The quota report is read when its tab is opened and refreshed only while it stays open
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-QUOTA-016
+ - id: MH-QUOTA-017
+ name: An expired grant is signed in again from its quota card through the confirmed re-login journey, and quota re-reads after
+ status: covered
+ kind: recovery
+ layer: unit
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-QUOTA-017
+ - id: MH-QUOTA-018
+ name: A grant routing blocks as needs_action is re-read instead of showing its pre-block quota
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_retry_policy.py::test_routing_blocker_drops_the_blocked_grants_quota_reading
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 893abfd9c..50ba06b81 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 276
+ assert len(endpoints) == 278
# Additive read-only backend projection inherits native backend-management
# authorization; it does not grant lower-tier credential-management access.
assert ("GET", "/api/backend/{name}/connection") in endpoints
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 5afef065e..c8623bc58 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -6780,6 +6780,8 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(
tmp_path,
):
service, store, adapter = _service(tmp_path)
+ from core.handlers.model_hub.quota import SubscriptionQuotaError
+
source = ModelHubSourceConfig(
id="src_huboauth01",
kind="subscription",
@@ -6802,6 +6804,14 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
+ quota_reads = []
+
+ async def subscription_quota(source_id, vendor, credential_ref):
+ quota_reads.append(source_id)
+ raise SubscriptionQuotaError("auth_expired")
+
+ adapter.subscription_quota = subscription_quota
+ assert asyncio.run(service.quota_summary())["sources"][0]["state"] == "auth_expired"
flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
@@ -6812,6 +6822,9 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(
}
)
result = asyncio.run(service.oauth_status(flow["flow_id"]))
+ # The same ref names a new grant: its quota is re-read, not held behind the old failure.
+ asyncio.run(service.quota_summary())
+ assert quota_reads == [source.id, source.id]
assert result["recovered"] is True
assert result["source"]["state"]["status"] == "standby"
@@ -6985,6 +6998,14 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
+ quota_reads = []
+
+ async def subscription_quota(source_id, vendor, credential_ref):
+ quota_reads.append(source_id)
+ return {"plan": None, "windows": []}
+
+ adapter.subscription_quota = subscription_quota
+ assert asyncio.run(service.quota_summary())["sources"][0]["state"] == "ok"
flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
@@ -7023,6 +7044,9 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(
assert adapter.revoked == []
assert adapter.orphan_cleanup_calls == []
assert service.revocations.list() == []
+ # The fail-closed grant does not keep its pre-failure quota reading inside the refresh window.
+ asyncio.run(service.quota_summary())
+ assert quota_reads == [source.id, source.id]
@pytest.mark.parametrize(
@@ -9533,3 +9557,60 @@ def test_signed_organization_member_completes_models_page_bootstrap(monkeypatch,
# A valid signed session still needs CSRF for writes.
response = client.post("/api/models/runtime/start", json={}, base_url=base_url, environ_base=remote_peer())
assert response.status_code == 403
+
+
+def test_quota_endpoints_serve_hub_subscriptions_and_rate_limit_forced_refresh(monkeypatch, tmp_path):
+ """MH-QUOTA-012: GET and forced-refresh routes return only hub subscriptions' parsed windows, per-Source failures, and a cached forced re-read."""
+
+ from core.handlers.model_hub.quota import SubscriptionQuotaError
+
+ service = _seed_response_conformance_service(tmp_path)
+ service.store.config.sources.append(
+ ModelHubSourceConfig(
+ id="src_codexsub01",
+ kind="subscription",
+ vendor="openai",
+ display_name="ChatGPT Pro",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="monthly",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[],
+ credential_ref="cred_codexsub01",
+ )
+ )
+ calls = []
+
+ async def subscription_quota(source_id, vendor, credential_ref):
+ calls.append(source_id)
+ if source_id == "src_codexsub01":
+ raise SubscriptionQuotaError("auth_expired")
+ return {"plan": None, "windows": [{
+ "id": "five_hour", "kind": "session", "label": "five_hour", "used_pct": 38.0,
+ "window_seconds": 18000, "resets_at": "2026-07-23T05:00:00Z",
+ }]}
+
+ service.adapter.subscription_quota = subscription_quota
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))
+ client = app.test_client()
+ origin = "http://127.0.0.1:15131"
+
+ response = client.get("/api/models/quota", base_url=origin)
+ assert response.status_code == 200
+ body = response.get_json()
+ _assert_valid("quota-summary.schema.json", body["quota"])
+ sources = {source["source_id"]: source for source in body["quota"]["sources"]}
+ # API-key Sources have no subscription quota and are absent.
+ assert set(sources) == {"src_subscribe01", "src_codexsub01"}
+ assert sources["src_subscribe01"]["state"] == "ok"
+ assert sources["src_subscribe01"]["windows"][0]["used_pct"] == 38.0
+ assert sources["src_codexsub01"]["state"] == "auth_expired"
+ assert "cred_" not in json.dumps(body)
+ assert sorted(calls) == ["src_codexsub01", "src_subscribe01"]
+
+ headers = csrf_headers(client, origin)
+ refreshed = client.post("/api/models/quota/refresh", headers=headers, base_url=origin)
+ assert refreshed.status_code == 200
+ _assert_valid("quota-summary.schema.json", refreshed.get_json()["quota"])
+ # Inside the forced-refresh interval the cached snapshot answers.
+ assert len(calls) == 2
diff --git a/tests/test_model_hub_quota.py b/tests/test_model_hub_quota.py
new file mode 100644
index 000000000..9c7f09e11
--- /dev/null
+++ b/tests/test_model_hub_quota.py
@@ -0,0 +1,617 @@
+"""Subscription quota: vendor report parsers, the service cache, and the adapter call."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+from jsonschema import Draft7Validator
+
+from core.handlers.model_hub.quota import (
+ QUOTA_FORCED_REFRESH_INTERVAL,
+ QUOTA_REFRESH_INTERVAL,
+ QuotaSourceRef,
+ SubscriptionQuotaCache,
+ SubscriptionQuotaError,
+ parse_claude_quota,
+ parse_codex_quota,
+)
+
+CONTRACTS = Path("docs/plans/model-hub-contracts")
+QUOTA_SCHEMA = json.loads((CONTRACTS / "quota-summary.schema.json").read_text(encoding="utf-8"))
+
+# Shaped after what Claude Code 2.x reads from `/api/oauth/usage`.
+CLAUDE_LEGACY = {
+ "five_hour": {"utilization": 38.0, "resets_at": "2026-09-25T11:14:00.402+00:00"},
+ "seven_day": {"utilization": 61, "resets_at": "2026-09-29T01:00:00+00:00"},
+ "seven_day_oauth_apps": None,
+ "seven_day_opus": None,
+ "seven_day_sonnet": {"utilization": 22.4, "resets_at": "2026-09-29T01:00:00+00:00"},
+ "seven_day_overage_included": {"utilization": 86, "resets_at": "2026-09-29T01:00:00+00:00"},
+ "extra_usage": {"is_enabled": True, "monthly_limit": 10000, "used_credits": 1240, "utilization": 12.4},
+}
+CLAUDE_LIMITS = {
+ **CLAUDE_LEGACY,
+ "limits": [
+ {"kind": "session", "group": "session", "percent": 38, "resets_at": "2026-09-25T11:14:00Z",
+ "scope": None, "severity": "normal", "is_active": True},
+ {"kind": "weekly_all", "group": "weekly", "percent": 61, "resets_at": "2026-09-29T01:00:00Z",
+ "scope": None, "severity": "normal", "is_active": True},
+ {"kind": "weekly_scoped", "group": "weekly", "percent": 86, "resets_at": "2026-09-29T01:00:00Z",
+ "scope": {"model": {"display_name": "Fable"}, "surface": None}, "severity": "warning", "is_active": True},
+ {"kind": "weekly_scoped", "group": "weekly", "percent": 5, "resets_at": "2026-09-29T01:00:00Z",
+ "scope": {"model": {"display_name": " 俳句\n模型 "}, "surface": None}},
+ {"kind": "monthly_surface", "group": "monthly", "percent": 40, "resets_at": None,
+ "scope": {"model": None, "surface": {"display_name": "Claude 应用"}}},
+ {"kind": "weekly_scoped", "percent": None, "scope": {"model": {"display_name": "Ghost"}}},
+ "not-a-row",
+ ],
+}
+# Shaped after openai/codex `RateLimitStatusPayload`.
+CODEX_REPORT = {
+ "plan_type": "pro",
+ "rate_limit": {
+ "allowed": True,
+ "limit_reached": False,
+ "primary_window": {"used_percent": 12, "limit_window_seconds": 18000,
+ "reset_after_seconds": 13200, "reset_at": 1790000000},
+ "secondary_window": {"used_percent": 45, "limit_window_seconds": 604800,
+ "reset_after_seconds": 400000, "reset_at": 1790400000},
+ },
+ "additional_rate_limits": [
+ {"limit_name": "GPT-5.2-Codex-Spark", "metered_feature": "codex_bengalfox",
+ "rate_limit": {"primary_window": {"used_percent": 8, "limit_window_seconds": 604800,
+ "reset_after_seconds": 400000, "reset_at": 1790400000},
+ "secondary_window": None}},
+ {"limit_name": "实验模型", "metered_feature": "future_feature",
+ "rate_limit": {"primary_window": {"used_percent": 3, "limit_window_seconds": 3600,
+ "reset_after_seconds": 100, "reset_at": 1790000100}}},
+ {"limit_name": "broken", "rate_limit": None},
+ ],
+ "credits": {"has_credits": False, "unlimited": False, "balance": None},
+}
+
+
+def _validate_windows(parsed):
+ validator = Draft7Validator(QUOTA_SCHEMA["definitions"]["QuotaWindow"])
+ for window in parsed["windows"]:
+ validator.validate(window)
+
+
+ ("state", "error_key", "valid"),
+ [
+ ("ok", None, True),
+ ("ok", "models.quota.error.unavailable", False),
+ *[(state, "models.quota.error.unavailable", True) for state in ("stale", "auth_expired", "unsupported", "error")],
+ *[(state, None, False) for state in ("stale", "auth_expired", "unsupported", "error")],
+ ],
+)
+def test_quota_contract_carries_a_reason_exactly_when_not_ok(state, error_key, valid):
+ """A non-ok Source without a reason, or an ok Source with one, violates the contract."""
+
+ source = {
+ "source_id": "src_claude", "vendor": "anthropic", "display_name": "Claude Max", "account_label": None,
+ "plan": None, "fetched_at": None, "state": state, "windows": [],
+ }
+ if error_key is not None:
+ source["error_key"] = error_key
+ errors = list(Draft7Validator(QUOTA_SCHEMA).iter_errors({"refresh_interval_seconds": 300, "sources": [source]}))
+ assert (not errors) is valid
+
+
+ ("kind", "scope_model", "valid"),
+ [
+ ("model_weekly", "Sonnet", True),
+ ("model_weekly", None, False),
+ *[(kind, None, True) for kind in ("session", "weekly", "other")],
+ *[(kind, "Sonnet", False) for kind in ("session", "weekly", "other")],
+ ],
+)
+def test_quota_contract_names_a_model_exactly_for_model_weekly(kind, scope_model, valid):
+ """A model-scoped window without its model, or a shared window with one, violates the contract."""
+
+ window = {"id": "w", "kind": kind, "label": "Sonnet", "used_pct": 10, "window_seconds": None, "resets_at": None}
+ if scope_model is not None:
+ window["scope_model"] = scope_model
+ errors = list(Draft7Validator(QUOTA_SCHEMA["definitions"]["QuotaWindow"]).iter_errors(window))
+ assert (not errors) is valid
+
+
+def test_claude_quota_parser_reads_legacy_windows_and_skips_nulls():
+ """MH-QUOTA-001: Claude's fixed windows parse; null and app-only windows are skipped."""
+
+ parsed = parse_claude_quota(json.dumps(CLAUDE_LEGACY))
+ _validate_windows(parsed)
+ by_id = {window["id"]: window for window in parsed["windows"]}
+ assert list(by_id) == ["five_hour", "seven_day", "seven_day_sonnet", "seven_day_overage_included"]
+ assert by_id["five_hour"]["kind"] == "session"
+ assert by_id["five_hour"]["window_seconds"] == 18000
+ assert by_id["five_hour"]["resets_at"] == "2026-09-25T11:14:00.402000Z"
+ assert by_id["seven_day"]["kind"] == "weekly"
+ assert by_id["seven_day_sonnet"] | {} == {
+ "id": "seven_day_sonnet", "kind": "model_weekly", "label": "Sonnet", "scope_model": "Sonnet",
+ "used_pct": 22.4, "window_seconds": 604800, "resets_at": "2026-09-29T01:00:00Z",
+ }
+ assert by_id["seven_day_overage_included"]["scope_model"] == "Fable"
+ # Money stays out of this lane: extra usage is never a window or a field.
+ assert "extra_usage" not in json.dumps(parsed)
+
+
+def test_claude_quota_parser_prefers_server_limits_and_keeps_unknown_rows():
+ """MH-QUOTA-002: Claude `limits[]` rows classify on kind, keep server model names (non-ASCII too), and render unknown kinds generically."""
+
+ parsed = parse_claude_quota(json.dumps(CLAUDE_LIMITS, ensure_ascii=False).encode())
+ _validate_windows(parsed)
+ kinds = [(window["kind"], window["label"]) for window in parsed["windows"]]
+ assert kinds == [
+ ("session", "session"),
+ ("weekly", "weekly"),
+ ("model_weekly", "Fable"),
+ ("model_weekly", "俳句 模型"),
+ ("other", "Claude 应用"),
+ ]
+ other = parsed["windows"][-1]
+ assert other["window_seconds"] is None and other["resets_at"] is None
+ assert "scope_model" not in other
+
+
+ ("seconds", "label"),
+ [(60, "1m"), (1800, "30m"), (3600, "1h"), (5400, "1h 30m"), (18000, "5h"), (86400, "1d"),
+ (90000, "25h"), (91800, "25h 30m"), (1209600, "14d"), (89, "1m"), (5430, "1h 30m")],
+)
+def test_codex_generic_limit_names_its_window_length_as_written(seconds, label):
+ """MH-QUOTA-003: An unrecognised Codex limit names its period exactly; a sub-hour window is not rounded to 1h."""
+
+ report = {"additional_rate_limits": [{"limit_name": "实验模型", "rate_limit": {"primary_window": {
+ "used_percent": 3, "limit_window_seconds": seconds, "reset_after_seconds": 10, "reset_at": 1790000100}}}]}
+ windows = parse_codex_quota(json.dumps(report, ensure_ascii=False))["windows"]
+ assert [window["label"] for window in windows if window["kind"] == "other"] == [f"实验模型 · {label}"]
+
+
+def test_codex_quota_parser_reads_primary_secondary_and_additional_limits():
+ """MH-QUOTA-003: Codex windows classify by length; Spark is named from its metered feature; unknown limits stay generic."""
+
+ parsed = parse_codex_quota(json.dumps(CODEX_REPORT, ensure_ascii=False))
+ _validate_windows(parsed)
+ assert parsed["plan"] == "pro"
+ windows = parsed["windows"]
+ assert [(window["kind"], window["label"]) for window in windows] == [
+ ("session", "primary_window"),
+ ("weekly", "secondary_window"),
+ ("model_weekly", "Spark"),
+ ("other", "实验模型 · 1h"),
+ ]
+ assert windows[0]["resets_at"] == "2026-09-21T14:13:20Z"
+ assert windows[2]["scope_model"] == "Spark"
+
+
+ ("parser", "body"),
+ [
+ (parse_claude_quota, "not json"),
+ (parse_claude_quota, json.dumps([1, 2])),
+ (parse_claude_quota, json.dumps({"error": {"type": "authentication_error"}})),
+ (parse_claude_quota, json.dumps({"account": {}})),
+ (parse_claude_quota, None),
+ (parse_codex_quota, json.dumps({"detail": "nope"})),
+ (parse_codex_quota, b"\xff\xfe"),
+ pytest.param(parse_codex_quota, json.dumps({"additional_rate_limits": [], "pad": "x" * (512 * 1024)}),
+ id="oversized-body"),
+ pytest.param(parse_codex_quota, '{"plan_type": "\\ud800", "rate_limit": {}}', id="lone-surrogate"),
+ ],
+)
+def test_quota_parsers_reject_a_malformed_body_as_one_source_failure(parser, body):
+ """MH-QUOTA-004: A body that is not the report shape is a sanitized per-Source `malformed` failure."""
+
+ with pytest.raises(SubscriptionQuotaError) as caught:
+ parser(body)
+ assert caught.value.reason == "malformed"
+ assert "nope" not in str(caught.value) and "authentication_error" not in str(caught.value)
+
+
+def test_quota_parsers_stop_reading_a_runaway_row_list():
+ """MH-QUOTA-004: A body with a huge row list costs a bounded read, not one row per upstream entry."""
+
+ row = {"kind": "weekly_scoped", "percent": 5, "scope": {"model": {"display_name": "M"}}}
+ parsed = parse_claude_quota(json.dumps({"limits": [row] * 2_000}))
+ assert len(parsed["windows"]) == 1 # dedup by id; the slice is what bounds the work
+ additional = [{"limit_name": f"m{i}", "rate_limit": {"primary_window": {"used_percent": 1, "limit_window_seconds": 3600}}}
+ for i in range(2_000)]
+ parsed = parse_codex_quota(json.dumps({"additional_rate_limits": additional}))
+ assert len(parsed["windows"]) == 16
+
+
+def test_quota_parsers_bound_values_from_a_hostile_body():
+ """MH-QUOTA-004: Percentages clamp to 0–100, non-finite values drop, and labels are bounded."""
+
+ body = {
+ "five_hour": {"utilization": 250, "resets_at": "garbage"},
+ "seven_day": {"utilization": float("nan")},
+ "limits": [],
+ "x" * 300: {"utilization": -5, "resets_at": None},
+ }
+ parsed = parse_claude_quota(json.dumps(body))
+ _validate_windows(parsed)
+ assert parsed["windows"][0] == {
+ "id": "five_hour", "kind": "session", "label": "five_hour", "used_pct": 100.0,
+ "window_seconds": 18000, "resets_at": None,
+ }
+ assert parsed["windows"][1]["used_pct"] == 0.0
+ assert len(parsed["windows"][1]["label"]) == 64
+ assert all(window["id"] != "seven_day" for window in parsed["windows"])
+
+ # A composed label and an out-of-range timestamp stay inside the contract.
+ codex = {"additional_rate_limits": [{"limit_name": "m" * 64, "rate_limit": {"primary_window": {
+ "used_percent": 1, "limit_window_seconds": 3600, "reset_at": 10**12}}}]}
+ parsed = parse_codex_quota(json.dumps(codex))
+ _validate_windows(parsed)
+ assert len(parsed["windows"][0]["label"]) == 64
+ parsed = parse_claude_quota(json.dumps({"five_hour": {"utilization": 1, "resets_at": "9999-12-31T23:59:00-05:00"}}))
+ assert parsed["windows"][0]["resets_at"] is None
+
+ # A limit with headroom never rounds up to the spent sentinel; a sub-second span is unreadable.
+ codex = {"rate_limit": {"primary_window": {"used_percent": 99.96, "limit_window_seconds": 0.5, "reset_at": 0.5}}}
+ parsed = parse_codex_quota(json.dumps(codex))
+ _validate_windows(parsed)
+ assert [(w["used_pct"], w["window_seconds"], w["resets_at"]) for w in parsed["windows"]] == [(99.9, None, None)]
+
+ # A JSON integer too large for a float is a missing value, not a failed Source.
+ huge = 10**4000
+ parsed = parse_claude_quota(json.dumps({"five_hour": {"utilization": huge}, "seven_day": {"utilization": 3}}))
+ assert [w["id"] for w in parsed["windows"]] == ["seven_day"]
+ codex = {"rate_limit": {"primary_window": {"used_percent": 5, "limit_window_seconds": huge, "reset_at": huge}}}
+ parsed = parse_codex_quota(json.dumps(codex))
+ _validate_windows(parsed)
+ assert [(w["used_pct"], w["window_seconds"], w["resets_at"]) for w in parsed["windows"]] == [(5.0, None, None)]
+
+ # Unknown metadata ahead of Claude's fixed keys does not crowd them out.
+ padded = {f"meta{i}": {} for i in range(100)} | {"five_hour": {"utilization": 7}}
+ assert [w["id"] for w in parse_claude_quota(json.dumps(padded))["windows"]] == ["five_hour"]
+
+
+class _Clock:
+ def __init__(self):
+ self.now = datetime(2026, 9, 25, 3, 0, tzinfo=timezone.utc)
+
+ def __call__(self):
+ return self.now
+
+
+class _Fetch:
+ def __init__(self):
+ self.calls = []
+ self.results = []
+
+ async def __call__(self, source_id, vendor, credential_ref):
+ self.calls.append((source_id, vendor, credential_ref))
+ result = self.results.pop(0) if self.results else {"plan": "max", "windows": [_WINDOW]}
+ if isinstance(result, BaseException):
+ raise result
+ return result
+
+
+_WINDOW = {"id": "five_hour", "kind": "session", "label": "five_hour", "used_pct": 10.0,
+ "window_seconds": 18000, "resets_at": "2026-09-25T05:00:00Z"}
+_CLAUDE = QuotaSourceRef("src_claude", "anthropic", "cred_a", "Claude Max", "[email protected]")
+_CODEX = QuotaSourceRef("src_codex", "openai", "cred_b", "ChatGPT Pro", None)
+_OTHER = QuotaSourceRef("src_kimi", "kimi", "cred_c", "Kimi", None)
+
+
+def _validate_summary(summary):
+ Draft7Validator(QUOTA_SCHEMA).validate(summary)
+
+
+async def test_quota_cache_refreshes_each_source_at_most_every_five_minutes():
+ """MH-QUOTA-005: A read re-fetches a Source only after the refresh interval; concurrent reads share one fetch."""
+
+ clock, fetch = _Clock(), _Fetch()
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ first, second = await asyncio.gather(cache.summary([_CLAUDE, _CODEX]), cache.summary([_CLAUDE, _CODEX]))
+ _validate_summary(first)
+ assert first == second
+ assert len(fetch.calls) == 2
+ assert first["refresh_interval_seconds"] == 300
+ assert [source["state"] for source in first["sources"]] == ["ok", "ok"]
+ assert first["sources"][0]["fetched_at"] == "2026-09-25T03:00:00Z"
+ assert first["sources"][0]["account_label"] == "[email protected]"
+
+ clock.now += QUOTA_REFRESH_INTERVAL - timedelta(seconds=1)
+ await cache.summary([_CLAUDE, _CODEX])
+ assert len(fetch.calls) == 2
+ clock.now += timedelta(seconds=1)
+ await cache.summary([_CLAUDE, _CODEX])
+ assert len(fetch.calls) == 4
+
+
+async def test_quota_cache_keeps_the_last_good_snapshot_as_stale():
+ """MH-QUOTA-006: A failed re-read keeps the last good windows and reports the Source stale; the next good read clears it."""
+
+ clock, fetch = _Clock(), _Fetch()
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ await cache.summary([_CLAUDE])
+ fetch.results = [SubscriptionQuotaError("unavailable")]
+ clock.now += QUOTA_REFRESH_INTERVAL
+ summary = await cache.summary([_CLAUDE])
+ _validate_summary(summary)
+ source = summary["sources"][0]
+ assert source["state"] == "stale"
+ assert source["error_key"] == "models.quota.error.unavailable"
+ assert source["windows"] == [_WINDOW]
+ assert source["fetched_at"] == "2026-09-25T03:00:00Z"
+
+ clock.now += QUOTA_REFRESH_INTERVAL
+ recovered = (await cache.summary([_CLAUDE]))["sources"][0]
+ assert recovered["state"] == "ok" and "error_key" not in recovered
+
+
+async def test_quota_cache_reports_auth_expired_and_never_a_page_failure():
+ """MH-QUOTA-007: A refused grant is auth_expired, an unexpected error is one Source's error, and other Sources still answer."""
+
+ clock, fetch = _Clock(), _Fetch()
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ fetch.results = [SubscriptionQuotaError("auth_expired"), RuntimeError("secret body text")]
+ summary = await cache.summary([_CLAUDE, _CODEX, _OTHER])
+ _validate_summary(summary)
+ claude, codex, other = summary["sources"]
+ assert claude["state"] == "auth_expired" and claude["windows"] == []
+ assert claude["error_key"] == "models.quota.error.auth_expired"
+ assert codex["state"] == "error" and codex["error_key"] == "models.quota.error.unavailable"
+ assert other["state"] == "unsupported"
+ assert "secret body text" not in json.dumps(summary)
+ assert [call[0] for call in fetch.calls] == ["src_claude", "src_codex"]
+
+
+async def test_quota_cache_forced_refresh_is_rate_limited_and_429_cools_down():
+ """MH-QUOTA-008: A forced refresh re-reads at most every 30 s; a vendor 429 suppresses reads until its cooldown ends."""
+
+ clock, fetch = _Clock(), _Fetch()
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ await cache.summary([_CLAUDE])
+ await cache.summary([_CLAUDE], force=True)
+ assert len(fetch.calls) == 1
+ clock.now += QUOTA_FORCED_REFRESH_INTERVAL
+ fetch.results = [SubscriptionQuotaError("rate_limited", retry_after_seconds=600)]
+ limited = (await cache.summary([_CLAUDE], force=True))["sources"][0]
+ assert len(fetch.calls) == 2
+ assert limited["state"] == "stale" and limited["error_key"] == "models.quota.error.rate_limited"
+
+ clock.now += timedelta(minutes=9)
+ await cache.summary([_CLAUDE], force=True)
+ assert len(fetch.calls) == 2
+ clock.now += timedelta(minutes=1)
+ assert (await cache.summary([_CLAUDE]))["sources"][0]["state"] == "ok"
+ assert len(fetch.calls) == 3
+
+
+async def test_quota_cache_caps_a_huge_retry_after_at_the_ceiling():
+ """MH-QUOTA-008: A hostile Retry-After records the one-hour ceiling instead of overflowing the refresh."""
+
+ clock, fetch = _Clock(), _Fetch()
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ await cache.summary([_CLAUDE])
+ clock.now += QUOTA_REFRESH_INTERVAL
+ fetch.results = [SubscriptionQuotaError("rate_limited", retry_after_seconds=1e15)]
+ limited = (await cache.summary([_CLAUDE]))["sources"][0]
+ assert limited["error_key"] == "models.quota.error.rate_limited"
+ clock.now += timedelta(minutes=59)
+ await cache.summary([_CLAUDE], force=True)
+ assert len(fetch.calls) == 2
+ clock.now += timedelta(minutes=1)
+ await cache.summary([_CLAUDE], force=True)
+ assert len(fetch.calls) == 3
+
+
+async def test_quota_cache_bounds_concurrent_vendor_fetches():
+ """MH-QUOTA-005: Many Sources queue behind a fixed number of in-flight fetches; each still gets its own read."""
+
+ active, peak, gate = 0, 0, asyncio.Event()
+
+ async def fetch(source_id, vendor, credential_ref):
+ nonlocal active, peak
+ active += 1
+ peak = max(peak, active)
+ await gate.wait()
+ active -= 1
+ return {"plan": None, "windows": [_WINDOW]}
+
+ cache = SubscriptionQuotaCache(fetch, now=_Clock())
+ sources = [QuotaSourceRef(f"src_{i}", "anthropic", f"cred_{i}", f"S{i}", None) for i in range(12)]
+ reading = asyncio.create_task(cache.summary(sources))
+ for _ in range(5):
+ await asyncio.sleep(0)
+ assert peak == 4
+ gate.set()
+ summary = await reading
+ assert peak == 4 and [source["state"] for source in summary["sources"]] == ["ok"] * 12
+
+
+async def test_quota_cache_throttles_from_the_vendor_request_not_the_queue():
+ """MH-QUOTA-008: A read that waited for a fetch slot starts its forced-refresh cooldown when it asks the vendor."""
+
+ clock, gate, calls = _Clock(), asyncio.Event(), []
+
+ async def fetch(source_id, vendor, credential_ref):
+ calls.append(source_id)
+ if len(calls) <= 4:
+ await gate.wait()
+ return {"plan": None, "windows": [_WINDOW]}
+
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ sources = [QuotaSourceRef(f"src_{i}", "anthropic", f"cred_{i}", f"S{i}", None) for i in range(5)]
+ reading = asyncio.create_task(cache.summary(sources))
+ for _ in range(5):
+ await asyncio.sleep(0)
+ assert calls == ["src_0", "src_1", "src_2", "src_3"]
+ # The fifth read sits in the queue past the forced-refresh interval.
+ clock.now += QUOTA_FORCED_REFRESH_INTERVAL * 2
+ gate.set()
+ await reading
+ assert calls[-1] == "src_4"
+ await cache.summary(sources, force=True)
+ # The four that asked the vendor a minute ago re-read; the one that only just asked does not.
+ assert sorted(calls[5:]) == ["src_0", "src_1", "src_2", "src_3"]
+
+
+async def test_quota_cache_forgets_a_reauthenticated_grant():
+ """MH-QUOTA-009: A Source bound to a new grant does not inherit the old grant's windows or failure."""
+
+ clock, fetch = _Clock(), _Fetch()
+ cache = SubscriptionQuotaCache(fetch, now=clock)
+ fetch.results = [SubscriptionQuotaError("auth_expired")]
+ await cache.summary([_CLAUDE])
+ rebound = QuotaSourceRef("src_claude", "anthropic", "cred_new", "Claude Max", None)
+ summary = await cache.summary([rebound])
+ assert summary["sources"][0]["state"] == "ok"
+ assert fetch.calls[-1] == ("src_claude", "anthropic", "cred_new")
+
+
+async def test_quota_cache_does_not_hold_the_page_on_a_slow_vendor(monkeypatch):
+ """MH-QUOTA-010: A vendor that has not answered by the read deadline leaves its Source unread without delaying the others."""
+
+ 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())
+ summary = await cache.summary([_CLAUDE, _CODEX])
+ assert [source["state"] for source in summary["sources"]] == ["ok", "error"]
+ release.set()
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ assert [source["state"] for source in (await cache.summary([_CLAUDE, _CODEX]))["sources"]] == ["ok", "ok"]
+
+
+class _Supervisor:
+ def __init__(self, client):
+ self._client = client
+
+ def client_if_running(self):
+ return self._client
+
+ def client(self): # pragma: no cover - a presentation read must never call this
+ raise AssertionError("quota read must not start the engine")
+
+
+class _EngineClient:
+ def __init__(self, response):
+ self.response = response
+ self.calls = []
+
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ self.calls.append((method, path, payload))
+ if path == "/auth-files":
+ return {"files": [
+ {"auth_index": "7", "id": "claude-a.json", "name": "claude-a.json", "provider": "claude"},
+ {"auth_index": "8", "id": "codex-b.json", "name": "codex-b.json", "provider": "codex",
+ "id_token": {"chatgpt_account_id": "acct_123"}},
+ ]}
+ return self.response
+
+
+class _StateStore:
+ def __init__(self, metadata):
+ self.metadata = metadata
+
+ def credential_metadata(self, credential_ref):
+ return self.metadata[credential_ref]
+
+
+def _adapter(response, metadata):
+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+
+ adapter = CLIProxyEngineAdapter.__new__(CLIProxyEngineAdapter)
+ client = _EngineClient(response)
+ adapter.supervisor = _Supervisor(client)
+ adapter.state_store = _StateStore(metadata)
+ return adapter, client
+
+
+_METADATA = {
+ "cred_a": {"kind": "oauth", "vendor": "anthropic", "auth_name": "claude-a.json", "source_id": "src_claude"},
+ "cred_b": {"kind": "oauth", "vendor": "openai", "auth_name": "codex-b.json", "source_id": "src_codex"},
+}
+
+
+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)
+ parsed = await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
+ assert set(parsed) == {"plan", "windows"}
+ method, path, payload = client.calls[-1]
+ assert (method, path) == ("POST", "/api-call")
+ assert payload["auth_index"] == "7"
+ assert payload["url"] == "https://api.anthropic.com/api/oauth/usage"
+ assert payload["header"]["Authorization"] == "Bearer $TOKEN$"
+ assert payload["header"]["anthropic-beta"] == "oauth-2025-04-20"
+ assert payload["header"]["User-Agent"] == "axios/1.15.2"
+
+ adapter, client = _adapter({"status_code": 200, "header": {}, "body": json.dumps(CODEX_REPORT)}, _METADATA)
+ await adapter.subscription_quota("src_codex", "openai", "cred_b")
+ payload = client.calls[-1][2]
+ assert payload["auth_index"] == "8"
+ assert payload["url"] == "https://chatgpt.com/backend-api/wham/usage"
+ assert payload["header"]["ChatGPT-Account-ID"] == "acct_123"
+ assert payload["header"]["User-Agent"] == "codex-cli"
+ assert "anthropic-beta" not in payload["header"]
+
+
+ ("response", "reason", "retry_after"),
+ [
+ ({"status_code": 401, "body": "{}"}, "auth_expired", None),
+ ({"status_code": 403, "body": "{}"}, "auth_expired", None),
+ ({"status_code": 429, "header": {"Retry-After": ["120"]}, "body": "{}"}, "rate_limited", 120.0),
+ ({"status_code": 429, "header": {"retry-after": ["Wed, 21 Oct 2015 07:28:00 GMT"]}, "body": "{}"}, "rate_limited", None),
+ ({"status_code": 429, "header": {"Retry-After": "soon"}, "body": "{}"}, "rate_limited", None),
+ ({"status_code": 500, "body": "{}"}, "unavailable", None),
+ ({"status_code": 200, "body": "<html>"}, "malformed", None),
+ ],
+)
+async def test_adapter_maps_vendor_statuses_to_sanitized_quota_failures(response, reason, retry_after):
+ """MH-QUOTA-011: Vendor statuses become sanitized reasons; a 429 carries its Retry-After."""
+
+ adapter, _client = _adapter(response, _METADATA)
+ with pytest.raises(SubscriptionQuotaError) as caught:
+ await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
+ assert caught.value.reason == reason
+ assert caught.value.retry_after_seconds == retry_after
+
+
+async def test_adapter_honours_a_future_http_date_retry_after():
+ """MH-QUOTA-011: A 429 whose Retry-After is an HTTP-date carries the delay until that date."""
+
+ from email.utils import format_datetime
+
+ later = datetime.now(timezone.utc) + timedelta(minutes=40)
+ adapter, _client = _adapter(
+ {"status_code": 429, "header": {"Retry-After": [format_datetime(later, usegmt=True)]}, "body": "{}"}, _METADATA
+ )
+ with pytest.raises(SubscriptionQuotaError) as caught:
+ await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
+ assert 38 * 60 < caught.value.retry_after_seconds <= 40 * 60
+
+
+async def test_adapter_quota_read_never_starts_the_engine():
+ """MH-QUOTA-011: With the engine stopped, or for a vendor without a report, the read fails without starting anything."""
+
+ adapter, _client = _adapter({}, _METADATA)
+ adapter.supervisor = _Supervisor(None)
+ with pytest.raises(SubscriptionQuotaError) as caught:
+ await adapter.subscription_quota("src_claude", "anthropic", "cred_a")
+ assert caught.value.reason == "unavailable"
+ with pytest.raises(SubscriptionQuotaError) as caught:
+ await adapter.subscription_quota("src_kimi", "kimi", "cred_a")
+ assert caught.value.reason == "unsupported"
diff --git a/tests/test_model_hub_retry_policy.py b/tests/test_model_hub_retry_policy.py
index 77a9ca029..1695eaa77 100644
--- a/tests/test_model_hub_retry_policy.py
+++ b/tests/test_model_hub_retry_policy.py
@@ -612,3 +612,25 @@ def test_selected_source_probe_does_not_claim_or_schedule_recovery(tmp_path, kin
assert service.store.load().to_payload() == before
assert service.events.list() == []
asyncio.run(run())
+
+
+def test_routing_blocker_drops_the_blocked_grants_quota_reading(tmp_path):
+ """MH-QUOTA-018: A grant routing marks needs_action is re-read, not shown with its pre-block quota."""
+
+ async def run():
+ service, _clock = clock_service(tmp_path)
+ source = service.store.config.sources[0]
+ source.kind, source.billing = "subscription", "monthly"
+ reads = []
+
+ async def subscription_quota(source_id, vendor, credential_ref):
+ reads.append(source_id)
+ return {"plan": None, "windows": []}
+
+ service.adapter.subscription_quota = subscription_quota
+ assert (await service.quota_summary())["sources"][0]["state"] == "ok"
+ await fail(service, service.store.load().sources[0], "credential_revoked")
+ assert service.store.load().sources[0].state.status == "needs_action"
+ await service.quota_summary()
+ assert reads == [source.id, source.id]
+ asyncio.run(run())
diff --git a/ui/e2e/model-catalog/fixture.tsx b/ui/e2e/model-catalog/fixture.tsx
index dfdd26005..80a037f07 100644
--- a/ui/e2e/model-catalog/fixture.tsx
+++ b/ui/e2e/model-catalog/fixture.tsx
@@ -11,6 +11,7 @@ import { blankBackendModel } from '../../src/components/settings/models/backendC
import { modelsApi } from '../../src/components/settings/models/modelsApi';
import type { AgentBackend, AgentSupply, BackendModel, BackendModelsPut } from '../../src/components/settings/models/types';
import { GatewayFixture } from './gatewayFixture';
+import { QuotaFixture } from './quotaFixture';
import { RouteFixture } from './routeFixture';
import { TokenScopeFixture } from './tokenScopeFixture';
@@ -68,4 +69,6 @@ createRoot(document.getElementById('root')!).render(params.get('view') === 'gate
? <I18nextProvider i18n={language}><GatewayFixture /></I18nextProvider>
: params.get('view') === 'route'
? <I18nextProvider i18n={language}><RouteFixture /></I18nextProvider>
+ : params.get('view') === 'quota'
+ ? <I18nextProvider i18n={language}><QuotaFixture /></I18nextProvider>
: <Fixture />);
diff --git a/ui/e2e/model-catalog/quota-layout.spec.ts b/ui/e2e/model-catalog/quota-layout.spec.ts
new file mode 100644
index 000000000..fa1d01c12
--- /dev/null
+++ b/ui/e2e/model-catalog/quota-layout.spec.ts
@@ -0,0 +1,41 @@
+import { expect, test, type Locator } from '@playwright/test';
+
+const box = async (locator: Locator) => {
+ await expect(locator).toBeVisible();
+ return (await locator.boundingBox())!;
+};
+const fits = (locator: Locator) => locator.evaluate((element) => element.scrollWidth <= element.clientWidth + 1);
+
+for (const lang of ['en', 'zh'] as const) {
+ test(`MH-QUOTA-015: holds the narrow layout at 360px — one account per line, stacked footers, wrapping labels (${lang})`, async ({ page }, testInfo) => {
+ await page.setViewportSize({ width: 360, height: 844 });
+ await page.goto(`/e2e/model-catalog/fixture.html?view=quota&lang=${lang}`);
+ const cards = page.getByRole('article');
+ await expect(cards).toHaveCount(2);
+ const [first, second] = await Promise.all([box(cards.nth(0)), box(cards.nth(1))]);
+
+ // One account per line: the second card starts below the first, in the same column.
+ expect(second.y).toBeGreaterThanOrEqual(first.y + first.height);
+ expect(Math.abs(second.x - first.x)).toBeLessThanOrEqual(1);
+ for (const card of [first, second]) expect(card.x + card.width).toBeLessThanOrEqual(360);
+
+ // Each footer stacks its reset line under the pace line.
+ for (const row of await page.locator('[data-quota-window]').all()) {
+ const reset = row.locator('.model-hub-quota-reset');
+ if (!(await reset.count())) continue;
+ const [pace, resetBox] = await Promise.all([box(row.locator('.model-hub-quota-pace')), box(reset)]);
+ expect(resetBox.y).toBeGreaterThanOrEqual(pace.y + pace.height - 1);
+ expect(await fits(row)).toBe(true);
+ }
+
+ // A long upstream name wraps inside its card instead of widening it.
+ const title = page.locator('[data-quota-window="x"] .model-hub-quota-row-title');
+ const [titleBox, cardBox] = await Promise.all([box(title), box(cards.nth(0))]);
+ expect(titleBox.x + titleBox.width).toBeLessThanOrEqual(cardBox.x + cardBox.width);
+ expect(await fits(title)).toBe(true);
+ expect(titleBox.height).toBeGreaterThan(20);
+
+ 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
new file mode 100644
index 000000000..8a414737f
--- /dev/null
+++ b/ui/e2e/model-catalog/quotaFixture.tsx
@@ -0,0 +1,39 @@
+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';
+
+const NOW = Date.parse('2026-09-25T08:00:00Z');
+const HOUR = 3_600_000;
+const iso = (ms: number) => new Date(ms).toISOString();
+const limit = (over: Partial<QuotaWindow>): QuotaWindow => ({
+ id: 'five_hour', kind: 'session', label: 'five_hour', used_pct: 38,
+ window_seconds: 18_000, resets_at: iso(NOW + 2 * HOUR), ...over,
+});
+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 sources: SourceQuota[] = [
+ {
+ source_id: 'src_claude', vendor: 'anthropic', display_name: 'Claude Max', account_label: '[email protected]',
+ plan: 'max', fetched_at: iso(NOW - 2 * 60_000), state: 'ok',
+ windows: [
+ limit({}),
+ 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 }),
+ ],
+ },
+ {
+ source_id: 'src_codex', vendor: 'openai', display_name: 'ChatGPT Pro', account_label: null,
+ plan: 'pro', fetched_at: iso(NOW - 60_000), state: 'ok',
+ windows: [
+ 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 }),
+ ],
+ },
+];
+
+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} />
+ </main>;
+}
diff --git a/ui/src/components/settings/models/QuotaTab.test.tsx b/ui/src/components/settings/models/QuotaTab.test.tsx
new file mode 100644
index 000000000..7bdcddca7
--- /dev/null
+++ b/ui/src/components/settings/models/QuotaTab.test.tsx
@@ -0,0 +1,273 @@
+// @vitest-environment jsdom
+// What the 订阅额度 tab says about a quota report: the windows it names, the pace
+// it claims, and what it admits about a reading that is not current.
+import { cleanup, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createInstance } from 'i18next';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+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';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'zh',
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+});
+
+const NOW = Date.parse('2026-09-25T03:00:00Z');
+const HOUR = 3_600_000;
+const iso = (ms: number) => new Date(ms).toISOString();
+
+const window = (over: Partial<QuotaWindow> = {}): QuotaWindow => ({
+ id: 'five_hour',
+ kind: 'session',
+ label: 'five_hour',
+ used_pct: 38,
+ window_seconds: 18_000,
+ resets_at: iso(NOW + 2 * HOUR),
+ ...over,
+});
+
+const claude = (over: Partial<SourceQuota> = {}): SourceQuota => ({
+ source_id: 'src_claude',
+ vendor: 'anthropic',
+ display_name: 'Claude Max',
+ account_label: '[email protected]',
+ plan: 'max',
+ fetched_at: iso(NOW - 2 * 60_000),
+ state: 'ok',
+ windows: [
+ window(),
+ window({ id: 'seven_day', kind: 'weekly', label: 'seven_day', used_pct: 61, window_seconds: 604_800, resets_at: iso(NOW + 4 * 24 * HOUR) }),
+ window({ id: 'fable', kind: 'model_weekly', label: 'Fable', scope_model: 'Fable', used_pct: 86, window_seconds: 604_800, resets_at: iso(NOW + 4 * 24 * HOUR) }),
+ window({ id: 'sonnet', kind: 'model_weekly', label: 'Sonnet', scope_model: 'Sonnet', used_pct: 22, window_seconds: 604_800, resets_at: iso(NOW + 4 * 24 * HOUR) }),
+ ],
+ ...over,
+});
+
+const codex = (over: Partial<SourceQuota> = {}): SourceQuota => ({
+ source_id: 'src_codex',
+ vendor: 'openai',
+ display_name: 'ChatGPT Pro',
+ account_label: null,
+ plan: 'pro',
+ fetched_at: iso(NOW - 60_000),
+ state: 'ok',
+ windows: [
+ window({ id: 'primary_window', label: 'primary_window', used_pct: 100, resets_at: iso(NOW + 47 * 60_000) }),
+ window({ id: 'secondary_window', kind: 'weekly', label: 'secondary_window', used_pct: 45, window_seconds: 604_800, resets_at: iso(NOW + 5 * 24 * HOUR) }),
+ window({ id: 'additional:0:primary_window', kind: 'model_weekly', label: 'Spark', scope_model: 'Spark', used_pct: 8, window_seconds: 604_800, resets_at: iso(NOW + 5 * 24 * HOUR) }),
+ ],
+ ...over,
+});
+
+const summary = (sources: SourceQuota[]): QuotaSummary => ({ refresh_interval_seconds: 300, sources });
+
+const draw = (quota: RegionRead<QuotaSummary>, over: { onRefresh?: () => void; onRequestReauth?: (id: string) => void } = {}) =>
+ render(
+ <I18nextProvider i18n={i18n}>
+ <QuotaTab quota={quota} now={NOW} onRefresh={over.onRefresh} onRequestReauth={over.onRequestReauth} />
+ </I18nextProvider>,
+ );
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('QuotaTab', () => {
+ it('MH-QUOTA-013: names every window in the final copy and states pace, reset, and status per account', () => {
+ const { container } = draw(readyRegion(summary([claude(), codex()])));
+
+ expect(screen.getByRole('heading', { name: '订阅额度' })).toBeTruthy();
+ expect(screen.getByText('2 个已登录的订阅账号')).toBeTruthy();
+ expect(screen.getByText('每 5 分钟自动刷新')).toBeTruthy();
+ expect(screen.getByRole('button', { name: '立即刷新' })).toBeTruthy();
+
+ const card = screen.getByRole('article', { name: 'Claude Max' });
+ for (const label of ['5 小时额度', '每周额度', 'Fable 每周额度', 'Sonnet 每周额度']) {
+ expect(within(card).getByText(label)).toBeTruthy();
+ }
+ expect(within(card).getAllByText('所有模型共用')).toHaveLength(2);
+ expect(within(card).getByText('只算 Fable 的用量')).toBeTruthy();
+ expect(within(card).getByText('单独计算的模型额度')).toBeTruthy();
+ expect(within(card).getByText('这些模型也会同时扣每周额度,任一项用完就会暂停')).toBeTruthy();
+ expect(within(card).getByText('可用')).toBeTruthy();
+ expect(within(card).getByText('max')).toBeTruthy();
+ expect(within(card).getByText('[email protected]')).toBeTruthy();
+
+ // Fable at 86% four days before a 7-day reset is spending faster than time.
+ const fable = card.querySelector('[data-quota-window="fable"]') as HTMLElement;
+ expect(fable.textContent).toMatch(/用得偏快,预计 .+ 用完/);
+ expect(within(fable).getByRole('meter', { name: 'Fable 每周额度 已用 86%' })).toBeTruthy();
+ expect(fable.textContent).toContain('14%');
+ const session = card.querySelector('[data-quota-window="five_hour"]') as HTMLElement;
+ expect(session.textContent).toContain('2 小时 0 分后重置');
+ expect(session.querySelector('.model-hub-quota-time-mark')).not.toBeNull();
+
+ // A spent window names itself in the status pill and says when it returns.
+ const codexCard = screen.getByRole('article', { name: 'ChatGPT Pro' });
+ expect(within(codexCard).getByText('5 小时额度已用完')).toBeTruthy();
+ expect(codexCard.textContent).toContain('已用完,47 分钟后恢复');
+ expect(within(codexCard).getByText('Spark 每周额度')).toBeTruthy();
+
+ // Summary: the tightest usable window, the spent count, and upcoming resets.
+ expect(screen.getByText('余量最少的额度')).toBeTruthy();
+ expect(container.textContent).toContain('Claude Max · Fable 每周额度');
+ expect(screen.getByText('已用完')).toBeTruthy();
+ 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.
+ expect(container.textContent).not.toMatch(/\$|USD|API 价格|回本/);
+ });
+
+ it('reports every account usable when nothing is spent, and reads pace from the window clock', () => {
+ draw(readyRegion(summary([claude()])));
+ expect(screen.getByText('所有账号都能正常使用')).toBeTruthy();
+
+ const fresh = window({ used_pct: 10, resets_at: iso(NOW + 4 * HOUR) });
+ expect(windowPace(fresh, NOW, false).pace.kind).toBe('ok');
+ expect(windowPace(window({ used_pct: 25, resets_at: iso(NOW + 4 * HOUR) }), NOW, false).pace.kind).toBe('slightly_fast');
+ expect(windowPace(window({ resets_at: iso(NOW - 1) }), NOW, false).pace.kind).toBe('reset');
+ expect(windowPace(fresh, NOW, true)).toMatchObject({ pace: { kind: 'paused' }, tone: 'stale' });
+ });
+
+ it('MH-QUOTA-014: keeps an expired grant\'s last reading under a banner that offers re-login', async () => {
+ const onRequestReauth = vi.fn();
+ draw(readyRegion(summary([
+ claude(),
+ codex({ state: 'auth_expired', error_key: 'models.quota.error.auth_expired', fetched_at: iso(NOW - 3 * HOUR - 12 * 60_000) }),
+ ])), { onRequestReauth });
+
+ const card = screen.getByRole('article', { name: 'ChatGPT Pro' });
+ expect(within(card).getByText('需重新登录')).toBeTruthy();
+ expect(within(card).getByRole('status').textContent).toBe('登录已过期,下面是 3 小时 12 分前的数据重新登录');
+ expect(within(card).getAllByText('暂停更新').length).toBeGreaterThan(0);
+ expect(card.classList.contains('model-hub-quota-card--retained')).toBe(true);
+ // A retained reading is not current, so it cannot fill the page summary,
+ // and an account that must sign in again is not called usable.
+ expect(screen.getByText('已读到的额度都没用完')).toBeTruthy();
+ expect(screen.queryByText('所有账号都能正常使用')).toBeNull();
+
+ await userEvent.click(within(card).getByRole('button', { name: '重新登录' }));
+ expect(onRequestReauth).toHaveBeenCalledWith('src_codex');
+ });
+
+ it('never shows a limit with headroom as 0% left or 100% used beside its usable status', () => {
+ expect(windowLeftPct(window({ used_pct: 99.9 }), NOW)).toBe(1);
+ expect(windowLeftPct(window({ used_pct: 100 }), NOW)).toBe(0);
+ expect(windowUsedPct(window({ used_pct: 99.9 }), NOW)).toBe(99);
+ expect(windowUsedPct(window({ used_pct: 100 }), NOW)).toBe(100);
+ draw(readyRegion(summary([claude({ windows: [window({ used_pct: 99.9, resets_at: iso(NOW + HOUR) })] })])));
+ expect(screen.getByRole('article').textContent).not.toContain('0%');
+ const meter = screen.getByRole('meter');
+ expect(meter.getAttribute('aria-label')).toContain('99%');
+ expect(meter.getAttribute('aria-label')).not.toContain('100%');
+ expect(meter.getAttribute('aria-valuenow')).toBe('99');
+ });
+
+ it('reads a spent window whose reset has come as given back, in every figure', () => {
+ // The reading predates the reset; until the next read the card must not say
+ // 「已重置」 and 「可用」 beside a full bar and 0% left.
+ for (const resetsAt of [NOW - 60_000, NOW]) {
+ const spent = window({ used_pct: 100, resets_at: iso(resetsAt) });
+ expect(windowLeftPct(spent, NOW)).toBe(100);
+ expect(windowUsedPct(spent, NOW)).toBe(0);
+ expect(windowPace(spent, NOW, false).pace.kind).toBe('reset');
+ draw(readyRegion(summary([claude({ windows: [spent] })])));
+ const card = screen.getByRole('article');
+ expect(card.textContent).toContain('100%');
+ expect(card.textContent).not.toContain('0% ');
+ const meter = within(card).getByRole('meter');
+ expect(meter.getAttribute('aria-valuenow')).toBe('0');
+ expect((meter.querySelector('i') as HTMLElement).style.width).toBe('0%');
+ expect(screen.getByText('所有账号都能正常使用')).toBeTruthy();
+ cleanup();
+ }
+ });
+
+ it('states an unread Source in words instead of an empty bar', () => {
+ draw(readyRegion(summary([
+ claude({ state: 'error', error_key: 'models.quota.error.unavailable', fetched_at: null, windows: [] }),
+ codex({ state: 'auth_expired', error_key: 'models.quota.error.auth_expired', fetched_at: null, windows: [] }),
+ ])), { onRequestReauth: () => {} });
+
+ expect(screen.getByText('暂时读不到额度,稍后会自动重试')).toBeTruthy();
+ const expired = screen.getByRole('article', { name: 'ChatGPT Pro' });
+ expect(within(expired).getByText('登录已过期,读不到额度')).toBeTruthy();
+ expect(within(expired).getByRole('button', { name: '重新登录' })).toBeTruthy();
+ expect(screen.queryAllByRole('meter')).toHaveLength(0);
+ });
+
+ it('names a known failure reason and never calls a windowless report usable', () => {
+ draw(readyRegion(summary([
+ claude({ state: 'ok', windows: [] }),
+ codex({ state: 'stale', error_key: 'models.quota.error.rate_limited', fetched_at: null, windows: [] }),
+ ])));
+
+ expect(within(screen.getByRole('article', { name: 'ChatGPT Pro' })).getByText('服务商暂时限制了额度查询')).toBeTruthy();
+ // An `ok` report with no windows reads as unavailable on its card, so the summary cannot call it usable.
+ const empty = screen.getByRole('article', { name: 'Claude Max' });
+ expect(within(empty).getByText('暂时读不到额度,稍后会自动重试')).toBeTruthy();
+ expect(within(empty).getByText('暂停更新')).toBeTruthy();
+ expect(screen.queryByText('所有账号都能正常使用')).toBeNull();
+ expect(screen.getByText('已读到的额度都没用完')).toBeTruthy();
+ });
+
+ it('keeps universal summary claims to the case where every account has a current reading', () => {
+ const spent = claude({ windows: [window({ used_pct: 100, resets_at: iso(NOW + HOUR) })] });
+ const expired = codex({ state: 'auth_expired', error_key: 'models.quota.error.auth_expired', fetched_at: null, windows: [] });
+ const mixed = draw(readyRegion(summary([spent, expired])));
+ expect(screen.getByText('暂时没有可读的额度')).toBeTruthy();
+ expect(screen.queryByText('所有额度都已用完')).toBeNull();
+ mixed.unmount();
+
+ draw(readyRegion(summary([spent])));
+ expect(screen.getByText('所有额度都已用完')).toBeTruthy();
+ });
+
+ it('keeps the last page under the failure strip and offers the empty state honestly', async () => {
+ const stale = draw(degradedRegion(summary([claude()]), 'read_failed', true));
+ expect(screen.getByText('刷新失败,请重试')).toBeTruthy();
+ expect(screen.getByRole('article', { name: 'Claude Max' })).toBeTruthy();
+ stale.unmount();
+
+ draw(loadingRegion());
+ expect(screen.getByText(/加载中|Loading/)).toBeTruthy();
+ cleanup();
+
+ const onRefresh = vi.fn();
+ draw(readyRegion(summary([])), { onRefresh });
+ expect(screen.getByText(/还没有已登录的订阅账号/)).toBeTruthy();
+ await userEvent.click(screen.getByRole('button', { name: '立即刷新' }));
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+
+ it('MH-QUOTA-015: renders an unrecognised window by its upstream name, with no invented hint; the 360px layout is held by ui/e2e/model-catalog/quota-layout.spec.ts', () => {
+ draw(readyRegion(summary([claude({ windows: [window({ id: 'x', kind: 'other', label: '非常长的上游额度名称'.repeat(4) })] })])));
+ expect(screen.getByText('非常长的上游额度名称'.repeat(4))).toBeTruthy();
+ expect(screen.getByRole('article').querySelector('[data-quota-window="x"] small')).toBeNull();
+ });
+
+ it('renders the English copy through the same keys', async () => {
+ await i18n.changeLanguage('en');
+ try {
+ draw(readyRegion(summary([claude()])));
+ expect(screen.getByRole('heading', { name: 'Subscription quota' })).toBeTruthy();
+ expect(screen.getByText('1 signed-in subscription account')).toBeTruthy();
+ expect(screen.getByText('Fable weekly limit')).toBeTruthy();
+ expect(screen.getByText('Counts Fable only')).toBeTruthy();
+ } finally {
+ await i18n.changeLanguage('zh');
+ }
+ });
+});
diff --git a/ui/src/components/settings/models/QuotaTab.tsx b/ui/src/components/settings/models/QuotaTab.tsx
new file mode 100644
index 000000000..1f39ae666
--- /dev/null
+++ b/ui/src/components/settings/models/QuotaTab.tsx
@@ -0,0 +1,369 @@
+// 订阅额度 — each logged-in subscription's own rate-limit windows
+// (`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.
+//
+// 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 { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
+import type { QuotaSummary, QuotaWindow, SourceQuota } from './types';
+import { VendorGlyph } from './vendorGlyph';
+import {
+ DAY_MS,
+ HOUR_MS,
+ MINUTE_MS,
+ exhaustedWindows,
+ quotaDuration,
+ quotaIsLive,
+ quotaIsRetained,
+ sourceStatus,
+ tightestWindow,
+ upcomingResets,
+ windowIsExhausted,
+ windowIsScoped,
+ windowLeftPct,
+ windowUsedPct,
+ windowPace,
+ windowResetAt,
+ type QuotaPace,
+ type QuotaTone,
+} from './quotaProjection';
+
+/** The copy helpers every panel shares, bound to one `now`. */
+const useQuotaText = (now: number) => {
+ const { t, i18n } = useTranslation();
+ const duration = React.useCallback((ms: number) => {
+ const d = quotaDuration(ms);
+ if (d.unit === 'days') return t('settings.models.quota.duration.days', { days: d.days, hours: d.hours }) as string;
+ if (d.unit === 'hours') return t('settings.models.quota.duration.hours', { hours: d.hours, minutes: d.minutes }) as string;
+ return t('settings.models.quota.duration.minutes', { minutes: d.minutes }) as string;
+ }, [t]);
+ const clock = React.useCallback((at: number) => {
+ const time = new Intl.DateTimeFormat(i18n.language, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(at);
+ const startOfDay = (ms: number) => { const day = new Date(ms); day.setHours(0, 0, 0, 0); return day.getTime(); };
+ const dayDiff = Math.round((startOfDay(at) - startOfDay(now)) / DAY_MS);
+ if (dayDiff === 0) return t('settings.models.quota.clock.today', { time }) as string;
+ if (dayDiff === 1) return t('settings.models.quota.clock.tomorrow', { time }) as string;
+ return new Intl.DateTimeFormat(i18n.language, {
+ weekday: 'short', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
+ }).format(at);
+ }, [i18n.language, now, t]);
+ const ago = React.useCallback((at: number) => {
+ const ms = Math.max(0, now - at);
+ return ms < HOUR_MS
+ ? t('settings.models.quota.ago.minutes', { count: Math.max(1, Math.round(ms / MINUTE_MS)) }) as string
+ : t('settings.models.quota.ago.long', { duration: duration(ms) }) as string;
+ }, [duration, now, t]);
+ /** A window's name: the vendor's own model name, framed in this product's words. */
+ const windowLabel = React.useCallback((window: QuotaWindow) => {
+ if (window.kind === 'session') return t('settings.models.quota.window.session') as string;
+ if (window.kind === 'weekly') return t('settings.models.quota.window.weekly') as string;
+ if (window.kind === 'model_weekly') return t('settings.models.quota.window.model', { model: window.scope_model ?? window.label }) as string;
+ return window.label;
+ }, [t]);
+ const windowHint = React.useCallback((window: QuotaWindow) => {
+ if (window.kind === 'model_weekly') return t('settings.models.quota.hint.model', { model: window.scope_model ?? window.label }) as string;
+ if (window.kind === 'session' || window.kind === 'weekly') return t('settings.models.quota.hint.shared') as string;
+ return null;
+ }, [t]);
+ const paceText = React.useCallback((pace: QuotaPace) => {
+ switch (pace.kind) {
+ case 'paused': return t('settings.models.quota.pace.paused') as string;
+ case 'reset': return t('settings.models.quota.pace.reset') as string;
+ case 'exhausted': return pace.remainingMs !== null
+ ? t('settings.models.quota.pace.exhausted', { duration: duration(pace.remainingMs) }) as string
+ : t('settings.models.quota.pace.exhaustedUnknown') as string;
+ case 'fast': return t('settings.models.quota.pace.fast', { time: clock(pace.runsOutAt) }) as string;
+ case 'slightly_fast': return t('settings.models.quota.pace.slightlyFast') as string;
+ default: return t('settings.models.quota.pace.ok') as string;
+ }
+ }, [clock, duration, t]);
+ return { duration, clock, ago, windowLabel, windowHint, paceText };
+};
+
+type QuotaText = ReturnType<typeof useQuotaText>;
+
+const toneClass = (tone: QuotaTone) => `model-hub-quota-tone--${tone}`;
+
+const WindowRow: React.FC<{ window: QuotaWindow; now: number; retained: boolean; nested?: boolean; text: QuotaText }> = ({
+ window, now, retained, nested, text,
+}) => {
+ const { t } = useTranslation();
+ const reading = windowPace(window, now, retained);
+ const label = text.windowLabel(window);
+ const hint = text.windowHint(window);
+ const resetAt = windowResetAt(window);
+ const untilReset = resetAt !== null ? resetAt - now : null;
+ const alarm = reading.tone === 'warn' || reading.tone === 'danger';
+ return (
+ <div className={cn('model-hub-quota-row', nested && 'model-hub-quota-row--nested')} data-quota-window={window.id}>
+ <div className="flex items-end justify-between gap-2.5">
+ <div className="model-hub-quota-row-title min-w-0">
+ <strong className="font-medium text-foreground">{label}</strong>
+ {hint && <small>{hint}</small>}
+ </div>
+ <div className={cn('model-hub-quota-left flex shrink-0 items-baseline gap-1', toneClass(reading.tone))}>
+ <b>{windowLeftPct(window, now)}%</b>
+ <span>{t('settings.models.quota.left')}</span>
+ </div>
+ </div>
+ <div
+ className="model-hub-quota-bar"
+ role="meter"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={windowUsedPct(window, now)}
+ aria-label={t('settings.models.quota.meter', { label, pct: windowUsedPct(window, now) }) as string}
+ >
+ <i className={toneClass(reading.tone)} style={{ width: `${windowUsedPct(window, now)}%` }} />
+ {untilReset !== null && untilReset > 0 && reading.elapsedPct !== null && (
+ <span className="model-hub-quota-time-mark" style={{ left: `${reading.elapsedPct}%` }} />
+ )}
+ </div>
+ <div className="model-hub-quota-row-foot">
+ <span className={cn('model-hub-quota-pace flex items-center gap-[5px]', toneClass(reading.tone))}>
+ {alarm ? <AlertTriangle className="size-[11px]" aria-hidden /> : <span className="model-hub-quota-dot" aria-hidden />}
+ {text.paceText(reading.pace)}
+ </span>
+ {untilReset !== null && (
+ <span className="model-hub-quota-reset flex items-center gap-[5px]">
+ <TimerReset className="size-[11px]" aria-hidden />
+ {untilReset > 0
+ ? <>{t('settings.models.quota.reset.in', { duration: text.duration(untilReset) })}<em>{text.clock(resetAt as number)}</em></>
+ : t('settings.models.quota.reset.done')}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+/** The no-reading line: the known states have their own copy, a named failure its own reason. */
+const unreadKey = (source: SourceQuota) => {
+ if (source.state === 'auth_expired') return 'settings.models.quota.unread.auth_expired' as const;
+ if (source.state === 'unsupported') return 'settings.models.quota.unread.unsupported' as const;
+ if (source.error_key === 'models.quota.error.rate_limited') return 'models.quota.error.rate_limited' as const;
+ if (source.error_key === 'models.quota.error.malformed') return 'models.quota.error.malformed' as const;
+ return 'settings.models.quota.unread.error' as const;
+};
+
+const AccountCard: React.FC<{
+ source: SourceQuota;
+ now: number;
+ text: QuotaText;
+ onRequestReauth?: (sourceId: string) => void;
+}> = ({ source, now, text, onRequestReauth }) => {
+ const { t } = useTranslation();
+ const retained = quotaIsRetained(source);
+ const status = sourceStatus(source, now);
+ const shared = source.windows.filter((window) => !windowIsScoped(window));
+ const scoped = source.windows.filter(windowIsScoped);
+ const statusTone: QuotaTone = status.kind === 'ok' ? 'ok' : status.kind === 'exhausted' ? 'danger' : 'stale';
+ const statusText = status.kind === 'exhausted'
+ ? t('settings.models.quota.status.exhausted', { label: text.windowLabel(status.window) })
+ : t(`settings.models.quota.status.${status.kind}`);
+ const expired = source.state === 'auth_expired';
+ const fetchedAt = source.fetched_at !== null ? Date.parse(source.fetched_at) : NaN;
+ return (
+ <article
+ className={cn('model-hub-quota-card min-w-0 rounded-xl border border-border bg-background', retained && 'model-hub-quota-card--retained')}
+ aria-label={source.display_name}
+ data-quota-source={source.source_id}
+ >
+ <header className="flex items-center gap-2.5">
+ <VendorGlyph vendor={source.vendor} className="size-7 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <strong className="model-hub-quota-account flex min-w-0 items-center gap-2 font-semibold text-foreground">
+ <span className="truncate">{source.display_name}</span>
+ {source.plan && <span className="model-hub-quota-plan shrink-0">{source.plan}</span>}
+ </strong>
+ {source.account_label && <small className="model-hub-quota-account-label block truncate">{source.account_label}</small>}
+ </div>
+ <span className={cn('model-hub-quota-status flex shrink-0 items-center gap-1.5', toneClass(statusTone))}>
+ <span className="model-hub-quota-dot" aria-hidden />{statusText}
+ </span>
+ </header>
+ {retained && !Number.isNaN(fetchedAt) && (
+ <div className="model-hub-quota-stale flex items-center gap-2" role="status">
+ <AlertTriangle className="size-[13px] shrink-0" aria-hidden />
+ <span className="min-w-0 flex-1">
+ {t(expired ? 'settings.models.quota.stale.authExpired' : 'settings.models.quota.stale.retained', { ago: text.ago(fetchedAt) })}
+ </span>
+ {expired && onRequestReauth && (
+ <Button variant="outline" size="sm" className="shrink-0" onClick={() => onRequestReauth(source.source_id)}>
+ {t('settings.models.quota.stale.reauth')}
+ </Button>
+ )}
+ </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">
+ {t(unreadKey(source))}
+ </span>
+ {expired && onRequestReauth && (
+ <Button variant="outline" size="sm" className="shrink-0" onClick={() => onRequestReauth(source.source_id)}>
+ {t('settings.models.quota.stale.reauth')}
+ </Button>
+ )}
+ </div>
+ )
+ : (
+ <div className="model-hub-quota-rows flex flex-col">
+ {shared.map((window) => <WindowRow key={window.id} window={window} now={now} retained={retained} text={text} />)}
+ {scoped.length > 0 && (
+ <div className="model-hub-quota-scoped flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
+ <Sparkles className="size-[11px]" aria-hidden />
+ {t('settings.models.quota.scoped.title')}
+ <span>{t('settings.models.quota.scoped.note')}</span>
+ </div>
+ )}
+ {scoped.map((window) => <WindowRow key={window.id} window={window} now={now} retained={retained} nested text={text} />)}
+ </div>
+ )}
+ </article>
+ );
+};
+
+const StatCard: React.FC<{ label: string; icon: React.ReactNode; value: React.ReactNode; note: React.ReactNode; primary?: boolean }> = ({
+ label, icon, value, note, primary,
+}) => (
+ <div className={cn('model-hub-usage-stat flex flex-col rounded-xl border border-border bg-background', primary && 'model-hub-quota-stat--primary')}>
+ <span className="model-hub-usage-stat-label flex items-center justify-between gap-2">{label}{icon}</span>
+ <span className="model-hub-usage-stat-value font-semibold text-foreground">{value}</span>
+ <span className="model-hub-usage-stat-note">{note}</span>
+ </div>
+);
+
+/** A live clock for pace and countdowns, re-read every half minute. */
+const useNow = (override?: number) => {
+ const [now, setNow] = React.useState(() => Date.now());
+ React.useEffect(() => {
+ if (override !== undefined) return undefined;
+ const timer = window.setInterval(() => setNow(Date.now()), 30_000);
+ return () => window.clearInterval(timer);
+ }, [override]);
+ return override ?? now;
+};
+
+export const QuotaTab: React.FC<{
+ quota: RegionRead<QuotaSummary>;
+ refreshing?: boolean;
+ onRefresh?: () => void | Promise<void>;
+ onRetry?: () => void | Promise<void>;
+ /** Asks to sign the expired grant in again; the page confirms before the journey starts. */
+ onRequestReauth?: (sourceId: string) => void;
+ /** Fixes the clock the projection reads; the tab ticks its own when absent. */
+ now?: number;
+}> = ({ quota: quotaRead, refreshing = false, onRefresh, onRetry, onRequestReauth, now: fixedNow }) => {
+ const { t } = useTranslation();
+ const now = useNow(fixedNow);
+ const text = useQuotaText(now);
+ const summary = foldRegionRead<QuotaSummary, QuotaSummary | null>(quotaRead, {
+ loading: () => null,
+ ready: (data) => data,
+ unread: () => null,
+ // The last reading stays on screen under the failure strip.
+ degraded: (staleData) => staleData,
+ });
+ const sources = summary?.sources ?? [];
+ const tightest = tightestWindow(sources, now);
+ const exhausted = exhaustedWindows(sources, now);
+ const upcoming = upcomingResets(sources, now);
+
+ return (
+ <section className="model-hub-usage" aria-label={t('settings.models.quota.title') as string}>
+ <div className="model-hub-usage-bar flex flex-col gap-3 rounded-xl border border-border bg-surface sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 flex-col gap-1">
+ <h2 className="model-hub-usage-title font-semibold text-foreground">{t('settings.models.quota.title')}</h2>
+ <p className="model-hub-usage-note flex flex-wrap gap-x-2">
+ {summary !== null && <span>{t('settings.models.quota.header', { count: sources.length })}</span>}
+ {summary !== null && <span aria-hidden>·</span>}
+ <span>{t('settings.models.quota.autoRefresh')}</span>
+ </p>
+ </div>
+ <Button variant="outline" size="sm" className="shrink-0 self-start sm:self-auto" disabled={refreshing} onClick={() => void onRefresh?.()}>
+ <RefreshCw className={cn('size-[13px]', refreshing && 'animate-spin')} aria-hidden />
+ {refreshing ? t('settings.models.quota.refreshing') : t('settings.models.quota.refresh')}
+ </Button>
+ </div>
+ {regionFailed(quotaRead) && (
+ <div className="model-hub-usage-failure flex items-center justify-between gap-3 rounded-xl border border-border bg-background text-destructive-ink">
+ <span>{t('settings.models.toast.refreshFailed')}</span>
+ <button type="button" onClick={() => void onRetry?.()} className="model-hub-action-mint shrink-0 font-semibold">
+ {t('settings.models.upstream.retry')}
+ </button>
+ </div>
+ )}
+ {summary === null
+ ? quotaRead.kind === 'loading' && <p className="model-hub-usage-pending text-muted">{t('common.loading')}</p>
+ : 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">
+ <StatCard
+ primary
+ label={t('settings.models.quota.stat.tightest')}
+ icon={<Gauge className="size-[15px]" aria-hidden />}
+ value={tightest ? <>{windowLeftPct(tightest.window, now)}%<small className="model-hub-quota-stat-unit">{t('settings.models.quota.left')}</small></> : '—'}
+ note={tightest
+ ? (() => {
+ const resetAt = windowResetAt(tightest.window);
+ return [
+ tightest.source.display_name,
+ text.windowLabel(tightest.window),
+ resetAt !== null && resetAt > now ? t('settings.models.quota.stat.resetsIn', { duration: text.duration(resetAt - now) }) : null,
+ ].filter(Boolean).join(' · ');
+ })()
+ // Like 「every account is usable」 below, 「every limit is used up」 is a
+ // claim about all accounts: make it only when each has a current reading.
+ : t(exhausted.length && sources.every(quotaIsLive) ? 'settings.models.quota.stat.tightestAllSpent' : 'settings.models.quota.stat.tightestUnread')}
+ />
+ <StatCard
+ label={t('settings.models.quota.stat.exhausted')}
+ icon={<Clock3 className="size-[15px]" aria-hidden />}
+ value={<>{exhausted.length}<small className="model-hub-quota-stat-unit">{t('settings.models.quota.stat.exhaustedUnit')}</small></>}
+ note={exhausted.length
+ ? (() => {
+ const resetAt = windowResetAt(exhausted[0].window);
+ return resetAt !== null
+ ? t('settings.models.quota.stat.exhaustedNote', { name: exhausted[0].source.display_name, time: text.clock(resetAt) })
+ : exhausted[0].source.display_name;
+ })()
+ // 「every account is usable」 is a claim about accounts; make it only
+ // when every account has a current reading to back it.
+ : t(sources.every(quotaIsLive) ? 'settings.models.quota.stat.exhaustedNone' : 'settings.models.quota.stat.exhaustedNoneObserved')}
+ />
+ </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>
+ ))}
+ </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} />)}
+ </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>
+ </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 5c8a8d884..18ff959da 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -16,7 +16,7 @@ import type { ModelsSurfaceKind } from './modelHubSurfaceState';
import { ApiCallError, modelsApi } from './modelsApi';
import { 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 Source, type UsageSummary } from './types';
+import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type QuotaSummary, type Source, type UsageSummary } from './types';
// The page navigates to Agents when the user clicks an Agent that needs
// attention, so it needs a router in scope. Every render site wants the same
@@ -126,6 +126,8 @@ const takeoverChain: AgentChain = { manual_override: {hops:[{source_id:'src_head
supply_state: 'ok',
};
+const quotaSummary: QuotaSummary = { refresh_interval_seconds: 300, sources: [] };
+
const takeoverMappingTitle = /Replacement source → gpt-5\.6-sol \((?:Taken over|已自动切换)\)/i;
const headMappingTitle = /^Paused source → gpt-5\.6-sol$/i;
@@ -223,6 +225,8 @@ const renderPage = (
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtimeValue);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
vi.spyOn(modelsApi, 'getUsageSummary').mockResolvedValue(usageSummary);
+ vi.spyOn(modelsApi, 'getQuota').mockResolvedValue(quotaSummary);
+ vi.spyOn(modelsApi, 'refreshQuota').mockResolvedValue(quotaSummary);
return render(
<ToastProvider>
<I18nextProvider i18n={i18n}>
@@ -549,7 +553,7 @@ describe('SettingsModelsPage surface branches', () => {
// Frame 09 is what the `sources` tab shows here — not what the Hub shows
// instead of its tabs. It is still Frame 09's body: none of the gateway
// overview leaks in beside it.
- expect(screen.getAllByRole('tab')).toHaveLength(3);
+ expect(screen.getAllByRole('tab')).toHaveLength(4);
expect(screen.queryByText(/^Recent switches$|^最近切换$/i)).toBeNull();
});
@@ -699,7 +703,7 @@ describe('SettingsModelsPage surface branches', () => {
await userEvent.click(toggle);
await waitFor(() => expect(start).toHaveBeenCalledOnce());
- expect(await screen.findAllByRole('tab')).toHaveLength(3);
+ expect(await screen.findAllByRole('tab')).toHaveLength(4);
});
it('keeps routing controls available while an enabled gateway process is unavailable', async () => {
@@ -726,7 +730,7 @@ describe('SettingsModelsPage surface branches', () => {
expect((toggle as HTMLButtonElement).disabled).toBe(true);
expect(await screen.findByText('Retained source')).toBeTruthy();
expect(screen.getByRole('button', { name: /Runtime mode:|运行模式[::]/i })).toBeTruthy();
- expect(screen.queryAllByRole('tab')).toHaveLength(3);
+ expect(screen.queryAllByRole('tab')).toHaveLength(4);
});
it('still allows persisted enablement to be turned off on an unsupported host', async () => {
@@ -801,7 +805,7 @@ describe('SettingsModelsPage surface branches', () => {
renderPage([retainedSource]);
expect(await screen.findByText('Retained source')).toBeTruthy();
- expect(screen.getAllByRole('tab')).toHaveLength(3);
+ expect(screen.getAllByRole('tab')).toHaveLength(4);
expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,有三大益处$/i)).toBeNull();
});
@@ -2305,7 +2309,7 @@ describe('SettingsModelsPage usage region', () => {
vi.restoreAllMocks();
renderPage(sources);
- await waitFor(() => expect(screen.getAllByRole('tab'), landing).toHaveLength(3));
+ await waitFor(() => expect(screen.getAllByRole('tab'), landing).toHaveLength(4));
await openUsage();
await waitFor(() => expect(vi.mocked(modelsApi.getUsageSummary), landing).toHaveBeenCalledWith(30));
}
@@ -2358,3 +2362,101 @@ describe('SettingsModelsPage usage region', () => {
expect(read.mock.calls.map(([days]) => days)).toEqual([30, 30]);
});
});
+
+// How the quota report is READ: off the first paint, live on open, and re-read on
+// the five-minute cadence the header promises for as long as the tab is open.
+describe('SettingsModelsPage quota region', () => {
+ const openQuota = () => userEvent.click(screen.getByRole('tab', { name: /^Subscription quota$|^订阅额度$/ }));
+
+ it('MH-QUOTA-016: reads quota only while its tab is open, polls every five minutes, and forces on refresh', async () => {
+ const intervals = vi.spyOn(window, 'setInterval');
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getQuota);
+ const force = vi.mocked(modelsApi.refreshQuota);
+ expect(read).not.toHaveBeenCalled();
+
+ await openQuota();
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
+ const poll = intervals.mock.calls.find(([, delay]) => delay === 5 * 60_000);
+ expect(poll).toBeTruthy();
+ await act(async () => { (poll![0] as () => void)(); });
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+
+ await userEvent.click(await screen.findByRole('button', { name: /^Refresh now$|^立即刷新$/ }));
+ await waitFor(() => expect(force).toHaveBeenCalledTimes(1));
+
+ const clear = vi.spyOn(window, 'clearInterval');
+ await userEvent.click(screen.getByRole('tab', { name: /^Sources & gateway$|^供应商与路由$/ }));
+ expect(clear).toHaveBeenCalled();
+ });
+
+ // 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
+ // re-read once the new grant lands instead of showing the expired one.
+ it('MH-QUOTA-017: signs an expired grant in again from the quota card and re-reads quota after', async () => {
+ const started = {
+ flow_id: 'flow_reauth',
+ intent: 'reauth' as const,
+ vendor: 'anthropic',
+ channel: 'native_cli' as const,
+ state: 'starting' as const,
+ presentation: { expects: 'none' as const },
+ };
+ const reauth = vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(started);
+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({ flow: { ...started, state: 'success' as const }, created: null, repaired: null });
+ renderPage([nativeSubscription]);
+ vi.mocked(modelsApi.getQuota).mockResolvedValue({
+ refresh_interval_seconds: 300,
+ sources: [{
+ source_id: nativeSubscription.id,
+ vendor: 'anthropic',
+ display_name: nativeSubscription.display_name,
+ account_label: null,
+ plan: null,
+ fetched_at: null,
+ state: 'auth_expired',
+ error_key: 'models.quota.error.auth_expired',
+ windows: [],
+ }],
+ });
+ await screen.findByText('Claude native login');
+ await openQuota();
+ const read = vi.mocked(modelsApi.getQuota);
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
+
+ const trigger = await screen.findByRole('button', { name: /^Sign in again$|^重新登录$/ });
+ await userEvent.click(trigger);
+ expect(reauth).not.toHaveBeenCalled();
+ // Cancelling returns focus to the quota card's button, not to the document.
+ await userEvent.click(await screen.findByRole('button', { name: /^Cancel$|^取消$/ }));
+ await waitFor(() => expect(document.activeElement).toBe(trigger));
+ await userEvent.click(trigger);
+ await userEvent.click(await screen.findByRole('button', { name: /^Start sign-in$|^开始登录$/i }));
+ await waitFor(() => expect(reauth).toHaveBeenCalledWith(nativeSubscription.id));
+ // The flow's first status poll lands after its 2 s cadence.
+ await waitFor(() => expect(read.mock.calls.length).toBeGreaterThanOrEqual(2), { timeout: 4000 });
+ // The finished sign-in closes its dialog; focus returns to the quota card's button, not the document.
+ await waitFor(() => expect(document.activeElement).toBe(trigger), { timeout: 4000 });
+ }, 12000);
+ it('returns focus to the quota tab when a refresh removed the re-login button behind its confirmation', async () => {
+ renderPage([nativeSubscription]);
+ vi.mocked(modelsApi.getQuota).mockResolvedValue({
+ refresh_interval_seconds: 300,
+ sources: [{
+ source_id: nativeSubscription.id, vendor: 'anthropic', display_name: nativeSubscription.display_name,
+ account_label: null, plan: null, fetched_at: null, state: 'auth_expired',
+ error_key: 'models.quota.error.auth_expired', windows: [],
+ }],
+ });
+ await screen.findByText('Claude native login');
+ await openQuota();
+ const trigger = await screen.findByRole('button', { name: /^Sign in again$|^重新登录$/ });
+ await userEvent.click(trigger);
+ // A background read settles while the confirmation is open and drops the button.
+ trigger.remove();
+ await userEvent.click(await screen.findByRole('button', { name: /^Cancel$|^取消$/ }));
+ await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('tab', { name: /^Subscription quota$|^订阅额度$/ })));
+ });
+});
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index de9aaab3e..d601c96e5 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -1,10 +1,11 @@
import * as React from 'react';
-import { ArrowDownToLine, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';
+import { ArrowDownToLine, Activity, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
@@ -32,6 +33,7 @@ import {
releaseSuspendedRouteAttempt,
} from './suspendedRouteAttempts';
import { SupplyGraph, SupplyLegend } from './SupplyGraph';
+import { QuotaTab } from './QuotaTab';
import { UsageTab } from './UsageTab';
import './modelHubSurface.css';
import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKeySet, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
@@ -65,12 +67,13 @@ import {
import { freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntime, runtimeCanAttemptInstall, runtimeIsRunning } from './runtimeLifecycle';
import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';
import { handOffProviderTab } from './providerTab';
+import { canReauth, reauthBodyKey, reauthCost } from './repair';
import { resumeGatewayAdoption } from './gatewayAdoption';
import { groupMigrationCandidates } from './migrationGrouping';
import { SUBSCRIPTION_MENU_ROWS, hasNativeSubscriptionCustody } from './subscriptionOptions';
import { VendorGlyph } from './vendorGlyph';
import { backendVisual } from './vendorMeta';
-import { USAGE_DEFAULT_WINDOW_DAYS, type AgentBackend, type AgentSupply, type ResolutionEvent, type RuntimeDependency, type Source, type UsageSummary } from './types';
+import { USAGE_DEFAULT_WINDOW_DAYS, type AgentBackend, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageSummary } from './types';
import type { UsageWindowOption } from './usageProjection';
const CHAIN_READ_CONCURRENCY = 6;
@@ -280,15 +283,22 @@ const ModelHubShell: React.FC<{ actions?: React.ReactNode; children: React.React
);
};
-type HubTab = 'sources' | 'usage' | 'logs';
+/** The service refreshes each Source at most this often; polling faster buys nothing. */
+const QUOTA_POLL_MS = 5 * 60_000;
+
+/** 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) =>
+ (opener.isConnected ? opener : document.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'))?.focus();
+
+type HubTab = 'sources' | 'quota' | 'usage' | 'logs';
const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ tab, onChange }) => {
const { t } = useTranslation();
return (
<div role="tablist" className="flex h-[39px] items-end gap-1 border-b border-border">
- {(['sources', 'usage', 'logs'] as const).map((id) => (
+ {(['sources', 'quota', 'usage', 'logs'] as const).map((id) => (
<button key={id} type="button" role="tab" aria-selected={tab === id} onClick={() => onChange(id)} className={cn('flex h-[41px] items-center gap-[7px] border-b-2 px-3.5 text-[13px] transition-colors', tab === id ? 'border-mint font-semibold text-foreground' : 'border-transparent font-normal text-muted hover:text-foreground')}>
- {id === 'sources' ? <Route className="size-3.5" /> : id === 'usage' ? <Gauge className="size-3.5" /> : <ScrollText className="size-3.5" />}
+ {id === 'sources' ? <Route className="size-3.5" /> : id === 'quota' ? <Gauge className="size-3.5" /> : id === 'usage' ? <Activity className="size-3.5" /> : <ScrollText className="size-3.5" />}
{t(`settings.models.shell.tab.${id === 'sources' ? 'hub' : id}`)}
</button>
))}
@@ -366,6 +376,8 @@ export const SettingsModelsPage: React.FC = () => {
const [loadingEvents, setLoadingEvents] = React.useState(false);
const [tab, setTab] = React.useState<HubTab>('sources');
const [usageRead, setUsageRead] = React.useState<RegionRead<UsageSummary>>(loadingRegion);
+ const [quotaRead, setQuotaRead] = React.useState<RegionRead<QuotaSummary>>(loadingRegion);
+ const [refreshingQuota, setRefreshingQuota] = React.useState(false);
const [usageWindow, setUsageWindow] = React.useState<UsageWindowOption>(USAGE_DEFAULT_WINDOW_DAYS);
const [startingRuntime, setStartingRuntime] = React.useState(false);
const [stoppingRuntime, setStoppingRuntime] = React.useState(false);
@@ -391,6 +403,13 @@ export const SettingsModelsPage: React.FC = () => {
// which replaces the overview that holds 添加订阅 — and only the create path
// owns the success-landing timer and reconcile flag below.
const [reauthSource, setReauthSource] = React.useState<Source | null>(null);
+ // A quota read can be the first to see a refused grant while the Source row
+ // is still healthy, so its re-login cannot route through the detail panel's
+ // repair button (which only a blocked row shows). It asks the same question
+ // here, then starts the same journey.
+ const [quotaReauthSource, setQuotaReauthSource] = React.useState<Source | null>(null);
+ // A re-login started from a quota card has no detail heading to return to.
+ const quotaReauthOpenerRef = React.useRef<HTMLElement | null>(null);
const subscriptionTriggerRef = React.useRef<HTMLButtonElement>(null);
const apiKeyTriggerRef = React.useRef<HTMLButtonElement | null>(null);
const subscriptionAnchorRef = subscriptionTriggerRef as React.RefObject<HTMLButtonElement>;
@@ -661,6 +680,43 @@ export const SettingsModelsPage: React.FC = () => {
await refreshUsage(usageWindow);
}, [refreshUsage, usageWindow]);
+ const [quotaReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<QuotaSummary>>((incoming) => {
+ if (!aliveRef.current) return;
+ setQuotaRead((previous) => settleRegionRead(previous, incoming));
+ }));
+
+ const readQuota = React.useCallback(async (force: boolean) => {
+ setQuotaRead(beginRegionRead);
+ await quotaReadAuthority.run(() => readRegion(() => (force ? modelsApi.refreshQuota() : modelsApi.getQuota())));
+ }, [quotaReadAuthority]);
+
+ /**
+ * Subscription quota is read lazily too, for the same reason as usage: it is
+ * a report, and the landing that decides routing must not wait on a vendor.
+ * While the tab stays open it re-reads on the service's own cadence; the
+ * service caches per Source, so an interval tick costs a vendor call only
+ * when that Source's reading is actually due.
+ */
+ React.useEffect(() => {
+ if (tab !== 'quota') return undefined;
+ void readQuota(false);
+ const timer = window.setInterval(() => { void readQuota(false); }, QUOTA_POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [tab, readQuota]);
+
+ const refreshQuotaNow = React.useCallback(async () => {
+ setRefreshingQuota(true);
+ try {
+ await readQuota(true);
+ } finally {
+ if (aliveRef.current) setRefreshingQuota(false);
+ }
+ }, [readQuota]);
+
+ const retryQuota = React.useCallback(async () => {
+ await readQuota(false);
+ }, [readQuota]);
+
const refreshEventHead = React.useCallback(async () => {
setEventsRead(beginRegionRead);
await eventReadAuthority.run(async () => {
@@ -1341,13 +1397,21 @@ export const SettingsModelsPage: React.FC = () => {
* one: `_materialize_reauth` can leave other agents without a source, so
* `/agents` and the chains behind it are stale too, not just this row.
*/
- const sourceReauthed = React.useCallback(() => { void refresh(); }, [refresh]);
+ const sourceReauthed = React.useCallback(() => {
+ void refresh();
+ // The Source now holds a new grant; the open quota tab re-reads for it
+ // instead of showing the expired one until the next tick.
+ if (tab === 'quota') void readQuota(false);
+ }, [readQuota, refresh, tab]);
const closeReauth = React.useCallback(() => {
setReauthSource(null);
// Back to the detail heading rather than to the button that opened this: a
// repair that worked unmounts that button (the row is no longer stopped), and
- // Radix would restore focus to a node that is gone — i.e. to <body>.
- window.setTimeout(() => sourceDetailHeadingRef.current?.focus(), 0);
+ // Radix would restore focus to a node that is gone — i.e. to <body>. From a
+ // quota card, back to its button, or to the quota tab once it is gone.
+ const opener = quotaReauthOpenerRef.current;
+ quotaReauthOpenerRef.current = null;
+ window.setTimeout(() => (opener ? focusQuotaOpener(opener) : sourceDetailHeadingRef.current?.focus()), 0);
}, []);
const closeSubscriptionPicker = React.useCallback(() => {
subscriptionPickerHandoffRef.current = false;
@@ -1427,7 +1491,24 @@ export const SettingsModelsPage: React.FC = () => {
route to either record. Frame 09 predates these tabs; it still
owns the direct-only body of `sources`. */}
<HubTabs tab={tab} onChange={setTab} />
- {tab === 'usage' ? <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
+ {tab === 'quota' ? <QuotaTab
+ quota={quotaRead}
+ refreshing={refreshingQuota}
+ onRefresh={refreshQuotaNow}
+ onRetry={retryQuota}
+ onRequestReauth={(sourceId) => {
+ const target = sources.find((source) => source.id === sourceId);
+ if (target && canReauth(target)) {
+ quotaReauthOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ setQuotaReauthSource(target);
+ return;
+ }
+ // Not a Source this page can sign in again: show it instead.
+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ selectSource({ sourceId, returnFocus: () => opener });
+ }}
+ />
+ : tab === 'usage' ? <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
: tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
: directEmpty ? <DirectHome agents={installedAgents} onSwitch={switchToGateway} />
: <div className="model-hub-overview">
@@ -1597,6 +1678,30 @@ export const SettingsModelsPage: React.FC = () => {
onConnected={subscriptionAdded}
/>
)}
+ {quotaReauthSource && (
+ <ConfirmDialog
+ open
+ onOpenChange={(open) => {
+ if (open) return;
+ setQuotaReauthSource(null);
+ const opener = quotaReauthOpenerRef.current;
+ quotaReauthOpenerRef.current = null;
+ if (opener) window.setTimeout(() => focusQuotaOpener(opener), 0);
+ }}
+ title={t('settings.models.repair.reauthTitle', { name: quotaReauthSource.display_name })}
+ description={t(reauthBodyKey(quotaReauthSource))}
+ confirmLabel={t('settings.models.repair.reauthConfirm') as string}
+ destructive={reauthCost(quotaReauthSource) === 'immediate'}
+ onConfirm={() => {
+ // The journey's only user gesture, as in the detail panel: allocate
+ // the provider tab here so the dialog's POST is not popup-blocked.
+ handOffProviderTab();
+ const target = quotaReauthSource;
+ setQuotaReauthSource(null);
+ setReauthSource(target);
+ }}
+ />
+ )}
{reauthSource && (
<OAuthConnectDialog
open
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index b3297b5c1..01f97e42f 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -208,6 +208,14 @@
--model-hub-usage-column-radius: 2px;
--model-hub-usage-note-ink: var(--model-hub-muted-b3);
+ /* Subscription quota tab. Reuses the usage tab's gutter and type scale. */
+ --model-hub-quota-bar-height: 6px;
+ --model-hub-quota-bar-radius: 4px;
+ --model-hub-quota-left-size: 17px;
+ --model-hub-quota-hint-size: 10px;
+ --model-hub-quota-row-gap: 14px;
+ --model-hub-quota-nested-indent: 12px;
+
/* Backend model catalog dialog. `--model-hub-catalog-row-gap` is read from a
* Tailwind arbitrary value in the dialog's markup, which has no selector of
* its own to declare it on. */
@@ -2199,6 +2207,172 @@
text-align: center;
}
+/* Subscription quota. A tone is one ink, read by every part of a window that
+ * speaks for it — bar, remaining figure, pace line, status pill — so a warning
+ * cannot be amber in one place and neutral in the next. */
+.model-hub-quota-tone--ok { --model-hub-quota-tone: var(--mint-ink); }
+.model-hub-quota-tone--warn { --model-hub-quota-tone: var(--gold-ink); }
+.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-stat--primary { border-color: var(--model-hub-mint-4d); }
+.model-hub-quota-stat-unit {
+ margin-left: 5px;
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-label-size);
+ font-weight: 400;
+}
+.model-hub-quota-timeline {
+ padding: 11px 14px;
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-quota-timeline-title {
+ margin-right: 6px;
+ color: var(--model-hub-ink-8c);
+ font-size: var(--model-hub-usage-label-size);
+}
+.model-hub-quota-chip {
+ padding: 4px 10px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--background);
+ color: var(--model-hub-ink-8c);
+}
+.model-hub-quota-chip b {
+ color: var(--foreground);
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+.model-hub-quota-chip.model-hub-quota-tone--danger {
+ border-color: color-mix(in srgb, var(--model-hub-quota-tone) 40%, transparent);
+}
+.model-hub-quota-chip.model-hub-quota-tone--danger b { color: var(--model-hub-quota-tone); }
+.model-hub-quota-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+.model-hub-quota-card { padding: 16px var(--model-hub-usage-padding-x) 18px; }
+.model-hub-quota-account { font-size: var(--model-hub-usage-title-size); }
+.model-hub-quota-plan {
+ padding: 1px 7px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--model-hub-ink-8c);
+ font-size: var(--model-hub-usage-note-size);
+ font-weight: 500;
+}
+.model-hub-quota-account-label {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-quota-status {
+ padding: 3px 8px;
+ border: 1px solid color-mix(in srgb, var(--model-hub-quota-tone) 30%, transparent);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--model-hub-quota-tone) 7%, transparent);
+ color: var(--model-hub-quota-tone);
+ font-size: var(--model-hub-usage-note-size);
+ white-space: nowrap;
+}
+.model-hub-quota-dot {
+ width: 6px;
+ height: 6px;
+ flex-shrink: 0;
+ border-radius: 999px;
+ background: var(--model-hub-quota-tone, currentColor);
+}
+.model-hub-quota-stale,
+.model-hub-quota-unread {
+ margin-top: 14px;
+ padding: 8px 10px;
+ border: 1px dashed var(--input);
+ border-radius: 8px;
+ color: var(--model-hub-ink-8c);
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-quota-rows {
+ gap: var(--model-hub-quota-row-gap);
+ margin-top: 18px;
+}
+.model-hub-quota-card--retained .model-hub-quota-rows { opacity: 0.55; }
+.model-hub-quota-row { min-width: 0; }
+.model-hub-quota-row--nested {
+ padding-left: var(--model-hub-quota-nested-indent);
+ border-left: 2px solid var(--border);
+}
+.model-hub-quota-row-title {
+ font-size: var(--model-hub-usage-cell-size);
+ overflow-wrap: anywhere;
+}
+.model-hub-quota-row-title small {
+ margin-left: 8px;
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-quota-hint-size);
+}
+.model-hub-quota-left b {
+ color: var(--foreground);
+ font-size: var(--model-hub-quota-left-size);
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+.model-hub-quota-left.model-hub-quota-tone--warn b,
+.model-hub-quota-left.model-hub-quota-tone--danger b { color: var(--model-hub-quota-tone); }
+.model-hub-quota-left span {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-quota-hint-size);
+}
+.model-hub-quota-bar {
+ position: relative;
+ height: var(--model-hub-quota-bar-height);
+ margin-top: 7px;
+ border-radius: var(--model-hub-quota-bar-radius);
+ background: var(--model-hub-wash-14);
+}
+.model-hub-quota-bar i {
+ position: absolute;
+ inset: 0 auto 0 0;
+ border-radius: var(--model-hub-quota-bar-radius);
+ background: color-mix(in srgb, var(--model-hub-quota-tone) 85%, transparent);
+}
+.model-hub-quota-time-mark {
+ position: absolute;
+ top: -3px;
+ bottom: -3px;
+ width: 2px;
+ margin-left: -1px;
+ border-radius: 1px;
+ background: var(--foreground);
+ opacity: 0.55;
+}
+.model-hub-quota-row-foot {
+ display: flex;
+ justify-content: space-between;
+ gap: 10px;
+ margin-top: 7px;
+ color: var(--model-hub-ink-8c);
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-quota-pace.model-hub-quota-tone--warn,
+.model-hub-quota-pace.model-hub-quota-tone--danger { color: var(--model-hub-quota-tone); }
+.model-hub-quota-reset { white-space: nowrap; }
+.model-hub-quota-reset em {
+ margin-left: 6px;
+ color: var(--model-hub-usage-note-ink);
+ font-style: normal;
+}
+.model-hub-quota-scoped {
+ margin: 2px 0 -4px;
+ color: var(--model-hub-ink-8c);
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-quota-scoped span {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-quota-hint-size);
+}
+.model-hub-quota-foot {
+ padding: 0 2px;
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-note-size);
+ line-height: 1.6;
+}
+
@media (min-width: 1024px) {
.model-hub-direct-grid {
grid-template-columns: minmax(0, 1fr) var(--model-hub-direct-benefits-width);
@@ -2216,6 +2390,11 @@
/* Stacked, each cell carries its own label, so the column gutter becomes a
* line gap and 16px of it would read as four separate rows. */
.model-hub-usage-row { grid-template-columns: minmax(0, 1fr); gap: 7px; }
+ /* One account per line; the pace and reset lines stack so neither truncates. */
+ .model-hub-quota-grid { grid-template-columns: minmax(0, 1fr); }
+ .model-hub-quota-row-foot { flex-direction: column; gap: 4px; }
+ .model-hub-quota-reset { white-space: normal; }
+ .model-hub-quota-timeline-title { width: 100%; }
}
@media (min-width: 1024px) {
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 6df889104..a4274fef1 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -41,6 +41,7 @@ import type {
SourceRepaired,
SupplyChannel,
SupplyGap,
+ QuotaSummary,
UsageSummary,
} from './types';
import { USAGE_DEFAULT_WINDOW_DAYS } from './types';
@@ -163,6 +164,10 @@ export type ModelsApi = {
* the server clamps it to retention and echoes what it served in
* `window_days`, which is the only number a view may display. */
getUsageSummary(days?: number): Promise<UsageSummary>;
+ /** Subscription rate-limit windows, served from the service's 5-minute cache. */
+ getQuota(): Promise<QuotaSummary>;
+ /** The same report, re-read now (the service bounds how often). */
+ refreshQuota(): Promise<QuotaSummary>;
getRuntimeStatus(): Promise<RuntimeDependency>;
/** Start the contract-owned client installation transaction. */
installRuntime(): Promise<RuntimeDependency>;
@@ -646,6 +651,8 @@ export const modelsApi: ModelsApi = {
).then((r) => r.events),
getUsageSummary: (days = USAGE_DEFAULT_WINDOW_DAYS) =>
call<{ usage: UsageSummary }>(`/api/models/usage?days=${days}`).then((r) => r.usage),
+ getQuota: () => call<{ quota: QuotaSummary }>('/api/models/quota').then((r) => r.quota),
+ refreshQuota: () => call<{ quota: QuotaSummary }>('/api/models/quota/refresh', jsonInit('POST')).then((r) => r.quota),
getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),
installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),
startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),
diff --git a/ui/src/components/settings/models/quotaProjection.ts b/ui/src/components/settings/models/quotaProjection.ts
new file mode 100644
index 000000000..1065763f2
--- /dev/null
+++ b/ui/src/components/settings/models/quotaProjection.ts
@@ -0,0 +1,155 @@
+// 订阅额度 — pure derivations over `quota-summary.schema.json`.
+//
+// Everything here is a function of the payload and one `now`, so the tab can be
+// drawn and tested against a fixed instant. Copy lives in the tab; this module
+// only decides which sentence applies and with which numbers.
+import type { QuotaWindow, SourceQuota } from './types';
+
+export const MINUTE_MS = 60_000;
+export const HOUR_MS = 60 * MINUTE_MS;
+export const DAY_MS = 24 * HOUR_MS;
+
+export type QuotaTone = 'ok' | 'warn' | 'danger' | 'stale';
+
+/** A duration in whole units, largest two first — the shape the copy states. */
+export type QuotaDuration =
+ | { unit: 'days'; days: number; hours: number }
+ | { unit: 'hours'; hours: number; minutes: number }
+ | { unit: 'minutes'; minutes: number };
+
+export function quotaDuration(ms: number): QuotaDuration {
+ // Whole minutes, rounded up: a countdown never claims less time than remains.
+ const total = Math.max(1, Math.ceil(ms / MINUTE_MS));
+ const days = Math.floor(total / (24 * 60));
+ const hours = Math.floor((total % (24 * 60)) / 60);
+ const minutes = total % 60;
+ if (days) return { unit: 'days', days, hours };
+ if (hours) return { unit: 'hours', hours, minutes };
+ return { unit: 'minutes', minutes };
+}
+
+const instant = (value: string | null): number | null => {
+ if (value === null) return null;
+ const ms = Date.parse(value);
+ return Number.isNaN(ms) ? null : ms;
+};
+
+export const windowResetAt = (window: QuotaWindow): number | null => instant(window.resets_at);
+
+/**
+ * A Source with a current reading, not a retained one. A report with no windows
+ * is not a reading: every summary figure and the card share this predicate.
+ */
+export const quotaIsLive = (source: SourceQuota): boolean => source.state === 'ok' && source.windows.length > 0;
+
+/** A Source whose windows are the last good reading, shown under a banner. */
+export const quotaIsRetained = (source: SourceQuota): boolean =>
+ (source.state === 'stale' || source.state === 'auth_expired') && source.fetched_at !== null && source.windows.length > 0;
+
+export const windowIsScoped = (window: QuotaWindow): boolean => window.kind === 'model_weekly';
+
+/** `true` once the window's reset instant has come; the reading predates it. */
+export function windowHasReset(window: QuotaWindow, now: number): boolean {
+ const resetAt = windowResetAt(window);
+ return resetAt !== null && resetAt <= now;
+}
+
+/**
+ * Share used as of `now`. A window past its reset has given its quota back, so
+ * it reads as unused until the next read: every figure, bar, and status derives
+ * from this one value so none can claim a reset beside a spent number.
+ */
+export const windowUsedNow = (window: QuotaWindow, now: number): number =>
+ windowHasReset(window, now) ? 0 : window.used_pct;
+
+/** `true` while the window is spent and has not yet reached its reset. */
+export const windowIsExhausted = (window: QuotaWindow, now: number): boolean => windowUsedNow(window, now) >= 100;
+
+export type QuotaPace =
+ | { kind: 'paused' }
+ | { kind: 'reset' }
+ | { kind: 'exhausted'; remainingMs: number | null }
+ | { kind: 'fast'; runsOutAt: number }
+ | { kind: 'slightly_fast' }
+ | { kind: 'ok' };
+
+export type QuotaPaceReading = { pace: QuotaPace; tone: QuotaTone; elapsedPct: number | null };
+
+/**
+ * How the window is being spent against its own clock.
+ *
+ * The thin mark on the bar is the share of the window that has elapsed; a bar
+ * past the mark is spending faster than time. "Fast" is reserved for a pace that
+ * would actually run the window out before it resets, with an 8-point margin so
+ * the first minutes of a fresh window do not flag every request.
+ */
+export function windowPace(window: QuotaWindow, now: number, retained: boolean): QuotaPaceReading {
+ const resetAt = windowResetAt(window);
+ const length = window.window_seconds !== null ? window.window_seconds * 1000 : null;
+ const remaining = resetAt !== null ? resetAt - now : null;
+ const elapsed = remaining !== null && length !== null ? Math.min(1, Math.max(0, 1 - remaining / length)) : null;
+ const elapsedPct = elapsed !== null ? Math.round(elapsed * 100) : null;
+ const used = windowUsedNow(window, now);
+ if (retained) return { pace: { kind: 'paused' }, tone: 'stale', elapsedPct };
+ if (windowHasReset(window, now)) return { pace: { kind: 'reset' }, tone: 'ok', elapsedPct };
+ if (used >= 100) return { pace: { kind: 'exhausted', remainingMs: remaining }, tone: 'danger', elapsedPct };
+ if (elapsed === null || elapsedPct === null || remaining === null || length === null) {
+ return { pace: { kind: 'ok' }, tone: 'ok', elapsedPct };
+ }
+ const rate = used / Math.max(elapsed, 0.02);
+ const toFull = rate > 0 ? ((100 - used) / rate) * length : Infinity;
+ if (used > elapsedPct + 8 && toFull < remaining) {
+ return { pace: { kind: 'fast', runsOutAt: now + toFull }, tone: 'warn', elapsedPct };
+ }
+ return { pace: { kind: used > elapsedPct ? 'slightly_fast' : 'ok' }, tone: 'ok', elapsedPct };
+}
+
+export type QuotaStatus =
+ | { kind: 'ok' }
+ | { kind: 'exhausted'; window: QuotaWindow }
+ | { kind: 'reauth' }
+ | { kind: 'paused' };
+
+export function sourceStatus(source: SourceQuota, now: number): QuotaStatus {
+ if (source.state === 'auth_expired') return { kind: 'reauth' };
+ if (!quotaIsLive(source)) return { kind: 'paused' };
+ const spent = source.windows.find((window) => windowIsExhausted(window, now));
+ return spent ? { kind: 'exhausted', window: spent } : { kind: 'ok' };
+}
+
+export type QuotaPick = { source: SourceQuota; window: QuotaWindow };
+
+const livePicks = (sources: SourceQuota[]): QuotaPick[] =>
+ sources.filter(quotaIsLive).flatMap((source) => source.windows.map((window) => ({ source, window })));
+
+/** The live window with the least left that is still usable. */
+export function tightestWindow(sources: SourceQuota[], now: number): QuotaPick | null {
+ return livePicks(sources)
+ .filter(({ window }) => windowUsedNow(window, now) < 100)
+ .sort((a, b) => windowUsedNow(b.window, now) - windowUsedNow(a.window, now))[0] ?? null;
+}
+
+/** Live windows that are spent right now, soonest recovery first. */
+export function exhaustedWindows(sources: SourceQuota[], now: number): QuotaPick[] {
+ return livePicks(sources)
+ .filter(({ window }) => windowIsExhausted(window, now))
+ .sort((a, b) => (windowResetAt(a.window) ?? Infinity) - (windowResetAt(b.window) ?? Infinity));
+}
+
+/** Live windows resetting within a week that have something to give back. */
+export function upcomingResets(sources: SourceQuota[], now: number, limit = 5): QuotaPick[] {
+ return livePicks(sources)
+ .filter(({ window }) => {
+ const resetAt = windowResetAt(window);
+ return windowUsedNow(window, now) > 0 && resetAt !== null && resetAt - now < 7 * DAY_MS;
+ })
+ .sort((a, b) => (windowResetAt(a.window) ?? 0) - (windowResetAt(b.window) ?? 0))
+ .slice(0, limit);
+}
+
+/** Whole percent left as of `now`, never negative; any headroom rounds up so it never reads as 0% left. */
+export const windowLeftPct = (window: QuotaWindow, now: number): number =>
+ Math.max(0, Math.ceil(100 - windowUsedNow(window, now)));
+
+/** 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);
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index e143c3ab1..440f82d65 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -824,6 +824,42 @@ export const USAGE_WINDOW_MIN_DAYS = 1 as const;
export const USAGE_WINDOW_MAX_DAYS = 62 as const;
export const USAGE_DEFAULT_WINDOW_DAYS = 30 as const;
+/** `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. */
+export type QuotaWindowKind = 'session' | 'weekly' | 'model_weekly' | 'other';
+
+export type QuotaWindow = {
+ id: string;
+ kind: QuotaWindowKind;
+ /** The upstream name. Views compose their own copy for `session`/`weekly`. */
+ label: string;
+ /** Present on `model_weekly`: the model the window alone counts. */
+ scope_model?: string;
+ used_pct: number;
+ window_seconds: number | null;
+ resets_at: string | null;
+};
+
+export type QuotaSourceState = 'ok' | 'stale' | 'auth_expired' | 'unsupported' | 'error';
+
+export type SourceQuota = {
+ source_id: string;
+ vendor: string;
+ display_name: string;
+ account_label: string | null;
+ plan: string | null;
+ fetched_at: string | null;
+ state: QuotaSourceState;
+ error_key?: string;
+ windows: QuotaWindow[];
+};
+
+export type QuotaSummary = {
+ refresh_interval_seconds: number;
+ sources: SourceQuota[];
+};
+
// ── API envelope + request shapes (api.md) ──────────────────────────────
export type ApiOk<T> = { ok: true; contract_version: typeof CONTRACT_VERSION } & T;
export type ApiErr = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 00956bdfd..3eb115e3c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -896,6 +896,7 @@
},
"tab": {
"hub": "Sources & gateway",
+ "quota": "Subscription quota",
"usage": "Usage",
"logs": "Logs"
}
@@ -1329,6 +1330,86 @@
"needs_action": "Needs attention",
"error": "Needs attention"
},
+ "quota": {
+ "title": "Subscription quota",
+ "header_one": "{{count}} signed-in subscription account",
+ "header_other": "{{count}} signed-in subscription accounts",
+ "autoRefresh": "Refreshes every 5 minutes",
+ "refresh": "Refresh now",
+ "refreshing": "Refreshing…",
+ "empty": "No signed-in subscription accounts yet. Add a Claude or ChatGPT subscription under Sources & gateway to see its quota here.",
+ "left": "left",
+ "window": {
+ "session": "5-hour limit",
+ "weekly": "Weekly limit",
+ "model": "{{model}} weekly limit"
+ },
+ "hint": {
+ "shared": "Shared by all models",
+ "model": "Counts {{model}} only"
+ },
+ "scoped": {
+ "title": "Per-model limits",
+ "note": "These models also count toward the weekly limit; whichever runs out first pauses use"
+ },
+ "pace": {
+ "ok": "Lasts until reset",
+ "slightlyFast": "A little fast, still lasts until reset",
+ "fast": "Running fast, expected to run out {{time}}",
+ "exhausted": "Used up, back in {{duration}}",
+ "exhaustedUnknown": "Used up",
+ "paused": "Updates paused",
+ "reset": "Reset"
+ },
+ "reset": {
+ "in": "Resets in {{duration}}",
+ "done": "Reset, waiting for refresh"
+ },
+ "meter": "{{label}}: {{pct}}% used",
+ "status": {
+ "ok": "Available",
+ "exhausted": "{{label}} used up",
+ "reauth": "Sign in again",
+ "paused": "Updates paused"
+ },
+ "stale": {
+ "authExpired": "Sign-in expired; showing data from {{ago}}",
+ "retained": "Can't read the latest quota; showing data from {{ago}}",
+ "reauth": "Sign in again"
+ },
+ "unread": {
+ "auth_expired": "Sign-in expired; quota unavailable",
+ "unsupported": "This subscription doesn't report quota",
+ "error": "Quota unavailable right now; retrying automatically"
+ },
+ "ago": {
+ "minutes_one": "{{count}} minute ago",
+ "minutes_other": "{{count}} minutes ago",
+ "long": "{{duration}} ago"
+ },
+ "duration": {
+ "days": "{{days}}d {{hours}}h",
+ "hours": "{{hours}}h {{minutes}}m",
+ "minutes": "{{minutes}}m"
+ },
+ "clock": {
+ "today": "today {{time}}",
+ "tomorrow": "tomorrow {{time}}"
+ },
+ "stat": {
+ "tightest": "Lowest remaining limit",
+ "tightestAllSpent": "Every limit is used up",
+ "tightestUnread": "No current reading yet",
+ "exhausted": "Used up",
+ "exhaustedUnit": "limits",
+ "exhaustedNone": "Every account is usable",
+ "exhaustedNoneObserved": "None used up in current readings",
+ "exhaustedNote": "{{name}} · back {{time}}",
+ "resetsIn": "resets in {{duration}}"
+ },
+ "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."
+ },
"usage": {
"title": "Usage",
"detail": "Metered tokens from the turns the gateway proxied, by local day.",
@@ -2123,6 +2204,15 @@
"error": {
"unclassified": "Unknown error — temporarily unavailable"
}
+ },
+ "quota": {
+ "error": {
+ "auth_expired": "Sign-in expired",
+ "rate_limited": "The provider is limiting quota reads",
+ "unsupported": "This subscription doesn't report quota",
+ "unavailable": "Quota unavailable right now",
+ "malformed": "The provider returned an unreadable quota report"
+ }
}
},
"accessBlocked": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 20df5dffa..791a1e58c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -896,6 +896,7 @@
},
"tab": {
"hub": "供应商与路由",
+ "quota": "订阅额度",
"usage": "用量",
"logs": "日志"
}
@@ -1329,6 +1330,86 @@
"needs_action": "需要处理",
"error": "需要处理"
},
+ "quota": {
+ "title": "订阅额度",
+ "header_one": "{{count}} 个已登录的订阅账号",
+ "header_other": "{{count}} 个已登录的订阅账号",
+ "autoRefresh": "每 5 分钟自动刷新",
+ "refresh": "立即刷新",
+ "refreshing": "刷新中…",
+ "empty": "还没有已登录的订阅账号。在「供应商与路由」里添加 Claude 或 ChatGPT 订阅后,这里会显示它们的额度。",
+ "left": "剩余",
+ "window": {
+ "session": "5 小时额度",
+ "weekly": "每周额度",
+ "model": "{{model}} 每周额度"
+ },
+ "hint": {
+ "shared": "所有模型共用",
+ "model": "只算 {{model}} 的用量"
+ },
+ "scoped": {
+ "title": "单独计算的模型额度",
+ "note": "这些模型也会同时扣每周额度,任一项用完就会暂停"
+ },
+ "pace": {
+ "ok": "够用到重置",
+ "slightlyFast": "稍快,仍够用到重置",
+ "fast": "用得偏快,预计 {{time}} 用完",
+ "exhausted": "已用完,{{duration}}后恢复",
+ "exhaustedUnknown": "已用完",
+ "paused": "暂停更新",
+ "reset": "已重置"
+ },
+ "reset": {
+ "in": "{{duration}}后重置",
+ "done": "已重置,等待刷新"
+ },
+ "meter": "{{label}} 已用 {{pct}}%",
+ "status": {
+ "ok": "可用",
+ "exhausted": "{{label}}已用完",
+ "reauth": "需重新登录",
+ "paused": "暂停更新"
+ },
+ "stale": {
+ "authExpired": "登录已过期,下面是 {{ago}}的数据",
+ "retained": "暂时读不到最新额度,下面是 {{ago}}的数据",
+ "reauth": "重新登录"
+ },
+ "unread": {
+ "auth_expired": "登录已过期,读不到额度",
+ "unsupported": "这个订阅不提供额度数据",
+ "error": "暂时读不到额度,稍后会自动重试"
+ },
+ "ago": {
+ "minutes_one": "{{count}} 分钟前",
+ "minutes_other": "{{count}} 分钟前",
+ "long": "{{duration}}前"
+ },
+ "duration": {
+ "days": "{{days}} 天 {{hours}} 小时",
+ "hours": "{{hours}} 小时 {{minutes}} 分",
+ "minutes": "{{minutes}} 分钟"
+ },
+ "clock": {
+ "today": "今天 {{time}}",
+ "tomorrow": "明天 {{time}}"
+ },
+ "stat": {
+ "tightest": "余量最少的额度",
+ "tightestAllSpent": "所有额度都已用完",
+ "tightestUnread": "暂时没有可读的额度",
+ "exhausted": "已用完",
+ "exhaustedUnit": "项额度",
+ "exhaustedNone": "所有账号都能正常使用",
+ "exhaustedNoneObserved": "已读到的额度都没用完",
+ "exhaustedNote": "{{name}} · {{time}} 恢复",
+ "resetsIn": "{{duration}}后重置"
+ },
+ "upcoming": "即将重置",
+ "footnote": "进度条是已用的部分,细竖线是这个周期已经过去的时间:进度条超过竖线,就是用得比时间快。"
+ },
"usage": {
"title": "用量",
"detail": "模型网关代理的对话所计量的 token,按本地日期汇总。",
@@ -2123,6 +2204,15 @@
"error": {
"unclassified": "未知错误,暂时不可用"
}
+ },
+ "quota": {
+ "error": {
+ "auth_expired": "登录已过期",
+ "rate_limited": "服务商暂时限制了额度查询",
+ "unsupported": "这个订阅不提供额度数据",
+ "unavailable": "暂时读不到额度",
+ "malformed": "服务商返回的额度数据读不懂"
+ }
}
},
"accessBlocked": {
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 0c8f756b9..274cb105e 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -547,6 +547,8 @@ _MEMBER_HTTP_RULES = tuple(
("POST", r"^/api/models/agents/[^/]+/probe$"),
("GET", r"^/api/models/agents/[^/]+/provenance$"),
("GET", r"^/api/models/(?:events|usage)$"),
+ ("GET", r"^/api/models/quota$"),
+ ("POST", r"^/api/models/quota/refresh$"),
("POST", r"^/api/models/oauth/(?:start|submit|cancel)$"),
("GET", r"^/api/models/oauth/status/[^/]+$"),
("POST", r"^/api/models/migration/(?:scan|apply)$"),
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index fe168a0bf..51d5aaa85 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -279,6 +279,9 @@ class ModelHubRemoteService:
# worker for as long as the disk takes. See `usage.BoundedUsageLedger`.
return await _rpc("usage_summary", {"days": days})
+ async def quota_summary(self, *, force: bool = False) -> dict:
+ return await _rpc("quota_summary", {"force": force})
+
def agent_chain(self, backend: str, model_id: str) -> dict:
return _rpc_sync(
"get_agent_chain",
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 283ad4c8b..3045bdcf4 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -1,8 +1,10 @@
from __future__ import annotations
import asyncio
+import email.utils
import json
import logging
+import math
import re
import secrets
import threading
@@ -37,6 +39,11 @@ 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 (
+ QUOTA_FETCH_TIMEOUT_SECONDS,
+ SubscriptionQuotaError,
+ parse_subscription_quota,
+)
from core.handlers.model_hub.async_owner import run_owned_in_thread
from vibe.model_hub_runtime.client import (
_OFFICIAL_BASE_URLS,
@@ -1146,18 +1153,8 @@ def _parse_oauth_control_plane_witness(
return False
-def _probe_oauth_control_plane_witness(
- *,
- client: EngineClient,
- auth: _AuthRecord,
- vendor: str,
-) -> None:
- """Use CPA's current auth record for a bodyless control-plane GET."""
-
- normalized_vendor = vendor.strip().lower()
- url = _OAUTH_CONTROL_PLANE_URLS.get(normalized_vendor)
- if url is None:
- raise EngineClientError("unsupported OAuth control-plane witness")
+def _oauth_account_call_headers(auth: _AuthRecord, normalized_vendor: str) -> dict[str, str]:
+ """Headers for a model-free account GET; CPA substitutes ``$TOKEN$``."""
headers = {
"Accept": "application/json",
@@ -1175,7 +1172,52 @@ def _probe_oauth_control_plane_witness(
headers["User-Agent"] = "codex-cli"
if auth.account_id:
headers["ChatGPT-Account-ID"] = auth.account_id
+ return headers
+
+
+# The vendors' own quota reports: the same endpoints their CLIs read for
+# `/usage` and `/status`. Anthropic gates its report behind the OAuth beta.
+_SUBSCRIPTION_QUOTA_URLS = {
+ "anthropic": "https://api.anthropic.com/api/oauth/usage",
+ "openai": "https://chatgpt.com/backend-api/wham/usage",
+ "codex": "https://chatgpt.com/backend-api/wham/usage",
+}
+
+def _retry_after_seconds(headers: object) -> float | None:
+ if not isinstance(headers, dict):
+ return None
+ for key, value in headers.items():
+ if not isinstance(key, str) or key.lower() != "retry-after":
+ continue
+ raw = str(value[0] if isinstance(value, list) and value else value).strip()
+ try:
+ seconds = float(raw)
+ except ValueError:
+ # RFC 9110 also allows an HTTP-date.
+ try:
+ moment = email.utils.parsedate_to_datetime(raw)
+ except (TypeError, ValueError, IndexError):
+ return None
+ if moment.tzinfo is None:
+ moment = moment.replace(tzinfo=timezone.utc)
+ seconds = (moment - datetime.now(timezone.utc)).total_seconds()
+ return seconds if math.isfinite(seconds) and seconds > 0 else None
+ return None
+
+
+def _fetch_subscription_quota(
+ *,
+ client: EngineClient,
+ auth: _AuthRecord,
+ vendor: str,
+) -> dict[str, Any]:
+ """Read one grant's quota report and keep only the parsed windows."""
+
+ url = _SUBSCRIPTION_QUOTA_URLS[vendor]
+ headers = _oauth_account_call_headers(auth, vendor)
+ if vendor == "anthropic":
+ headers["anthropic-beta"] = "oauth-2025-04-20"
payload = client.management_request(
"POST",
"/api-call",
@@ -1185,6 +1227,43 @@ def _probe_oauth_control_plane_witness(
"url": url,
"header": headers,
},
+ timeout=QUOTA_FETCH_TIMEOUT_SECONDS,
+ )
+ status = payload.get("status_code")
+ if status in {401, 403}:
+ raise SubscriptionQuotaError("auth_expired")
+ if status == 429:
+ raise SubscriptionQuotaError(
+ "rate_limited",
+ retry_after_seconds=_retry_after_seconds(payload.get("header")),
+ )
+ 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"))
+
+
+def _probe_oauth_control_plane_witness(
+ *,
+ client: EngineClient,
+ auth: _AuthRecord,
+ vendor: str,
+) -> None:
+ """Use CPA's current auth record for a bodyless control-plane GET."""
+
+ normalized_vendor = vendor.strip().lower()
+ url = _OAUTH_CONTROL_PLANE_URLS.get(normalized_vendor)
+ if url is None:
+ raise EngineClientError("unsupported OAuth control-plane witness")
+
+ payload = client.management_request(
+ "POST",
+ "/api-call",
+ payload={
+ "auth_index": auth.auth_index,
+ "method": "GET",
+ "url": url,
+ "header": _oauth_account_call_headers(auth, normalized_vendor),
+ },
)
if not _parse_oauth_control_plane_witness(
normalized_vendor,
@@ -2521,6 +2600,52 @@ class CLIProxyEngineAdapter:
credential_ref, source_id=source_id, vendor=vendor, auth_provider=endpoint[2],
)
+ async def subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> dict[str, Any]:
+ """Read the bound grant's rate-limit windows without starting the engine."""
+
+ normalized_vendor = vendor.strip().lower()
+ endpoint = _OAUTH_ENDPOINTS.get(normalized_vendor)
+ if endpoint is None or normalized_vendor not in _SUBSCRIPTION_QUOTA_URLS:
+ raise SubscriptionQuotaError("unsupported")
+ try:
+ metadata = await asyncio.to_thread(self.state_store.credential_metadata, credential_ref)
+ except (EngineStateError, OSError, ValueError):
+ raise SubscriptionQuotaError("unavailable") from None
+ if (
+ metadata.get("kind") != "oauth"
+ or metadata.get("source_id") not in {None, source_id}
+ or str(metadata.get("vendor") or "").strip().lower() != normalized_vendor
+ or metadata.get("activation_state") not in {None, "active"}
+ ):
+ raise SubscriptionQuotaError("unavailable")
+ # A presentation read never starts, repairs, or restarts the engine.
+ client = await asyncio.to_thread(self.supervisor.client_if_running)
+ if client is None:
+ raise SubscriptionQuotaError("unavailable")
+ try:
+ inventory = await run_owned_in_thread(_auth_inventory, client)
+ except (EngineClientError, OSError):
+ raise SubscriptionQuotaError("unavailable") from None
+ auth_name = str(metadata.get("auth_name") or "")
+ matches = [
+ auth
+ for auth in inventory.values()
+ if (auth.name == auth_name or auth.identity == auth_name)
+ and auth.provider == endpoint[2]
+ and auth.auth_index
+ ]
+ if len(matches) != 1:
+ raise SubscriptionQuotaError("unavailable")
+ try:
+ return await run_owned_in_thread(
+ _fetch_subscription_quota,
+ client=client,
+ auth=matches[0],
+ vendor=normalized_vendor,
+ )
+ except (EngineClientError, OSError):
+ raise SubscriptionQuotaError("unavailable") from None
+
async def oauth_status(self, flow_id: str) -> OAuthFlowState:
flow = self._get_flow(flow_id)
async with flow.operation_lock:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d5643fd75..fab5f3b70 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4940,6 +4940,35 @@ async def model_hub_usage_get(starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/models/quota", include_in_schema=False)
+async def model_hub_quota_get(starlette_request: FastAPIRequest):
+ # Native and awaited: a read may wait (bounded) on vendor quota calls.
+ async def handler():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ quota = await _model_hub_service().quota_summary()
+ return _model_hub_success(quota=quota)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/models/quota/refresh", include_in_schema=False)
+async def model_hub_quota_refresh(starlette_request: FastAPIRequest):
+ async def handler():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ quota = await _model_hub_service().quota_summary(force=True)
+ return _model_hub_success(quota=quota)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.route("/api/models/agents/<backend>/chains", methods=["GET"])
def model_hub_agent_chains_get(backend):
from core.handlers.model_hub import ModelHubError