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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(models): add usage analytics (#2167)
Call Whitec7829d5ff728
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 34cd64de2..e8a298f14 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -199,9 +199,16 @@ async def dispatch_model_hub_rpc(# Reads the ledger file and the config store, and takes the same lock a# concurrent `record()` holds across `fsync()`. On the controller loop# that is every turn on this machine waiting on one settings page.+ usage_kwargs = {}+ if "days" in payload:+ usage_kwargs["days"] = payload["days"]+ if "window" in payload:+ usage_kwargs["window"] = payload["window"]+ if not usage_kwargs:+ usage_kwargs["days"] = USAGE_DEFAULT_WINDOW_DAYSreturn await asyncio.to_thread(service.usage_summary,- days=payload.get("days", USAGE_DEFAULT_WINDOW_DAYS),+ **usage_kwargs,)if operation == "quota_summary":return await service.quota_summary(force=payload.get("force") is True)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex be24601ae..ebaa00470 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -145,7 +145,13 @@ from .resolver import ()from .revocations import CredentialRevocationJournalfrom .retry import RECOVERY_EXHAUSTED_CODE, RecoveryPolicy, RecoveryRequest, RETRY_DELAYS, source_identity-from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter+from .usage import (+ USAGE_DEFAULT_WINDOW_DAYS,+ USAGE_WINDOW_KEYS,+ BoundedUsageLedger,+ SourceIdentity,+ UsageWriter,+)CONTRACT_VERSION = 10@@ -5444,7 +5450,12 @@ class ModelHubService:"interrupted": would_interrupt,}- def usage_summary(self, *, days: int = USAGE_DEFAULT_WINDOW_DAYS) -> dict:+ def usage_summary(+ self,+ *,+ days: Optional[int] = None,+ window: Optional[str] = None,+ ) -> dict:"""Report metered token usage, labelled from current Source config.Config is what this method owns: which identities exist right now and what@@ -5460,18 +5471,27 @@ class ModelHubService:Source an ID came from, and answers for one Source with another's models."""+ if window is not None and days is not None:+ raise ModelHubError("invalid_parameter", status=400)+ if window is not None and window not in USAGE_WINDOW_KEYS:+ raise ModelHubError("invalid_parameter", status=400)+config = self.store.load()+ identities = [+ SourceIdentity(+ source_id=source.id,+ label=source.display_name,+ model_ids=[model.id for model in source.models],+ )+ for source in config.sources+ ]+ now = self.now()+ if window is not None:+ return self.usage.report(window=window, now=now, identities=identities)return self.usage.summary(- days=days,- now=self.now(),- identities=[- SourceIdentity(- source_id=source.id,- label=source.display_name,- model_ids=[model.id for model in source.models],- )- for source in config.sources- ],+ days=USAGE_DEFAULT_WINDOW_DAYS if days is None else days,+ now=now,+ identities=identities,)async def _fetch_subscription_quota(self, source_id: str, vendor: str, credential_ref: str) -> Mapping[str, Any]:diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.pyindex 4732bdb54..ac4b1988a 100644--- a/core/handlers/model_hub/usage.py+++ b/core/handlers/model_hub/usage.py@@ -35,7 +35,7 @@ import threadingfrom concurrent.futures import Executorfrom concurrent.futures import Future as CFuturefrom dataclasses import dataclass, replace-from datetime import date, datetime, timedelta, timezone+from datetime import date, datetime, time, timedelta, timezonefrom pathlib import Pathfrom typing import Callable, Final, Mapping, Optional, Sequence@@ -50,6 +50,8 @@ logger = logging.getLogger(__name__)USAGE_RETENTION_DAYS: Final = 62USAGE_MAX_ROWS: Final = 400USAGE_DEFAULT_WINDOW_DAYS: Final = 30+USAGE_HOURLY_RETENTION_HOURS: Final = 24+USAGE_WINDOW_KEYS: Final = ("24h", "7d", "30d", "60d")# The largest integer the settings page holds exactly. Nothing on this side of the# wire needs it: `json.loads` reads a counter of any size into an exact `int`, and# so do the rpc and client hops. The doubles appear one boundary later, in the@@ -99,6 +101,11 @@ USAGE_PUBLISHED_COUNT_BOUND: Final = USAGE_MAX_ROWS * USAGE_COUNTER_CEILING# cannot be read — it recorded no instant, or recorded one that has not happened —# sorts as the least recently metered._OLDEST_INSTANT: Final = datetime.min.replace(tzinfo=timezone.utc)+# A persisted owner day has no timezone of its own. Every IANA timezone currently+# in use fits inside UTC-12..UTC+14, so this is the smallest conservative envelope+# that can contain one whole local day without consulting today's host timezone.+_OWNER_DAY_MAX_AHEAD: Final = timedelta(hours=14)+_OWNER_DAY_MAX_BEHIND: Final = timedelta(hours=12)_COUNTER_KEYS: Final = ("requests",@@ -272,6 +279,300 @@ def _timestamp(value: object) -> Optional[str]:return parsed.isoformat()+def _local(moment: datetime) -> datetime:+ """Return one carried instant in the server's local timezone."""++ return _aware(moment).astimezone()+++def _local_midnight(day: date) -> datetime:+ """Construct a server-local midnight for a calendar date."""++ # Start naive so the OS applies the offset and DST rule for this date,+ # rather than borrowing today's offset for a historical calendar day.+ return datetime.combine(day, time.min).astimezone()+++def _utc_owner_day_envelope(day: date) -> Optional[tuple[datetime, datetime]]:+ """Return the conservative UTC interval a timezone-less owner day can occupy."""++ try:+ start = (+ datetime.combine(day, time.min).replace(tzinfo=timezone.utc)+ - _OWNER_DAY_MAX_AHEAD+ )+ end = (+ datetime.combine(day + timedelta(days=1), time.min).replace(+ tzinfo=timezone.utc,+ )+ + _OWNER_DAY_MAX_BEHIND+ )+ except (OverflowError, OSError, ValueError):+ return None+ return start, end+++def _local_owner_day_window(day: date) -> Optional[tuple[datetime, datetime]]:+ """Return the current-zone interval for an owner day with a usable instant."""++ try:+ return (+ _local_midnight(day).astimezone(timezone.utc),+ _local_midnight(day + timedelta(days=1)).astimezone(timezone.utc),+ )+ except (OverflowError, OSError, ValueError):+ return None+++def _intervals_overlap(+ first_start: datetime,+ first_end: datetime,+ second_start: datetime,+ second_end: datetime,+) -> bool:+ """Whether two half-open instant intervals overlap."""++ return first_start < second_end and first_end > second_start+++def _has_unresolved_hourly_mass(row: dict) -> bool:+ """Whether daily counters still contain usage no hourly field can locate."""++ hours = row.get("hours")+ expired = row.get("hourly_expired_totals")+ if not isinstance(hours, list):+ return True+ if expired is None:+ expired = _empty_totals()+ elif not isinstance(expired, dict):+ return True+ known = _empty_totals()+ for item in hours:+ if not isinstance(item, dict):+ return True+ _accumulate(known, item)+ _accumulate(known, expired)+ return any(known[key] != row[key] for key in _COUNTER_KEYS)+++def _hourly_owner_day_window(+ row: dict,+) -> Optional[tuple[datetime, datetime]]:+ """Return the window that bounds any hourly uncertainty in a row.++ A timestamp-less daily-only row has no trustworthy hour, so its owner date+ uses the timezone-independent envelope. A merged row with an hour list can+ also contain older residual mass that the later exact timestamp cannot+ locate; that residual uses the same envelope. A timestamp on a daily-only+ legacy row keeps the existing local-day compatibility semantics.+ Fully reconciled rows keep the local-day window for future or otherwise+ incomplete slice validation.+ """++ day = row.get("day")+ if not isinstance(day, str):+ return None+ calendar_day = _calendar_day(day)+ if calendar_day is None:+ return None+ unresolved = _has_unresolved_hourly_mass(row)+ if unresolved and (+ isinstance(row.get("hours"), list)+ or _instant(row.get("last_metered_at")) is None+ ):+ envelope = _utc_owner_day_envelope(calendar_day)+ if envelope is not None:+ return envelope+ return _local_owner_day_window(calendar_day)+++def _hourly_uncertainty_was_dropped(+ rows: Sequence[dict],+ held: Sequence[dict],+ start: datetime,+ end: datetime,+) -> bool:+ """Whether capacity removed unresolved mass that overlaps the hourly view."""++ held_keys = {_row_key(row) for row in held}+ for row in rows:+ if _row_key(row) in held_keys or not _has_unresolved_hourly_mass(row):+ continue+ owner_day_window = _hourly_owner_day_window(row)+ if owner_day_window is not None and _intervals_overlap(+ start,+ end,+ *owner_day_window,+ ):+ return True+ return False+++def _overlaps_local_day(start: datetime, end: datetime, day: date) -> bool:+ """Whether an instant interval intersects a local calendar day.++ A UTC hour can straddle local midnight in a fractional-offset zone. Its+ contributions then belong to two daily owners, not just the start's date.+ Unrepresentable persisted dates are invalid evidence, never a read failure.+ """++ window = _local_owner_day_window(day)+ return (+ window is not None+ and start < end+ and _intervals_overlap(start, end, *window)+ )+++def _hour_start(moment: datetime) -> datetime:+ """Return the UTC boundary of the actual hour containing ``moment``."""++ return _aware(moment).astimezone(timezone.utc).replace(+ minute=0,+ second=0,+ microsecond=0,+ )+++def _hour_key(moment: datetime) -> str:+ """Spell one hourly bucket with its canonical UTC boundary."""++ return _hour_start(moment).isoformat(timespec="seconds")+++def _hour_key_parts(value: object, *, day: Optional[date] = None) -> Optional[tuple[str, datetime]]:+ """Parse and normalize a persisted hourly key to its UTC boundary."""++ if not isinstance(value, str) or not value.strip() or _calendar_day(value.strip()) is not None:+ return None+ try:+ parsed = datetime.fromisoformat(value.strip())+ except ValueError:+ return None+ try:+ if parsed.tzinfo is None or parsed.utcoffset() is None:+ return None+ except (OverflowError, OSError, ValueError):+ return None+ carried = _carried(parsed)+ if carried is None:+ return None+ if carried.minute or carried.second or carried.microsecond:+ return None+ if day is not None:+ try:+ end = carried + timedelta(hours=1)+ except OverflowError:+ return None+ if not _overlaps_local_day(carried, end, day):+ return None+ return carried.isoformat(timespec="seconds"), carried+++def _hour_starts(now: datetime) -> tuple[datetime, ...]:+ """Return the 24 actual consecutive UTC-hour starts ending at ``now``."""++ current = _hour_start(now)+ return tuple(+ current - timedelta(hours=offset)+ for offset in range(USAGE_HOURLY_RETENTION_HOURS - 1, -1, -1)+ )+++def _merge_hour_slices(target: dict, incoming: dict) -> None:+ """Merge optional hourly slices without changing the daily aggregate."""++ target_hours = target.get("hours")+ incoming_hours = incoming.get("hours")+ target_complete = target.get("hourly_history_complete") is True+ incoming_complete = incoming.get("hourly_history_complete") is True++ if target_hours is None:+ target["hours"] = None if incoming_hours is None else [dict(item) for item in incoming_hours]+ elif incoming_hours is not None:+ by_key = {item["key"]: item for item in target_hours}+ for item in incoming_hours:+ existing = by_key.get(item["key"])+ if existing is None:+ by_key[item["key"]] = dict(item)+ continue+ _accumulate(existing, item)+ existing["last_metered_at"] = _newer_timestamp(+ existing.get("last_metered_at"),+ item.get("last_metered_at"),+ )+ target["hours"] = sorted(by_key.values(), key=lambda item: item["key"])++ target_expired = target.get("hourly_expired_totals")+ incoming_expired = incoming.get("hourly_expired_totals")+ # A zero aggregate has no expiry interval. Every nonzero contributor must+ # supply its boundary; merging cannot repair an older undated aggregate.+ expiry_bounds = [+ _instant(row.get("hourly_expired_before"))+ for row in (target, incoming)+ if any((row.get("hourly_expired_totals") or {}).values())+ ]+ target["hourly_expired_before"] = (+ max(expiry_bounds).isoformat()+ if expiry_bounds and all(bound is not None for bound in expiry_bounds)+ else None+ )+ if target_expired is None or incoming_expired is None:+ target["hourly_expired_totals"] = None+ else:+ expired = dict(target_expired)+ _accumulate(expired, incoming_expired)+ target["hourly_expired_totals"] = expired+ target["hourly_history_complete"] = target_complete and incoming_complete+++def _normalize_hour_slice(item: object) -> Optional[dict]:+ """Normalize one nested hourly slice, or drop it as corrupt."""++ if not isinstance(item, dict):+ return None+ # The UTC key is durable evidence. Re-checking it against the row's local+ # calendar day would reinterpret old data after the host timezone changes and+ # discard a slice that still belongs in the 24-hour projection.+ parts = _hour_key_parts(item.get("key"))+ if parts is None:+ return None+ key, _start = parts+ counters = _normalize_hourly_totals(item)+ if counters is None:+ return None+ return {+ "key": key,+ **counters,+ "last_metered_at": _timestamp(item.get("last_metered_at")),+ }+++def _normalize_hourly_totals(value: object) -> Optional[dict]:+ """Read strict counters for either a retained slice or pruned history."""++ if not isinstance(value, dict):+ return None+ totals: dict[str, int] = {}+ for key in _COUNTER_KEYS:+ counter = value.get(key)+ if not isinstance(counter, int) or isinstance(counter, bool) or counter < 0:+ return None+ if counter > USAGE_COUNTER_CEILING:+ return None+ totals[key] = counter+ for subset, superset in _COUNTER_SUBSETS:+ if totals[subset] > totals[superset]:+ return None+ if totals["token_reports"] == 0 and any(+ totals[key] for key in ("input_tokens", "cached_input_tokens", "output_tokens")+ ):+ # Token magnitudes require a report, which in turn requires a request.+ # Reject impossible hourly evidence without altering released daily totals.+ return None+ return totals++def _normalize_row(row: object) -> Optional[dict]:"""Project one persisted row onto the current shape, or drop it.@@ -306,9 +607,77 @@ def _normalize_row(row: object) -> Optional[dict]:"model_id": model_id,**counters,}+ if row.get("history_degraded") is True:+ # Internal witness that an earlier read lost evidence. It never crosses+ # the public usage-summary boundary.+ normalized["history_degraded"] = Truefor subset, superset in _COUNTER_SUBSETS:normalized[subset] = min(normalized[subset], normalized[superset])normalized["last_metered_at"] = _timestamp(row.get("last_metered_at"))+ raw_hours = row.get("hours")+ if isinstance(raw_hours, list):+ # An empty list with the producer's complete flag can be ordinary+ # retention expiry: the daily owner outlives its 24-hour slices.+ by_key: dict[str, dict] = {}+ invalid_hour = False+ duplicate_hour = False+ over_capacity = False+ for item in raw_hours:+ normalized_hour = _normalize_hour_slice(item)+ if normalized_hour is None:+ invalid_hour = True+ continue+ key = normalized_hour["key"]+ if key in by_key:+ # A duplicate key is ambiguous persisted evidence. Discard the+ # nested history immediately so an unbounded duplicate list+ # cannot consume memory or be counted repeatedly.+ duplicate_hour = True+ invalid_hour = True+ break+ by_key[key] = normalized_hour+ if len(by_key) > USAGE_HOURLY_RETENTION_HOURS:+ # A corrupt file can contain arbitrarily many unique slices.+ # Once the explicit capacity is exceeded, no temporal subset is+ # authoritative enough to repair, so stop retaining them.+ over_capacity = True+ invalid_hour = True+ break+ if duplicate_hour or over_capacity:+ hours = []+ else:+ hours = list(by_key.values())+ nested_totals = _empty_totals()+ for item in hours:+ _accumulate(nested_totals, item)+ if any(nested_totals[key] > counters[key] for key in _COUNTER_KEYS):+ # The daily row is the authoritative released aggregate. A nested+ # corruption that exceeds it cannot be repaired by clamping one+ # arbitrary hour, so discard all hourly slices and report the+ # temporal history as unavailable.+ hours = []+ invalid_hour = True+ normalized["hours"] = sorted(hours, key=lambda item: item["key"])+ normalized["hourly_history_complete"] = (+ row.get("hourly_history_complete") is True and not invalid_hour+ )+ normalized["hourly_expired_totals"] = _normalize_hourly_totals(+ row.get("hourly_expired_totals")+ )+ expiry = _hour_key_parts(row.get("hourly_expired_before"))+ normalized["hourly_expired_before"] = expiry[0] if expiry else None+ if (+ row.get("hourly_expired_totals") is not None+ and normalized["hourly_expired_totals"] is None+ ):+ normalized["hourly_history_complete"] = False+ else:+ # Released files have no hourly field. Their daily totals remain valid,+ # but no hour may be invented from the daily row's last timestamp.+ normalized["hours"] = None+ normalized["hourly_history_complete"] = False+ normalized["hourly_expired_totals"] = None+ normalized["hourly_expired_before"] = Nonereturn normalized@@ -333,6 +702,12 @@ class SourceIdentity:model_ids: Sequence[str] = ()+@dataclass(frozen=True)+class _LedgerRead:+ rows: list[dict]+ degraded: bool++def _keyed_identities(identities: Optional[Sequence[SourceIdentity]],) -> tuple[dict[str, Optional[str]], dict[tuple[str, str], str]]:@@ -363,7 +738,9 @@ def _keyed_identities(return sources, models-def _recency(row: dict, ceiling: datetime) -> tuple[str, datetime]:+def _recency(+ row: dict, ceiling: datetime, *, utc_owner_days: bool = False,+) -> tuple[str, datetime]:"""Order rows oldest-metered first, so the bound evicts what costs least.Ordering by key instead would evict by spelling: an early-sorting model would@@ -387,15 +764,31 @@ def _recency(row: dict, ceiling: datetime) -> tuple[str, datetime]:recurring: `_retained` keeps a future instant out of the file, and each timethat was the only place it happened, the report path ordered by the raw value.- The day is a different question and is deliberately not answered here. A row- dated after today reports nothing to anybody, so it does not belong in the set- at all; ranking it as though it were today's would still let it evict a real- row. Membership is each caller's own filter — a retention window on the way in,- the requested window on the way out — and the one caller that had neither is the- defect this ordering keeps being handed.+ Daily reports retain the existing owner-day ordering. Write retention and+ hourly reads also admit old-zone owners through UTC evidence, so their recency+ calendar label must follow that evidence in the current zone. An owner with+ neither a usable instant nor a usable hourly key is admitted by its+ plausibility envelope but ranks below every known instant, so uncertainty+ cannot evict a newer call. This changes eviction only, never persisted daily+ ownership."""metered = _instant(row["last_metered_at"])+ if utc_owner_days:+ evidence = [metered] if metered is not None and metered <= ceiling else []+ for item in row.get("hours") or ():+ parts = _hour_key_parts(item.get("key"))+ if parts is None or parts[1] > ceiling:+ continue+ evidence.append(parts[1])+ latest = _instant(item.get("last_metered_at"))+ if latest is not None and latest <= ceiling:+ evidence.append(latest)+ if evidence:+ latest = max(evidence)+ return (local_usage_day(latest).isoformat(), latest)+ if metered is None or metered > ceiling:+ return ("", _OLDEST_INSTANT)if metered is None or metered > ceiling:return (row["day"], _OLDEST_INSTANT)return (row["day"], metered)@@ -453,6 +846,127 @@ def _newer_timestamp(current: Optional[str], candidate: Optional[str]) -> Optionreturn candidate if candidate_instant > current_instant else current+def _retain_hour_slices(row: dict, measured: datetime) -> dict:+ """Keep only the recent, usable hour slices needed by the 24-hour report."""++ hours = row.get("hours")+ if hours is None:+ return row++ current_start = _hour_start(measured).astimezone(timezone.utc)+ oldest_start = current_start - timedelta(hours=USAGE_HOURLY_RETENTION_HOURS - 1)+ retained: dict[str, dict] = {}+ expired = row.get("hourly_expired_totals")+ expired_known = isinstance(expired, dict)+ if expired_known:+ expired = dict(expired)+ expired_before = _instant(row.get("hourly_expired_before"))+ boundary_known = expired_before is not None or not any((expired or {}).values())+ incomplete = row.get("hourly_history_complete") is not True+ if any((expired or {}).values()) and (+ expired_before is None or oldest_start < expired_before+ ):+ # Counts alone prove reconciliation, not that pruned hours remain+ # outside this report. A clock rollback can bring them back in range.+ incomplete = True+ for item in hours:+ parts = _hour_key_parts(item.get("key"))+ if parts is None:+ incomplete = True+ continue+ key, start = parts+ instant = start.astimezone(timezone.utc)+ metered = _instant(item.get("last_metered_at"))+ if instant > measured or (metered is not None and metered > measured):+ # Future slices cannot be evidence of usage and must not occupy the+ # bounded recent history. A current-hour aggregate may also contain+ # future-stamped calls; its counters cannot be split retrospectively.+ incomplete = True+ continue+ if instant < oldest_start:+ # Keep the expired portion of the daily aggregate separate so a+ # partial oldest local day can distinguish ordinary retention from a+ # missing in-horizon slice.+ if expired_known:+ _accumulate(expired, item)+ if boundary_known:+ end = instant + timedelta(hours=1)+ expired_before = max(expired_before, end) if expired_before else end+ continue+ retained[key] = {**item, "key": key}+ latest_metered = _instant(row.get("last_metered_at"))+ if (+ not incomplete+ and row.get("requests", 0) > 0+ and latest_metered is not None+ and oldest_start <= latest_metered <= measured+ and _hour_key(latest_metered) not in retained+ ):+ logger.warning(+ "Model Hub usage ledger row %s has complete hourly history without "+ "its latest metered hour; publishing it as incomplete",+ _row_key(row),+ )+ incomplete = True+ row_day_overlaps = False+ if not incomplete:+ owner_day_window = _hourly_owner_day_window(row)+ if owner_day_window is not None:+ row_day_overlaps = _intervals_overlap(+ oldest_start,+ measured,+ *owner_day_window,+ )+ if not incomplete and (row_day_overlaps or retained or expired_known):+ # Compare durable UTC slices even when a host timezone change makes the+ # persisted local owner day fall outside the current display grid.+ nested_totals = _empty_totals()+ for item in retained.values():+ _accumulate(nested_totals, item)+ if expired_known:+ _accumulate(nested_totals, expired)+ if not expired_known or any(+ nested_totals[key] != row[key] for key in _COUNTER_KEYS+ ):+ logger.warning(+ "Model Hub usage ledger row %s cannot reconcile its complete "+ "in-horizon day with retained and expired hourly counters; "+ "publishing it as incomplete",+ _row_key(row),+ )+ incomplete = True+ if len(retained) > USAGE_HOURLY_RETENTION_HOURS:+ retained = dict(+ sorted(+ retained.items(),+ key=lambda item: _hour_key_parts(item[0])[1],+ )[-USAGE_HOURLY_RETENTION_HOURS:]+ )+ incomplete = True+ return {+ **row,+ "hours": sorted(retained.values(), key=lambda item: item["key"]),+ "hourly_expired_totals": expired if expired_known else None,+ "hourly_expired_before": expired_before.isoformat() if expired_before else None,+ "hourly_history_complete": not incomplete,+ }+++def _has_recent_hourly_evidence(row: dict, start: datetime, end: datetime) -> bool:+ """Use the same durable UTC evidence for write retention and hourly reads."""++ latest = _instant(row.get("last_metered_at"))+ if latest is not None and start <= latest <= end:+ return True+ for item in row.get("hours") or ():+ parts = _hour_key_parts(item.get("key"))+ if parts is not None and start <= parts[1] <= end:+ # Selection preserves evidence of uncertainty too. The shared+ # retention validator rejects future-stamped counters afterward.+ return True+ return False++class BoundedUsageLedger:"""Persist metered upstream-call token counts as a bounded daily aggregate."""@@ -473,36 +987,26 @@ class BoundedUsageLedger:self._now = nowself._lock = threading.RLock()- def _within_capacity(self, rows: list[dict], *, measured: datetime) -> list[dict]:- """Return at most `max_rows` of these rows, evicting the least recently metered.-- `_recency` orders by day first, so this may only be handed rows that are- already reportable. Given a future-dated row it does the opposite of its- job: that row outranks every real one, survives, and then reads refuse it- — which is the defect `_retained` exists to close, and which reappeared- the one time this was called on rows straight out of the file.-- So the two callers are the two places a reportable set is formed, and- neither is the parse. `_write` calls it on rows `_retained` has already- placed inside the ledger's own day window; `window` calls it on rows it- has already filtered to the requested one. Both keep the same survivors- in the same order.-- `measured` is what those two filters cannot supply: the day they bound is- only the first half of the order, and an instant inside today can still be- one no clock has reached. It is the reading each caller already took for its- own window, so the eviction and the placement answer to one clock — and on- the write path it changes nothing, because `_retained` has already brought- every instant back under it.+ def _within_capacity(+ self, rows: list[dict], *, measured: datetime, utc_owner_days: bool = False,+ ) -> list[dict]:+ """Bound an already-reportable set using its admission policy.++ Daily readers preserve owner-day ordering. Writes and hourly readers use+ UTC evidence for recency too, so a future old-zone owner cannot displace a+ newer call merely because its original calendar label sorts later."""if len(rows) <= self.max_rows:return rows- return sorted(rows, key=lambda row: _recency(row, measured))[-self.max_rows :]+ return sorted(+ rows,+ key=lambda row: _recency(row, measured, utc_owner_days=utc_owner_days),+ )[-self.max_rows :]- def _read(self) -> list[dict]:+ def _read(self) -> _LedgerRead:if not self.path.exists():- return []+ return _LedgerRead([], False)# Degrading to empty keeps a broken optional-feature file from failing# startup, but the next write replaces that file — so this is the last# moment its history is recoverable, and saying nothing would erase it@@ -517,10 +1021,10 @@ class BoundedUsageLedger:payload = json.loads(self.path.read_text(encoding="utf-8"))except (OSError, ValueError, RecursionError) as exc:logger.warning("Model Hub usage ledger %s is unreadable: %s", self.path, exc)- return []+ return _LedgerRead([], True)if not isinstance(payload, list):logger.warning("Model Hub usage ledger %s is not a list of rows", self.path)- return []+ return _LedgerRead([], True)rows: dict[tuple[str, str, str], dict] = {}dropped = 0for item in payload:@@ -537,6 +1041,9 @@ class BoundedUsageLedger:existing["last_metered_at"],row["last_metered_at"],)+ if row.get("history_degraded") is True:+ existing["history_degraded"] = True+ _merge_hour_slices(existing, row)if dropped:logger.warning("Model Hub usage ledger %s dropped %d unusable row(s)", self.path, dropped@@ -547,17 +1054,21 @@ class BoundedUsageLedger:# wrote. Same answer as every other door, for the same reason: a row whose# magnitude no published document could carry is dropped, not saturated.held = []+ degraded = dropped > 0 or any(+ row.get("history_degraded") is True for row in rows.values()+ )for row in rows.values():if all(row[key] <= USAGE_COUNTER_CEILING for key in _COUNTER_KEYS):held.append(row)continue+ degraded = Truelogger.warning("Model Hub usage ledger %s dropped row %s: merged counters outgrew ""what the file can carry",self.path,_row_key(row),)- return sorted(held, key=_row_key)+ return _LedgerRead(sorted(held, key=_row_key), degraded)def _write(self, rows: list[dict], *, measured: datetime) -> None:"""Persist the rows the file can hold, at both of the capacities it has.@@ -582,7 +1093,7 @@ class BoundedUsageLedger:holdable: list[dict] = []for row in rows:if all(row[key] <= USAGE_COUNTER_CEILING for key in _COUNTER_KEYS):- holdable.append(row)+ holdable.append(_retain_hour_slices(row, measured))continuelogger.warning("Model Hub usage ledger %s dropped row %s: counters outgrew what the "@@ -590,7 +1101,17 @@ class BoundedUsageLedger:self.path,_row_key(row),)- retained = self._within_capacity(holdable, measured=measured)+ retained = self._within_capacity(holdable, measured=measured, utc_owner_days=True)+ if _hourly_uncertainty_was_dropped(+ holdable,+ retained,+ _hour_starts(measured)[0],+ measured,+ ):+ # Capacity may evict an uncertain owner in favor of a known newer+ # call. Preserve the existing degradation witness on a survivor so+ # reopening cannot publish the retained row as complete history.+ retained = [{**row, "history_degraded": True} for row in retained]write_state_document(self.path, sorted(retained, key=_row_key))def record(@@ -642,10 +1163,25 @@ class BoundedUsageLedger:returnwith self._lock:persisted_at = _aware(self._now())- rows = {_row_key(row): row for row in self._read()}+ read = self._read()+ rows = {_row_key(row): row for row in read.rows}+ if read.degraded:+ # A successful write must not turn damaged history into a+ # complete report. Carry the uncertainty forward in the+ # surviving/new rows until the ledger is explicitly repaired.+ for row in rows.values():+ row["history_degraded"] = Truefolded = Falsefor call in calls:metered_at = min(_aware(call.at), persisted_at)+ # Ordinary delayed writes retain the date captured before queueing,+ # even if the host zone changes. Future calls still clamp to the+ # persistence clock, including its local date.+ owner_day = (+ local_usage_day(persisted_at).isoformat()+ if _aware(call.at) > persisted_at+ else call.owner_day+ )usage = call.usage# A live call carries identities, not keys, and this is the one place# they become one: derive here and every row downstream — new,@@ -657,7 +1193,7 @@ class BoundedUsageLedger:if source_key is not None and model_key is not None:increment = _normalize_row({- "day": local_usage_day(metered_at).isoformat(),+ "day": owner_day,"source_id": source_key,"model_id": model_key,"requests": call.requests,@@ -666,6 +1202,19 @@ class BoundedUsageLedger:"cached_input_tokens": usage.cached_input_tokens if usage else 0,"output_tokens": usage.output_tokens if usage else 0,"last_metered_at": metered_at.isoformat(),+ "hours": [+ {+ "key": _hour_key(metered_at),+ "requests": call.requests,+ "token_reports": call.requests if usage is not None else 0,+ "input_tokens": usage.input_tokens if usage else 0,+ "cached_input_tokens": usage.cached_input_tokens if usage else 0,+ "output_tokens": usage.output_tokens if usage else 0,+ "last_metered_at": metered_at.isoformat(),+ }+ ],+ "hourly_expired_totals": _empty_totals(),+ "hourly_history_complete": True,})if increment is None:@@ -679,6 +1228,8 @@ class BoundedUsageLedger:extra={"source_id_usable": source_key is not None},)continue+ if read.degraded:+ increment["history_degraded"] = Trueexisting = rows.get(_row_key(increment))if existing is None:rows[_row_key(increment)] = increment@@ -688,6 +1239,7 @@ class BoundedUsageLedger:existing["last_metered_at"],increment["last_metered_at"],)+ _merge_hour_slices(existing, increment)folded = Trueif not folded:return@@ -695,23 +1247,12 @@ class BoundedUsageLedger:self._write(retained, measured=persisted_at)def _retained(self, rows: list[dict], measured: datetime) -> list[dict]:- """Keep the rows this ledger's own clock can place, bounded at both edges.-- `window` already refuses to report a row dated after today, so a future row- contributes to nothing a reader can see — while still holding one of the- `max_rows` slots and outranking every real row in `_recency`, which evicts- the least recently metered. A clock that jumps forward while many pairs are- metered and is then corrected would therefore fill the ledger with rows that- report nothing and evict every new one, and metering would stop until those- dates arrive. Retention keeping what reads refuse is the defect; one window- with both edges, measured by this module rather than declared by the file,- is what closes it.-- A row inside the window may still claim an instant that has not happened.- That is not evidence of a misplaced row, only of an unmeasurable recency, so- it is bounded rather than dropped: the file supplies the instant, this module- supplies its spelling and its ceiling.+ """Keep daily owners or real evidence needed by the hourly reader.+ A host timezone change can move an old local owner outside the current+ daily window without aging its UTC evidence. Retain that owner unchanged;+ only daily reports use its calendar label. Future timestamps alone never+ rescue an otherwise unreportable row or consume the bounded capacity.`measured` is read at the write, never handed in from a call — see `record`."""@@ -719,25 +1260,43 @@ class BoundedUsageLedger:oldest = (today - timedelta(days=self.retention_days - 1)).isoformat()newest = today.isoformat()ceiling = _aware(measured).isoformat()+ hourly_start = _hour_starts(measured)[0]placed = []for row in rows:- if not oldest <= row["day"] <= newest:+ has_recent_hourly_evidence = _has_recent_hourly_evidence(+ row, hourly_start, measured,+ )+ owner_day_window = _hourly_owner_day_window(row)+ has_plausible_hourly_evidence = (+ owner_day_window is not None+ and _intervals_overlap(+ hourly_start,+ measured,+ *owner_day_window,+ )+ )+ if (+ not oldest <= row["day"] <= newest+ and not has_recent_hourly_evidence+ and not has_plausible_hourly_evidence+ ):continuemetered = _instant(row["last_metered_at"])if metered is not None and metered > measured:row = {**row, "last_metered_at": ceiling}- placed.append(row)+ placed.append(_retain_hour_slices(row, measured))return placed- def window(self, *, days: int, now: datetime) -> list[dict]:- """Return the rows inside the trailing local-day window, oldest first."""+ def _window_rows(self, *, days: int, now: datetime) -> tuple[list[dict], bool]:+ """Return reportable rows and whether reading the ledger degraded."""bounded_days = max(1, min(int(days), self.retention_days))today = local_usage_day(now)first_day = (today - timedelta(days=bounded_days - 1)).isoformat()last_day = today.isoformat()with self._lock:- rows = self._read()+ read = self._read()+ rows = read.rowsplaced = [row for row in rows if first_day <= row["day"] <= last_day]# The reportable set is formed here, so this is where the file's row# capacity bounds what `summary` can publish — after the date filter, never@@ -757,7 +1316,67 @@ class BoundedUsageLedger:len(placed) - len(held),self.max_rows,)- return sorted(held, key=_row_key)+ return sorted(held, key=_row_key), read.degraded++ def window(self, *, days: int, now: datetime) -> list[dict]:+ """Return the rows inside the trailing local-day window, oldest first."""++ rows, _degraded = self._window_rows(days=days, now=now)+ return rows++ def _hourly_rows(+ self,+ *,+ starts: Sequence[datetime],+ now: datetime,+ ) -> tuple[list[dict], bool]:+ """Select hourly owners by durable UTC evidence before local projection."""++ report_instant = _aware(now)+ horizon_start = starts[0].astimezone(timezone.utc)+ with self._lock:+ read = self._read()++ candidates: list[dict] = []+ for row in read.rows:+ if _has_recent_hourly_evidence(row, horizon_start, report_instant):+ candidates.append(row)+ continue+ latest = _instant(row.get("last_metered_at"))+ if (+ latest is not None+ and latest < horizon_start+ and not (+ isinstance(row.get("hours"), list)+ and _has_unresolved_hourly_mass(row)+ )+ ):+ continue+ owner_day_window = _hourly_owner_day_window(row)+ if owner_day_window is not None and _intervals_overlap(+ horizon_start,+ report_instant,+ *owner_day_window,+ ):+ candidates.append(row)+ continue++ held = self._within_capacity(candidates, measured=report_instant, utc_owner_days=True)+ if len(held) < len(candidates):+ logger.warning(+ "Model Hub usage ledger %s held %d hourly report row(s) over "+ "its capacity of %d; dropped the least recently metered",+ self.path,+ len(candidates) - len(held),+ self.max_rows,+ )+ capacity_degraded = _hourly_uncertainty_was_dropped(+ candidates,+ held,+ horizon_start,+ report_instant,+ )+ return sorted(held, key=_row_key), read.degraded or capacity_degradeddef summary(self,@@ -790,7 +1409,26 @@ class BoundedUsageLedger:bounded_days = max(1, min(int(days), self.retention_days))today = local_usage_day(now)- rows = self.window(days=bounded_days, now=now)+ rows, _degraded = self._window_rows(days=bounded_days, now=now)+ return self._summary_from_rows(+ rows,+ window_days=bounded_days,+ from_day=(today - timedelta(days=bounded_days - 1)).isoformat(),+ to_day=today.isoformat(),+ identities=identities,+ )++ def _summary_from_rows(+ self,+ rows: Sequence[dict],+ *,+ window_days: int,+ from_day: str,+ to_day: str,+ identities: Optional[Sequence[SourceIdentity]],+ ) -> dict:+ """Aggregate one exact set of daily or hourly rows."""+keyed_source_labels, keyed_model_labels = _keyed_identities(identities)totals = _empty_totals()@@ -828,9 +1466,9 @@ class BoundedUsageLedger:_accumulate(day, row)return {- "window_days": bounded_days,- "from_day": (today - timedelta(days=bounded_days - 1)).isoformat(),- "to_day": today.isoformat(),+ "window_days": window_days,+ "from_day": from_day,+ "to_day": to_day,"totals": totals,"sources": [{@@ -848,6 +1486,209 @@ class BoundedUsageLedger:"days": [by_day[day] for day in sorted(by_day)],}+ def report(+ self,+ *,+ window: str,+ now: datetime,+ identities: Optional[Sequence[SourceIdentity]] = None,+ ) -> dict:+ """Build one modern dense report without reallocating daily history."""++ if window not in USAGE_WINDOW_KEYS:+ raise ValueError(f"unsupported usage window: {window!r}")+ if window == "24h":+ return self._hourly_report(now=now, identities=identities)+ days = int(window[:-1])+ bounded_days = max(1, min(days, self.retention_days))+ report_local = _local(now)+ today = report_local.date()+ from_day = today - timedelta(days=bounded_days - 1)+ rows, read_degraded = self._window_rows(days=bounded_days, now=now)+ summary = self._summary_from_rows(+ rows,+ window_days=bounded_days,+ from_day=from_day.isoformat(),+ to_day=today.isoformat(),+ identities=identities,+ )+ by_day = {+ row["day"]: []+ for row in rows+ if from_day.isoformat() <= row["day"] <= today.isoformat()+ }+ for row in rows:+ if row["day"] in by_day:+ by_day[row["day"]].append(+ {+ "source_id": row["source_id"],+ "model_id": row["model_id"],+ **{key: row[key] for key in _COUNTER_KEYS},+ }+ )+ buckets = []+ for index in range(bounded_days):+ bucket_day = from_day + timedelta(days=index)+ start = _local_midnight(bucket_day)+ end = (+ report_local+ if bucket_day == today+ else _local_midnight(bucket_day + timedelta(days=1))+ )+ buckets.append(+ {+ "key": bucket_day.isoformat(),+ "start_at": start.isoformat(),+ "end_at": end.isoformat(),+ "history_complete": not read_degraded,+ "rows": sorted(+ by_day.get(bucket_day.isoformat(), []),+ key=lambda row: (row["source_id"], row["model_id"]),+ ),+ }+ )+ return {+ **summary,+ "window_key": window,+ "granularity": "day",+ "from_at": buckets[0]["start_at"],+ "to_at": report_local.isoformat(),+ "buckets": buckets,+ }++ def _hourly_report(+ self,+ *,+ now: datetime,+ identities: Optional[Sequence[SourceIdentity]],+ ) -> dict:+ """Project only measured nested slices onto 24 actual consecutive hours."""++ report_instant = _aware(now)+ starts = _hour_starts(now)+ interval_by_instant = {+ start.astimezone(timezone.utc): (start, index)+ for index, start in enumerate(starts)+ }+ first_start = starts[0]+ report_local = _local(now)+ last_day = report_local.date()+ # DST plus a fractional offset can make these 24 actual intervals touch+ # three local dates. Select rows from their durable UTC-hour evidence+ # before applying the current host timezone to their local presentation.+ rows, read_degraded = self._hourly_rows(starts=starts, now=report_instant)+ measured_by_bucket: list[dict[tuple[str, str], dict]] = [+ {} for _ in starts+ ]+ incomplete: set[int] = set(range(len(starts))) if read_degraded else set()++ for row in rows:+ # Read-only projection must apply the same temporal evidence policy+ # as persistence, including future slices in an otherwise valid day.+ owner_day_window = _hourly_owner_day_window(row)+ row = _retain_hour_slices(row, report_instant)+ row_day = _calendar_day(row["day"])+ if row.get("hourly_history_complete") is not True:+ overlapping = False+ latest = _instant(row.get("last_metered_at"))+ owner_mismatch = (+ latest is not None+ and first_start <= latest <= report_instant+ and local_usage_day(latest) != row_day+ )+ if owner_day_window is not None:+ for index, start in enumerate(starts):+ end = (+ starts[index + 1]+ if index + 1 < len(starts)+ else report_instant+ )+ if _intervals_overlap(start, end, *owner_day_window):+ incomplete.add(index)+ overlapping = True+ if not overlapping or owner_mismatch:+ # Even partial owner-day overlap cannot localize missing+ # calls when durable UTC evidence disagrees with that day.+ # No old-zone offset exists for reconstructing their hours.+ incomplete.update(range(len(starts)))+ # A damaged request counter cannot erase the incomplete witness.+ if row["requests"] <= 0:+ continue+ for item in row.get("hours") or ():+ parts = _hour_key_parts(item.get("key"))+ if parts is None:+ continue+ _key, start = parts+ bucket = interval_by_instant.get(start)+ if bucket is None:+ continue+ _start_utc, index = bucket+ key = (row["source_id"], row["model_id"])+ projected = measured_by_bucket[index].get(key)+ if projected is None:+ start_local = start.astimezone()+ projected = {+ "day": start_local.date().isoformat(),+ "source_id": row["source_id"],+ "model_id": row["model_id"],+ **{counter: 0 for counter in _COUNTER_KEYS},+ "last_metered_at": None,+ }+ measured_by_bucket[index][key] = projected+ _accumulate(projected, item)+ projected["last_metered_at"] = _newer_timestamp(+ projected["last_metered_at"],+ item.get("last_metered_at"),+ )++ bucket_rows = []+ summary_rows = []+ for index, start in enumerate(starts):+ end = starts[index + 1] if index + 1 < len(starts) else report_instant+ start_local = start.astimezone()+ end_local = end.astimezone()+ projected_rows = [+ {+ "source_id": row["source_id"],+ "model_id": row["model_id"],+ **{counter: row[counter] for counter in _COUNTER_KEYS},+ }+ for row in sorted(+ measured_by_bucket[index].values(),+ key=lambda row: (row["source_id"], row["model_id"]),+ )+ ]+ bucket_rows.append(+ {+ "key": start_local.isoformat(timespec="seconds"),+ "start_at": start_local.isoformat(),+ "end_at": end_local.isoformat(),+ "history_complete": index not in incomplete,+ "rows": projected_rows,+ }+ )+ summary_rows.extend(measured_by_bucket[index].values())++ days = sorted({+ *(start.astimezone().date().isoformat() for start in starts),+ last_day.isoformat(),+ })+ summary = self._summary_from_rows(+ summary_rows,+ window_days=len(days),+ from_day=days[0],+ to_day=days[-1],+ identities=identities,+ )+ return {+ **summary,+ "window_key": "24h",+ "granularity": "hour",+ "from_at": first_start.astimezone().isoformat(),+ "to_at": report_local.isoformat(),+ "buckets": bucket_rows,+ }+class _AbandonableWriter(Executor):"""One serialized worker for ledger writes that the process can walk away from.@@ -941,20 +1782,29 @@ class UsageCall:usage: Optional[ProtocolUsageReport]at: datetimerequests: int = 1+ owner_day: str = ""++ def __post_init__(self) -> None:+ # An init field intentionally survives dataclasses.replace during a fold.+ # Recomputing it from `at` later would use a possibly different host zone.+ if not self.owner_day:+ object.__setattr__(self, "owner_day", local_usage_day(self.at).isoformat())@property- def fold_key(self) -> tuple[str, str, str, bool]:- """What makes two calls one row, in the terms available before the write.+ def fold_key(self) -> tuple[str, str, str, str, bool]:+ """What makes two calls one daily row and one hourly slice.The ledger's own row key plus whether tokens were reported, which is thepart that keeps a fold arithmetically identical to the calls it replaces.- The day is this call's own bucket, exactly as `record` describes: the write- may still clamp it to the moment it persists, and two buckets clamped onto- one day meet again in `record_many`, which folds by row key regardless.+ The hour is part of the queue key so a flush cannot merge calls from+ different hours before the ledger sees their temporal identity. The local+ date must also remain: a UTC hour can cross local midnight, and folding+ those calls would move the earlier day's counts into the later day."""return (- local_usage_day(_aware(self.at)).isoformat(),+ self.owner_day,+ _hour_key(self.at),self.source_id,self.model_id,self.usage is not None,@@ -1019,7 +1869,7 @@ class UsageWriter:def __init__(self, ledger: BoundedUsageLedger, *, durability_wait: float = _DURABILITY_WAIT_SECONDS):self.ledger = ledgerself._durability_wait = durability_wait- self._pending: dict[tuple[str, str, str, bool], _QueuedRow] = {}+ self._pending: dict[tuple[str, str, str, str, bool], _QueuedRow] = {}# The batch on its way to disk, kept visible so a drain that times out# can count it: in the executor is not the same as persisted.self._writing: tuple[_QueuedRow, ...] = ()diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex ac21e8864..7ec2bee52 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -34,7 +34,7 @@{"method": "POST", "path": "/api/models/agents/<backend>/probe", "response_schema": "ProbeResponse", "exercise": {"path": "/api/models/agents/claude/probe", "status": 200, "json": {"model": "claude-opus-4-6"}}},{"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/usage?days=<n>", "response_schema": "UsageResponse", "exercises": [{"path": "/api/models/usage?days=30", "status": 200}, {"path": "/api/models/usage?window=24h", "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"}}},diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex a66b165c0..80e0fd53a 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -61,7 +61,7 @@ remain readable; ephemeral envelopes use only the terminal version.| POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. || 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/usage?days=<n>` | → `{usage: UsageSummary \| UsageReport}` | The released `days` selector remains supported and is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. The exclusive modern `window=24h\|7d\|30d\|60d` selector returns the dense temporal report; sending both selectors or an invalid `window` returns `400 invalid_parameter`. || GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline. Never starts the engine. || 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. |@@ -81,6 +81,37 @@ PUT and compatibility chains/reorder share backend-default semantics and effectipreserving all manual arrays. Exact manual order is saved through the chain resource;DELETE restores automatic and POST preview evaluates the draft without a write.+### Usage report windows++`GET /api/models/usage?days=<n>` keeps the released daily-only response shape.+`days` remains the only selector in that compatibility form; malformed values keep+the released defaulting behavior.++`GET /api/models/usage?window=<key>` is the modern form. Its `window` is one of+`24h`, `7d`, `30d`, or `60d`, and it is mutually exclusive with `days`. The response+rejects invalid or conflicting repeated `window` values with HTTP 400; identical+valid repeats are equivalent to one selector. The successful response+keeps the legacy `UsageSummary` fields and adds `window_key`, `granularity`,+`from_at`, `to_at`, and a dense chronological `buckets` matrix. The 24-hour report+has 24 actual consecutive hourly buckets, including the current partial hour. The+daily reports have one bucket per server-local calendar day.++Hourly persistence, queue coalescing, and interval identity use UTC hour boundaries.+The returned `key`, `start_at`, and `end_at` render those boundaries in the server-local+offset, so fractional-offset zones may show `:30` or `:45`, and a DST transition may+change the displayed wall-clock span while each interval remains one actual hour.+An hourly interval can overlap two local-day storage owners; both contributions+are joined into the same source/model row. Hourly `days` totals follow the bucket+start date, while daily reports retain local-calendar accounting. `from_day`,+`to_day`, and `window_days` cover every local date touched, including the report's+current date; around a DST transition the 24-hour view can touch three dates.++Each bucket carries `history_complete` independently of `token_reports`. A legacy+daily-only ledger can therefore contribute to daily reports while leaving affected+hourly buckets incomplete; its daily count is never assigned to an hour using+`last_metered_at`. Bucket rows are sparse `(source_id, model_id)` pairs, and the+`totals`, `sources`, and `days` fields aggregate those same measured bucket rows.+### Native migration terminal recoveryThe migration apply response is successful only after the grouped custody transaction@@ -1407,7 +1438,8 @@ so one model is one row rather than one row per spelling.Days are local-calendar days on the Avibe host. `from_day` and `to_day` bound therequested window even when no turn fell inside it; `days[]` contains only days that-carry a metered turn. `label` is joined from current Source config, so it is `null`+carry a metered turn (grouped by bucket start date for hourly reports, as described+under usage report windows). `label` is joined from current Source config, so it is `null`for a Source that has since been removed and follows a rename immediately.## Runtime installation and host supportdiff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.jsonindex 7e4c8b2ec..b2ef261dc 100644--- a/docs/plans/model-hub-contracts/usage-summary.schema.json+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/usage-summary.schema.json","title": "Model Hub usage summary",- "description": "Metered token usage over a trailing local-day window, aggregated from the turns the gateway proxied. A report only: no consumer of this document may feed it back into resolution, admission, or cooldown.",+ "description": "Metered token usage over a trailing local-day or recent-hour window, aggregated from the turns the gateway proxied. A report only: no consumer of this document may feed it back into resolution, admission, or cooldown.","type": "object","required": ["window_days",@@ -12,10 +12,32 @@"sources","days"],+ "oneOf": [+ {+ "not": {+ "anyOf": [+ {"required": ["window_key"]},+ {"required": ["granularity"]},+ {"required": ["from_at"]},+ {"required": ["to_at"]},+ {"required": ["buckets"]}+ ]+ }+ },+ {+ "required": [+ "window_key",+ "granularity",+ "from_at",+ "to_at",+ "buckets"+ ]+ }+ ],"additionalProperties": false,"properties": {"window_days": {- "description": "Requested window after clamping to the retained range.",+ "description": "Daily window after clamping to the retained range, or the number of local dates touched by an hourly report, including its current report date.","type": "integer","minimum": 1,"maximum": 62@@ -39,11 +61,37 @@}},"days": {- "description": "One entry per local day carrying a metered turn, oldest first.",+ "description": "One entry per local day carrying a metered turn, oldest first. Hourly reports group the published bucket rows by bucket start date; daily reports retain local-calendar accounting.","type": "array","items": {"$ref": "#/definitions/DayUsage"}+ },+ "window_key": {+ "description": "Modern report selector served by the API.",+ "enum": ["24h", "7d", "30d", "60d"]+ },+ "granularity": {+ "description": "Temporal granularity of the dense bucket matrix.",+ "enum": ["hour", "day"]+ },+ "from_at": {+ "description": "RFC3339 start of the first dense bucket, with the server-local UTC offset.",+ "type": "string",+ "format": "date-time"+ },+ "to_at": {+ "description": "RFC3339 report time, with the server-local UTC offset.",+ "type": "string",+ "format": "date-time"+ },+ "buckets": {+ "description": "Dense chronological buckets: 24 for 24h, or one per local calendar day for the daily windows.",+ "type": "array",+ "minItems": 1,+ "items": {+ "$ref": "#/definitions/UsageBucket"+ }}},"definitions": {@@ -89,6 +137,81 @@}}},+ "UsageBucketRow": {+ "type": "object",+ "required": [+ "source_id",+ "model_id",+ "requests",+ "token_reports",+ "input_tokens",+ "cached_input_tokens",+ "output_tokens"+ ],+ "additionalProperties": false,+ "properties": {+ "source_id": {+ "type": "string",+ "minLength": 1+ },+ "model_id": {+ "type": "string",+ "minLength": 1+ },+ "requests": {+ "$ref": "#/definitions/Count"+ },+ "token_reports": {+ "$ref": "#/definitions/Count"+ },+ "input_tokens": {+ "$ref": "#/definitions/Count"+ },+ "cached_input_tokens": {+ "$ref": "#/definitions/Count"+ },+ "output_tokens": {+ "$ref": "#/definitions/Count"+ }+ }+ },+ "UsageBucket": {+ "type": "object",+ "required": [+ "key",+ "start_at",+ "end_at",+ "history_complete",+ "rows"+ ],+ "additionalProperties": false,+ "properties": {+ "key": {+ "description": "Server-local rendering of the canonical UTC hour boundary, with an explicit offset; fractional-offset zones may show :30 or :45.",+ "type": "string",+ "minLength": 1+ },+ "start_at": {+ "description": "Inclusive server-local rendering of the canonical UTC hour boundary.",+ "type": "string",+ "format": "date-time"+ },+ "end_at": {+ "description": "Exclusive server-local rendering of the next canonical UTC hour boundary; the final bucket ends at report time.",+ "type": "string",+ "format": "date-time"+ },+ "history_complete": {+ "type": "boolean"+ },+ "rows": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/UsageBucketRow"+ }+ }+ }+ },"SourceUsage": {"type": "object","required": [diff --git a/docs/plans/model-usage-analytics.md b/docs/plans/model-usage-analytics.mdnew file mode 100644index 000000000..f284509d1--- /dev/null+++ b/docs/plans/model-usage-analytics.md@@ -0,0 +1,363 @@+# Model usage analytics++Status: implementation.++## Approved behavior++The owner approved the interactive usage preview on September 24, 2026, including+the subsequent explicit pin interaction. This approval is the visual reference+for the new usage surface; existing Model Hub tokens and primitives still own+the surrounding shell. The reference is the orchestrator Session's Show Page+(`seskugjeceav3`), not a new navigation shell to copy into the product.++- A shared time range and multi-select Source/model filters drive the statistics,+ chart, table, and CSV export.+- Offer 24 hours, 7 days, 30 days, and 60 days. The initial view is 24 hours.+ Use hourly lines for 24 hours, daily lines for 7 days, and daily stacked bars+ for 30/60 days. Display the server-returned time boundaries and time zone.+- The hourly view includes the current partial hour and preceding 23 hourly+ intervals. Label the partial hour and disclose the actual range. It is an+ hourly-bucket view, not an exact second-level sliding window.+- Metrics: all tokens, input including cache, output, cache reads, requests.+ Groups: total, token type, model, Source (labelled supplier in the UI).+ Token-type grouping is unavailable for request counts.+- Total tokens = input + output. Disjoint token series use noncached input+ (`input_tokens - cached_input_tokens`), cached input, and output.+- A model's identity is `(source_id, model_id)`, never its label. Different+ configured Sources remain distinct even when labels or vendor brands match.+- A hover opens readable exact figures for its time bucket. Clicking a point+ opens an ordinary, dismissible detail popover. Outside click closes it.+ Only the explicit pin control in the popover corner pins/unpins the detail;+ clicking the plot again never toggles pinning. Pinned details survive outside+ clicks; changing report scope clears the pin. Escape dismisses the detail.+ Pinning also narrows the table to that bucket; unpinning restores the range.+- The chart precedes the exact-count details table. Chart legend visibility is+ presentation only and must not silently change report scope or CSV contents.+- Preserve honest unavailable/partial-report states, historical identities,+ loading/failure behavior, keyboard access, light/dark themes, and narrow screens.++## Shared wire contract++The existing `GET /api/models/usage?days=N` remains supported with its current+shape and default. The same route accepts an exclusive `window` selector:+`24h | 7d | 30d | 60d`. Invalid or conflicting selectors return 400.+The controller RPC, its client, and service forward this selector explicitly.+The modern UI uses `window` exclusively.++A modern response retains `{ok, contract_version, usage}`. `usage` extends the+existing UsageSummary fields with the following required fields:++```ts+type UsageWindowKey = '24h' | '7d' | '30d' | '60d';+type UsageBucketRow = UsageCounters & {+ source_id: string;+ model_id: string;+};+type UsageBucket = {+ key: string;+ start_at: string; // RFC3339, inclusive, explicit server-local UTC offset+ end_at: string; // RFC3339, exclusive; current bucket ends at report time+ history_complete: boolean;+ rows: UsageBucketRow[];+};+type UsageReport = UsageSummary & {+ window_key: UsageWindowKey;+ granularity: 'hour' | 'day';+ from_at: string; // first bucket start+ to_at: string; // report time+ buckets: UsageBucket[];+};+```++`buckets` is dense and chronological: 24, 7, 30, or 60 entries. Daily keys+are local `YYYY-MM-DD`; hourly keys are offset-aware instants, unambiguous+across DST. Hourly intervals are actual consecutive hours, with the final+interval partial. Daily intervals are server-local calendar days.+Hourly identity is UTC-aligned across persistence, queue coalescing, and report+projection, then displayed with the server-local offset. Fractional-offset time+zones can therefore display boundaries at `:30` or `:45`; a DST offset change+must never move a measured call between incompatible bucket grids.++Each bucket's rows are sparse, unique source/model pairs. `sources` supplies+their existing joined display identities. `totals`, `sources`, and `days`+aggregate these exact same rows, including for hourly reports. For hourly+reports `window_days` names the number of local calendar dates touched by the+reported buckets; it must not pretend that 24 hours means today's calendar day.+An hourly interval can intersect two daily storage owners; the report joins+both contributions into one source/model row. Its `days` rollup follows bucket+start dates, while daily reports retain the original local-calendar accounting.+Daily reports preserve the legacy aggregate's bounds and survivor set.++`history_complete` means the time granularity is available for that bucket;+it is independent of `token_reports`, which describes vendor reporting.+Legacy daily usage must never be allocated to an invented hour using its+last-metered timestamp. Preserve it in daily reports, report only measured+hourly counts, and mark affected hourly buckets incomplete. The UI renders+gaps/partial-history language rather than claiming zero historical usage.+Timestamp-less legacy mass uses the conservative UTC envelope of its persisted+owner day (UTC+14 through UTC-12), never an inferred timestamp from another call.+Every intersecting hourly bucket remains incomplete even after an exact call is+merged into the same row. The hourly notice states, once, "Includes historical+usage without hourly time"; daily totals remain exact.+A completely idle, fully observed bucket can display zero. A bucket containing+requests but no token reports displays an unavailable token value, not zero.++Only the ledger produces the temporal matrix; the service joins identities;+RPC and HTTP preserve the fields; the browser projects filters/groups over+this one matrix. This report remains isolated from admission and routing.+No credential or upstream request-body fields are added.++## Storage boundary and ownership++The existing bounded ledger remains the sole metering owner. Extend it with+bounded recent hour aggregates without discarding the released list-of-daily-+rows format. Prefer optional nested hour slices in the retained daily rows:+one atomic write captures each call in both granularities. Older files load+without fabricated hourly history. Daily totals remain authoritative for+daily reports and include pre-upgrade usage; hourly slices are never added to+those totals a second time. Retain only the hourly slices needed for the+24-hour view, with explicit capacity and corruption handling. Persist the+aggregate counters pruned outside that horizon so a partial oldest local day can+distinguish ordinary retention expiry from a missing in-horizon slice. The optional+internal `hourly_expired_before` field records their exclusive UTC-hour boundary;+if a clock rollback brings pruned evidence into range, hourly history is incomplete.+Nonzero expired counters without a valid boundary also retain uncertainty. Keep+UTC-recent rows through subsequent writes after host timezone changes, without+changing their original daily ownership or the daily reports' capacity policy.+Existing batching must not combine calls from different hours before the ledger sees+their temporal identity. It must also retain distinct local-day owners when a+UTC hour spans midnight; a fold is valid only within both temporal boundaries.++The backend lane owns Python, the JSON schema/API documentation, and Python+tests. The UI lane owns frontend code, localizations, frontend tests, and+UI-side fixtures. The orchestrator owns integration, this plan, public user+documentation, regression acceptance, and final PR/review/CI delivery.+Interface deviations must be agreed with the orchestrator before integration.++## Acceptance++1. Real metered calls survive restart and reconcile across daily/hourly totals,+ Source/model filters, token metrics, and series/table projections.+2. Released daily-only files keep their existing totals. Hourly history gaps+ are explicit; corrupt/future/DST boundaries do not fabricate known usage.+3. Cache is counted exactly once; missing vendor usage and actual zero differ.+4. Hover, click-away, explicit pin/unpin, Escape, touch, and keyboard controls+ work without moving or changing the time being pinned.+5. Focused backend and frontend tests, changed-file lint, and the production UI+ build pass. Exercise the boundary with real fixture data, including Unicode+ and same-labelled Sources/models. CI owns repository-wide gates.+6. User-facing browser checks run against hermetic fixtures or a task-owned+ local Incus environment; never modify the running personal Avibe instance.+7. Current-head Codex review, CI, and resolved-thread gates are required.+ Opening the implementation PR is authorized; merging/deploying is not.++## Temporal boundary review decision++The September 24 integration reproductions exposed repeated temporal-ownership+defects, so further lane-level patching was paused for an orchestrator review of+the entire write/coalesce/read path. The independent local review covered head+`124b5e4a5` and reported three findings. At this decision there is one formal+findings-bearing local review head and no implementation PR review head.+Companion docs PR #47 has one findings-bearing head (`1cbc090010`), solely for+publication ordering; its unresolved release-order thread remains a separate gate.++| Root cause | Scope decision | Consuming evidence |+| --- | --- | --- |+| Queue coalescing lost the local-day owner when UTC hours span midnight | A fold must share both the local calendar date and UTC hour, as well as source/model and report presence. Daily storage stays authoritative; hourly projection joins owners. | Queue two same-hour calls across Nepal midnight and compare persisted daily/hourly reports with separate writes. |+| Read projection bypassed time-dependent slice validity | Reuse the existing recent-slice policy at report time; future evidence makes the owning day's intersecting intervals incomplete, while ordinary expired slices do not. Never move rejected counts into another hour. | Future-hour and future-stamped current-hour fixtures, before and after a subsequent write, alongside ordinary-expiry coverage. |+| HTTP scalar lookup hid conflicting selector values | Validate every modern `window` value; allow identical valid repeats, reject conflicting or invalid repeats, and preserve legacy `days` parsing. | Actual HTTP selector tests in both parameter orders and through controller IPC. |++These changes preserve the wire and storage contracts and do not justify a new+ledger, migration, or time-zone subsystem. Tests passing on earlier heads did not+close these gaps: verification must exercise the queue and read/write boundaries,+not only direct ledger recording.++## September 25 delivery-loop diagnosis++The orchestrator re-read all 33 GitHub review threads, including resolved and+outdated threads, and their originating review commits. Nine heads have findings:+`03a839f423` (5), `ee6fe9c902` (4), `5f0a695f62` (5), `57653ae5ff` (3),+`acc11668c2` (3), `3e71916d82` (4), `53d8204785` (2), `8354e502ed` (3),+and `d6d6db179` (4). There is no clean pass. Comment positions can migrate to a+new head; these counts use the review's commit, not a comment's current position.+The repeated classes are temporal evidence/completeness, display identity+allocation, and detail interaction/accessibility. The circuit breaker therefore+requires a scope decision, not indefinite waiting for another review event.++The previous UTC read-path repair and its consuming timezone test were checked+directly. That test never recorded another call after changing timezone, leaving+the local-day write-retention gate untested. The expired aggregate reconciles+counts but lacks a temporal boundary. The missing-history projection assumes an+old local owner can locate uncertainty in the current zone. All three are failures+to carry UTC evidence through the entire read/write/report lifecycle.++Decision: keep the existing bounded daily ledger, wire contract, and approved+pending queue. Complete the UTC evidence policy at its existing owner:++- Thread `PRRT_kwDOPbFPYs6lwkc0`: preserve real, UTC-recent evidence across a+ subsequent write even when the old local owner day is outside today's grid.+ Keep the original daily ownership; do not invent a new daily allocation.+- Thread `PRRT_kwDOPbFPYs6lwkdB`: carry an exclusive UTC expiry boundary with+ pruned hourly counters. A horizon behind already-pruned evidence is incomplete;+ an old nonzero expired aggregate without a boundary is not proof of completeness.+- Thread `PRRT_kwDOPbFPYs6lwkdF`: a mismatched local owner cannot bound unknown+ hours after a timezone change. Include the authoritative latest UTC hour and+ conservatively retain uncertainty where its allocation cannot be recovered.+- Thread `PRRT_kwDOPbFPYs6lwkc8`: keyboard activation moves focus into the detail;+ dismissal returns focus without reopening it. Hover must not steal focus.+- CI: consume the already-merged SQLAlchemy constraint from master. Separately+ fix the ToastProvider-owned timer lifecycle exposed by the actual UI CI log;+ do not classify that uncaught exception as a dependency installation failure.++Verification must first fail on the pre-fix owner boundary, then cover timezone+changes plus subsequent writes/reopened ledgers, backward and ordinary forward+retention, partial/no local-day overlap, and keyboard activation/dismissal. Use+focused tests, a production UI build, real fixture browser/HTTP+IPC acceptance,+and current-head CI. Do not redesign storage, alter public docs, manually trigger+Codex, or merge/deploy/restart the live service. Preserve the existing durable+Watch and report the final gated head to the coordinating session.++The independent local review of `aac9d257b` reproduced a remaining capacity+interaction: an old-zone future owner could outrank a newer call at `max_rows=1`.+Membership and eviction must use compatible evidence. For write retention and+hourly capacity only, derive the recency calendar label from usable UTC evidence,+not the old owner label. Keep the persisted owner unchanged and retain the exact+existing day-first policy for daily report capacity. Ordinary same-zone ordering+is unchanged. Verify both timezone directions with and without hourly history,+both with room for the old row and with capacity for only the newest call.++Integrated browser acceptance exposed a second dismissal path: removing the+mobile tooltip reveals the SVG underneath a stationary pointer, generating+pointer-enter without pointer movement. Pointer-enter may show ordinary details+but must not clear an Escape dismissal; deliberate movement, focus, or activation+can reopen them. Focus restoration is limited to users still inside the chart,+so Escape does not reclaim focus after Tab has moved outside this non-modal+detail. The existing desktop/mobile dismissal case covers both stationary+closure and subsequent deliberate hover; the keyboard unit case also covers+Tab-away dismissal.++After subscription quota PR #2171 landed as `6af1066eb`, the coordinating+session requested a master integration before readiness. Preserve both reports'+API/schema registrations, fixtures, scenario IDs, four-tab navigation, and+independent lazy-read lifecycles; the usage consumer continues to send modern+window selectors. Scope analytics-specific stat styling to its own root because+quota reuses the legacy stat classes. The quota browser case first reproduced+the unintended type-scale override and now guards the original quota styling.++Review of `a27e7346c7` added two findings (35 threads across ten findings-bearing+heads). The completeness and identity-display classes have recurred, so the+orchestrator inspected their owners before choosing another change:++- Historical identity collision detection and display currently reconstruct a+ localized fallback from the language name. The translator must instead supply+ one fallback value to projection, chart, table, filter, and export. Require it+ in the pure projection API so a caller cannot silently fall back to literals.+ Exercise changed translation resources and collision handling, not just two+ fixed locale names.+- Strict hourly slice/expiry validation checks subset bounds but not whether+ token evidence has a token report. Daily normalization remains the released,+ permissive compatibility boundary. Reject impossible hourly/expired counters+ at their shared strict reader and carry the incomplete witness through report+ projection even when the daily request counter is zero. Verify retained,+ expired, and daily-only shapes before and after a subsequent real write.++These are bounded repairs to existing owners, not another storage redesign.+Keep valid zero-token reports and unreported requests distinct, preserve daily+counts, and do not change public API fields or the approved pending-queue policy.++Review of `39b083743a` added three findings (38 threads across eleven+findings-bearing heads). The coordinating owner approved one bounded structural+closure round before further implementation:++- Replace the current-zone interpretation of timestamp-less owner dates with+ one shared conservative UTC plausibility envelope. Read selection, write+ retention, uncertainty projection, and capacity ranking must agree; an+ unknown-time owner must not evict a known newer call. Sweep all hourly paths+ that reinterpret owner dates, and cover absent/invalid timestamps, both zone+ directions, partial/no overlap, expiry, subsequent writes, and bounded capacity.+ Keep daily ownership, public fields, and persisted metadata unchanged.+- Reuse the Model Hub percentage formatter with the active translator locale+ for every usage percentage, preserving unavailable/zero guards and precision.+- Expose the active metric column's direction through `aria-sort` and a+ translated sort-state label; test the state against the actual row order.++The owner initially set a convergence rule: future P0/P1 findings and regressions of+existing fixes remain actionable. New P2/P3 findings outside temporal evidence,+locale formatting, existing-control accessibility, or this PR's contract are+recorded as known follow-ups and dispositioned without another implementation+round. Recurrence of the three approved classes requires a fresh class-level+root-cause report. Readiness requires an exact-head clean review or only+owner-approved follow-up dispositions, zero unresolved threads, full green CI,+and a clean merge state. The coordinating owner alone performs the merge.++Parent review of the local envelope implementation found that a fresh component+timestamp still became an unjustified bound on older unlocated mass. A fixed-time+merge repair did not close the lifecycle: a delayed call's timestamp could age+out before the unknown historical usage, and read selection discarded the row+before its envelope reached projection. Selection, retention, and projection+therefore still had competing owners of temporal evidence.++At 13:32 CST on September 25, the coordinating owner superseded the proposed+final precision attempt and selected the conservative contract immediately:++- Timestamp-less legacy mass does not contribute to hourly series. Only actual+ measured hourly slices contribute; do not reverse-engineer old counts.+- Every bucket intersecting that mass's conservative owner-day UTC envelope is+ incomplete. A fresh component timestamp never narrows the envelope of old mass.+- Show one hourly notice: "Includes historical usage without hourly time", with+ matching English and Chinese translations. Daily totals remain exact.+- Delete precision-only machinery the contract does not need. No new persisted+ metadata, storage rewrite, or pending-queue policy change is allowed.++The invariant is that adding an exact call cannot remove incomplete marking+from any bucket the legacy mass could occupy. Test the relevant merge,+reopen, delayed-write, timezone, retention, capacity, and expiry boundaries with+explicit timezone selection and restoration; do not build another precision+subsystem. The timestamp-less-legacy review thread is dispositioned by this+contract after the implementation is pushed. Frontend locale/sort fixes ship in+the same push. Review, CI, thread, and merge-authority gates remain unchanged.++At 14:26 CST on September 25, review of `cb651cb8f4` prompted the final bounded+round. The 14:28 owner override includes capture-time day ownership:++- OR `history_degraded` across duplicate ledger rows. Test both read orders on+ daily and hourly reports, then a write/reopen. No other merge-algebra change.+- Freeze the local-day owner on the in-memory `UsageCall` when captured. Carry+ it through replacement, queue folding, and persistence using the existing+ persisted `day` field. Keep deliberate future-call clamping. Compare folded+ and unfolded writes across host-zone changes and preserve midnight,+ fractional-offset, and DST coverage. No queue compaction or schema change.+- Accept the Source CSV identifier and more-than-six chart identities findings+ as follow-ups; do not expand the CSV contract or redesign chart encoding here.++This supersedes the earlier convergence rule: after this single push, only+P0/P1 findings or a regression of the duplicate-degradation repair trigger code+changes. Every other P2/P3, including temporal precision, is recorded under+known residuals, replied to, and resolved without another implementation round.+Readiness still requires completed exact-head Codex review with a clean pass or+only dispositioned follow-ups, zero unresolved threads, full green CI, and+`CLEAN`. The coordinating owner alone performs the merge.++## Known residuals / follow-ups++- CSV's Source ID column can contain the bounded internal ledger key when a+ canonical Source ID exceeds the verbatim limit. Normal identifiers are+ unchanged. A follow-up can explicitly name the ledger key or supply the+ canonical Source ID through the identity join.+- More than six simultaneously displayed model/source identities reuse palette+ colors. Tooltip/table labels and filtering remain exact; secondary visual+ encodings or series grouping are a follow-up.+- An internal caller supplying a naive `UsageCall.at` can still have its absolute+ hour reinterpreted if the host zone changes before persistence, while the+ captured owner date remains fixed. Current production metering clocks supply+ aware UTC instants. Local review reproduced the naive-input case; normalizing+ the instant at capture or explicitly rejecting naive input is a follow-up+ under the final P2/P3 disposition rule, not another precision repair here.++## Known by design++- This is metered gateway usage, not native subscription quota or monetary cost.+- Historical daily counts cannot be reverse-engineered into hourly data.+- The approved preview's illustrative sidebar/data are not production changes.+- Source/model labels come from current configuration; deleted identities keep+ the existing honest historical-identity rendering.diff --git a/tests/e2e/test_model_hub_usage_events.py b/tests/e2e/test_model_hub_usage_events.pyindex 49d94845a..9c46fb398 100644--- a/tests/e2e/test_model_hub_usage_events.py+++ b/tests/e2e/test_model_hub_usage_events.py@@ -2,10 +2,16 @@from __future__ import annotations+import asyncioimport json+import subprocess+import sys+from datetime import datetime, timedelta, timezoneimport pytest+from core.handlers.model_hub.stream_wire import ProtocolUsageReport+from core.handlers.model_hub.usage import BoundedUsageLedger, UsageWriterfrom tests.e2e.test_model_hub_sources import (_configure_protocol,_create_source,@@ -15,6 +21,55 @@ from tests.e2e.test_model_hub_sources import (pytestmark = pytest.mark.e2e_model_hub+def usage_analytics_app(model_hub_app_factory):+ """Seed configured identities without depending on live credential discovery."""++ def seed_sources(app) -> None:+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ """+from config.v2_config import (+ MODEL_HUB_BACKENDS, ModelHubModelConfig, ModelHubSourceConfig,+ ModelHubSourceStateConfig, V2Config,+)+config = V2Config.default()+config.model_hub.enabled = False+for backend in MODEL_HUB_BACKENDS:+ config.model_hub.agents[backend].mode = "direct"+config.model_hub.sources = [+ ModelHubSourceConfig(+ id=source_id, kind="api_key", vendor="custom",+ display_name="供应商 · 同名", protocol="openai_chat",+ supply_channel="hub", billing="metered",+ state=ModelHubSourceStateConfig(),+ models=[+ ModelHubModelConfig(id=model_id, provenance="manual")+ for model_id in ("shared-model", "模型-β")+ ],+ credential_ref="synthetic-unavailable-" + source_id,+ )+ for source_id in ("src_usageaaa1", "src_usagebbb2")+]+config.update.auto_update = False+config.update.check_interval_minutes = 0+config.save()+""",+ ],+ cwd=app.repo_root,+ env=app.env,+ capture_output=True,+ text=True,+ timeout=20,+ )+ assert result.returncode == 0, result.stdout + result.stderr++ with model_hub_app_factory(before_start=seed_sources) as app:+ yield app++def test_e2_usage_windows_are_bounded(model_hub_app,) -> None:@@ -40,6 +95,180 @@ def test_e2_usage_windows_are_bounded("output_tokens": 0,}++def test_e2_usage_reports_reconcile_across_http_ipc_and_restart(+ usage_analytics_app,+) -> None:+ """MH-USAGE-E2E-001: the matrix retains exact pair identities through real IPC."""++ model_hub_app = usage_analytics_app+ common_model = "shared-model"+ unicode_model = "模型-β"+ sources = model_hub_app.client.get("/api/models/sources").json()["sources"]+ first = next(source for source in sources if source["id"] == "src_usageaaa1")+ second = next(source for source in sources if source["id"] == "src_usagebbb2")+ assert first["id"] != second["id"]+ now = datetime.now(timezone.utc)+ ledger = BoundedUsageLedger(+ model_hub_app.avibe_home / "state" / "model_hub_usage.json"+ )+ calls = (+ (first["id"], common_model, timedelta(minutes=70), (150, 100, 25)),+ (first["id"], common_model, timedelta(minutes=130), (40, 20, 5)),+ (second["id"], common_model, timedelta(minutes=130), (80, 0, 10)),+ (second["id"], unicode_model, timedelta(minutes=190), None),+ (first["id"], common_model, timedelta(hours=48), (200, 40, 30)),+ )++ async def meter_calls() -> None:+ # Queue together so the production writer must preserve different hours+ # for the same pair before flushing one atomic ledger transaction.+ writer = UsageWriter(ledger)+ for source_id, model_id, ago, counts in calls:+ writer.record(+ source_id=source_id,+ model_id=model_id,+ usage=(+ ProtocolUsageReport.of(+ input_tokens=counts[0],+ cached_input_tokens=counts[1],+ output_tokens=counts[2],+ )+ if counts is not None+ else None+ ),+ at=now - ago,+ )+ assert await writer.drain(timeout=5) == 0++ # The test runtime has no active turns, so the controller cannot race this+ # fixture with another metering write.+ asyncio.run(meter_calls())++ expected_hourly = {+ "requests": 4,+ "token_reports": 3,+ "input_tokens": 270,+ "cached_input_tokens": 120,+ "output_tokens": 40,+ }+ expected_daily = {+ "requests": 5,+ "token_reports": 4,+ "input_tokens": 470,+ "cached_input_tokens": 160,+ "output_tokens": 70,+ }+ for window, count in (("24h", 24), ("7d", 7), ("30d", 30), ("60d", 60)):+ response = model_hub_app.client.get(f"/api/models/usage?window={window}")+ body = response.json()+ assert response.status == 200, body+ report = body["usage"]+ expected = expected_hourly if window == "24h" else expected_daily+ assert report["window_key"] == window+ assert report["granularity"] == ("hour" if window == "24h" else "day")+ assert report["totals"] == expected+ buckets = report["buckets"]+ assert len(buckets) == count+ assert len({bucket["key"] for bucket in buckets}) == count+ assert buckets[0]["start_at"] == report["from_at"]+ assert buckets[-1]["end_at"] == report["to_at"]+ for before, after in zip(buckets, buckets[1:]):+ assert before["end_at"] == after["start_at"]+ for bucket in buckets:+ assert isinstance(bucket["history_complete"], bool)+ start = datetime.fromisoformat(bucket["start_at"])+ end = datetime.fromisoformat(bucket["end_at"])+ assert start.utcoffset() is not None+ assert end.utcoffset() is not None+ assert start <= end+ pairs = [+ (row["source_id"], row["model_id"]) for row in bucket["rows"]+ ]+ assert len(pairs) == len(set(pairs))+ rows = [row for bucket in buckets for row in bucket["rows"]]+ if window == "24h":+ assert len([+ row for row in rows+ if row["source_id"] == first["id"] and row["model_id"] == common_model+ ]) == 2+ assert {(row["source_id"], row["model_id"]) for row in rows} == {+ (first["id"], common_model),+ (second["id"], common_model),+ (second["id"], unicode_model),+ }+ for key, value in expected.items():+ assert sum(row[key] for row in rows) == value+ assert sum(source[key] for source in report["sources"]) == value+ assert sum(day[key] for day in report["days"]) == value+ assert {source["label"] for source in report["sources"]} == {+ "供应商 · 同名"+ }+ for source in report["sources"]:+ for key in expected:+ assert sum(model[key] for model in source["models"]) == source[key]++ for query in (+ "window=1d", "window=", "window=24h&days=7",+ "window=24h&window=7d", "window=7d&window=24h",+ "window=invalid&window=24h", "window=24h&window=invalid",+ ):+ response = model_hub_app.client.get(f"/api/models/usage?{query}")+ assert response.status == 400, response.json()+ repeated = model_hub_app.client.get("/api/models/usage?window=24h&window=24h")+ assert repeated.status == 200, repeated.json()+ assert repeated.json()["usage"]["totals"] == expected_hourly+ legacy = model_hub_app.client.get("/api/models/usage?days=7").json()["usage"]+ assert legacy["totals"] == expected_daily+ assert "buckets" not in legacy++ model_hub_app.restart_controller()+ for window, expected in (("24h", expected_hourly), ("7d", expected_daily)):+ response = model_hub_app.client.get(f"/api/models/usage?window={window}")+ assert response.status == 200, response.json()+ assert response.json()["usage"]["totals"] == expected+++def test_e2_daily_only_history_is_not_invented_as_hourly_usage(+ model_hub_app_factory,+) -> None:+ """MH-USAGE-E2E-002: released daily files never fabricate hourly history."""++ now = datetime.now(timezone.utc)+ counts = {+ "requests": 3,+ "token_reports": 2,+ "input_tokens": 150,+ "cached_input_tokens": 100,+ "output_tokens": 25,+ }++ def seed_legacy(app) -> None:+ path = app.avibe_home / "state" / "model_hub_usage.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps([{+ "day": now.astimezone().date().isoformat(),+ "source_id": "historical-source",+ "model_id": "历史模型",+ "last_metered_at": now.isoformat(),+ **counts,+ }]),+ encoding="utf-8",+ )++ with model_hub_app_factory(before_start=seed_legacy) as app:+ daily = app.client.get("/api/models/usage?window=7d")+ assert daily.status == 200, daily.json()+ assert daily.json()["usage"]["totals"] == counts+ hourly = app.client.get("/api/models/usage?window=24h")+ assert hourly.status == 200, hourly.json()+ report = hourly.json()["usage"]+ assert report["totals"] == dict.fromkeys(counts, 0)+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ assert not any(bucket["rows"] for bucket in report["buckets"])++def test_e3_event_feed_paginates_and_never_persists_credentials(mock_llm_upstream,model_hub_app,diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 28820ad8f..e848d2941 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -74,6 +74,7 @@ capabilities:- tests/test_model_hub_request_body_budget.py- tests/test_model_hub_l3.py- tests/test_model_hub_usage.py+ - tests/test_ui_server_fastapi.py- tests/test_model_hub_quota.py- tests/test_local_deps.py- tests/test_opencode_server.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex bddc8db0d..6d76fced2 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -23,6 +23,7 @@ capability:- tests/test_model_hub_request_body_budget.py- tests/test_model_hub_l3.py- tests/test_model_hub_usage.py+ - tests/test_ui_server_fastapi.py- tests/test_model_hub_quota.py- ui/src/components/settings/models/QuotaTab.test.tsx- tests/test_local_deps.py@@ -680,6 +681,68 @@ scenarios:kind: observationlayer: unittest: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-027+ - id: MH-USAGE-BACKEND-001+ name: Modern usage reports keep dense hourly buckets and distinct Unicode Source/model identities+ status: covered+ kind: contract+ layer: unit+ test: tests/test_model_hub_usage.py::test_modern_hourly_report_is_dense_and_keeps_source_model_identity+ - id: MH-USAGE-BACKEND-002+ name: UsageWriter preserves temporal identity when a flush spans different hours+ status: covered+ kind: concurrency+ layer: unit+ test: tests/test_model_hub_usage.py::test_usage_writer_never_coalesces_different_hours_before_persistence+ - id: MH-USAGE-BACKEND-003+ name: Released daily-only usage remains available while hourly history stays unavailable+ status: covered+ kind: compatibility+ layer: unit+ test: tests/test_model_hub_usage.py::test_legacy_daily_rows_are_preserved_but_never_allocated_to_an_hour+ - id: MH-USAGE-BACKEND-004+ name: Corrupt nested hourly slices cannot duplicate or exceed their daily owner+ status: covered+ kind: persistence+ layer: unit+ test: tests/test_model_hub_usage.py::test_corrupt_nested_hours_are_deduplicated_bounded_and_marked_unavailable+ - id: MH-USAGE-BACKEND-005+ name: Modern usage selector reaches the controller RPC and rejects invalid query combinations+ status: covered+ kind: contract+ layer: unit+ test: tests/test_ui_server_fastapi.py::test_the_usage_route_forwards_a_modern_window_and_rejects_selector_conflicts+ - id: MH-USAGE-BACKEND-006+ name: Fractional-offset and DST hourly reports join every local-day owner across midnight+ status: covered+ kind: compatibility+ layer: unit+ test: tests/test_model_hub_usage.py::test_hourly_report_joins_every_local_day_owner_across_midnight+ related_tests:+ - tests/test_model_hub_usage.py::test_legacy_usage_after_local_midnight_marks_the_overlapping_hour_incomplete+ - id: MH-USAGE-BACKEND-007+ name: Queued same-hour calls preserve their distinct local-day owners through persistence+ status: covered+ kind: concurrency+ layer: unit+ test: tests/test_model_hub_usage.py::test_usage_writer_preserves_daily_owners_inside_one_utc_hour+ - id: MH-USAGE-BACKEND-008+ name: Read and write boundaries exclude future hourly evidence without claiming complete zero usage+ status: covered+ kind: recovery+ layer: unit+ test: tests/test_model_hub_usage.py::test_future_hourly_evidence_is_incomplete_on_read_and_after_a_write+ - id: MH-USAGE-E2E-001+ name: Measured hourly and daily reports reconcile through HTTP and IPC after a controller restart+ status: covered+ kind: persistence+ layer: e2e+ test: tests/e2e/test_model_hub_usage_events.py::test_e2_usage_reports_reconcile_across_http_ipc_and_restart+ - id: MH-USAGE-E2E-002+ name: The real usage API preserves released daily history without inventing hourly counts+ status: covered+ kind: compatibility+ layer: e2e+ test: tests/e2e/test_model_hub_usage_events.py::test_e2_daily_only_history_is_not_invented_as_hourly_usage- id: MH-QUOTA-001name: Claude's fixed quota windows parse and null or app-only windows are skippedstatus: covereddiff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex c8623bc58..d8ad0ea57 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -4371,6 +4371,27 @@ def test_usage_summary_rpc_reads_the_ledger_off_the_controller_loop(tmp_path):assert summarised_on and loop_thread not in summarised_on+def test_usage_summary_rpc_forwards_the_modern_window_without_days(tmp_path):+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc++ service, _store, _adapter = _service(tmp_path)+ observed: list[dict] = []++ def usage_summary(**kwargs):+ observed.append(kwargs)+ return {"window_key": kwargs["window"]}++ service.usage_summary = usage_summary++ async def exercise():+ return await dispatch_model_hub_rpc(service, "usage_summary", {"window": "24h"})++ payload = asyncio.run(exercise())++ assert payload == {"window_key": "24h"}+ assert observed == [{"window": "24h"}]++def test_agents_endpoint_projects_each_enabled_named_agent_live(tmp_path):service, store, _adapter = _service(tmp_path)store.requested_model = lambda backend: {diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex 7890408ca..fdd0ede7b 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -22,6 +22,8 @@ import subprocessimport sysimport textwrapimport threading+import time+from dataclasses import replacefrom datetime import date, datetime, timedelta, timezonefrom pathlib import Path@@ -52,6 +54,7 @@ from core.handlers.model_hub.usage import (USAGE_RETENTION_DAYS,BoundedUsageLedger,SourceIdentity,+ UsageCall,UsageWriter,local_usage_day,)@@ -563,6 +566,1916 @@ def test_summary_reports_a_day_range_even_when_it_carries_no_turn(tmp_path: Pathassert summary["from_day"] < summary["to_day"]+def test_modern_hourly_report_is_dense_and_keeps_source_model_identity(+ tmp_path: Path,+) -> None:+ """MH-USAGE-BACKEND-001: modern windows reconcile measured hourly usage."""++ ledger = _ledger(tmp_path, now=_Clock(NOW + timedelta(hours=3)))+ unicode_model = "模型🧪/e\u0301"+ ledger.record(+ source_id="src_a",+ model_id=unicode_model,+ usage=ProtocolUsageReport(input_tokens=100, cached_input_tokens=40, output_tokens=7),+ at=NOW,+ )+ ledger.record(+ source_id="src_b",+ model_id=unicode_model,+ usage=ProtocolUsageReport(input_tokens=12, output_tokens=3),+ at=NOW + timedelta(hours=1),+ )+ ledger.record(+ source_id="src_a",+ model_id="model-missing-report",+ usage=None,+ at=NOW + timedelta(hours=2),+ )+ ledger.record(+ source_id="src_a",+ model_id=unicode_model,+ usage=ProtocolUsageReport(input_tokens=999, output_tokens=1),+ at=NOW - timedelta(hours=48),+ )++ report = ledger.report(+ window="24h",+ now=NOW + timedelta(hours=3),+ identities=[+ SourceIdentity(source_id="src_a", label="same label", model_ids=[unicode_model]),+ SourceIdentity(source_id="src_b", label="same label", model_ids=[unicode_model]),+ ],+ )++ assert report["window_key"] == "24h"+ assert report["granularity"] == "hour"+ assert len(report["buckets"]) == 24+ assert report["buckets"] == sorted(report["buckets"], key=lambda bucket: bucket["start_at"])+ assert report["totals"] == {+ "requests": 3,+ "token_reports": 2,+ "input_tokens": 112,+ "cached_input_tokens": 40,+ "output_tokens": 10,+ }+ measured = {+ (row["source_id"], row["model_id"]): row+ for bucket in report["buckets"]+ for row in bucket["rows"]+ }+ assert measured[("src_a", unicode_model)]["input_tokens"] == 100+ assert measured[("src_b", unicode_model)]["input_tokens"] == 12+ assert measured[("src_a", "model-missing-report")]["token_reports"] == 0+ assert {source["label"] for source in report["sources"]} == {"same label"}+ assert report["totals"]["input_tokens"] + report["totals"]["output_tokens"] == 122++ daily = ledger.report(+ window="60d",+ now=NOW + timedelta(hours=3),+ identities=[+ SourceIdentity(source_id="src_a", label="same label", model_ids=[unicode_model]),+ SourceIdentity(source_id="src_b", label="same label", model_ids=[unicode_model]),+ ],+ )+ assert daily["totals"]["requests"] == 4+ assert daily["totals"]["input_tokens"] == 1111+ assert len(daily["buckets"]) == 60+++def test_usage_writer_never_coalesces_different_hours_before_persistence(tmp_path: Path) -> None:+ """MH-USAGE-BACKEND-002: queued calls retain distinct hourly identity."""++ async def exercise() -> dict:+ ledger = _ledger(tmp_path, now=_Clock(NOW + timedelta(hours=2)))+ writer = UsageWriter(ledger)+ writer.record(+ source_id="src_a",+ model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=2),+ at=NOW,+ )+ writer.record(+ source_id="src_a",+ model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=5),+ at=NOW + timedelta(hours=1),+ )+ assert len(writer._pending) == 2+ assert await writer.drain(timeout=5) == 0+ return ledger.report(window="24h", now=NOW + timedelta(hours=2))++ report = asyncio.run(exercise())+ nonempty = [bucket for bucket in report["buckets"] if bucket["rows"]]+ assert len(nonempty) == 2+ assert sum(bucket["rows"][0]["requests"] for bucket in nonempty) == 2+ assert sum(bucket["rows"][0]["token_reports"] for bucket in nonempty) == 2+ assert sum(bucket["rows"][0]["input_tokens"] for bucket in nonempty) == 7++[email protected]("reported", [False, True])+def test_usage_writer_preserves_daily_owners_inside_one_utc_hour(+ tmp_path: Path, reported: bool,+) -> None:+ """MH-USAGE-BACKEND-007: queue folds retain both daily and hourly ownership."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 23, 18, 30, tzinfo=timezone.utc)+ calls = tuple(+ datetime(2026, 9, 23, 18, minute, tzinfo=timezone.utc)+ for minute in (13, 14, 20, 21)+ )+ usage = (+ ProtocolUsageReport(input_tokens=10, cached_input_tokens=3, output_tokens=2)+ if reported else None+ )++ async def exercise() -> None:+ queued = _ledger(tmp_path / "queued", now=_Clock(now))+ separate = _ledger(tmp_path / "separate", now=_Clock(now))+ writer = UsageWriter(queued)+ for at in calls:+ writer.record(source_id="src_a", model_id="model-x", usage=usage, at=at)+ separate.record(source_id="src_a", model_id="model-x", usage=usage, at=at)+ pending_rows = len(writer._pending)+ assert await writer.drain(timeout=5) == 0+ assert pending_rows == 2++ fresh = _ledger(tmp_path / "queued", now=_Clock(now))+ assert fresh.summary(days=1, now=now) == separate.summary(days=1, now=now)+ assert fresh.summary(days=1, now=now)["totals"]["requests"] == 2+ assert fresh.summary(days=7, now=now) == separate.summary(days=7, now=now)+ assert [day["requests"] for day in fresh.summary(days=7, now=now)["days"]] == [2, 2]+ for window in ("24h", "7d"):+ assert fresh.report(window=window, now=now) == separate.report(window=window, now=now)+ [bucket] = [+ bucket for bucket in fresh.report(window="24h", now=now)["buckets"]+ if bucket["rows"]+ ]+ assert bucket["rows"][0]["requests"] == 4++ try:+ os.environ["TZ"] = "Asia/Kathmandu"+ time.tzset()+ asyncio.run(exercise())+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()+++ ("capture_zone", "flush_zone", "switch_between_calls", "expected_days"),+ [+ ("UTC", "Asia/Kathmandu", False, {"2026-09-24": 18}),+ ("Asia/Kathmandu", "UTC", False, {"2026-09-24": 7, "2026-09-25": 11}),+ ("UTC", "Asia/Kathmandu", True, {"2026-09-24": 7, "2026-09-25": 11}),+ ("Asia/Kathmandu", "UTC", True, {"2026-09-24": 18}),+ ],+)+def test_queued_usage_keeps_capture_day_across_host_zone_change(+ tmp_path: Path,+ capture_zone: str,+ flush_zone: str,+ switch_between_calls: bool,+ expected_days: dict[str, int],+) -> None:+ """Queued/folded calls must keep the same daily owners as immediate writes.++ The existing midnight test keeps TZ fixed; it cannot catch recomputing the+ captured owner in fold keys, dataclass replacement, or delayed persistence.+ """++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 0, tzinfo=timezone.utc)++ async def exercise() -> None:+ immediate = _ledger(tmp_path / "immediate", now=_Clock(now))+ unfolded = _ledger(tmp_path / "unfolded", now=_Clock(now))+ queued = _ledger(tmp_path / "queued", now=_Clock(now))+ writer = UsageWriter(queued)+ calls = []+ keys = []+ for index, (minute, tokens) in enumerate(((14, 7), (45, 11))):+ if index and switch_between_calls:+ os.environ["TZ"] = flush_zone+ time.tzset()+ at = datetime(2026, 9, 24, 18, minute, tzinfo=timezone.utc)+ usage = ProtocolUsageReport(input_tokens=tokens)+ call = UsageCall(source_id="src_a", model_id="model-x", usage=usage, at=at)+ calls.append(call)+ keys.append(call.fold_key)+ immediate.record(source_id="src_a", model_id="model-x", usage=usage, at=at)+ writer.record(source_id="src_a", model_id="model-x", usage=usage, at=at)++ os.environ["TZ"] = flush_zone+ time.tzset()+ assert [replace(call).fold_key for call in calls] == keys+ assert len(writer._pending) == len(expected_days)+ unfolded.record_many([replace(call) for call in calls])+ assert await writer.drain(timeout=5) == 0++ expected_rows = json.loads(immediate.path.read_text(encoding="utf-8"))+ assert {row["day"]: row["input_tokens"] for row in expected_rows} == expected_days+ for ledger in (unfolded, queued):+ assert json.loads(ledger.path.read_text(encoding="utf-8")) == expected_rows+ fresh = BoundedUsageLedger(ledger.path, now=_Clock(now))+ for window in ("24h", "7d"):+ assert fresh.report(window=window, now=now) == immediate.report(window=window, now=now)+ assert fresh.report(window=window, now=now)["totals"]["input_tokens"] == 18++ try:+ os.environ["TZ"] = capture_zone+ time.tzset()+ asyncio.run(exercise())+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()+++def test_queued_future_call_still_clamps_day_after_host_zone_change(tmp_path: Path) -> None:+ """Freezing normal owners must not bypass the existing future-call ceiling."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 24, 23, 30, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ call = UsageCall(+ source_id="src_a", model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=7), at=now + timedelta(days=2),+ )+ os.environ["TZ"] = "Asia/Kathmandu"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.record_many([call])++ [row] = json.loads(ledger.path.read_text(encoding="utf-8"))+ assert row["day"] == "2026-09-25"+ assert row["last_metered_at"] == now.isoformat()+ assert row["hours"][0]["key"] == "2026-09-24T23:00:00+00:00"+ for window in ("24h", "7d"):+ assert ledger.report(window=window, now=now)["totals"]["input_tokens"] == 7+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()+++ ("future_minute", "owner_day"),+ [+ pytest.param(45, "2026-09-24", id="current-hour"),+ pytest.param(75, "2026-09-24", id="next-hour"),+ pytest.param(45, "2026-09-25", id="old-zone-current-hour"),+ ],+)+def test_future_hourly_evidence_is_incomplete_on_read_and_after_a_write(+ tmp_path: Path, future_minute: int, owner_day: str,+) -> None:+ """MH-USAGE-BACKEND-008: future evidence cannot masquerade as complete history.++ A current UTC slice still witnesses uncertain history when a timezone change+ leaves its old owner outside the local grid; same-zone fixtures missed this.+ """++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 24, 12, 15, tzinfo=timezone.utc)+ future = now.replace(minute=0) + timedelta(minutes=future_minute)+ counts = {+ "requests": 1, "token_reports": 1, "input_tokens": 10,+ "cached_input_tokens": 3, "output_tokens": 2,+ }+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(json.dumps([{+ "day": owner_day, "source_id": "src_future", "model_id": "model-x",+ **counts,+ "last_metered_at": future.isoformat(),+ "hourly_history_complete": True,+ "hours": [{+ "key": future.replace(minute=0).isoformat(), **counts,+ "last_metered_at": future.isoformat(),+ }],+ }]), encoding="utf-8")+ before = ledger.path.read_bytes()+ report = ledger.report(window="24h", now=now)+ assert ledger.path.read_bytes() == before+ assert report["totals"]["requests"] == 0+ if owner_day == "2026-09-24":+ assert all(+ bucket["history_complete"] == (bucket["start_at"][:10] != owner_day)+ for bucket in report["buckets"]+ )+ assert ledger.summary(days=1, now=now)["totals"] == counts+ else:+ assert all(not bucket["history_complete"] for bucket in report["buckets"])+ assert ledger.summary(days=1, now=now)["totals"]["requests"] == 0++ # A real call triggers persistence; read and write use the same policy.+ ledger.record(+ source_id="src_real", model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=5), at=now,+ )+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ assert report["totals"]["requests"] == 1+ assert report["totals"]["input_tokens"] == 5+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ assert ledger.summary(days=1, now=now)["totals"]["requests"] == (+ 2 if owner_day == "2026-09-24" else 1+ )+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()+++def test_legacy_daily_rows_are_preserved_but_never_allocated_to_an_hour(+ tmp_path: Path,+) -> None:+ """MH-USAGE-BACKEND-003: released daily-only rows stay daily-only."""++ ledger = _ledger(tmp_path)+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_legacy",+ "model_id": "model-legacy",+ "requests": 2,+ "token_reports": 2,+ "input_tokens": 10,+ "cached_input_tokens": 3,+ "output_tokens": 4,+ "last_metered_at": NOW.isoformat(),+ }+ ]+ ),+ encoding="utf-8",+ )++ hourly = ledger.report(window="24h", now=NOW)+ daily = ledger.report(window="7d", now=NOW)++ assert hourly["totals"]["requests"] == 0+ assert all(not bucket["rows"] for bucket in hourly["buckets"])+ assert any(not bucket["history_complete"] for bucket in hourly["buckets"])+ assert daily["totals"]["requests"] == 2+ assert daily["totals"]["input_tokens"] == 10+ assert all(bucket["history_complete"] for bucket in daily["buckets"])++[email protected]("requests", [0, 2])[email protected]("history_shape", ["retained", "expired", "legacy"])+def test_tokens_without_reports_never_become_complete_empty_hourly_history(+ tmp_path: Path, requests: int, history_shape: str,+) -> None:+ """Invalid counter relationships preserve daily counts but not hourly certainty."""++ now = NOW + timedelta(minutes=15)+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ counts = {+ "requests": requests, "token_reports": 0,+ "input_tokens": 7, "cached_input_tokens": 1, "output_tokens": 3,+ }+ start = now.replace(minute=0, second=0, microsecond=0)+ damaged = {+ "day": local_usage_day(now).isoformat(),+ "source_id": "src_corrupt", "model_id": "model-corrupt",+ **counts, "last_metered_at": now.isoformat(),+ }+ if history_shape != "legacy":+ damaged.update({+ "hours": (+ [{"key": start.isoformat(), **counts, "last_metered_at": now.isoformat()}]+ if history_shape == "retained" else []+ ),+ "hourly_expired_totals": counts if history_shape == "expired" else {key: 0 for key in counts},+ "hourly_expired_before": (start - timedelta(hours=24)).isoformat(),+ "hourly_history_complete": True,+ })+ ledger.path.write_text(json.dumps([damaged]), encoding="utf-8")++ hourly = ledger.report(window="24h", now=now)+ assert not hourly["buckets"][-1]["history_complete"]+ assert hourly["totals"]["input_tokens"] == 0+ assert ledger.summary(days=1, now=now)["totals"]["input_tokens"] == 7++ ledger.record(+ source_id="src_corrupt", model_id="model-corrupt",+ usage=ProtocolUsageReport(input_tokens=2, output_tokens=1),+ at=now,+ )+ reopened = _ledger(tmp_path).report(window="24h", now=now)+ assert not reopened["buckets"][-1]["history_complete"]+ assert reopened["totals"]["input_tokens"] == 2+ assert ledger.summary(days=1, now=now)["totals"]["input_tokens"] == 9+++def test_corrupt_nested_hours_are_deduplicated_bounded_and_marked_unavailable(+ tmp_path: Path,+) -> None:+ """MH-USAGE-BACKEND-004: corrupt nested slices cannot overstate usage."""++ ledger = _ledger(tmp_path)+ ledger.path.parent.mkdir(parents=True)+ key = NOW.astimezone().replace(minute=0, second=0, microsecond=0).isoformat()+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_corrupt",+ "model_id": "model-corrupt",+ "requests": 2,+ "token_reports": 2,+ "input_tokens": 10,+ "cached_input_tokens": 0,+ "output_tokens": 2,+ "last_metered_at": NOW.isoformat(),+ "hourly_history_complete": True,+ "hours": [+ {+ "key": key,+ "requests": 2,+ "token_reports": 2,+ "input_tokens": 9,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ },+ {+ "key": key,+ "requests": 2,+ "token_reports": 2,+ "input_tokens": 9,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ },+ ],+ }+ ]+ ),+ encoding="utf-8",+ )++ report = ledger.report(window="24h", now=NOW)++ assert report["totals"]["requests"] == 0+ assert all(not bucket["rows"] for bucket in report["buckets"])+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ assert ledger.summary(days=1, now=NOW)["totals"]["requests"] == 2+++ "hours",+ [+ [{"key": "2026-07-23T12:00", "requests": 1}],+ [+ {+ "key": "2026-07-23T12:00+00:00",+ "requests": 1,+ "token_reports": "one",+ "input_tokens": 4,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }+ ],+ [+ {+ "key": "2026-07-23T12:00+00:00",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 4,+ "cached_input_tokens": 5,+ "output_tokens": 1,+ }+ ],+ ],+)+def test_malformed_nested_hours_are_unavailable_without_inventing_usage(+ tmp_path: Path,+ hours: list[dict],+) -> None:+ ledger = _ledger(tmp_path)+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": local_usage_day(NOW).isoformat(),+ "source_id": "src_corrupt",+ "model_id": "model-corrupt",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 4,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ "last_metered_at": NOW.isoformat(),+ "hourly_history_complete": True,+ "hours": hours,+ }+ ]+ ),+ encoding="utf-8",+ )++ report = ledger.report(window="24h", now=NOW)++ assert report["totals"]["requests"] == 0+ assert all(not bucket["rows"] for bucket in report["buckets"])+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ assert ledger.summary(days=1, now=NOW)["totals"]["requests"] == 1+++def test_recent_usage_without_its_hour_cannot_claim_complete_hourly_history(+ tmp_path: Path,+) -> None:+ """A complete flag is insufficient when the latest metered hour is absent."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 24, 12, 15, tzinfo=timezone.utc)+ counts = {+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 4,+ "cached_input_tokens": 1,+ "output_tokens": 2,+ }+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": "2026-09-24",+ "source_id": "src_missing_hour",+ "model_id": "model-missing-hour",+ **counts,+ "last_metered_at": (now - timedelta(minutes=30)).isoformat(),+ "hourly_history_complete": True,+ "hours": [],+ }+ ]+ ),+ encoding="utf-8",+ )++ report = ledger.report(window="24h", now=now)++ assert report["totals"]["requests"] == 0+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ assert ledger.summary(days=1, now=now)["totals"] == counts+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()+++def test_missing_in_horizon_hour_cannot_be_hidden_by_a_present_latest_hour(+ tmp_path: Path,+) -> None:+ """A present latest slice does not prove earlier same-day slices exist."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 24, 12, 15, tzinfo=timezone.utc)+ counts = {+ "requests": 2,+ "token_reports": 2,+ "input_tokens": 8,+ "cached_input_tokens": 2,+ "output_tokens": 4,+ }+ latest = now - timedelta(minutes=30)+ latest_key = latest.replace(minute=0, second=0, microsecond=0)+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": "2026-09-24",+ "source_id": "src_missing_earlier",+ "model_id": "model-missing-earlier",+ **counts,+ "last_metered_at": latest.isoformat(),+ "hourly_history_complete": True,+ "hours": [+ {+ "key": latest_key.isoformat(),+ **{**counts, "requests": 1, "token_reports": 1,+ "input_tokens": 4, "cached_input_tokens": 1,+ "output_tokens": 2},+ "last_metered_at": latest.isoformat(),+ }+ ],+ }+ ]+ ),+ encoding="utf-8",+ )++ report = ledger.report(window="24h", now=now)++ assert report["totals"]["requests"] == 1+ assert any(+ row["requests"] == 1+ for bucket in report["buckets"]+ for row in bucket["rows"]+ )+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ assert ledger.summary(days=1, now=now)["totals"] == counts+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()+++def test_daily_midnight_uses_the_date_specific_local_offset() -> None:+ from core.handlers.model_hub.usage import _local_midnight++ previous_tz = os.environ.get("TZ")+ try:+ os.environ["TZ"] = "America/New_York"+ time.tzset()+ winter = _local_midnight(date(2026, 1, 15))+ summer = _local_midnight(date(2026, 7, 15))+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert winter.utcoffset() != summer.utcoffset()+++def test_hourly_retention_expiry_does_not_poison_retained_hours(tmp_path: Path) -> None:+ """Expired slices outside the report horizon are not missing history."""++ previous_tz = os.environ.get("TZ")+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(NOW))+ ledger.record(+ source_id="src_expiry",+ model_id="model-expiry",+ usage=ProtocolUsageReport(input_tokens=25),+ at=NOW - timedelta(hours=25),+ )+ ledger.record(+ source_id="src_expiry",+ model_id="model-expiry",+ usage=ProtocolUsageReport(input_tokens=23),+ at=NOW - timedelta(hours=23),+ )+ hourly = ledger.report(window="24h", now=NOW)+ daily = ledger.report(window="7d", now=NOW)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert hourly["totals"]["requests"] == 1+ assert hourly["totals"]["input_tokens"] == 23+ assert all(bucket["history_complete"] for bucket in hourly["buckets"])+ assert daily["totals"]["requests"] == 2+ assert daily["totals"]["input_tokens"] == 48+++def test_partial_oldest_day_reconciles_expired_and_retained_hours(+ tmp_path: Path,+) -> None:+ """A missing in-horizon slice cannot hide behind expired daily usage."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 23, 18, 30, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Asia/Kathmandu"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps(+ [+ {+ "day": "2026-09-23",+ "source_id": "src_partial-oldest",+ "model_id": "model-partial-oldest",+ "requests": 3,+ "token_reports": 3,+ "input_tokens": 30,+ "cached_input_tokens": 0,+ "output_tokens": 3,+ "last_metered_at": "2026-09-23T17:20:00+00:00",+ "hourly_history_complete": True,+ "hourly_expired_totals": {+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 10,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ },+ "hours": [+ {+ "key": "2026-09-23T17:00:00+00:00",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 10,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ "last_metered_at": "2026-09-23T17:20:00+00:00",+ }+ ],+ }+ ]+ ),+ encoding="utf-8",+ )+ report = ledger.report(window="24h", now=now)+ daily = ledger.summary(days=2, now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 1+ assert daily["totals"]["requests"] == 3+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+++def test_hourly_boundaries_match_across_lord_howe_dst_transition(tmp_path: Path) -> None:+ """Hourly identity stays UTC-stable while Lord Howe displays a 30-minute jump."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 10, 4, 3, 15, tzinfo=timezone.utc)+ at = datetime(2026, 10, 3, 14, 45, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Australia/Lord_Howe"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.record(+ source_id="src_lord-howe",+ model_id="model-dst",+ usage=ProtocolUsageReport(input_tokens=1),+ at=at,+ )+ hourly = ledger.report(window="24h", now=now)+ daily = ledger.report(window="7d", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ populated = [bucket for bucket in hourly["buckets"] if bucket["rows"]]+ transition = next(+ bucket+ for bucket in hourly["buckets"]+ if bucket["start_at"] == "2026-10-04T01:30:00+10:30"+ )+ assert len(populated) == 1+ assert populated[0]["start_at"] == "2026-10-04T00:30:00+10:30"+ assert populated[0]["end_at"] == "2026-10-04T01:30:00+10:30"+ assert transition["end_at"] == "2026-10-04T03:00:00+11:00"+ assert hourly["totals"]["requests"] == 1+ assert daily["totals"]["requests"] == 1+ assert all(bucket["history_complete"] for bucket in hourly["buckets"])+++def test_hourly_boundaries_display_non_dst_fractional_offset(tmp_path: Path) -> None:+ """UTC-hour identity remains stable in a non-DST fractional-offset zone."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 24, 12, 30, tzinfo=timezone.utc)+ at = datetime(2026, 9, 24, 11, 45, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Asia/Kathmandu"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.record(+ source_id="src-kathmandu",+ model_id="model-fractional",+ usage=ProtocolUsageReport(input_tokens=1),+ at=at,+ )+ hourly = ledger.report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ populated = [bucket for bucket in hourly["buckets"] if bucket["rows"]]+ assert len(populated) == 1+ assert populated[0]["start_at"] == "2026-09-24T16:45:00+05:45"+ assert populated[0]["end_at"] == "2026-09-24T17:45:00+05:45"+ assert hourly["totals"]["requests"] == 1+ assert all(bucket["history_complete"] for bucket in hourly["buckets"])+++def test_hourly_report_uses_utc_evidence_after_a_timezone_change(+ tmp_path: Path,+) -> None:+ """A stored hour remains reportable when the host timezone changes."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Pacific/Kiritimati"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.record(+ source_id="src-timezone-change",+ model_id="model-timezone-change",+ usage=ProtocolUsageReport(input_tokens=7),+ at=now - timedelta(hours=6),+ )++ os.environ["TZ"] = "Pacific/Honolulu"+ time.tzset()+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 1+ assert report["totals"]["input_tokens"] == 7+ [populated] = [bucket for bucket in report["buckets"] if bucket["rows"]]+ assert populated["rows"][0]["source_id"] == "src-timezone-change"+ assert all(bucket["history_complete"] for bucket in report["buckets"])+++ ("old_zone", "new_zone"),+ [+ ("Pacific/Kiritimati", "Pacific/Honolulu"),+ ("Pacific/Honolulu", "Pacific/Kiritimati"),+ ],+)[email protected]("daily_only", [False, True])[email protected]("max_rows", [1, 4])+def test_timezone_change_preserves_recent_owners_across_a_write(+ tmp_path: Path, old_zone: str, new_zone: str, daily_only: bool, max_rows: int,+) -> None:+ """Recent UTC evidence survives writes at either local retention edge.++ Read-only timezone coverage missed the subsequent write deleting its owner.+ Released daily-only owners must also survive without inventing hourly counts.+ At capacity, an old owner label must not evict a more recently metered call.+ """++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = old_zone+ time.tzset()+ ledger = _ledger(tmp_path, retention_days=1, max_rows=max_rows, now=_Clock(now))+ ledger.record(+ source_id="src_old-zone", model_id="模型-β",+ usage=ProtocolUsageReport(input_tokens=7), at=now - timedelta(hours=6),+ )+ original = json.loads(ledger.path.read_text(encoding="utf-8"))[0]+ if daily_only:+ original = {+ key: value for key, value in original.items()+ if key != "hours" and not key.startswith("hourly_")+ }+ ledger.path.write_text(json.dumps([original]), encoding="utf-8")++ os.environ["TZ"] = new_zone+ time.tzset()+ reopened = _ledger(tmp_path, retention_days=1, max_rows=max_rows, now=_Clock(now))+ reopened.record(+ source_id="src_new-zone", model_id="模型-β",+ usage=ProtocolUsageReport(input_tokens=11), at=now,+ )+ persisted = json.loads(ledger.path.read_text(encoding="utf-8"))+ hourly = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ bounded_hourly = _ledger(tmp_path, max_rows=1, now=_Clock(now)).report(+ window="24h", now=now,+ )+ daily = reopened.summary(days=1, now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert daily["totals"]["input_tokens"] == 11+ assert bounded_hourly["totals"]["input_tokens"] == 11+ if max_rows == 1:+ assert [item["source_id"] for item in persisted] == ["src_new-zone"]+ assert hourly["totals"]["requests"] == 1+ assert hourly["totals"]["input_tokens"] == 11+ return+ old = next(item for item in persisted if item["source_id"] == "src_old-zone")+ assert old["day"] == original["day"]+ assert old["input_tokens"] == 7+ assert hourly["totals"]["requests"] == (1 if daily_only else 2)+ assert hourly["totals"]["input_tokens"] == (11 if daily_only else 18)+ if not daily_only:+ assert all(item["history_complete"] for item in hourly["buckets"])+ else:+ assert any(not item["history_complete"] for item in hourly["buckets"])++[email protected]("new_zone", ["UTC", "Pacific/Honolulu", "Asia/Kathmandu"])+def test_legacy_latest_hour_remains_uncertain_after_timezone_change(+ tmp_path: Path, new_zone: str,+) -> None:+ """Local-owner overlap cannot erase uncertainty at the actual UTC call.++ The previous no-overlap test missed owners overlapping only later buckets.+ """++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ latest = datetime(2026, 9, 24, 12, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = new_zone+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps([{+ "day": "2026-09-25", "source_id": "src_legacy", "model_id": "model",+ "requests": 2, "token_reports": 2, "input_tokens": 7,+ "cached_input_tokens": 0, "output_tokens": 0,+ "last_metered_at": latest.isoformat(),+ }]),+ encoding="utf-8",+ )+ report = ledger.report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 0+ [affected] = [+ bucket for bucket in report["buckets"]+ if datetime.fromisoformat(bucket["start_at"]) <= latest+ < datetime.fromisoformat(bucket["end_at"])+ ]+ assert affected["history_complete"] is False+ # Without the original zone, the other daily call cannot be placed either.+ assert all(not bucket["history_complete"] for bucket in report["buckets"])++[email protected]("rewrite", [False, True])+def test_pruned_hours_do_not_become_complete_zero_after_clock_rollback(+ tmp_path: Path, rewrite: bool,+) -> None:+ """A previously pruned hour can re-enter the horizon without its counters.++ Forward-only retention tests never queried behind the persisted expiry bound.+ """++ previous_tz = os.environ.get("TZ")+ clock = _Clock(datetime(2026, 9, 24, 17, 30, tzinfo=timezone.utc))+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ ledger = _ledger(tmp_path, now=clock)+ for hour in (12, 16):+ ledger.record(+ source_id="src_rollback", model_id="model",+ usage=ProtocolUsageReport(input_tokens=7),+ at=clock.moment.replace(hour=hour),+ )+ clock.moment = datetime(2026, 9, 25, 13, 30, tzinfo=timezone.utc)+ ledger.record(source_id="src_other", model_id="model", usage=None, at=clock.moment)+ forward = ledger.report(window="24h", now=clock.moment)+ assert all(bucket["history_complete"] for bucket in forward["buckets"])+ clock.moment -= timedelta(hours=2)+ if rewrite:+ ledger.record(source_id="src_new", model_id="model", usage=None, at=clock.moment)+ report = _ledger(tmp_path, now=clock).report(window="24h", now=clock.moment)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ [expired_bucket] = [+ bucket for bucket in report["buckets"]+ if bucket["start_at"] == "2026-09-24T12:00:00+00:00"+ ]+ assert expired_bucket["rows"] == []+ assert expired_bucket["history_complete"] is False++[email protected]("boundary", [None, "invalid", "2026-09-24T12:30:00Z"])+def test_undated_expired_totals_cannot_claim_complete_hourly_history(+ tmp_path: Path, boundary: str | None,+) -> None:+ """Older or damaged expiry metadata cannot prove which hours were removed.++ Counter-only reconciliation missed an undated expired contribution, including+ when a valid duplicate is merged onto it during a subsequent write.+ """++ now = datetime(2026, 9, 25, 13, 30, tzinfo=timezone.utc)+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.record(+ source_id="src_expiry", model_id="model",+ usage=ProtocolUsageReport(input_tokens=7), at=now - timedelta(hours=1),+ )+ [recent] = json.loads(ledger.path.read_text(encoding="utf-8"))+ expired = {+ **recent,+ "hours": [],+ "hourly_expired_totals": {+ key: recent[key] for key in (+ "requests", "token_reports", "input_tokens",+ "cached_input_tokens", "output_tokens",+ )+ },+ "hourly_expired_before": boundary,+ "last_metered_at": (now - timedelta(hours=25)).isoformat(),+ }+ ledger.path.write_text(json.dumps([expired, recent]), encoding="utf-8")+ before = ledger.report(window="24h", now=now)+ ledger.record(+ source_id="src_expiry", model_id="model",+ usage=ProtocolUsageReport(input_tokens=3), at=now,+ )+ after = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)++ assert before["totals"]["input_tokens"] == 7+ assert after["totals"]["input_tokens"] == 10+ assert ledger.summary(days=7, now=now)["totals"]["input_tokens"] == 17+ assert any(not bucket["history_complete"] for bucket in before["buckets"])+ assert any(not bucket["history_complete"] for bucket in after["buckets"])+++def test_hourly_report_preserves_uncertainty_for_timezone_orphaned_daily_rows(+ tmp_path: Path,+) -> None:+ """A daily-only row outside the new local day cannot claim empty hours."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Pacific/Kiritimati"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps([{+ "day": "2026-09-25",+ "source_id": "src-timezone-orphan",+ "model_id": "model-timezone-orphan",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ "last_metered_at": "2026-09-24T23:30:00+00:00",+ }]),+ encoding="utf-8",+ )++ os.environ["TZ"] = "Pacific/Honolulu"+ time.tzset()+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 0+ assert all(not bucket["history_complete"] for bucket in report["buckets"])+++ ("old_zone", "new_zone"),+ [+ ("Pacific/Kiritimati", "Pacific/Honolulu"),+ ("Pacific/Honolulu", "Pacific/Kiritimati"),+ ],+)[email protected]("timestamp", [None, "not-an-instant"])[email protected]("overlap", [False, True])+def test_timestampless_owner_days_use_a_conservative_utc_envelope(+ tmp_path: Path,+ old_zone: str,+ new_zone: str,+ timestamp: str | None,+ overlap: bool,+) -> None:+ """Unknown owner dates are selected only when their UTC envelope can overlap."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = old_zone+ time.tzset()+ owner_day = local_usage_day(now)+ if not overlap:+ owner_day -= timedelta(days=3)+ row = {+ "day": owner_day.isoformat(),+ "source_id": "src-unknown-time",+ "model_id": "model-unknown-time",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }+ if timestamp is not None:+ row["last_metered_at"] = timestamp+ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps([row]), encoding="utf-8")++ os.environ["TZ"] = new_zone+ time.tzset()+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 0+ if overlap:+ assert any(not bucket["history_complete"] for bucket in report["buckets"])+ else:+ assert all(bucket["history_complete"] for bucket in report["buckets"])+++ ("old_zone", "new_zone"),+ [+ ("Pacific/Kiritimati", "Pacific/Honolulu"),+ ("Pacific/Honolulu", "Pacific/Kiritimati"),+ ],+)[email protected]("timestamp", [None, "not-an-instant"])[email protected]("max_rows", [1, 4])+def test_timestampless_owner_survives_write_and_capacity_ranking(+ tmp_path: Path,+ old_zone: str,+ new_zone: str,+ timestamp: str | None,+ max_rows: int,+) -> None:+ """The shared envelope keeps unknown owners without outranking known calls."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = old_zone+ time.tzset()+ owner_day = local_usage_day(now)+ row = {+ "day": owner_day.isoformat(),+ "source_id": "src-old-zone",+ "model_id": "model-old-zone",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }+ if timestamp is not None:+ row["last_metered_at"] = timestamp+ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps([row]), encoding="utf-8")++ os.environ["TZ"] = new_zone+ time.tzset()+ ledger = _ledger(+ tmp_path,+ retention_days=1,+ max_rows=max_rows,+ now=_Clock(now),+ )+ ledger.record(+ source_id="src-new-zone",+ model_id="model-new-zone",+ usage=ProtocolUsageReport(input_tokens=11),+ at=now,+ )+ persisted = json.loads(path.read_text(encoding="utf-8"))+ hourly = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert any(row["source_id"] == "src-new-zone" for row in persisted)+ if max_rows == 1:+ assert [row["source_id"] for row in persisted] == ["src-new-zone"]+ assert all(not bucket["history_complete"] for bucket in hourly["buckets"])+ else:+ assert {row["source_id"] for row in persisted} == {+ "src-old-zone", "src-new-zone",+ }+ assert any(not bucket["history_complete"] for bucket in hourly["buckets"])+++ ("old_zone", "new_zone"),+ [+ ("Pacific/Kiritimati", "Pacific/Honolulu"),+ ("Pacific/Honolulu", "Pacific/Kiritimati"),+ ],+)[email protected]("timestamp", [None, "not-an-instant"])+def test_timestampless_owner_outside_the_envelope_expires_on_write(+ tmp_path: Path,+ old_zone: str,+ new_zone: str,+ timestamp: str | None,+) -> None:+ """An unknown owner day outside the hourly envelope still expires normally."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = old_zone+ time.tzset()+ owner_day = local_usage_day(now) - timedelta(days=3)+ row = {+ "day": owner_day.isoformat(),+ "source_id": "src-expired-unknown-time",+ "model_id": "model-expired-unknown-time",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }+ if timestamp is not None:+ row["last_metered_at"] = timestamp+ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps([row]), encoding="utf-8")++ os.environ["TZ"] = new_zone+ time.tzset()+ ledger = _ledger(tmp_path, retention_days=1, now=_Clock(now))+ ledger.record(+ source_id="src-new-zone",+ model_id="model-new-zone",+ usage=ProtocolUsageReport(input_tokens=11),+ at=now,+ )+ persisted = json.loads(path.read_text(encoding="utf-8"))+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert [row["source_id"] for row in persisted] == ["src-new-zone"]++[email protected]("timestamp", [None, "not-an-instant"])+def test_same_identity_merge_preserves_date_only_hourly_uncertainty(+ tmp_path: Path, timestamp: str | None,+) -> None:+ """A fresh call cannot turn an earlier timestamp-less owner into certainty."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ row = {+ "day": local_usage_day(now).isoformat(),+ "source_id": "src-merged",+ "model_id": "model-merged",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }+ if timestamp is not None:+ row["last_metered_at"] = timestamp+ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps([row]), encoding="utf-8")++ ledger = _ledger(tmp_path, now=_Clock(now))+ before = ledger.report(window="24h", now=now)+ before_incomplete = {+ bucket["start_at"]+ for bucket in before["buckets"]+ if not bucket["history_complete"]+ }+ ledger.record(+ source_id="src-merged",+ model_id="model-merged",+ usage=ProtocolUsageReport(input_tokens=3),+ at=now,+ )+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ daily = ledger.summary(days=1, now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["input_tokens"] == 3+ after_incomplete = {+ bucket["start_at"]+ for bucket in report["buckets"]+ if not bucket["history_complete"]+ }+ assert after_incomplete == before_incomplete+ assert daily["totals"]["input_tokens"] == 10+++def test_delayed_exact_merge_does_not_age_out_legacy_hourly_uncertainty(+ tmp_path: Path,+) -> None:+ """A delayed exact call cannot narrow legacy mass at a later report time."""++ previous_tz = os.environ.get("TZ")+ write_now = datetime(2026, 9, 25, 22, 15, tzinfo=timezone.utc)+ captured_at = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ report_now = datetime(2026, 9, 26, 1, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps([{+ "day": "2026-09-25",+ "source_id": "src-delayed-merge",+ "model_id": "model-delayed-merge",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }]), encoding="utf-8")++ ledger = _ledger(tmp_path, now=_Clock(write_now))+ before = ledger.report(window="24h", now=report_now)+ before_incomplete = {+ bucket["start_at"]+ for bucket in before["buckets"]+ if not bucket["history_complete"]+ }+ ledger.record(+ source_id="src-delayed-merge",+ model_id="model-delayed-merge",+ usage=ProtocolUsageReport(input_tokens=3),+ at=captured_at,+ )+ after = _ledger(tmp_path, now=_Clock(report_now)).report(+ window="24h",+ now=report_now,+ )+ daily = ledger.summary(days=2, now=report_now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ after_incomplete = {+ bucket["start_at"]+ for bucket in after["buckets"]+ if not bucket["history_complete"]+ }+ assert len(before_incomplete) == 24+ assert after_incomplete == before_incomplete+ assert after["totals"]["input_tokens"] == 0+ assert daily["totals"]["input_tokens"] == 10++[email protected]("unknown_first", [False, True])+def test_duplicate_known_and_date_only_rows_preserve_hourly_uncertainty(+ tmp_path: Path, unknown_first: bool,+) -> None:+ """Duplicate-row coalescing cannot make unknown historical mass certain."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ owner_day = local_usage_day(now).isoformat()+ unknown = {+ "day": owner_day,+ "source_id": "src-duplicate-uncertainty",+ "model_id": "model-duplicate-uncertainty",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ }+ known = {+ **unknown,+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 3,+ "last_metered_at": now.isoformat(),+ "hours": [{+ "key": now.replace(minute=0, second=0, microsecond=0).isoformat(),+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 3,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ "last_metered_at": now.isoformat(),+ }],+ "hourly_expired_totals": {+ "requests": 0,+ "token_reports": 0,+ "input_tokens": 0,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ },+ "hourly_history_complete": True,+ }+ path = tmp_path / "state" / "usage.json"+ path.parent.mkdir(parents=True)+ rows = [unknown, known] if unknown_first else [known, unknown]+ path.write_text(json.dumps(rows), encoding="utf-8")++ ledger = _ledger(tmp_path, now=_Clock(now))+ report = ledger.report(window="24h", now=now)+ incomplete = {+ bucket["start_at"]+ for bucket in report["buckets"]+ if not bucket["history_complete"]+ }++ assert len(incomplete) == 15+ assert report["totals"]["input_tokens"] == 3+ assert ledger.summary(days=1, now=now)["totals"]["input_tokens"] == 10+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++[email protected]("owner_day", [date.min, date.max])+def test_timestampless_owner_day_extremes_do_not_overflow(+ tmp_path: Path, owner_day: date,+) -> None:+ """Envelope construction degrades safely at both representable date edges."""++ previous_tz = os.environ.get("TZ")+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps([{+ "day": owner_day.isoformat(),+ "source_id": "src-extreme",+ "model_id": "model-extreme",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 1,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ }]),+ encoding="utf-8",+ )++ report = ledger.report(window="24h", now=now)+ ledger.record(+ source_id="src-new",+ model_id="model-new",+ usage=ProtocolUsageReport(input_tokens=2),+ at=now,+ )+ daily = ledger.summary(days=1, now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 0+ assert daily["totals"]["requests"] == 1+++def test_timezone_orphaned_hourly_rows_reconcile_against_utc_slices(+ tmp_path: Path,+) -> None:+ """A local-day owner outside the current grid cannot hide a missing hour."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 0, 15, tzinfo=timezone.utc)+ counts = {+ "requests": 2,+ "token_reports": 2,+ "input_tokens": 20,+ "cached_input_tokens": 0,+ "output_tokens": 2,+ }+ try:+ os.environ["TZ"] = "Pacific/Kiritimati"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(+ json.dumps([{+ "day": "2026-09-25",+ "source_id": "src-timezone-orphan-hourly",+ "model_id": "model-timezone-orphan-hourly",+ **counts,+ "last_metered_at": "2026-09-24T23:15:00+00:00",+ "hourly_history_complete": True,+ "hourly_expired_totals": {+ "requests": 0,+ "token_reports": 0,+ "input_tokens": 0,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ },+ "hours": [{+ "key": "2026-09-24T23:00:00+00:00",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 10,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ "last_metered_at": "2026-09-24T23:15:00+00:00",+ }],+ }]),+ encoding="utf-8",+ )++ os.environ["TZ"] = "Pacific/Honolulu"+ time.tzset()+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 1+ assert all(not bucket["history_complete"] for bucket in report["buckets"])+++ ("zone", "now", "calls", "from_day", "to_day", "window_days"),+ [+ (+ "Asia/Kathmandu",+ datetime(2026, 9, 23, 18, 30, tzinfo=timezone.utc),+ (+ datetime(2026, 9, 23, 18, 14, tzinfo=timezone.utc),+ datetime(2026, 9, 23, 18, 20, tzinfo=timezone.utc),+ ),+ "2026-09-23", "2026-09-24", 2,+ ),+ (+ "Pacific/Chatham",+ datetime(2026, 9, 27, 10, 30, tzinfo=timezone.utc),+ (+ datetime(2026, 9, 26, 11, 5, tzinfo=timezone.utc),+ datetime(2026, 9, 26, 11, 20, tzinfo=timezone.utc),+ ),+ "2026-09-26", "2026-09-28", 3,+ ),+ ],+)+def test_hourly_report_joins_every_local_day_owner_across_midnight(+ tmp_path: Path,+ zone: str,+ now: datetime,+ calls: tuple[datetime, datetime],+ from_day: str,+ to_day: str,+ window_days: int,+) -> None:+ """MH-USAGE-BACKEND-006: one hour joins all daily owners across midnight/DST."""++ previous_tz = os.environ.get("TZ")+ try:+ os.environ["TZ"] = zone+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ for at in calls:+ ledger.record(+ source_id="src_midnight",+ model_id="model-midnight",+ usage=ProtocolUsageReport(input_tokens=10, cached_input_tokens=3, output_tokens=2),+ at=at,+ )+ # A fresh reader exercises the persisted keys, not an in-memory projection.+ report = _ledger(tmp_path, now=_Clock(now)).report(window="24h", now=now)+ daily = ledger.summary(days=7, now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"] == daily["totals"]+ assert report["totals"]["requests"] == 2+ assert report["totals"]["input_tokens"] == 20+ assert report["from_day"] == from_day+ assert report["to_day"] == to_day+ assert report["window_days"] == window_days+ assert len(report["buckets"]) == 24+ assert all(bucket["history_complete"] for bucket in report["buckets"])+ [populated] = [bucket for bucket in report["buckets"] if bucket["rows"]]+ assert len(populated["rows"]) == 1+ assert populated["rows"][0]["requests"] == 2+ assert sum(day["requests"] for day in report["days"]) == 2+ for before, after in zip(report["buckets"], report["buckets"][1:]):+ assert before["end_at"] == after["start_at"]+++def test_legacy_usage_after_local_midnight_marks_the_overlapping_hour_incomplete(+ tmp_path: Path,+) -> None:+ """Missing history belongs to every overlapping hour, not just its start date."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 23, 18, 30, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Asia/Kathmandu"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(json.dumps([{+ "day": "2026-09-24",+ "source_id": "src_legacy",+ "model_id": "model-legacy",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 10,+ "cached_input_tokens": 0,+ "output_tokens": 2,+ "last_metered_at": now.isoformat(),+ }]), encoding="utf-8")+ report = ledger.report(window="24h", now=now)+ daily = ledger.summary(days=1, now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 0+ assert daily["totals"]["requests"] == 1+ [incomplete] = [+ bucket for bucket in report["buckets"] if not bucket["history_complete"]+ ]+ assert incomplete["start_at"] == "2026-09-23T23:45:00+05:45"+ assert incomplete["end_at"] == "2026-09-24T00:15:00+05:45"+++def test_expired_legacy_rows_do_not_reenter_hourly_history_after_timezone_change(+ tmp_path: Path,+) -> None:+ """A stale instant must win over a new host-zone day fallback."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)+ try:+ os.environ["TZ"] = "Pacific/Honolulu"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(json.dumps([{+ "day": "2026-09-25",+ "source_id": "src-expired-legacy",+ "model_id": "model-expired-legacy",+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ "last_metered_at": "2026-09-24T10:00:00+00:00",+ }]), encoding="utf-8")++ report = ledger.report(window="24h", now=now)+ daily = ledger.report(window="7d", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 0+ assert all(bucket["history_complete"] for bucket in report["buckets"])+ assert daily["totals"]["requests"] == 1+++def test_recent_hourly_evidence_survives_a_stale_daily_timestamp(+ tmp_path: Path,+) -> None:+ """A valid UTC slice remains authoritative when the daily recency is stale."""++ previous_tz = os.environ.get("TZ")+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)+ counts = {+ "requests": 1,+ "token_reports": 1,+ "input_tokens": 7,+ "cached_input_tokens": 0,+ "output_tokens": 1,+ }+ try:+ os.environ["TZ"] = "Pacific/Honolulu"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(json.dumps([{+ "day": "2026-09-25",+ "source_id": "src-recent-hour",+ "model_id": "model-recent-hour",+ **counts,+ "last_metered_at": "2026-09-24T10:00:00+00:00",+ "hourly_history_complete": True,+ "hourly_expired_totals": {+ "requests": 0,+ "token_reports": 0,+ "input_tokens": 0,+ "cached_input_tokens": 0,+ "output_tokens": 0,+ },+ "hours": [{+ "key": "2026-09-25T11:00:00+00:00",+ **counts,+ "last_metered_at": "2026-09-25T11:15:00+00:00",+ }],+ }]), encoding="utf-8")++ report = ledger.report(window="24h", now=now)+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++ assert report["totals"]["requests"] == 1+ assert report["totals"]["input_tokens"] == 7+ assert all(bucket["history_complete"] for bucket in report["buckets"])+++ "content",+ [+ pytest.param("not json", id="unreadable"),+ pytest.param('{"rows": []}', id="not-a-list"),+ pytest.param('[{"day": "not-a-day"}]', id="unusable-row"),+ ],+)+def test_degraded_ledger_history_is_not_published_as_complete_zero(+ tmp_path: Path,+ content: str,+) -> None:+ """A read failure makes the affected modern report buckets uncertain."""++ ledger = _ledger(tmp_path)+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text(content, encoding="utf-8")++ daily = ledger.report(window="7d", now=NOW)+ hourly = ledger.report(window="24h", now=NOW)++ assert all(not bucket["history_complete"] for bucket in daily["buckets"])+ assert all(not bucket["history_complete"] for bucket in hourly["buckets"])+++def test_degraded_ledger_history_survives_a_followup_write(tmp_path: Path) -> None:+ """A later write cannot turn discarded history into a complete zero."""++ now = NOW+ ledger = _ledger(tmp_path, now=_Clock(now))+ ledger.path.parent.mkdir(parents=True)+ ledger.path.write_text("not json", encoding="utf-8")++ ledger.record(+ source_id="src_after-degraded-read",+ model_id="model-after-degraded-read",+ usage=ProtocolUsageReport(input_tokens=7),+ at=now,+ )++ fresh = _ledger(tmp_path, now=_Clock(now))+ daily = fresh.report(window="7d", now=now)+ hourly = fresh.report(window="24h", now=now)+ persisted = json.loads(fresh.path.read_text(encoding="utf-8"))++ assert daily["totals"]["requests"] == 1+ assert hourly["totals"]["requests"] == 1+ assert all(not bucket["history_complete"] for bucket in daily["buckets"])+ assert all(not bucket["history_complete"] for bucket in hourly["buckets"])+ assert all(row["history_degraded"] is True for row in persisted)++[email protected]("marked_first", [False, True])+def test_duplicate_rows_preserve_degradation_in_both_orders_and_after_write(+ tmp_path: Path, marked_first: bool,+) -> None:+ """Duplicate merge ORs the witness; single damaged-row tests miss its loss."""++ previous_tz = os.environ.get("TZ")+ try:+ os.environ["TZ"] = "UTC"+ time.tzset()+ ledger = _ledger(tmp_path, now=_Clock(NOW))+ ledger.record(+ source_id="src_a", model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=7), at=NOW,+ )+ [plain] = json.loads(ledger.path.read_text(encoding="utf-8"))+ marked = {**plain, "history_degraded": True}+ rows = [marked, plain] if marked_first else [plain, marked]+ ledger.path.write_text(json.dumps(rows), encoding="utf-8")++ for window in ("24h", "7d"):+ report = ledger.report(window=window, now=NOW)+ assert report["totals"]["input_tokens"] == 14+ assert all(not bucket["history_complete"] for bucket in report["buckets"])++ ledger.record(+ source_id="src_a", model_id="model-x",+ usage=ProtocolUsageReport(input_tokens=3), at=NOW,+ )+ fresh = _ledger(tmp_path, now=_Clock(NOW))+ for window in ("24h", "7d"):+ report = fresh.report(window=window, now=NOW)+ assert report["totals"]["input_tokens"] == 17+ assert all(not bucket["history_complete"] for bucket in report["buckets"])+ [persisted] = json.loads(fresh.path.read_text(encoding="utf-8"))+ assert persisted["history_degraded"] is True+ finally:+ if previous_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = previous_tz+ time.tzset()++def test_a_window_excludes_days_outside_it(tmp_path: Path) -> None:ledger = _ledger(tmp_path)diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex ae4439c83..1532adff6 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -487,6 +487,35 @@ def test_the_usage_read_is_served_natively_rather_than_from_a_compat_worker(monkassert asked == [7]+def test_the_usage_route_forwards_a_modern_window_and_rejects_selector_conflicts(monkeypatch):+ """MH-USAGE-BACKEND-005: the HTTP route preserves modern selector semantics."""++ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")+ asked: list[dict] = []++ class LedgerClient:+ async def usage_summary(self, **kwargs) -> dict:+ asked.append(kwargs)+ return {"window_key": kwargs["window"]}++ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: LedgerClient())++ for query in ("window=24h", "window=24h&window=24h"):+ modern = app.test_client().get(f"/api/models/usage?{query}")+ assert modern.status_code == 200+ assert modern.get_json()["usage"] == {"window_key": "24h"}+ for query in (+ "days=7&window=24h", "window=hour",+ "window=24h&window=7d", "window=7d&window=24h",+ "window=invalid&window=24h", "window=24h&window=invalid",+ "window=&window=24h", "window=24h&window=",+ ):+ rejected = app.test_client().get(f"/api/models/usage?{query}")+ assert rejected.status_code == 400, query+ assert rejected.get_json()["error"] == "invalid_parameter"+ assert asked == [{"window": "24h"}, {"window": "24h"}]++def test_scope_settings_routes_report_localized_stale_agent_binding_conflicts(monkeypatch):from core.services import settings as settings_servicefrom storage.settings_service import StaleScopeAgentBindingErrordiff --git a/ui/e2e/e-usage-logs.spec.ts b/ui/e2e/e-usage-logs.spec.tsindex 499fc7cbe..2e2df2989 100644--- a/ui/e2e/e-usage-logs.spec.ts+++ b/ui/e2e/e-usage-logs.spec.ts@@ -31,21 +31,18 @@ test.describe('E · usage and logs', () => {await expect(window).toBeVisible();await expect(window.getByRole('radio', { checked: true })).toHaveCount(1);- // Two honest shapes, and the tab has to say which it is. `count()` reads- // instantly, and the tab renders NEITHER shape while the read is in flight- // — so branching on it this early would classify a valid empty report as- // populated. Waiting on one shape or the other settles the read first.- const empty = page.getByText(copy('usage.empty'), { exact: true });- const populated = page.getByRole('heading', { name: copy('usage.bySource.title'), level: 3 });+ // Two honest shapes, and the tab has to say which it is. The report-specific+ // empty card is distinct from a loading state, while a populated report+ // carries both its chart and exact-count table.+ const empty = page.getByRole('heading', { name: copy('usage.empty.report.title'), level: 3 });+ const populated = page.getByRole('heading', { name: copy('usage.chart.title'), level: 3 });await expect(empty.or(populated)).toBeVisible();- if (await empty.count()) {+ if (await empty.isVisible()) {await expect(empty).toBeVisible();return;}- // Populated owes both breakdowns — a total with no attribution cannot be- // acted on.await expect(populated).toBeVisible();- await expect(page.getByRole('heading', { name: copy('usage.byDay.title'), level: 3 })).toBeVisible();+ await expect(page.getByRole('heading', { name: copy('usage.table.title'), level: 3 })).toBeVisible();});test('E1 · picking another window moves the selection and re-reads the range', async ({ hub, page }) => {@@ -57,18 +54,6 @@ test.describe('E · usage and logs', () => {const total = await options.count();test.skip(total < 2, 'This build offers a single usage window, so there is nothing to switch between.');- const note = page.locator('.model-hub-usage-note');- // The tab's own loading/unread copy IS the detail text, so a `before`- // captured mid-read is indistinguishable from a settled empty report — and- // the branch below would skip the only assertion that the selection moved- // the reading. Even a successfully loaded empty window renders a range, so- // waiting for one is waiting for the read to settle, not for data.- await expect(note).toContainText(/–|—|Nothing metered yet/, { timeout: 20_000 });- const before = (await note.innerText()).trim();- // Named, not matched on state: `getByRole('radio').and('[aria-checked=false]')`- // re-resolves on every assertion, so the moment the click lands it stops- // pointing at the option that was clicked and starts pointing at the next- // still-unchecked one — which is, correctly, still false.const checked = (await window.getByRole('radio', { checked: true }).innerText()).trim();const labels = (await options.allInnerTexts()).map((label) => label.trim());const targetLabel = labels.find((label) => label !== checked);@@ -82,17 +67,7 @@ test.describe('E · usage and logs', () => {// option without unchecking the first has stopped being a radio group.await expect(target).toHaveAttribute('aria-checked', 'true');await expect(window.getByRole('radio', { checked: true })).toHaveCount(1);-- // And the reading follows it. The wait above has already ruled out the- // loading text, so a `before` that still reads as the static explainer is a- // genuinely empty window: an instance that never metered a turn, where the- // range has nothing to restate. That is a state, not a pass by default, so- // it is named here instead of being swept into the assertion.- if (before !== copy('usage.detail')) {- await expect- .poll(async () => (await note.innerText()).trim(), { timeout: 15_000 })- .not.toBe(before);- }+ await expect(window.getByRole('radio', { checked: true })).toHaveText(targetLabel!);});test('E3 · the logs tab shows the switch history, or says there is none', async ({ hub, page }) => {diff --git a/ui/e2e/model-catalog/fixture.tsx b/ui/e2e/model-catalog/fixture.tsxindex 80a037f07..22a2aa6e7 100644--- a/ui/e2e/model-catalog/fixture.tsx+++ b/ui/e2e/model-catalog/fixture.tsx@@ -14,6 +14,7 @@ import { GatewayFixture } from './gatewayFixture';import { QuotaFixture } from './quotaFixture';import { RouteFixture } from './routeFixture';import { TokenScopeFixture } from './tokenScopeFixture';+import { UsageFixture } from './usageFixture';const params = new URLSearchParams(location.search);const backend = params.get('backend') as AgentBackend;@@ -69,6 +70,8 @@ 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') === 'usage'+ ? <I18nextProvider i18n={language}><UsageFixture /></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.tsindex fa1d01c12..4d28677ed 100644--- a/ui/e2e/model-catalog/quota-layout.spec.ts+++ b/ui/e2e/model-catalog/quota-layout.spec.ts@@ -12,6 +12,8 @@ for (const lang of ['en', 'zh'] as const) {await page.goto(`/e2e/model-catalog/fixture.html?view=quota&lang=${lang}`);const cards = page.getByRole('article');await expect(cards).toHaveCount(2);+ // Usage analytics must not override the quota summary's shared type scale.+ await expect(page.locator('.model-hub-usage-stat-label').first()).toHaveCSS('font-size', '11px');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.diff --git a/ui/e2e/model-catalog/usage.spec.ts b/ui/e2e/model-catalog/usage.spec.tsnew file mode 100644index 000000000..aa9b93d90--- /dev/null+++ b/ui/e2e/model-catalog/usage.spec.ts@@ -0,0 +1,140 @@+import { expect, test, type Locator, type Page } from '@playwright/test';++const openUsage = async (page: Page, theme: 'light' | 'dark' = 'dark') => {+ await page.goto(`/e2e/model-catalog/fixture.html?view=usage&lang=en&theme=${theme}`);+ await expect(page.getByRole('heading', { name: 'Usage', level: 2 })).toBeVisible();+};++const focusWithKeyboard = async (page: Page, target: Locator) => {+ for (let step = 0; step < 40; step += 1) {+ await page.keyboard.press('Tab');+ if (await target.evaluate((element) => element === document.activeElement)) return;+ }+ throw new Error('Keyboard focus did not reach the usage bucket');+};++test.describe('hermetic UsageTab', () => {+ test('hovers left, middle, and right buckets and pins without clicking the plot', async ({ page }) => {+ await openUsage(page);+ const hitAreas = page.locator('.model-hub-usage-hit-area');+ const count = await hitAreas.count();+ const indexes = [...new Set([0, Math.floor(count / 2), count - 1])];++ for (const index of indexes) {+ await hitAreas.nth(index).hover();+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });+ await expect(dialog).toBeVisible();+ await expect(dialog.getByRole('button', { name: 'Pin this bucket' })).toBeVisible();+ await dialog.getByRole('button', { name: 'Pin this bucket' }).click();+ await expect(dialog).toHaveAttribute('data-pinned', 'true');++ await page.mouse.click(4, 4);+ await expect(dialog).toBeVisible();+ await expect(dialog).toHaveAttribute('data-pinned', 'true');++ await dialog.getByRole('button', { name: 'Unpin this bucket' }).click();+ await expect(dialog).toHaveAttribute('data-pinned', 'false');+ await page.mouse.click(4, 4);+ await expect(dialog).toHaveCount(0);+ }+ });++ test('click-away closes an ordinary hover detail and Escape releases a pin', async ({ page }) => {+ await openUsage(page);+ const hitAreas = page.locator('.model-hub-usage-hit-area');+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });++ await hitAreas.nth(12).hover();+ await expect(dialog).toBeVisible();+ await page.mouse.click(4, 4);+ await expect(dialog).toHaveCount(0);++ await hitAreas.nth(12).hover();+ await dialog.getByRole('button', { name: 'Pin this bucket' }).click();+ await expect(dialog).toHaveAttribute('data-pinned', 'true');+ await dialog.getByRole('button', { name: 'Unpin this bucket' }).focus();+ await page.locator('body').press('Escape');+ await expect(dialog).toHaveCount(0);++ // Closing an overlay beneath a stationary pointer must not reopen it;+ // a subsequent deliberate pointer move can inspect another bucket.+ await hitAreas.nth(0).hover();+ await expect(dialog).toBeVisible();+ await expect(dialog).toHaveAttribute('data-pinned', 'false');+ });++ test('keyboard activation owns detail focus, preserves it through hover, and clears pin on scope change', async ({ page }) => {+ await openUsage(page);+ const bucket = page.getByRole('button', { name: /Usage bucket/ }).nth(0);+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });++ await focusWithKeyboard(page, bucket);+ await page.keyboard.press('Enter');+ const pin = dialog.getByRole('button', { name: 'Pin this bucket' });+ await expect(pin).toBeFocused();++ await page.keyboard.press('Escape');+ await expect(dialog).toHaveCount(0);+ await expect(bucket).toBeFocused();++ await page.locator('.model-hub-usage-hit-area').nth(1).hover();+ await expect(bucket).toBeFocused();++ await page.keyboard.press('Space');+ await expect(dialog).toBeVisible();+ await expect(dialog.getByRole('button', { name: 'Pin this bucket' })).toBeFocused();+ await page.keyboard.press('Space');+ await expect(dialog).toHaveAttribute('data-pinned', 'true');++ const nextWindow = page.getByRole('radio', { name: '7 days' });+ await nextWindow.click();+ await expect(dialog).toHaveCount(0);+ await expect(nextWindow).toBeFocused();+ });++ test('window switching renders coherent line and bar reports', async ({ page }) => {+ await openUsage(page);+ await expect(page.locator('.model-hub-usage-svg')).toBeVisible();+ await page.getByRole('radio', { name: '7 days' }).click();+ await expect(page.locator('.model-hub-usage-svg')).toBeVisible();+ await expect(page.getByText('7 daily points')).toBeVisible();+ await page.getByRole('radio', { name: '30 days' }).click();+ await expect(page.locator('.model-hub-usage-svg')).toBeVisible();+ await expect(page.getByText('30 daily points')).toBeVisible();+ await page.getByRole('radio', { name: '60 days' }).click();+ await expect(page.locator('.model-hub-usage-svg')).toBeVisible();+ await expect(page.getByText('60 daily points')).toBeVisible();+ await expect(page.locator('body')).not.toContainText('T24:00:00');+ });++ for (const theme of ['light', 'dark'] as const) {+ test(`${theme} theme renders the complete usage surface`, async ({ page }) => {+ await openUsage(page, theme);+ await expect(page.locator('html')).toHaveAttribute('data-theme', theme);+ await expect(page.getByRole('heading', { name: 'Exact usage details', level: 3 })).toBeVisible();+ await expect(page.locator('.model-hub-usage-svg')).toBeVisible();+ });+ }++ test('narrow layout keeps the chart and scrolls the exact table inside its card', async ({ page }) => {+ await page.setViewportSize({ width: 390, height: 844 });+ await openUsage(page);+ const statColumns = await page.locator('.model-hub-usage-stat-grid').evaluate((node) =>+ getComputedStyle(node).gridTemplateColumns.split(' ').length);+ expect(statColumns).toBe(1);+ await expect(page.locator('.model-hub-usage-table-scroll')).toHaveCSS('overflow-x', 'auto');+ const fitsViewport = await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth);+ expect(fitsViewport).toBe(true);+ expect(await page.locator('.model-hub-usage-svg').textContent()).not.toContain('2026');+ const scrollOwner = page.locator('main');+ const scrollMetrics = await scrollOwner.evaluate((node) => ({+ clientHeight: node.clientHeight,+ scrollHeight: node.scrollHeight,+ overflowY: getComputedStyle(node).overflowY,+ }));+ expect(scrollMetrics.overflowY).toBe('auto');+ expect(scrollMetrics.scrollHeight).toBeGreaterThan(scrollMetrics.clientHeight);+ await page.getByRole('heading', { name: 'Exact usage details', level: 3 }).scrollIntoViewIfNeeded();+ expect(await scrollOwner.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);+ });+});diff --git a/ui/e2e/model-catalog/usageFixture.tsx b/ui/e2e/model-catalog/usageFixture.tsxnew file mode 100644index 000000000..2a81a416a--- /dev/null+++ b/ui/e2e/model-catalog/usageFixture.tsx@@ -0,0 +1,127 @@+import { useEffect, useMemo, useState } from 'react';++import { UsageTab } from '../../src/components/settings/models/UsageTab';+import { readyRegion } from '../../src/components/settings/models/regionRead';+import type { UsageBucketRow, UsageCounters, UsageReport, UsageWindowKey } from '../../src/components/settings/models/types';++const params = new URLSearchParams(location.search);+const CURRENT_AT = '2026-09-24T20:37:00+08:00';+const CURRENT_MS = Date.UTC(2026, 8, 24, 12, 37);+const HOUR_MS = 60 * 60 * 1000;+const DAY_MS = 24 * HOUR_MS;++const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({+ requests: 3,+ token_reports: 3,+ input_tokens: 120,+ cached_input_tokens: 40,+ output_tokens: 60,+ ...over,+});++const row = (over: Partial<UsageBucketRow> = {}): UsageBucketRow => ({+ ...counters(),+ source_id: 'source-alpha',+ model_id: 'model-shared',+ ...over,+});++const localAt = (ms: number): string => {+ const shifted = new Date(ms + 8 * HOUR_MS);+ const pad = (value: number) => String(value).padStart(2, '0');+ return `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}T${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:00+08:00`;+};++const dayKey = (ms: number): string => localAt(ms).slice(0, 10);++const rowsFor = (index: number, count: number): UsageBucketRow[] => {+ if (index === 1) return [row({ source_id: 'source-alpha' })];+ if (index === Math.floor(count / 2)) return [row({ source_id: 'source-beta' })];+ if (index === count - 2) return [row({ source_id: 'source-alpha', model_id: 'model-second' })];+ return [];+};++const makeReport = (windowKey: UsageWindowKey): UsageReport => {+ const count = windowKey === '24h' ? 24 : Number(windowKey.slice(0, -1));+ const granularity = windowKey === '24h' ? 'hour' : 'day';+ const firstStart = windowKey === '24h'+ ? Date.UTC(2026, 8, 24, 12) - 23 * HOUR_MS+ : Date.UTC(2026, 8, 24) - 8 * HOUR_MS - (count - 1) * DAY_MS;+ const buckets = Array.from({ length: count }, (_, index) => {+ const startMs = firstStart + index * (granularity === 'hour' ? HOUR_MS : DAY_MS);+ const endMs = index === count - 1 ? CURRENT_MS : startMs + (granularity === 'hour' ? HOUR_MS : DAY_MS);+ return {+ key: granularity === 'day' ? dayKey(startMs) : localAt(startMs),+ start_at: localAt(startMs),+ end_at: localAt(endMs),+ history_complete: index !== count - 1,+ rows: rowsFor(index, count),+ };+ });+ return {+ window_days: windowKey === '24h' ? 1 : count,+ from_day: dayKey(firstStart),+ to_day: '2026-09-24',+ totals: counters({+ requests: 9,+ token_reports: 9,+ input_tokens: 360,+ cached_input_tokens: 120,+ output_tokens: 180,+ }),+ sources: [+ {+ source_id: 'source-alpha',+ label: 'Same supplier',+ last_metered_at: '2026-09-24T18:00:00+08:00',+ ...counters({ requests: 6, token_reports: 6, input_tokens: 240, cached_input_tokens: 80, output_tokens: 120 }),+ models: [+ { model_id: 'model-shared', label: 'Same model', ...counters() },+ { model_id: 'model-second', label: 'Second model', ...counters() },+ ],+ },+ {+ source_id: 'source-beta',+ label: 'Same supplier',+ last_metered_at: '2026-09-24T10:00:00+08:00',+ ...counters(),+ models: [{ model_id: 'model-shared', label: 'Same model', ...counters() }],+ },+ ],+ days: [],+ window_key: windowKey,+ granularity,+ from_at: localAt(firstStart),+ to_at: CURRENT_AT,+ buckets,+ };+};++export function UsageFixture() {+ const [windowKey, setWindowKey] = useState<UsageWindowKey>('24h');+ const usage = useMemo(() => readyRegion(makeReport(windowKey)), [windowKey]);++ useEffect(() => {+ const theme = params.get('theme');+ if (theme === 'light' || theme === 'dark') document.documentElement.dataset.theme = theme;+ return () => {+ delete document.documentElement.dataset.theme;+ };+ }, []);++ return (+ <main+ style={{+ boxSizing: 'border-box',+ width: '100%',+ height: '100dvh',+ overflowY: 'auto',+ padding: '24px 0 48px',+ }}+ >+ <div style={{ width: 'min(1100px, calc(100vw - 32px))', margin: '0 auto' }}>+ <UsageTab usage={usage} windowKey={windowKey} onWindowChange={setWindowKey} />+ </div>+ </main>+ );+}diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 18ff959da..edf51c933 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 QuotaSummary, 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 UsageReport } 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@@ -131,7 +131,7 @@ 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;-const usageSummary: UsageSummary = {+const usageSummary: UsageReport = {window_days: 30,from_day: '2026-07-20',to_day: '2026-08-18',@@ -148,6 +148,48 @@ const usageSummary: UsageSummary = {models: [{ model_id: 'claude-opus-4-6', label: 'claude-opus-4-6', requests: 12, token_reports: 12, input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 }],}],days: [{ day: '2026-08-18', requests: 12, token_reports: 12, input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 }],+ window_key: '24h',+ granularity: 'hour',+ from_at: '2026-08-18T00:00:00+00:00',+ to_at: '2026-08-18T04:00:00+00:00',+ buckets: [+ {+ key: '2026-08-18T00:00:00+00:00',+ start_at: '2026-08-18T00:00:00+00:00',+ end_at: '2026-08-18T01:00:00+00:00',+ history_complete: true,+ rows: [{+ source_id: 'src_retained',+ model_id: 'claude-opus-4-6',+ requests: 12,+ token_reports: 12,+ input_tokens: 148230,+ cached_input_tokens: 96010,+ output_tokens: 4120,+ }],+ },+ {+ key: '2026-08-18T01:00:00+00:00',+ start_at: '2026-08-18T01:00:00+00:00',+ end_at: '2026-08-18T02:00:00+00:00',+ history_complete: true,+ rows: [],+ },+ {+ key: '2026-08-18T02:00:00+00:00',+ start_at: '2026-08-18T02:00:00+00:00',+ end_at: '2026-08-18T03:00:00+00:00',+ history_complete: true,+ rows: [],+ },+ {+ key: '2026-08-18T03:00:00+00:00',+ start_at: '2026-08-18T03:00:00+00:00',+ end_at: '2026-08-18T04:00:00+00:00',+ history_complete: true,+ rows: [],+ },+ ],};/**@@ -2311,7 +2353,7 @@ describe('SettingsModelsPage usage region', () => {await waitFor(() => expect(screen.getAllByRole('tab'), landing).toHaveLength(4));await openUsage();- await waitFor(() => expect(vi.mocked(modelsApi.getUsageSummary), landing).toHaveBeenCalledWith(30));+ await waitFor(() => expect(vi.mocked(modelsApi.getUsageSummary), landing).toHaveBeenCalledWith('24h'));}});@@ -2324,7 +2366,7 @@ describe('SettingsModelsPage usage region', () => {// not be part of the read that draws it.expect(read).not.toHaveBeenCalled();await openUsage();- await waitFor(() => expect(read).toHaveBeenCalledWith(30));+ await waitFor(() => expect(read).toHaveBeenCalledWith('24h'));});it('re-reads with the span the control was moved to', async () => {@@ -2334,8 +2376,8 @@ describe('SettingsModelsPage usage region', () => {const read = vi.mocked(modelsApi.getUsageSummary);await waitFor(() => expect(read).toHaveBeenCalledTimes(1));- await userEvent.click(screen.getByRole('radio', { name: /^7d$|^7 天$/ }));- await waitFor(() => expect(read).toHaveBeenLastCalledWith(7));+ await userEvent.click(screen.getByRole('radio', { name: /^7 days$|^7 天$/ }));+ await waitFor(() => expect(read).toHaveBeenLastCalledWith('7d'));});it('re-reads on every open, because the figure is live', async () => {@@ -2359,7 +2401,7 @@ describe('SettingsModelsPage usage region', () => {await userEvent.click(await screen.findByRole('button', { name: /^Retry$|^重试$/ }));await waitFor(() => expect(read).toHaveBeenCalledTimes(2));- expect(read.mock.calls.map(([days]) => days)).toEqual([30, 30]);+ expect(read.mock.calls.map(([window]) => window)).toEqual(['24h', '24h']);});});diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex d601c96e5..1234c57df 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -73,11 +73,20 @@ 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 QuotaSummary, type RuntimeDependency, type Source, type UsageSummary } from './types';-import type { UsageWindowOption } from './usageProjection';+import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';const CHAIN_READ_CONCURRENCY = 6;const EVENT_PAGE = 20;+type ModelsTranslate = (key: string, options?: Record<string, unknown>) => string;++const useModelsTranslation = () => {+ const translation = useTranslation();+ return {+ ...translation,+ t: translation.t as unknown as ModelsTranslate,+ };+};+type RouteTarget = {agent: AgentSupply;modelId: string;@@ -181,7 +190,7 @@ export const RuntimePill: React.FC<{stopping?: boolean;directCount?: number;}> = ({ read, starting, stopping = false, directCount }) => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();const projection = foldRegionRead<RuntimeDependency, { runtime: RuntimeDependency; authoritative: boolean } | null>(read, {loading: () => null,ready: (runtime) => ({ runtime, authoritative: true }),@@ -232,7 +241,7 @@ const RuntimeClosedState: React.FC<{starting: boolean;stopping: boolean;}> = ({ read, runtime, starting, stopping }) => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();const health = runtime?.status.health ?? null;const key = stopping? 'stopping'@@ -264,7 +273,7 @@ const RuntimeClosedState: React.FC<{};const ModelHubShell: React.FC<{ actions?: React.ReactNode; children: React.ReactNode; rootRef?: React.Ref<HTMLDivElement> }> = ({ actions, children, rootRef }) => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();return (<div ref={rootRef} className="model-hub-shell"><header className="model-hub-shell-head">@@ -293,7 +302,7 @@ const focusQuotaOpener = (opener: HTMLElement) =>type HubTab = 'sources' | 'quota' | 'usage' | 'logs';const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ tab, onChange }) => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();return (<div role="tablist" className="flex h-[39px] items-end gap-1 border-b border-border">{(['sources', 'quota', 'usage', 'logs'] as const).map((id) => (@@ -307,7 +316,7 @@ const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ t};const DirectHome: React.FC<{ agents: AgentSupply[]; onSwitch: (agent: AgentSupply) => void }> = ({ agents, onSwitch }) => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();if (agents.length === 0) {return <section className="model-hub-direct-empty"><h2>{t('settings.models.direct.empty.title')}</h2><p>{t('settings.models.direct.empty.body')}</p><span>{t('settings.models.direct.empty.install')}</span></section>;}@@ -348,13 +357,13 @@ const DirectHome: React.FC<{ agents: AgentSupply[]; onSwitch: (agent: AgentSuppl};const TakeoverPill: React.FC<{ count: number }> = ({ count }) => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();if (count === 0) return null;return <span className="model-hub-takeover-pill"><span className="model-hub-runtime-dot" />{t('settings.models.takeover.pill', { count })}</span>;};export const SettingsModelsPage: React.FC = () => {- const { t } = useTranslation();+ const { t } = useModelsTranslation();const { showToast } = useToast();const navigate = useNavigate();// An Agent named in the warning list is a destination, not a label: the page@@ -375,10 +384,10 @@ export const SettingsModelsPage: React.FC = () => {const [eventsRead, setEventsRead] = React.useState<RegionRead<EventFeed>>(loadingRegion);const [loadingEvents, setLoadingEvents] = React.useState(false);const [tab, setTab] = React.useState<HubTab>('sources');- const [usageRead, setUsageRead] = React.useState<RegionRead<UsageSummary>>(loadingRegion);+ const [usageRead, setUsageRead] = React.useState<RegionRead<UsageReport>>(loadingRegion);+ const [usageWindow, setUsageWindow] = React.useState<UsageWindowKey>(USAGE_DEFAULT_WINDOW);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);const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);@@ -649,14 +658,14 @@ export const SettingsModelsPage: React.FC = () => {});}));- const [usageReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<UsageSummary>>((incoming) => {+ const [usageReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<UsageReport>>((incoming) => {if (!aliveRef.current) return;setUsageRead((previous) => settleRegionRead(previous, incoming));}));- const refreshUsage = React.useCallback(async (days: UsageWindowOption) => {+ const refreshUsage = React.useCallback(async (window: UsageWindowKey) => {setUsageRead(beginRegionRead);- await usageReadAuthority.run(() => readRegion(() => modelsApi.getUsageSummary(days)));+ await usageReadAuthority.run(() => readRegion(() => modelsApi.getUsageSummary(window)));}, [usageReadAuthority]);/**@@ -1508,7 +1517,7 @@ export const SettingsModelsPage: React.FC = () => {selectSource({ sourceId, returnFocus: () => opener });}}/>- : tab === 'usage' ? <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />+ : tab === 'usage' ? <UsageTab usage={usageRead} windowKey={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">diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsxindex 002c69e70..4c14b3edf 100644--- a/ui/src/components/settings/models/UsageTab.test.tsx+++ b/ui/src/components/settings/models/UsageTab.test.tsx@@ -1,21 +1,16 @@// @vitest-environment jsdom-// What the 用量 tab is allowed to SAY about a report. The derivations themselves-// are `usageProjection.test.ts`'s subject; every assertion here is about a claim-// the tab could make that the payload does not support — a span it was not-// served, an identity it cannot render, an empty window drawn as zeroes, or a-// shortfall presented as spare capacity.-import { cleanup, render, screen, within } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { readFileSync } from 'node:fs';-import { join } from 'node:path';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 { degradedRegion, loadingRegion, readyRegion, unreadRegion, type RegionRead } from './regionRead';-import type { UsageByModel, UsageBySource, UsageCounters, UsageSummary } from './types';+import zh from '../../../i18n/zh.json';+import { readyRegion } from './regionRead';+import type { UsageBucket, UsageBucketRow, UsageCounters, UsageReport, UsageWindowKey } from './types';import { UsageTab } from './UsageTab';+import { buildUsageCsv, csvCell } from './usageCsv';const i18n = createInstance();void i18n.use(initReactI18next).init({@@ -26,377 +21,657 @@ void i18n.use(initReactI18next).init({});const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({- requests: 12,- token_reports: 12,- input_tokens: 148230,- cached_input_tokens: 96010,- output_tokens: 4120,+ requests: 2,+ token_reports: 2,+ input_tokens: 100,+ cached_input_tokens: 25,+ output_tokens: 40,...over,});-const model = (over: Partial<UsageByModel> = {}): UsageByModel => ({+const row = (over: Partial<UsageBucketRow> = {}): UsageBucketRow => ({...counters(),- model_id: 'claude-opus-4-6',- label: 'claude-opus-4-6',+ source_id: 'source-a',+ model_id: 'model-a',...over,});-const source = (over: Partial<UsageBySource> = {}): UsageBySource => ({- ...counters(),- source_id: 'src_conform001',- label: 'Contract source',- last_metered_at: '2026-08-18T03:14:00+00:00',- models: [model()],+const bucket = (+ key: string,+ rows: UsageBucketRow[] = [row()],+ over: Partial<UsageBucket> = {},+): UsageBucket => ({+ key,+ start_at: `2026-09-24T${key}:00:00+08:00`,+ end_at: `2026-09-24T${String(Number(key) + 1).padStart(2, '0')}:00:00+08:00`,+ history_complete: true,+ rows,...over,});-const summary = (over: Partial<UsageSummary> = {}): UsageSummary => ({- window_days: 30,- from_day: '2026-07-20',- to_day: '2026-08-18',- totals: counters(),- sources: [source()],- days: [{ ...counters(), day: '2026-08-18' }],+const report = (over: Partial<UsageReport> = {}): UsageReport => ({+ window_days: 1,+ from_day: '2026-09-24',+ to_day: '2026-09-24',+ totals: counters({ requests: 6, token_reports: 6, input_tokens: 300, cached_input_tokens: 75, output_tokens: 120 }),+ sources: [{+ source_id: 'source-a',+ label: 'Shared label',+ last_metered_at: '2026-09-24T02:00:00+08:00',+ ...counters({ requests: 6, token_reports: 6, input_tokens: 300, cached_input_tokens: 75, output_tokens: 120 }),+ models: [{ model_id: 'model-a', label: 'Shared model', ...counters({ requests: 6, token_reports: 6, input_tokens: 300, cached_input_tokens: 75, output_tokens: 120 }) }],+ }],+ days: [],+ window_key: '24h',+ granularity: 'hour',+ from_at: '2026-09-24T00:00:00+08:00',+ to_at: '2026-09-24T03:00:00+08:00',+ buckets: [bucket('00'), bucket('01'), bucket('02')],...over,});const draw = (- usage: RegionRead<UsageSummary>,- over: { windowDays?: 7 | 30 | 60; onWindowChange?: (days: number) => void; onRetry?: () => void } = {},-) =>- render(- <I18nextProvider i18n={i18n}>- <UsageTab- usage={usage}- windowDays={over.windowDays ?? 30}- onWindowChange={over.onWindowChange ?? (() => {})}- onRetry={over.onRetry}- />- </I18nextProvider>,- );--/** A table's rows that carry figures — the ones headed by a row rather than by a column. */-const bodyRows = (table: HTMLElement) =>- within(table).getAllByRole('row').filter((row) => within(row).queryAllByRole('rowheader').length > 0);--/**- * One row's stated figures, its row header first — which is the order that decides- * which column each of them answers.- */-const figures = (row: HTMLElement) => [...within(row).getAllByRole('rowheader'), ...within(row).getAllByRole('cell')];--const surfaceCss = readFileSync(join(__dirname, 'modelHubSurface.css'), 'utf8');--const rule = (selector: string) => {- const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');- return surfaceCss.match(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`))?.[1] ?? '';-};+ value: UsageReport,+ over: { windowKey?: UsageWindowKey; onWindowChange?: (window: UsageWindowKey) => void } = {},+) => render(+ <I18nextProvider i18n={i18n}>+ <UsageTab+ usage={readyRegion(value)}+ windowKey={over.windowKey ?? '24h'}+ onWindowChange={over.onWindowChange ?? vi.fn()}+ />+ </I18nextProvider>,+);afterEach(cleanup);describe('UsageTab', () => {+ it('defaults to 24 hours and forwards the selected contract window', async () => {+ const onWindowChange = vi.fn();+ draw(report(), { onWindowChange });++ expect(screen.getByRole('radio', { name: '24 hours', checked: true })).toBeTruthy();+ await userEvent.click(screen.getByRole('radio', { name: '7 days' }));+ expect(onWindowChange).toHaveBeenCalledWith('7d');+ });+it('MH-USAGE-016: names the window the report was served over, not the one asked for', () => {- // The server clamps `days` to retention and answers with what it covered.- // Printing the request back would caption a 62-day report as 7.- const { container } = draw(readyRegion(summary({ window_days: 62 })), { windowDays: 7 });- expect(container.textContent).toContain('trailing 62 days');- expect(container.textContent).not.toContain('trailing 7 days');+ const { container } = draw(report({+ from_at: '2026-08-18T00:00:00+08:00',+ to_at: '2026-08-18T03:00:00+08:00',+ }), { windowKey: '7d' });++ const heading = container.querySelector('.model-hub-usage-heading');+ expect(heading?.textContent).toContain('Aug 18, 2026');+ expect(heading?.textContent).not.toContain('Sep 24, 2026');});it('MH-USAGE-017: keeps a vanished Source identifiable and a vanished model unnamed', () => {- // Asymmetric by contract: `src_*` is a string the user could have seen- // elsewhere, a ledger key is a digest nobody typed.- const key = 'claude-opus-4-6-20260514-thinking#9f2c1d';- const { container } = draw(- readyRegion(summary({ sources: [source({ label: null, models: [model({ label: null, model_id: key })] })] })),- );- expect(container.textContent).toContain('src_conform001');- expect(container.textContent).toContain(en.settings.models.usage.bySource.goneSource);- expect(container.textContent).toContain(en.settings.models.usage.bySource.goneModel);- expect(container.textContent).not.toContain(key);- expect(container.textContent).not.toContain('9f2c1d');+ const vanishedModelId = 'model-opaque-digest-9f2c1d';+ const { container } = draw(report({+ sources: [{+ source_id: 'source-vanished',+ label: null,+ last_metered_at: null,+ ...counters(),+ models: [{ model_id: vanishedModelId, label: null, ...counters() }],+ }],+ buckets: [bucket('00', [row({ source_id: 'source-vanished', model_id: vanishedModelId })])],+ }));++ expect(container.textContent).toContain('source-vanished');+ expect(container.textContent).toContain('Unknown model');+ expect(container.textContent).not.toContain(vanishedModelId);});it('MH-USAGE-018: reads a shortfall as reports that never arrived', () => {- // The schema forbids the other reading outright: the gap between requests- // and token reports is missing evidence, never spare quota.- const { container } = draw(readyRegion(summary({ totals: counters({ requests: 12, token_reports: 9 }) })));- expect(container.textContent).toContain('3 requests came back with no token report');- expect(container.textContent).not.toContain(en.settings.models.usage.requests.reported);+ const shortfall = counters({+ requests: 4,+ token_reports: 1,+ input_tokens: 100,+ cached_input_tokens: 25,+ output_tokens: 40,+ });+ const { container } = draw(report({+ totals: shortfall,+ sources: [],+ buckets: [bucket('00', [row(shortfall)])],+ }));++ expect(container.textContent).toContain('3 requests have no token report');+ expect(container.textContent).toContain('All tokens');+ });++ it('uses the translated historical-model label for filters, chart, table, and collisions', async () => {+ const translated = createInstance();+ await translated.use(initReactI18next).init({+ lng: 'de',+ fallbackLng: 'en',+ resources: {+ en: { translation: en },+ de: { translation: { settings: { models: { usage: { unknownModel: 'Historisches Modell' } } } } },+ },+ interpolation: { escapeValue: false },+ });+ const value = report({+ sources: [{+ source_id: 'source-a',+ label: 'Supplier',+ last_metered_at: null,+ ...counters(),+ models: [{ model_id: 'model-a', label: 'Historisches Modell', ...counters() }],+ }],+ buckets: [bucket('00', [row({ model_id: 'removed-model' }), row()])],+ });+ const { container } = render(+ <I18nextProvider i18n={translated}>+ <UsageTab usage={readyRegion(value)} windowKey="24h" onWindowChange={vi.fn()} />+ </I18nextProvider>,+ );+ const labels = [+ 'Supplier · Historisches Modell · source-a · removed-model',+ 'Supplier · Historisches Modell · source-a · model-a',+ ];+ for (const label of labels) expect(within(screen.getByRole('table')).getByText(label)).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: 'All Model' }));+ for (const label of labels) expect(screen.getByRole('option', { name: new RegExp(label) })).toBeTruthy();+ fireEvent.pointerDown(document.body);+ await userEvent.click(screen.getByRole('button', { name: 'Model' }));+ for (const label of labels) expect(container.querySelector('.model-hub-usage-legend')?.textContent).toContain(label);+ expect(container.textContent).not.toContain('Unknown model');});- it('confirms full reporting when every request carried its tokens', () => {- const { container } = draw(readyRegion(summary()));- expect(container.textContent).toContain(en.settings.models.usage.requests.reported);+ it('formats every percentage in the active locale even when translations fall back', async () => {+ const translated = createInstance();+ await translated.use(initReactI18next).init({+ lng: 'de-DE',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+ });+ const { container } = render(+ <I18nextProvider i18n={translated}>+ <UsageTab usage={readyRegion(report({+ buckets: [bucket('00', [+ row({ input_tokens: 2, cached_input_tokens: 1, output_tokens: 0 }),+ row({ model_id: 'model-b', input_tokens: 14, cached_input_tokens: 1, output_tokens: 0 }),+ ])],+ }))} windowKey="24h" onWindowChange={vi.fn()} />+ </I18nextProvider>,+ );++ expect(container.querySelector('.model-hub-usage-stat-grid')?.textContent).toContain('12,5\u00a0%');+ expect(container.querySelector('tbody')?.textContent).toContain('12,5\u00a0%');+ expect(container.querySelector('tbody')?.textContent).toContain('87,5\u00a0%');+ expect(container.querySelector('tfoot')?.textContent).toContain('100\u00a0%');+ expect(container.textContent).not.toContain('12.5%');});- it('says nothing was metered instead of drawing a table of zeroes', () => {- const { container } = draw(readyRegion(summary({ sources: [], days: [] })));- expect(container.textContent).toContain(en.settings.models.usage.empty);- expect(container.textContent).not.toContain(en.settings.models.usage.bySource.title);- expect(container.textContent).not.toContain(en.settings.models.usage.byDay.title);+ it('exposes the current sort direction together with the actual detail row order', async () => {+ const { container } = draw(report({+ buckets: [bucket('00', [+ row({ input_tokens: 2, cached_input_tokens: 1, output_tokens: 0 }),+ row({ model_id: 'model-b', input_tokens: 14, cached_input_tokens: 1, output_tokens: 0 }),+ ])],+ }));+ const header = screen.getByRole('columnheader', { name: /All tokens/ });+ const amounts = () => within(container.querySelector('tbody')!).getAllByRole('row').map(+ (detail) => within(detail).getAllByRole('cell')[5]?.textContent,+ );++ expect(header.getAttribute('aria-sort')).toBe('descending');+ expect(within(header).getByRole('button', { name: /Sorted descending/ })).toBeTruthy();+ expect(amounts()).toEqual(['14', '2']);+ await userEvent.click(within(header).getByRole('button'));+ expect(header.getAttribute('aria-sort')).toBe('ascending');+ expect(within(header).getByRole('button', { name: /Sorted ascending/ })).toBeTruthy();+ expect(amounts()).toEqual(['2', '14']);+ await userEvent.click(within(header).getByRole('button'));+ expect(header.getAttribute('aria-sort')).toBe('descending');+ expect(amounts()).toEqual(['14', '2']);});- it('MH-USAGE-019: plots every day of the window, including the ones that carried nothing', () => {- // One reported day inside a 30-day span. Drawing `days[]` directly would- // close the gap and read as a month of continuous traffic.- const { container } = draw(readyRegion(summary()));- expect(container.querySelectorAll('.model-hub-usage-track')).toHaveLength(30);- expect(screen.getByRole('img', { name: /Metered tokens per day/ })).toBeTruthy();+ it('MH-USAGE-019: plots every bucket in the window, including the ones that carried nothing', () => {+ const { container } = draw(report({+ buckets: [bucket('00', []), bucket('01', []), bucket('02', [row()])],+ }));++ expect(screen.getAllByRole('button', { name: /Usage bucket/ })).toHaveLength(3);+ expect(container.textContent).toContain('3 hourly points');});- it('MH-USAGE-021: draws a day of calls whose tokens never came back, and names the window unreported', () => {- // Every request in the window answered without a token report, which the- // schema permits and the requests card already states as a shortfall. The- // series has nothing to scale, so every bar sits on its floor — but the days- // ran, and folding them into 「no metered turn」 would report our own missing- // evidence as the user's idleness.- const unreported = counters({ requests: 4, token_reports: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 });- const { container } = draw(readyRegion(summary({- from_day: '2026-08-16',- to_day: '2026-08-18',- window_days: 3,+ it('MH-USAGE-021: draws calls whose tokens never came back, and names the window unreported', () => {+ const unreported = counters({+ requests: 4,+ token_reports: 0,+ input_tokens: 0,+ cached_input_tokens: 0,+ output_tokens: 0,+ });+ const { container } = draw(report({totals: unreported,- sources: [source({ ...unreported, models: [model(unreported)] })],- days: [{ ...unreported, day: '2026-08-16' }, { ...unreported, day: '2026-08-18' }],- })));-- expect(container.textContent).toContain(en.settings.models.usage.byDay.unreported);- expect(container.textContent).not.toContain(en.settings.models.usage.byDay.quiet);- expect(container.textContent).not.toContain(en.settings.models.usage.byDay.zero);- // Every column says what its day carried, so a bar the report could not- // measure still reads as a day that ran rather than as an unexplained sliver.- // (Whether it is floored to one is CSS the DOM cannot answer for; the decision- // behind it is `usageDayIsMetered`, asserted over columns in- // `usageProjection.test.ts`.)- //- // The two kinds of day in this window state their tokens differently, which is- // the point: a day of uncosted calls has no number to print, while the day- // between them ran nothing and so really did cost zero.- const readouts = [...container.querySelectorAll('.model-hub-usage-track')].map((track) => track.getAttribute('title'));- expect(readouts).toEqual([- 'Aug 16, 2026 · — tokens · 4 requests',- 'Aug 17, 2026 · 0 tokens · 0 requests',- 'Aug 18, 2026 · — tokens · 4 requests',+ sources: [],+ buckets: [bucket('00', [row(unreported)])],+ }));++ expect(container.textContent).toContain('Some requests have no token report; token values are unavailable');+ expect(container.textContent).toContain('—');+ expect(container.querySelector('tfoot')?.textContent).not.toContain('100%');+ });++ it('MH-USAGE-023: states every bucket in accessible text, not only in a pointer tooltip', () => {+ draw(report());+ const buckets = screen.getAllByRole('button', { name: /Usage bucket/ });++ expect(buckets.map((item) => item.getAttribute('aria-label'))).toEqual([+ 'Usage bucket Sep 24, 2026, 00:00 UTC+08:00 – Sep 24, 2026, 01:00 UTC+08:00',+ 'Usage bucket Sep 24, 2026, 01:00 UTC+08:00 – Sep 24, 2026, 02:00 UTC+08:00',+ 'Usage bucket Sep 24, 2026, 02:00 UTC+08:00 – Sep 24, 2026, 03:00 UTC+08:00',]);});+ it('MH-USAGE-024: every figure the report states names the row and the column it answers', () => {+ draw(report());+ const table = screen.getByRole('table');+ const headers = within(table).getAllByRole('columnheader');+ const rows = within(table).getAllByRole('row').filter((item) => within(item).queryAllByRole('rowheader').length > 0);++ expect(headers.length).toBeGreaterThan(1);+ expect(rows.length).toBeGreaterThan(0);+ for (const rowElement of rows) {+ expect(within(rowElement).getAllByRole('rowheader')).toHaveLength(1);+ expect(within(rowElement).getAllByRole('cell')).toHaveLength(headers.length - 1);+ }+ });+it('MH-USAGE-025: reads a window whose reports all came back zero as measured, not as missing', () => {- // The mirror of MH-USAGE-021, one question over. Every call here WAS costed and- // the answer was nothing — an explicit all-zero usage block, which- // `extract_protocol_usage` forwards as a report rather than as an absence, so- // `token_reports` equals `requests` while every token count is 0. Reading that- // as 「no day reported its tokens」 would call a valid upstream answer missing- // evidence, and blanking the figures would hide a cost the report does state.- const free = counters({ requests: 4, token_reports: 4, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 });- const { container } = draw(readyRegion(summary({- from_day: '2026-08-17',- to_day: '2026-08-18',- window_days: 2,- totals: free,- sources: [source({ ...free, models: [model(free)] })],- days: [{ ...free, day: '2026-08-18' }],- })));-- expect(container.textContent).toContain(en.settings.models.usage.byDay.zero);- expect(container.textContent).not.toContain(en.settings.models.usage.byDay.unreported);- expect(container.textContent).not.toContain(en.settings.models.usage.byDay.quiet);- // A measured zero is a number, and the requests card has no shortfall to state- // about it either — nothing went unreported.- expect(container.textContent).toContain(en.settings.models.usage.requests.reported);- expect(container.textContent).not.toContain(en.settings.models.usage.tokens.none);- // And the cached card may say what MH-USAGE-026 forbids it to say, because here- // it is true: these calls were costed, and the cost included no input.- expect(container.textContent).toContain(en.settings.models.usage.cached.none);- const tokenFigures = [...container.querySelectorAll('[data-usage-token]')];- expect(tokenFigures.length).toBeGreaterThan(0);- for (const figure of tokenFigures) expect(figure.textContent).toBe('0');+ const measuredZero = counters({+ requests: 4,+ token_reports: 4,+ input_tokens: 0,+ cached_input_tokens: 0,+ output_tokens: 0,+ });+ const { container } = draw(report({+ totals: measuredZero,+ sources: [],+ buckets: [bucket('00', [row(measuredZero)])],+ }));++ expect(container.textContent).not.toContain('Some requests have no token report');+ const card = container.querySelector('.model-hub-usage-stat-label')?.parentElement;+ expect(card?.textContent).toContain('0');});- it('MH-USAGE-026: every token figure on screen states its own coverage, whatever states it', () => {- // The class MH-USAGE-021 and MH-USAGE-025 are two members of: a token figure- // printed without asking whether anything reported it. Asked of every figure the- // tab renders rather than of a list of the seven known ones — the marker is- // emitted by the single door they all go through, so a card, cell, or column- // added later is covered by existing rather than by an edit here.- const uncosted = counters({ requests: 6, token_reports: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 });- const { container } = draw(readyRegion(summary({- from_day: '2026-08-17',- to_day: '2026-08-18',- window_days: 2,- totals: uncosted,- sources: [source({ ...uncosted, models: [model(uncosted)] })],- // Both reported days carried calls nobody costed, so no day of this window- // may print a token number at all.- days: [{ ...uncosted, day: '2026-08-17' }, { ...uncosted, day: '2026-08-18' }],- })));-- const tokenFigures = [...container.querySelectorAll('[data-usage-token]')];- expect(tokenFigures.length).toBeGreaterThan(0);- for (const figure of tokenFigures) expect(figure.textContent).toBe(en.settings.models.usage.blank);- // …and the sentences that interpolate a figure instead of holding one say the- // same thing, since a tooltip and a note have no element of their own to mark.- const readouts = [...container.querySelectorAll('.model-hub-usage-track')].map((track) => track.getAttribute('title'));- expect(readouts).toEqual([- 'Aug 17, 2026 · — tokens · 6 requests',- 'Aug 18, 2026 · — tokens · 6 requests',- ]);- // The notes go the same way. The tokens card replaces the input/output split- // rather than blanking both halves of it — 「— in · — out」 states a breakdown of- // a number nobody gave — and the cached card must not read an absence of reports- // as an absence of input.- expect(container.textContent).toContain(en.settings.models.usage.tokens.none);- expect(container.textContent).not.toContain(' in · ');- expect(container.textContent).not.toContain(en.settings.models.usage.cached.none);+ it('does not claim a 100% share when the selected total is zero', () => {+ const measuredZero = counters({+ requests: 4,+ token_reports: 4,+ input_tokens: 0,+ cached_input_tokens: 0,+ output_tokens: 0,+ });+ const { container } = draw(report({+ totals: measuredZero,+ sources: [],+ buckets: [bucket('00', [row(measuredZero)])],+ }));++ expect(container.querySelector('tfoot')?.textContent).not.toContain('100%');});- it('MH-USAGE-023: states every day of the window in text, not only in a pointer tooltip', () => {- const { container } = draw(readyRegion(summary()));- const tooltips = [...container.querySelectorAll('.model-hub-usage-track')].map((track) => track.getAttribute('title') ?? '');-- // A `title` opens on hover alone, and the chart is one image whose columns- // assistive tech never enumerates — so the same three figures have to exist- // as cells outside it. Read out of the tooltips rather than out of a list of- // days: the two readings of a day cannot disagree, whatever the window holds.- const rows = bodyRows(screen.getByRole('table', { name: /Metered tokens and requests per day/ }));- expect(rows).toHaveLength(tooltips.length);- rows.forEach((row, index) => {- const said = tooltips[index].split(' · ');- const stated = figures(row).map((figure) => figure.textContent ?? '');- expect(stated).toHaveLength(said.length);- stated.forEach((text, column) => expect(said[column]).toContain(text));+ it('MH-USAGE-026: every token figure on screen states its own coverage', () => {+ const unreported = counters({+ requests: 2,+ token_reports: 0,+ input_tokens: 0,+ cached_input_tokens: 0,+ output_tokens: 0,});+ const { container } = draw(report({+ totals: unreported,+ sources: [],+ buckets: [bucket('00', [row(unreported)])],+ }));++ expect(container.textContent).toContain('Some requests have no token report; token values are unavailable');+ expect(container.querySelector('.model-hub-usage-table-scroll')?.textContent).toContain('—');});- it('MH-USAGE-027: keeps a 390px viewport within bounds and states long chart labels without clipping', () => {- const longPeak = counters({ input_tokens: 123_456_789_012, output_tokens: 34_567_890 });- const { container } = draw(readyRegion(summary({- from_day: '2026-08-16',- to_day: '2026-08-18',- window_days: 3,- totals: longPeak,- sources: [source({ ...longPeak, models: [model(longPeak)] })],- days: [{ ...longPeak, day: '2026-08-18' }],- })));-- // A table's intrinsic columns can remain wider than the one-pixel `sr-only`- // box applied to the table itself. A generic paint/layout container is the- // boundary that keeps the complete semantic table out of visual geometry.- const dailyTable = screen.getByRole('table', { name: /Metered tokens and requests per day/ });- expect(dailyTable.classList.contains('sr-only')).toBe(false);- expect(dailyTable.parentElement?.classList.contains('sr-only')).toBe(true);- expect(dailyTable.parentElement?.classList.contains('model-hub-usage-a11y-table')).toBe(true);- expect(rule('.model-hub-usage-a11y-table')).toContain('contain: strict');-- const axis = container.querySelector('.model-hub-usage-axis');- const labels = [...(axis?.querySelectorAll('.model-hub-usage-axis-label') ?? [])];- expect(labels).toHaveLength(3);- expect(labels[1].textContent).toContain('123,491,356,902');- expect(labels[1].textContent).toContain('Aug 18, 2026');- for (const label of labels) expect(label.classList.contains('truncate')).toBe(false);-- // jsdom has no layout engine, so the narrow-width browser property is stated- // by the same min-zero fractional grid and emergency wrapping Chrome uses.- // No track owns an intrinsic pixel width, so this holds below and above 390px- // rather than special-casing the reproduced fixture width.- expect(rule('.model-hub-usage-axis')).toContain('grid-template-columns: var(--model-hub-usage-axis-columns)');- expect(rule('.model-hub-usage-axis-label')).toContain('min-width: 0');- expect(rule('.model-hub-usage-axis-label')).toContain('overflow-wrap: anywhere');- expect(rule('.model-hub-usage-axis')).toContain('--model-hub-usage-axis-columns: minmax(0, 1fr) minmax(0, 2fr) minmax(0, 1fr)');+ it('MH-USAGE-027: keeps the usage surface within a narrow semantic layout', () => {+ const { container } = draw(report());+ const chart = container.querySelector('.model-hub-usage-chart-wrap');+ const tableScroll = container.querySelector('.model-hub-usage-table-scroll');++ expect(chart).not.toBeNull();+ expect(tableScroll).not.toBeNull();+ expect(screen.getAllByRole('button', { name: /Usage bucket/ })).toHaveLength(3);});- it('MH-USAGE-024: every figure the report states names the row and the column it answers', () => {- // The class this closes: a per-row figure stated by visual position alone,- // which no reader who cannot see the layout can recover. Asked of whatever- // tables the tab renders rather than of a list of them, so a third panel of- // figures is covered by existing instead of by an edit here.- const { container } = draw(readyRegion(summary({+ it('renders exact accounting and preserves source/model pair rows', () => {+ const second = row({ source_id: 'source-b', model_id: 'model-a' });+ const value = report({+ totals: counters({ requests: 4, token_reports: 4, input_tokens: 200, cached_input_tokens: 50, output_tokens: 80 }),sources: [- source({ models: [model({ model_id: 'claude-opus-4-6', label: 'claude-opus-4-6' })] }),- // The ragged shape: a Source with no metering timestamp, over a model that- // has none by definition. Both stop before the last column.- source({- source_id: 'src_probe002',- label: 'Probe source',+ {+ source_id: 'source-a',+ label: 'Same source label',+ last_metered_at: null,+ ...counters(),+ models: [{ model_id: 'model-a', label: 'Same model label', ...counters() }],+ },+ {+ source_id: 'source-b',+ label: 'Same source label',last_metered_at: null,- models: [model({ model_id: 'claude-haiku-4-5', label: 'claude-haiku-4-5' })],- }),+ ...counters(),+ models: [{ model_id: 'model-a', label: 'Same model label', ...counters() }],+ },],- })));-- const named: string[] = [];- for (const table of screen.getAllByRole('table')) {- const headers = within(table).getAllByRole('columnheader');- expect(headers.length).toBeGreaterThan(1);- // Whether this table's headers can leave the accessibility tree, which is- // what decides whether position alone is enough. jsdom loads no stylesheet,- // so the class is the only readable statement of it.- const stacks = /(^|\s)hidden(\s|$)/.test(headers[0].parentElement?.className ?? '');- const rows = bodyRows(table);- expect(rows.length).toBeGreaterThan(0);- for (const row of rows) {- const heads = within(row).getAllByRole('rowheader');- expect(heads).toHaveLength(1);- named.push(heads[0].textContent ?? '');- const stated = figures(row);- // A figure answers the column it sits in, so no row may end early: the- // model row has no metering timestamp of its own and holds that column- // open with an empty cell rather than shifting the ones before it under- // the wrong header.- expect(stated).toHaveLength(headers.length);- stated.forEach((figure, column) => {- const label = figure.querySelector('.model-hub-usage-cell-label');- // Where the headers go, the cell's own label is the association that- // stays — so every figure that states something has to carry one, and it- // has to name the column the figure sits in. Two statements about one- // cell, which a drifting column order would answer differently.- if (stacks && figure !== heads[0] && figure.textContent !== '') expect(label).not.toBeNull();- if (label !== null) expect(label.textContent).toBe(headers[column].textContent);- });- }+ buckets: [bucket('00', [row(), second]), bucket('01', []), bucket('02', [])],+ });+ draw(value);++ expect(screen.getByText('Same source label · Same model label · source-a')).toBeTruthy();+ expect(screen.getByText('Same source label · Same model label · source-b')).toBeTruthy();+ expect(screen.getByText('All tokens = input + output. Cache reads are included in input and shown separately.')).toBeTruthy();+ expect(screen.getAllByText('50.0%').length).toBeGreaterThan(0);+ });++ it('keeps incomplete empty buckets out of the ordinary empty state and shows gaps', () => {+ const incomplete = report({+ totals: counters({ requests: 0, token_reports: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 }),+ sources: [],+ buckets: [+ bucket('00', [], { history_complete: false }),+ bucket('01', [], { history_complete: false }),+ bucket('02', [], { history_complete: false }),+ ],+ });+ const { container } = draw(incomplete);++ expect(screen.getAllByText('Some buckets have incomplete history').length).toBeGreaterThan(0);+ expect(screen.queryByText('No usage in this window')).toBeNull();+ expect(container.querySelectorAll('.model-hub-usage-unknown-point')).toHaveLength(9);+ expect(screen.getAllByText('—').length).toBeGreaterThan(0);+ });++ it.each([+ ['en', 'Includes historical usage without hourly time'],+ ['zh', '含无具体小时记录的历史用量'],+ ])('shows one localized historical-hourly notice in %s, only for incomplete hourly reports', async (language, note) => {+ const translated = createInstance();+ await translated.use(initReactI18next).init({+ lng: language,+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ const page = (value: UsageReport) => (+ <I18nextProvider i18n={translated}>+ <UsageTab usage={readyRegion(value)} windowKey={value.window_key} onWindowChange={vi.fn()} />+ </I18nextProvider>+ );+ const partial = report({ buckets: [bucket('00', [row()], { history_complete: false })] });+ const { rerender } = render(page(partial));++ expect(screen.getAllByText(note)).toHaveLength(1);+ expect(within(screen.getByRole('status')).getByText(note)).toBeTruthy();+ rerender(page(report()));+ expect(screen.queryByText(note)).toBeNull();+ rerender(page({ ...partial, window_key: '7d', granularity: 'day' }));+ expect(screen.queryByText(note)).toBeNull();+ });++ it('keeps ordinary detail dismissible and pins directly from hover', async () => {+ const { container } = draw(report());+ const buckets = screen.getAllByRole('button', { name: /Usage bucket/ });+ fireEvent.pointerEnter(buckets[0]);+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' })).toBeTruthy();++ fireEvent.pointerDown(document.body);+ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();++ fireEvent.pointerEnter(buckets[1]);+ const pin = screen.getByRole('button', { name: 'Pin this bucket' });+ await userEvent.click(pin);+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' }).getAttribute('data-pinned')).toBe('true');+ fireEvent.pointerDown(document.body);+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' })).toBeTruthy();+ expect(container.querySelector('.model-hub-usage-details-header p')?.textContent).toContain('Showing Sep 24, 2026');++ await userEvent.click(screen.getByRole('button', { name: 'Unpin this bucket' }));+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' }).getAttribute('data-pinned')).toBe('false');+ fireEvent.pointerDown(document.body);+ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();+ });++ it('moves keyboard focus into detail and restores the bucket without reopening on Escape', async () => {+ const rendered = draw(report());+ const bucketButton = screen.getAllByRole('button', { name: /Usage bucket/ })[0]!;+ const user = userEvent.setup();++ for (let step = 0; step < 32 && document.activeElement !== bucketButton; step += 1) {+ await user.tab();}+ expect(document.activeElement).toBe(bucketButton);++ await user.keyboard('{Enter}');+ const pin = screen.getByRole('button', { name: 'Pin this bucket' });+ expect(document.activeElement).toBe(pin);++ await user.keyboard('{Escape}');+ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();+ expect(document.activeElement).toBe(bucketButton);++ await user.keyboard(' ');+ const repinned = screen.getByRole('button', { name: 'Pin this bucket' });+ expect(document.activeElement).toBe(repinned);++ await user.keyboard('{Enter}');+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' }).getAttribute('data-pinned')).toBe('true');++ rendered.rerender(+ <I18nextProvider i18n={i18n}>+ <UsageTab+ usage={readyRegion(report({ buckets: [bucket('00', [row({ requests: 3 })]), bucket('01'), bucket('02')] }))}+ windowKey="24h"+ onWindowChange={vi.fn()}+ />+ </I18nextProvider>,+ );++ expect(screen.getByRole('dialog', { name: 'Usage bucket details' }).getAttribute('data-pinned')).toBe('true');+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Unpin this bucket' }));++ await user.keyboard('{Escape}');+ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();+ expect(document.activeElement).toBe(bucketButton);++ // A non-modal detail must not reclaim focus after the user tabs elsewhere.+ await user.keyboard('{Enter}');+ await user.tab();+ const tableGrouping = screen.getByRole('button', { name: 'By model' });+ expect(document.activeElement).toBe(tableGrouping);+ await user.keyboard('{Escape}');+ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();+ expect(document.activeElement).toBe(tableGrouping);+ });++ it('dismisses pinned details on the first Escape', async () => {+ draw(report());+ fireEvent.pointerEnter(screen.getAllByRole('button', { name: /Usage bucket/ })[0]!);+ await userEvent.click(screen.getByRole('button', { name: 'Pin this bucket' }));+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' })).toBeTruthy();++ fireEvent.keyDown(document, { key: 'Escape' });++ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();+ });++ it('clears a pinned bucket that disappears from a same-window refresh', async () => {+ const value = report();+ const rendered = draw(value);+ fireEvent.pointerEnter(screen.getAllByRole('button', { name: /Usage bucket/ })[1]!);+ await userEvent.click(screen.getByRole('button', { name: 'Pin this bucket' }));+ expect(screen.getByRole('dialog', { name: 'Usage bucket details' }).getAttribute('data-pinned')).toBe('true');++ rendered.rerender(+ <I18nextProvider i18n={i18n}>+ <UsageTab usage={readyRegion(report({ buckets: [bucket('00')] }))} windowKey="24h" onWindowChange={vi.fn()} />+ </I18nextProvider>,+ );++ expect(screen.queryByRole('dialog', { name: 'Usage bucket details' })).toBeNull();+ expect(rendered.container.querySelector('.model-hub-usage-details-header p')?.textContent).toContain('same filters');+ });- // …and the rows are the whole report's, not the subset that happens to render:- // every Source, every model under it, and every day the chart draws.- const days = container.querySelectorAll('.model-hub-usage-track').length;- expect(named).toHaveLength(4 + days);- expect(named).toEqual(expect.arrayContaining(['Contract source', 'Probe source', 'claude-opus-4-6', 'claude-haiku-4-5']));+ it('shows both offsets in the report heading across a DST change', () => {+ const { container } = draw(report({+ from_at: '2026-11-01T01:00:00-04:00',+ to_at: '2026-11-01T01:00:00-05:00',+ }));++ expect(container.textContent).toContain('UTC-04:00');+ expect(container.textContent).toContain('UTC-05:00');});- it('keeps the last report on screen while a new one is read, and claims no failure', () => {- const { container } = draw(degradedRegion(summary(), 'refreshing', false));- expect(container.textContent).toContain('Contract source');- expect(container.textContent).not.toContain(en.settings.models.toast.refreshFailed);+ it('includes both bucket offsets in DST-adjacent detail text', () => {+ const dst = report({+ buckets: [bucket('00', [row()], {+ start_at: '2026-11-01T01:00:00-04:00',+ end_at: '2026-11-01T01:00:00-05:00',+ })],+ });+ draw(dst);+ fireEvent.pointerEnter(screen.getByRole('button', { name: /Usage bucket/ }));+ expect(screen.getByRole('dialog').textContent).toContain('UTC-04:00');+ expect(screen.getByRole('dialog').textContent).toContain('UTC-05:00');});- it('keeps the last report on screen when a refresh fails, under a retry', async () => {- // The alternative is an empty state, which would read as "nothing was ever- // metered" — a different claim from "the figure could not be refreshed".- const onRetry = vi.fn();- const { container } = draw(degradedRegion(summary(), 'read_failed', true), { onRetry });- expect(container.textContent).toContain('Contract source');- expect(container.textContent).toContain(en.settings.models.toast.refreshFailed);- await userEvent.click(screen.getByRole('button', { name: en.settings.models.upstream.retry }));- expect(onRetry).toHaveBeenCalledTimes(1);+ it('labels the current 24-hour bucket when it is only partially elapsed', () => {+ const value = report({+ to_at: '2026-09-24T02:15:00+08:00',+ buckets: [+ bucket('00'),+ bucket('01'),+ bucket('02', [row()], { end_at: '2026-09-24T02:15:00+08:00' }),+ ],+ });+ draw(value);++ fireEvent.pointerEnter(screen.getAllByRole('button', { name: /Usage bucket/ })[2]!);++ expect(screen.getByRole('dialog').textContent).toContain('Current partial hour');+ expect(screen.getByRole('dialog').textContent).toContain('History complete');});- it('offers a retry with no report to show when the first read never landed', () => {- const { container } = draw(unreadRegion<UsageSummary>());- expect(container.textContent).toContain(en.settings.models.toast.refreshFailed);- expect(container.textContent).not.toContain(en.settings.models.usage.empty);+ it('neutralizes formula-like supplier/model labels without quoting numeric counters', () => {+ expect(csvCell('=supplier')).toBe("'=supplier");+ expect(csvCell('@model')).toBe("'@model");+ expect(csvCell('\tmodel')).toBe("'\tmodel");+ expect(csvCell(120)).toBe('120');});- it('draws no report and no failure while the first read is in flight', () => {- const { container } = draw(loadingRegion<UsageSummary>());- expect(container.textContent).not.toContain(en.settings.models.toast.refreshFailed);- expect(container.textContent).not.toContain(en.settings.models.usage.empty);+ it('exports pinned raw rows with identity and interval metadata', () => {+ const value = report({+ sources: [{+ source_id: 'source-formula',+ label: '=supplier',+ last_metered_at: null,+ ...counters({ input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 }),+ models: [{ model_id: 'model-formula', label: '@model', ...counters() }],+ }],+ buckets: [+ bucket('00', [row({+ source_id: 'source-formula',+ model_id: 'model-formula',+ requests: 4,+ token_reports: 1,+ input_tokens: 148230,+ cached_input_tokens: 96010,+ output_tokens: 4120,+ })]),+ bucket('01', [row()]),+ ],+ });+ const headers = {+ bucketKey: 'bucket_key',+ startAt: 'start_at',+ endAt: 'end_at',+ historyComplete: 'history_complete',+ sourceId: 'source_id',+ modelId: 'model_id',+ ledgerKey: 'ledger_key',+ sourceLabel: 'source_label',+ modelLabel: 'model_label',+ requests: 'requests',+ tokenReports: 'token_reports',+ inputTokens: 'input_tokens',+ nonCachedInputTokens: 'non_cached_input_tokens',+ cachedInputTokens: 'cached_input_tokens',+ outputTokens: 'output_tokens',+ totalTokens: 'total_tokens',+ };+ const csv = buildUsageCsv(value, { sourceIds: [], modelKeys: [] }, '00', headers, 'Unknown model');++ expect(csv.split('\r\n')).toHaveLength(2);+ expect(csv).toContain('2026-09-24T00:00:00+08:00');+ expect(csv).toContain("source-formula,'@model,model-formula");+ expect(csv).toContain("'=supplier");+ expect(csv).toContain("'@model");+ expect(csv).toContain('4,1,148230');+ expect(csv).toContain('148230');+ expect(csv).not.toContain('148,230');+ expect(csv).toContain('152350');++ const unknownCsv = buildUsageCsv(report({+ buckets: [bucket('00', [row({ token_reports: 0 })])],+ }), { sourceIds: [], modelKeys: [] }, '00', headers, 'Unknown model');+ expect(unknownCsv.split('\r\n')[0]).toContain('token_reports');+ expect(unknownCsv.split('\r\n')[1]?.split(',').slice(-7)).toEqual(['2', '0', '', '', '', '', '']);++ const idleCsv = buildUsageCsv(report({+ buckets: [bucket('00', [])],+ }), { sourceIds: [], modelKeys: [] }, '00', headers, 'Unknown model');+ expect(idleCsv.split('\r\n')[1]?.split(',').slice(-7)).toEqual(['0', '0', '0', '0', '0', '0', '0']);});- it('hands its owner a window the contract accepts, as a number', async () => {- // The control speaks strings; `days` is a bounded number on the wire.- const onWindowChange = vi.fn();- draw(readyRegion(summary()), { onWindowChange });- await userEvent.click(screen.getByRole('radio', { name: '7d' }));- expect(onWindowChange).toHaveBeenCalledWith(7);+ it('does not export a folded ledger key as the canonical model ID', () => {+ const foldedKey = `model-head-${'x'.repeat(180)}`;+ const csv = buildUsageCsv(report({+ sources: [{+ source_id: 'source-removed',+ label: null,+ last_metered_at: null,+ ...counters(),+ models: [],+ }],+ buckets: [bucket('00', [row({+ source_id: 'source-removed',+ model_id: foldedKey,+ })])],+ }), { sourceIds: [], modelKeys: [] }, '00', {+ bucketKey: 'bucket_key',+ startAt: 'start_at',+ endAt: 'end_at',+ historyComplete: 'history_complete',+ sourceId: 'source_id',+ modelId: 'model_id',+ ledgerKey: 'ledger_key',+ sourceLabel: 'source_label',+ modelLabel: 'model_label',+ requests: 'requests',+ tokenReports: 'token_reports',+ inputTokens: 'input_tokens',+ nonCachedInputTokens: 'non_cached_input_tokens',+ cachedInputTokens: 'cached_input_tokens',+ outputTokens: 'output_tokens',+ totalTokens: 'total_tokens',+ }, 'Unknown model');++ const [header, line] = csv.split('\r\n');+ expect(header).toContain('model_id,ledger_key');+ expect(line?.split(',').slice(5, 7)).toEqual(['', foldedKey]);});});diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsxindex c4a8e00b5..27000788e 100644--- a/ui/src/components/settings/models/UsageTab.tsx+++ b/ui/src/components/settings/models/UsageTab.tsx@@ -1,457 +1,1181 @@-import type { TranslationKey } from '@/i18n/types';-// 用量 — the metered-token report over a trailing local-day window-// (`usage-summary.schema.json`).-//-// It is a report and only a report: nothing on this tab feeds resolution,-// admission, or cooldown, and the span it names is the `window_days` the server-// answered with rather than the number the user asked for. The two are the same-// for every option offered here, which is a property `usageProjection.test.ts`-// enforces rather than a coincidence to rely on.-//-// The 額度 half the tab label used to promise is absent on purpose. `cycle_used_pct`-// has exactly one production writer and it writes `None`, so a quota reading would-// be an invention; the tab is named for what it can actually show.-//-// Drawn against `design.pen MS/ConfigPanel → cp-usage-body`. No frame exists for-// this tab on the local surface, so the geometry follows the source table's own-// vocabulary — 12px card radius, 18px gutter, 11px column labels — instead of-// importing a second panel's spacing into the middle of this one. Two deliberate-// departures from that frame: the day series is a column chart because the day-// count is a window parameter and not a fixed five, and the panels stack instead-// of splitting because the table carries nested rows and a trend reads wide.import * as React from 'react';+import {+ ArrowDown,+ ArrowDownToLine,+ ChevronDown,+ CircleHelp,+ Cpu,+ Filter,+ LoaderCircle,+ Network,+ Pin,+ PinOff,+ Search,+ X,+ Zap,+} from 'lucide-react';import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';import { SegmentedRadio } from '@/components/ui/segmented';-import { formatCount, formatDayTime, formatPercent } from './format';+import { cn } from '@/lib/utils';+import { formatPercent } from './format';import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';-import type { UsageByModel, UsageBySource, UsageCounters, UsageSummary } from './types';+import type { UsageCounters, UsageReport, UsageWindowKey } from './types';import {- USAGE_WINDOW_OPTIONS,- formatLocalDay,- modelIdentity,- sourceIdentity,+ aggregateCounters,+ filterBucketRows,+ filteredRows,+ formatBucketAxisLabel,+ formatBucketLabel,+ formatBucketRange,+ identityDisplayLabel,+ modelLabel,+ pairKey,+ reportHasPartialHistory,+ reportHasUnknownTokens,+ seriesFor,+ sourceIdentityLabel,+ sourceLabel,+ usageLabelContext,usageCachedInputShare,- usageDayColumns,- usageDayIsMetered,usageIsEmpty,+ usageMetricValue,+ usageNonCachedInput,usageReportShortfall,usageTokensAreKnown,- usageTokensAreReported,- usageTotalTokens,- type UsageDayColumn,+ type UsageFilter,+ type UsageGroup,type UsageIdentity,- type UsageWindowOption,+ type UsageMetric,+ type UsageSeries,} from './usageProjection';+import { USAGE_WINDOW_OPTIONS } from './usageProjection';+import { buildUsageCsv } from './usageCsv';+import './modelHubSurface.css';++const SERIES_COLORS = [+ 'var(--mint)',+ 'var(--violet)',+ 'var(--cyan)',+ 'var(--gold)',+ 'var(--destructive)',+ 'var(--primary)',+] as const;++type FilterOption = { key: string; label: string; detail?: string };+type UsageTranslate = (key: string, options?: Record<string, unknown>) => string;++const metricKeys: UsageMetric[] = ['tokens', 'input', 'output', 'cache', 'requests'];+const groupKeys: UsageGroup[] = ['total', 'type', 'model', 'source'];++const useUsageTranslation = () => {+ const translation = useTranslation();+ return {+ ...translation,+ t: translation.t as unknown as UsageTranslate,+ };+};-/** A number that reads against a vendor's own console: grouped, never compacted. */const useCount = () => {const { i18n } = useTranslation();- return (value: number) => formatCount(value, i18n.language);+ return React.useCallback((value: number) => new Intl.NumberFormat(i18n.language).format(value), [i18n.language]);};-/** Anything a token figure is derived from: a totals bucket, a row, or a day. */-type TokenCoverage = Pick<UsageCounters, 'requests' | 'token_reports'>;--/**- * The one way this tab turns a token count into text.- *- * A rendered `0` cannot say which of three things it means — a cost reported as- * nothing, a cost nobody reported, or nothing having run at all — and every panel- * this tab draws states token figures, so wording any single one of them correctly- * leaves all the others to be found one review round at a time. The figure asks- * its own bucket first: for calls that no upstream ever costed there is no- * measurement to print, and the blank marker the cached share and the metering- * timestamp already use says exactly that.- *- * Coverage travels with the value rather than being checked by the caller, so a- * new token figure cannot be written without naming the counters it came from.- */-const useTokenText = () => {- const { t } = useTranslation();- const count = useCount();- return (counters: TokenCoverage, value: number) =>- usageTokensAreKnown(counters) ? count(value) : (t('settings.models.usage.blank') as string);+const tokenText = (+ counters: UsageCounters,+ metric: UsageMetric,+ count: (value: number) => string,+ blank: string,+): string => {+ const value = usageMetricValue(counters, metric);+ return value === null ? blank : count(value);};-/**- * A token figure standing on its own, as a cell or a card value.- *- * `data-usage-token` is not styling: it is what lets a test enumerate every token- * figure on screen and assert they all went through the door, which is a claim- * about completeness that a per-site test cannot make. A figure interpolated into- * a translated sentence has no element of its own and uses `useTokenText`- * directly; its sentence is then the asserted unit.- */-const TokenFigure: React.FC<{ counters: TokenCoverage; value: number }> = ({ counters, value }) => {- const tokenText = useTokenText();- return <span data-usage-token="">{tokenText(counters, value)}</span>;-};+const metricLabel = (metric: UsageMetric, t: UsageTranslate): string =>+ t(`settings.models.usage.metric.${metric}`);-/**- * A row's own name, or the honest absence of one.- *- * A Source that has left the inventory keeps its canonical id, so the reader can- * still tell which line of the report is which. A model has no displayable- * identity at all once its label is gone — its ledger key is a digest — so the- * row says so in words instead of printing the key.- */-const RowIdentity: React.FC<{ identity: UsageIdentity; goneKey: TranslationKey }> = ({ identity, goneKey }) => {- const { t } = useTranslation();- if (identity.kind === 'label') return <span className="truncate" title={identity.text}>{identity.text}</span>;- return (- <span className="flex min-w-0 items-baseline gap-1.5">- {identity.id !== null && <span className="truncate font-mono" title={identity.id}>{identity.id}</span>}- <span className="model-hub-usage-gone shrink-0">{t(goneKey)}</span>- </span>- );-};+function MultiFilter({+ label,+ icon,+ options,+ selected,+ onChange,+}: {+ label: string;+ icon: React.ReactNode;+ options: FilterOption[];+ selected: readonly string[];+ onChange: (next: string[]) => void;+}) {+ const { t } = useUsageTranslation();+ const [open, setOpen] = React.useState(false);+ const [query, setQuery] = React.useState('');+ const rootRef = React.useRef<HTMLDivElement>(null);+ const triggerRef = React.useRef<HTMLButtonElement>(null);++ React.useEffect(() => {+ if (!open) return undefined;+ const onPointerDown = (event: PointerEvent) => {+ if (!rootRef.current?.contains(event.target as Node)) {+ setOpen(false);+ triggerRef.current?.focus();+ }+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ setOpen(false);+ triggerRef.current?.focus();+ }+ };+ document.addEventListener('pointerdown', onPointerDown);+ document.addEventListener('keydown', onKeyDown);+ return () => {+ document.removeEventListener('pointerdown', onPointerDown);+ document.removeEventListener('keydown', onKeyDown);+ };+ }, [open]);++ const visibleOptions = options.filter((option) => (+ option.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())+ || option.detail?.toLocaleLowerCase().includes(query.toLocaleLowerCase())+ ));+ const buttonLabel = selected.length === 0+ ? t('settings.models.usage.filters.all', { label })+ : selected.length === 1+ ? options.find((option) => option.key === selected[0])?.label ?? label+ : t('settings.models.usage.filters.selected', { label, count: selected.length });++ const toggle = (key: string) => {+ onChange(selected.includes(key) ? selected.filter((item) => item !== key) : [...selected, key]);+ };-/**- * The by-source table's columns, in the order the rows state them.- *- * One list, read by the header row and by every cell's own label, so the two- * cannot come to name a column differently.- */-const SOURCE_COLUMNS = ['source', 'tokens', 'requests', 'cached', 'lastMetered'] as const;--type SourceColumn = (typeof SOURCE_COLUMNS)[number];--const columnLabel = (column: SourceColumn): TranslationKey => `settings.models.usage.bySource.col.${column}`;--/**- * One measured cell, told which column it answers.- *- * A cell's column is the position it holds in its row, which is what makes the- * header row above it an answer and not decoration — so no row may end early: the- * model row holds its empty column open below rather than shifting the cells after- * it. The label repeats the header on the cell itself because the header is the- * first thing that goes when the surface narrows, and a stacked cell has to remain- * a labelled number rather than an unattributed one. Between them the two cover- * both widths, so a per-cell `aria-colindex` would restate what position already- * says; the index earns its keep only for a row that skips a column in the middle,- * and holding the place with an empty cell is the simpler way to not have one.- */-const Cell: React.FC<{ column: SourceColumn; children: React.ReactNode }> = ({ column, children }) => {- const { t } = useTranslation();return (- <span role="cell" className="model-hub-usage-cell flex items-baseline justify-between gap-2 md:justify-end">- <span className="model-hub-usage-cell-label md:hidden">{t(columnLabel(column))}</span>- <span className="min-w-0 truncate">{children}</span>- </span>+ <div className="model-hub-usage-filter" ref={rootRef}>+ <Button+ ref={triggerRef}+ type="button"+ variant="outline"+ size="sm"+ aria-expanded={open}+ aria-haspopup="listbox"+ className={cn('model-hub-usage-filter-trigger', selected.length > 0 && 'is-filtered')}+ onClick={() => { setOpen((value) => !value); setQuery(''); }}+ >+ {icon}+ <span className="truncate">{buttonLabel}</span>+ <ChevronDown aria-hidden className="size-3 shrink-0" />+ </Button>+ {open && (+ <div className="model-hub-usage-filter-menu" role="listbox" aria-label={label} aria-multiselectable="true">+ <div className="model-hub-usage-filter-search">+ <Search aria-hidden className="size-3.5 shrink-0" />+ <input+ autoFocus+ value={query}+ aria-label={t('settings.models.usage.filters.search', { label }) as string}+ placeholder={t('settings.models.usage.filters.search', { label }) as string}+ onChange={(event) => setQuery(event.target.value)}+ />+ </div>+ <button+ type="button"+ role="option"+ aria-selected={selected.length === 0}+ className="model-hub-usage-filter-option"+ onClick={() => onChange([])}+ >+ <Checkbox checked={selected.length === 0} presentational />+ {t('settings.models.usage.filters.all', { label })}+ </button>+ <div className="model-hub-usage-filter-divider" />+ {visibleOptions.map((option) => (+ <button+ type="button"+ role="option"+ aria-selected={selected.includes(option.key)}+ className="model-hub-usage-filter-option"+ key={option.key}+ onClick={() => toggle(option.key)}+ >+ <Checkbox checked={selected.includes(option.key)} presentational />+ <span className="min-w-0 truncate">+ <span className="block truncate">{option.label}</span>+ {option.detail && <span className="block truncate text-[10px] text-muted">{option.detail}</span>}+ </span>+ </button>+ ))}+ {visibleOptions.length === 0 && <p className="model-hub-usage-filter-empty">{t('settings.models.usage.filters.noMatch')}</p>}+ <p className="model-hub-usage-filter-foot">{t('settings.models.usage.filters.hint')}</p>+ </div>+ )}+ </div>);-};+}-const StatCard: React.FC<{ label: string; value: React.ReactNode; note: string }> = ({ label, value, note }) => (- <div className="model-hub-usage-stat flex flex-col rounded-xl border border-border bg-background">- <span className="model-hub-usage-stat-label">{label}</span>- <span className="model-hub-usage-stat-value font-semibold text-foreground">{value}</span>- <span className="model-hub-usage-stat-note">{note}</span>+const ChartLegend: React.FC<{+ series: UsageSeries[];+ hidden: readonly string[];+ onToggle: (key: string) => void;+ labels: Map<string, string>;+ count: (value: number) => string;+ blank: string;+ ariaLabel: string;+}> = ({ series, hidden, onToggle, labels, count, blank, ariaLabel }) => (+ <div className="model-hub-usage-legend" aria-label={ariaLabel}>+ {series.map((item) => {+ const values = item.values.filter((value): value is number => value !== null);+ const total = values.reduce((sum, value) => sum + value, 0);+ const isHidden = hidden.includes(item.key);+ return (+ <button+ type="button"+ key={item.key}+ aria-pressed={!isHidden}+ className={cn('model-hub-usage-legend-item', isHidden && 'is-hidden')}+ onClick={() => onToggle(item.key)}+ >+ <span className="model-hub-usage-legend-swatch" style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />+ <span>{labels.get(item.key) ?? item.label}</span>+ <strong>{values.length === 0 ? blank : count(total)}</strong>+ </button>+ );+ })}</div>);-const StatGrid: React.FC<{ summary: UsageSummary }> = ({ summary }) => {- const { t, i18n } = useTranslation();+function UsageChart({+ report,+ filter,+ metric,+ group,+ pinnedKey,+ scopeKey,+ onPin,+}: {+ report: UsageReport;+ filter: UsageFilter;+ metric: UsageMetric;+ group: UsageGroup;+ pinnedKey: string | null;+ scopeKey: string;+ onPin: (key: string | null) => void;+}) {+ const { t, i18n } = useUsageTranslation();const count = useCount();- const totals = summary.totals;- const shortfall = usageReportShortfall(totals);- const cachedShare = usageCachedInputShare(totals);- return (- <div className="grid gap-4 sm:grid-cols-3">- <StatCard- label={t('settings.models.usage.tokens.label') as string}- value={<TokenFigure counters={totals} value={usageTotalTokens(totals)} />}- // The input/output split is a reading of the same unreported total, so it- // cannot survive on its own once the total is blank: it says what nobody- // reported instead.- note={(usageTokensAreKnown(totals)- ? t('settings.models.usage.tokens.detail', { input: count(totals.input_tokens), output: count(totals.output_tokens) })- : t('settings.models.usage.tokens.none')) as string}- />- <StatCard- label={t('settings.models.usage.requests.label') as string}- value={count(totals.requests)}- // A shortfall means reports that never arrived, never capacity left- // unused, and the copy has to say which of the two it is.- note={(shortfall > 0- ? t('settings.models.usage.requests.shortfall', { count: shortfall })- : t('settings.models.usage.requests.reported')) as string}- />- <StatCard- label={t('settings.models.usage.cached.label') as string}- value={cachedShare === null ? (t('settings.models.usage.blank') as string) : formatPercent(cachedShare, i18n.language)}- // 「No input tokens in this window」 is the same defect one card over: with- // nothing reported there were no input tokens WE KNOW OF, and an absence of- // reports is not an absence of usage. Coverage is asked before the share, so- // the card states the missing reports rather than an empty input.- note={(!usageTokensAreKnown(totals)- ? t('settings.models.usage.tokens.none')- : cachedShare === null- ? t('settings.models.usage.cached.none')- : t('settings.models.usage.cached.detail', { cached: count(totals.cached_input_tokens), input: count(totals.input_tokens) })) as string}- />- </div>- );-};+ const [hovered, setHovered] = React.useState<number | null>(null);+ const [inspected, setInspected] = React.useState<number | null>(null);+ const [dismissed, setDismissed] = React.useState(false);+ const [hidden, setHidden] = React.useState<string[]>([]);+ const [width, setWidth] = React.useState(920);+ const [keyboardActivation, setKeyboardActivation] = React.useState(0);+ const hostRef = React.useRef<HTMLDivElement>(null);+ const pinButtonRef = React.useRef<HTMLButtonElement>(null);+ const bucketButtonRefs = React.useRef(new Map<string, HTMLButtonElement>());+ const invokingBucketKeyRef = React.useRef<string | null>(null);+ const suppressNextBucketFocusRef = React.useRef(false);+ const focusPinAfterOpenRef = React.useRef(false);+ const previousUsageInputRef = React.useRef({ report, scopeKey, group, metric });+ const hoverClearTimer = React.useRef<number | null>(null);+ const pendingHoverTimer = React.useRef<number | null>(null);+ const [escapeDismissed, setEscapeDismissed] = React.useState(false);+ const pinnedIndex = pinnedKey === null ? -1 : report.buckets.findIndex((bucket) => bucket.key === pinnedKey);+ const requestedIndex = dismissed || escapeDismissed+ ? null+ : pinnedIndex >= 0 ? pinnedIndex : inspected ?? hovered;+ const activeIndex = requestedIndex !== null+ && requestedIndex >= 0+ && requestedIndex < report.buckets.length+ ? requestedIndex+ : null;+ const bars = report.window_key === '30d' || report.window_key === '60d';+ const unknownModelLabel = t('settings.models.usage.unknownModel');+ const series = React.useMemo(() => seriesFor(report, filter, group, metric, unknownModelLabel), [filter, group, metric, unknownModelLabel, report]);+ const labels = React.useMemo(() => new Map(series.map((item) => [+ item.key,+ item.key === 'total'+ ? metricLabel(metric, t)+ : item.key === 'input'+ ? t('settings.models.usage.series.input')+ : item.key === 'cache'+ ? t('settings.models.usage.series.cache')+ : item.key === 'output'+ ? t('settings.models.usage.series.output')+ : item.key === 'requests'+ ? t('settings.models.usage.series.requests')+ : item.label,+ ])), [metric, series, t]);+ const visibleSeries = series.filter((item) => !hidden.includes(item.key));+ const narrow = width < 560;+ const height = narrow ? 236 : 292;+ const left = narrow ? 40 : 54;+ const right = 16;+ const top = 18;+ const bottom = 38;+ const plotWidth = Math.max(1, width - left - right);+ const plotHeight = Math.max(1, height - top - bottom);+ const lineHitWidth = Math.min(28, Math.max(8, plotWidth / Math.max(1, report.buckets.length - 1) * 0.82));+ const values = report.buckets.map((_, index) => bars+ ? visibleSeries.reduce((sum, item) => sum + (item.values[index] ?? 0), 0)+ : Math.max(0, ...visibleSeries.map((item) => item.values[index] ?? 0)));+ const rawMax = Math.max(1, ...values);+ const scale = 10 ** Math.floor(Math.log10(rawMax));+ const max = Math.ceil(rawMax / scale / 0.5) * scale * 0.5;+ const x = (index: number) => left + (bars+ ? (index + 0.5) / report.buckets.length+ : index / Math.max(1, report.buckets.length - 1)) * plotWidth;+ const y = (value: number) => top + plotHeight * (1 - value / max);+ const bucket = activeIndex === null || activeIndex < 0 ? null : report.buckets[activeIndex];+ const bucketRows = bucket === null ? [] : filterBucketRows(bucket, filter);+ const bucketTotals = aggregateCounters(bucketRows);+ const activeValue = bucket && !bucket.history_complete && bucketRows.length === 0+ ? null+ : usageMetricValue(bucketTotals, metric);+ const currentPartialHour = bucket !== null+ && report.window_key === '24h'+ && activeIndex === report.buckets.length - 1+ && Date.parse(bucket.end_at) - Date.parse(bucket.start_at) < 60 * 60 * 1000;+ const tickIndexes = report.buckets.length <= 7+ ? report.buckets.map((_, index) => index)+ : [...new Set([0, Math.floor((report.buckets.length - 1) / 2), report.buckets.length - 1])];-const ModelRow: React.FC<{ model: UsageByModel }> = ({ model }) => {- const { t, i18n } = useTranslation();- const count = useCount();- const share = usageCachedInputShare(model);- return (- <div role="row" className="model-hub-usage-row model-hub-usage-row--model grid border-t border-border md:items-center">- <span role="rowheader" className="model-hub-usage-model flex min-w-0 items-baseline">- <RowIdentity identity={modelIdentity(model)} goneKey="settings.models.usage.bySource.goneModel" />- </span>- <Cell column="tokens"><TokenFigure counters={model} value={usageTotalTokens(model)} /></Cell>- <Cell column="requests">{count(model.requests)}</Cell>- <Cell column="cached">- {share === null ? (t('settings.models.usage.blank') as string) : formatPercent(share, i18n.language)}- </Cell>- {/* A model has no metering timestamp of its own; the column stays empty- rather than repeating the Source's, and holds its place so every cell- before it still sits under the header it answers. */}- <span role="cell" className="hidden md:block" />- </div>- );-};+ const cancelPendingHover = () => {+ if (pendingHoverTimer.current !== null) {+ window.clearTimeout(pendingHoverTimer.current);+ pendingHoverTimer.current = null;+ }+ };+ const cancelHoverClear = () => {+ if (hoverClearTimer.current !== null) {+ window.clearTimeout(hoverClearTimer.current);+ hoverClearTimer.current = null;+ }+ };+ const handleEscape = React.useCallback(() => {+ if (pendingHoverTimer.current !== null) {+ window.clearTimeout(pendingHoverTimer.current);+ pendingHoverTimer.current = null;+ }+ if (hoverClearTimer.current !== null) {+ window.clearTimeout(hoverClearTimer.current);+ hoverClearTimer.current = null;+ }+ const invokingButton = invokingBucketKeyRef.current === null+ ? null+ : bucketButtonRefs.current.get(invokingBucketKeyRef.current) ?? null;+ if (pinnedKey !== null) {+ onPin(null);+ }+ setEscapeDismissed(true);+ setHovered(null);+ setInspected(null);+ setDismissed(true);+ focusPinAfterOpenRef.current = false;+ invokingBucketKeyRef.current = null;+ if (activeIndex !== null && invokingButton !== null+ && hostRef.current?.contains(document.activeElement)) {+ suppressNextBucketFocusRef.current = true;+ invokingButton.focus();+ }+ }, [activeIndex, onPin, pinnedKey]);-const SourceRows: React.FC<{ source: UsageBySource }> = ({ source }) => {- const { t, i18n } = useTranslation();- const count = useCount();- const share = usageCachedInputShare(source);- return (- // A Source and the models under it are one group of rows, which is also what- // the border draws: the group is the unit a reader scans, not each line.- <div role="rowgroup" className="border-b border-border last:border-b-0">- <div role="row" className="model-hub-usage-row grid md:items-center">- <span role="rowheader" className="model-hub-usage-source flex min-w-0 items-baseline font-semibold text-foreground">- <RowIdentity identity={sourceIdentity(source)} goneKey="settings.models.usage.bySource.goneSource" />- </span>- <Cell column="tokens"><TokenFigure counters={source} value={usageTotalTokens(source)} /></Cell>- <Cell column="requests">{count(source.requests)}</Cell>- <Cell column="cached">- {share === null ? (t('settings.models.usage.blank') as string) : formatPercent(share, i18n.language)}- </Cell>- <Cell column="lastMetered">- {source.last_metered_at === null ? (t('settings.models.usage.blank') as string) : formatDayTime(source.last_metered_at, i18n.language)}- </Cell>- </div>- {source.models.map((model) => <ModelRow key={model.model_id} model={model} />)}- </div>- );-};+ React.useEffect(() => {+ const previousInput = previousUsageInputRef.current;+ const inputChanged = previousInput.report !== report+ || previousInput.scopeKey !== scopeKey+ || previousInput.group !== group+ || previousInput.metric !== metric;+ if (!inputChanged) return;+ const scopeChanged = previousInput.scopeKey !== scopeKey;+ previousUsageInputRef.current = { report, scopeKey, group, metric };+ const invokingKey = invokingBucketKeyRef.current;+ const invokingDetailSurvives = !scopeChanged+ && pinnedKey !== null+ && invokingKey !== null+ && report.buckets.some((currentBucket) => currentBucket.key === invokingKey);+ setHovered(null);+ setInspected(null);+ setDismissed(false);+ setEscapeDismissed(false);+ setHidden([]);+ if (!invokingDetailSurvives) invokingBucketKeyRef.current = null;+ suppressNextBucketFocusRef.current = false;+ focusPinAfterOpenRef.current = false;+ }, [group, metric, pinnedKey, report, scopeKey]);-const BySourcePanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {- const { t } = useTranslation();- const titleId = React.useId();- return (- <section className="model-hub-usage-card overflow-hidden rounded-xl border border-border bg-background">- <h3 id={titleId} className="model-hub-usage-card-head model-hub-usage-section-title border-b border-border font-semibold text-foreground">- {t('settings.models.usage.bySource.title')}- </h3>- {/* A table by role rather than by tag. The layout is a CSS grid that stacks- into labelled lines on a narrow surface, which a `<table>` can only do- through a `display` override — and overriding `display` is exactly what- strips a table of the semantics it was chosen for. Explicit roles keep- the grid and the structure at every width. */}- <div role="table" aria-labelledby={titleId}>- <div role="row" className="model-hub-usage-head hidden border-b border-border font-semibold md:grid">- {SOURCE_COLUMNS.map((column, index) => (- <span key={column} role="columnheader" className={index === 0 ? 'truncate' : 'flex justify-end truncate'}>- {t(columnLabel(column))}- </span>- ))}- </div>- {summary.sources.map((source) => <SourceRows key={source.source_id} source={source} />)}- </div>- </section>- );-};+ React.useEffect(() => {+ if (!focusPinAfterOpenRef.current || activeIndex === null) return;+ focusPinAfterOpenRef.current = false;+ pinButtonRef.current?.focus();+ }, [activeIndex, keyboardActivation]);++ React.useEffect(() => {+ if (!hostRef.current || typeof ResizeObserver === 'undefined') return undefined;+ const observer = new ResizeObserver((entries) => {+ setWidth(Math.max(280, entries[0]?.contentRect.width ?? 920));+ });+ observer.observe(hostRef.current);+ return () => observer.disconnect();+ }, []);++ React.useEffect(() => {+ const onPointerDown = (event: PointerEvent) => {+ if (pinnedKey !== null || hostRef.current?.contains(event.target as Node)) return;+ setHovered(null);+ setInspected(null);+ setDismissed(true);+ invokingBucketKeyRef.current = null;+ focusPinAfterOpenRef.current = false;+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ handleEscape();+ };+ document.addEventListener('pointerdown', onPointerDown);+ document.addEventListener('keydown', onKeyDown);+ return () => {+ document.removeEventListener('pointerdown', onPointerDown);+ document.removeEventListener('keydown', onKeyDown);+ };+ }, [handleEscape, pinnedKey]);++ React.useEffect(() => () => {+ if (hoverClearTimer.current !== null) window.clearTimeout(hoverClearTimer.current);+ if (pendingHoverTimer.current !== null) window.clearTimeout(pendingHoverTimer.current);+ }, []);++ const scheduleHoverClear = () => {+ if (pinnedKey !== null || inspected !== null) return;+ cancelPendingHover();+ cancelHoverClear();+ hoverClearTimer.current = window.setTimeout(() => {+ hoverClearTimer.current = null;+ setHovered(null);+ }, 100);+ };++ const setHover = (index: number, reopenAfterEscape = false) => {+ if ((escapeDismissed && !reopenAfterEscape) || pinnedKey !== null || inspected !== null) return;+ cancelPendingHover();+ cancelHoverClear();+ const next = Math.max(0, Math.min(report.buckets.length - 1, index));+ if (reopenAfterEscape) setEscapeDismissed(false);+ setDismissed(false);+ if (hovered === null || hovered === next) {+ setHovered(next);+ return;+ }+ pendingHoverTimer.current = window.setTimeout(() => {+ pendingHoverTimer.current = null;+ if (escapeDismissed && !reopenAfterEscape) return;+ setHovered(next);+ }, 100);+ };+ const openDetail = (index: number) => {+ if (pinnedKey !== null) return;+ invokingBucketKeyRef.current = null;+ focusPinAfterOpenRef.current = false;+ setEscapeDismissed(false);+ setDismissed(false);+ setInspected(index);+ setHovered(null);+ };+ const openKeyboardDetail = (index: number) => {+ if (pinnedKey !== null) return;+ invokingBucketKeyRef.current = report.buckets[index]?.key ?? null;+ focusPinAfterOpenRef.current = true;+ setKeyboardActivation((value) => value + 1);+ setEscapeDismissed(false);+ setDismissed(false);+ setInspected(index);+ setHovered(null);+ };+ const handleBucketFocus = (index: number) => {+ if (suppressNextBucketFocusRef.current) {+ suppressNextBucketFocusRef.current = false;+ return;+ }+ setHover(index, true);+ };+ const toggleHidden = (key: string) => {+ setHidden((current) => {+ if (current.includes(key)) return current.filter((item) => item !== key);+ if (current.length >= series.length - 1) return current;+ return [...current, key];+ });+ };+ const svgIndexFromPointer = (event: React.PointerEvent<SVGSVGElement>) => {+ const bounds = event.currentTarget.getBoundingClientRect();+ const position = ((event.clientX - bounds.left) / bounds.width) * width;+ const index = bars+ ? Math.floor((position - left) / plotWidth * report.buckets.length)+ : Math.round((position - left) / plotWidth * (report.buckets.length - 1));+ return Math.max(0, Math.min(report.buckets.length - 1, index));+ };+ const pinLabel = pinnedKey !== null+ ? t('settings.models.usage.chart.unpin')+ : t('settings.models.usage.chart.pin');-/**- * The trend, over every day of the window rather than every day reported.- *- * `usageDayColumns` is what densifies it; the track behind each column is what- * makes the zero-fill legible. A bar of zero height in an empty row is- * indistinguishable from a missing bar, and the difference — an idle day versus a- * day the report does not cover — is the whole reason the series is drawn.- *- * Which day ran is `usageDayIsMetered`'s answer and never a token total: an- * upstream can serve a call and report nothing about it, so a window of those has- * bars to draw and a peak it cannot name. Whether a day's cost is known at all is- * `usageTokensAreReported`'s separate answer — asked of the very same zero.- */-const ByDayPanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {- const { t, i18n } = useTranslation();- const count = useCount();- const tokenText = useTokenText();- const columns = React.useMemo(() => usageDayColumns(summary), [summary]);- // Only a day whose tokens were reported can be the busiest one. A day with no- // report has no measured cost to compare, so naming it the peak would put a- // superlative on a number the report never carried.- const peak = columns.reduce<UsageDayColumn | null>(- (best, column) => (usageTokensAreReported(column) && column.tokens > (best?.tokens ?? 0) ? column : best),- null,- );- const metered = columns.some(usageDayIsMetered);- const reported = columns.some(usageTokensAreReported);- const day = (value: string) => formatLocalDay(value, i18n.language);- // One day's figures as a hover readout. The table below states the same three- // values in cells, and MH-USAGE-023 derives its expectation from this sentence- // so the two readings of a day cannot answer differently.- const readout = (column: UsageDayColumn) =>- t('settings.models.usage.byDay.column', {- day: day(column.day),- tokens: tokenText(column, column.tokens),- requests: count(column.requests),- }) as string;return (- <section className="model-hub-usage-card overflow-hidden rounded-xl border border-border bg-background">- <h3 className="model-hub-usage-card-head model-hub-usage-section-title border-b border-border font-semibold text-foreground">- {t('settings.models.usage.byDay.title')}- </h3>- <div className="model-hub-usage-plot flex flex-col">+ <div className="model-hub-usage-chart-content">+ <ChartLegend+ series={series}+ hidden={hidden}+ onToggle={toggleHidden}+ labels={labels}+ count={count}+ blank={t('settings.models.usage.blank') as string}+ ariaLabel={t('settings.models.usage.chart.legend') as string}+ />+ <div className="model-hub-usage-chart-wrap" ref={hostRef}>+ <svg+ className="model-hub-usage-svg"+ viewBox={`0 0 ${width} ${height}`}+ aria-hidden="true"+ onPointerMove={(event) => {+ if (event.pointerType !== 'touch') setHover(svgIndexFromPointer(event), true);+ }}+ onPointerLeave={scheduleHoverClear}+ >+ <defs>+ <pattern id="usage-unknown-pattern" width="6" height="6" patternUnits="userSpaceOnUse">+ <path d="M-1,1 l2,-2 M0,6 L6,0 M5,7 l2,-2" stroke="var(--model-hub-usage-unknown)" strokeWidth="1" />+ </pattern>+ </defs>+ {[0, 1, 2, 3, 4].map((step) => (+ <g key={step}>+ <line x1={left} x2={width - right} y1={y(max * step / 4)} y2={y(max * step / 4)} className="model-hub-usage-grid" strokeDasharray={step === 0 ? undefined : '3 5'} />+ <text x={left - 10} y={y(max * step / 4) + 4} textAnchor="end" className="model-hub-usage-tick">{count(max * step / 4)}</text>+ </g>+ ))}+ {activeIndex !== null && activeIndex >= 0 && (+ <rect+ x={x(activeIndex) - (bars ? plotWidth / report.buckets.length / 2 : 18)}+ y={top}+ width={bars ? plotWidth / report.buckets.length : 36}+ height={plotHeight}+ className="model-hub-usage-highlight"+ rx="4"+ />+ )}+ {bars+ ? report.buckets.map((currentBucket, index) => {+ let offset = 0;+ return (+ <g key={currentBucket.key}>+ {visibleSeries.map((item) => {+ const value = item.values[index];+ const start = offset;+ offset += value ?? 0;+ return (+ <rect+ key={item.key}+ x={x(index) - plotWidth / report.buckets.length * 0.32}+ y={y(offset)}+ width={plotWidth / report.buckets.length * 0.64}+ height={value === null ? 4 : Math.max(0, y(start) - y(offset))}+ fill={value === null ? 'url(#usage-unknown-pattern)' : SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]}+ opacity={activeIndex !== null && activeIndex !== index ? 0.48 : 0.88}+ rx="2"+ />+ );+ })}+ </g>+ );+ })+ : visibleSeries.map((item) => {+ const path = item.values.reduce<string[]>((segments, value, index) => {+ if (value === null) return segments;+ const previous = item.values[index - 1];+ const command = previous === null || previous === undefined ? 'M' : 'L';+ segments.push(`${command}${x(index)},${y(value)}`);+ return segments;+ }, []).join(' ');+ return (+ <g key={item.key}>+ <path d={path} fill="none" stroke={SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />+ {item.values.map((value, index) => value === null+ ? <circle key={index} cx={x(index)} cy={y(0)} r="3" className="model-hub-usage-unknown-point" />+ : <circle key={index} cx={x(index)} cy={y(value)} r={activeIndex === index ? 4.5 : 2.5} fill={SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]} stroke="var(--background)" strokeWidth="1.5" />)}+ </g>+ );+ })}+ {activeIndex !== null && activeIndex >= 0 && (+ <line x1={x(activeIndex)} x2={x(activeIndex)} y1={top} y2={top + plotHeight} className="model-hub-usage-crosshair" />+ )}+ {report.buckets.map((currentBucket, index) => (+ <rect+ key={`hit-${currentBucket.key}`}+ className="model-hub-usage-hit-area"+ x={bars ? x(index) - plotWidth / report.buckets.length / 2 : x(index) - lineHitWidth / 2}+ y={top}+ width={bars ? plotWidth / report.buckets.length : lineHitWidth}+ height={plotHeight}+ onPointerEnter={() => {+ // Removing a dismissed tooltip can expose a stationary pointer.+ // Only a real move, focus, or activation should reopen it.+ setHover(index);+ }}+ onClick={() => openDetail(index)}+ />+ ))}+ {tickIndexes.map((index) => (+ <text+ key={`tick-${report.buckets[index].key}`}+ x={x(index)}+ y={height - 12}+ textAnchor={index === 0 ? 'start' : index === report.buckets.length - 1 ? 'end' : 'middle'}+ className="model-hub-usage-tick"+ >+ {formatBucketAxisLabel(report.buckets[index], i18n.language)}+ </text>+ ))}+ </svg><div- role="img"- aria-label={t('settings.models.usage.byDay.chart', { from: day(summary.from_day), to: day(summary.to_day) }) as string}- className="model-hub-usage-chart flex items-end"+ className="sr-only"+ role="group"+ aria-label={t('settings.models.usage.chart.detail') as string}>- {columns.map((column) => (- <div- key={column.day}- className="model-hub-usage-track flex flex-1 items-end"- title={readout(column)}+ {report.buckets.map((currentBucket, index) => (+ <button+ type="button"+ key={`accessible-${currentBucket.key}`}+ ref={(element) => {+ if (element) bucketButtonRefs.current.set(currentBucket.key, element);+ else bucketButtonRefs.current.delete(currentBucket.key);+ }}+ aria-label={t('settings.models.usage.chart.bucket', {+ bucket: formatBucketRange(currentBucket, i18n.language, true),+ }) as string}+ onPointerEnter={() => {+ setHover(index);+ }}+ onFocus={() => handleBucketFocus(index)}+ onClick={() => openKeyboardDetail(index)}>- {/* A metered day is floored to a visible sliver so the quietest one- still reads as activity — including one whose tokens never came- back, which is why the floor asks about calls and not about- tokens. Only a day that carried nothing keeps zero height and- shows the track alone. */}- <div className="model-hub-usage-column w-full" style={{ height: usageDayIsMetered(column) ? `max(2px, ${column.ratio * 100}%)` : 0 }} />- </div>+ {formatBucketRange(currentBucket, i18n.language, true)}+ </button>))}</div>- {/* Every day's figures again, as a table. A pointer tooltip is the one- readout a keyboard or screen-reader user cannot open, and `role="img"`- above hides the columns from assistive tech by design — so the series- needs a second reading, in cells rather than one sentence per day,- which is the same per-column association the Source table carries.- Sibling of the image, never a child: inside it, it would be hidden- along with everything else. */}- {/* Apply the visually-hidden box to a generic wrapper. A table keeps its- intrinsic column width even when the table itself is only one pixel- wide; containing that layout inside the clipped wrapper keeps its- semantics without letting it widen the document. */}- <div className="model-hub-usage-a11y-table sr-only">- <table>- <caption>{t('settings.models.usage.byDay.table', { from: day(summary.from_day), to: day(summary.to_day) })}</caption>- <thead>- <tr>- <th scope="col">{t('settings.models.usage.byDay.col.day')}</th>- <th scope="col">{t('settings.models.usage.tokens.label')}</th>- <th scope="col">{t('settings.models.usage.requests.label')}</th>- </tr>- </thead>- <tbody>- {columns.map((column) => (- <tr key={column.day}>- <th scope="row">{day(column.day)}</th>- <td><TokenFigure counters={column} value={column.tokens} /></td>- <td>{count(column.requests)}</td>- </tr>+ {bucket && (+ <div+ className={cn('model-hub-usage-tooltip', pinnedKey !== null && 'is-pinned')}+ role="dialog"+ aria-label={t('settings.models.usage.chart.detail') as string}+ data-pinned={pinnedKey !== null ? 'true' : 'false'}+ onPointerEnter={() => {+ cancelPendingHover();+ cancelHoverClear();+ }}+ onPointerLeave={scheduleHoverClear}+ onKeyDownCapture={(event) => {+ if (event.key !== 'Escape') return;+ event.stopPropagation();+ handleEscape();+ }}+ >+ <div className="model-hub-usage-tooltip-head">+ <span>{formatBucketRange(bucket, i18n.language, true)}</span>+ <div className="model-hub-usage-tooltip-actions">+ {pinnedKey !== null && <span>{t('settings.models.usage.chart.pinned')}</span>}+ <button+ type="button"+ ref={pinButtonRef}+ className="model-hub-usage-pin"+ aria-label={pinLabel as string}+ aria-pressed={pinnedKey !== null}+ title={pinLabel as string}+ onClick={() => onPin(pinnedKey !== null ? null : bucket.key)}+ >+ {pinnedKey !== null ? <PinOff aria-hidden className="size-3.5" /> : <Pin aria-hidden className="size-3.5" />}+ </button>+ </div>+ </div>+ <div className="model-hub-usage-tooltip-total">+ <strong>{activeValue === null ? t('settings.models.usage.blank') : count(activeValue)}</strong>+ <span>{metricLabel(metric, t)}</span>+ </div>+ <div className="model-hub-usage-tooltip-lines">+ {visibleSeries.map((item) => (+ <div key={item.key}>+ <span><i style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />{labels.get(item.key) ?? item.label}</span>+ <b>{item.values[activeIndex as number] === null ? t('settings.models.usage.blank') : count(item.values[activeIndex as number] ?? 0)}</b>+ </div>))}- </tbody>- </table>- </div>- <div className="model-hub-usage-axis">- <span className="model-hub-usage-axis-label">{day(summary.from_day)}</span>- <span className="model-hub-usage-axis-label model-hub-usage-peak">- {peak !== null- ? t('settings.models.usage.byDay.peak', { tokens: tokenText(peak, peak.tokens), day: day(peak.day) })- // No peak is three different windows, and the tokens cannot tell them- // apart: one nobody used, one whose upstreams never reported what the- // calls cost, and one that was measured and really did cost nothing.- // Coverage is asked before activity, because a window with any report- // in it can state what its reports said — the calls that came back- // without one are the requests card's shortfall to name, not this- // sentence's.- : reported- ? t('settings.models.usage.byDay.zero')- : metered- ? t('settings.models.usage.byDay.unreported')- : t('settings.models.usage.byDay.quiet')}- </span>- <span className="model-hub-usage-axis-label">{day(summary.to_day)}</span>- </div>+ </div>+ <div className="model-hub-usage-tooltip-foot">+ <span>+ {bucket.history_complete || bucketRows.length > 0 ? count(bucketTotals.requests) : t('settings.models.usage.blank')}+ {' '}+ {t('settings.models.usage.requests.unit')}+ </span>+ {currentPartialHour && <span>{t('settings.models.usage.chart.currentPartial')}</span>}+ <span>{bucket.history_complete ? t('settings.models.usage.chart.complete') : t('settings.models.usage.chart.partial')}</span>+ </div>+ </div>+ )}</div>- </section>+ <div className="model-hub-usage-chart-foot">+ <span>{t('settings.models.usage.chart.points', { count: report.buckets.length, granularity: t(`settings.models.usage.granularity.${report.granularity}`) })}</span>+ <span>{hidden.length > 0 ? t('settings.models.usage.chart.legendOnly') : t('settings.models.usage.chart.interaction')}</span>+ </div>+ </div>);+}++type TableRow = {+ key: string;+ label: string;+ detail: string;+ counters: UsageCounters;};+function tableRows(+ report: UsageReport,+ filter: UsageFilter,+ group: 'model' | 'source',+ pinnedKey: string | null,+ unknownModelLabel: string,+): TableRow[] {+ const buckets = pinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === pinnedKey);+ const rows = buckets.flatMap((bucket) => filterBucketRows(bucket, filter));+ const grouped = new Map<string, TableRow>();+ const labelContext = usageLabelContext(report, filteredRows(report, filter), unknownModelLabel);+ for (const row of rows) {+ const key = group === 'source' ? row.source_id : pairKey(row.source_id, row.model_id);+ const identity = group === 'source'+ ? null+ : {+ key,+ sourceId: row.source_id,+ modelId: row.model_id,+ sourceLabel: sourceLabel(report, row.source_id),+ modelLabel: modelLabel(report, row.source_id, row.model_id),+ } satisfies UsageIdentity;+ const previous = grouped.get(key);+ grouped.set(key, {+ key,+ label: group === 'source'+ ? sourceIdentityLabel(report, row.source_id, labelContext)+ : identityDisplayLabel(identity!, unknownModelLabel, labelContext),+ detail: group === 'source' ? '' : sourceIdentityLabel(report, row.source_id, labelContext),+ counters: aggregateCounters([...(previous ? [previous.counters] : []), row]),+ });+ }+ return [...grouped.values()];+}++const StatCard: React.FC<{ label: string; value: React.ReactNode; note: React.ReactNode }> = ({ label, value, note }) => (+ <div className="model-hub-usage-stat-card">+ <span className="model-hub-usage-stat-label">{label}</span>+ <strong className="model-hub-usage-stat-value">{value}</strong>+ <span className="model-hub-usage-stat-note">{note}</span>+ </div>+);+export const UsageTab: React.FC<{- usage: RegionRead<UsageSummary>;- /** The window the user asked for. The report answers with what it served. */- windowDays: UsageWindowOption;- onWindowChange: (days: UsageWindowOption) => void;+ usage: RegionRead<UsageReport>;+ windowKey: UsageWindowKey;+ onWindowChange: (window: UsageWindowKey) => void;onRetry?: () => void | Promise<void>;-}> = ({ usage: usageRead, windowDays, onWindowChange, onRetry }) => {- const { t, i18n } = useTranslation();- const summary = foldRegionRead<UsageSummary, UsageSummary | null>(usageRead, {+}> = ({ usage: usageRead, windowKey, onWindowChange, onRetry }) => {+ const { t, i18n } = useUsageTranslation();+ const count = useCount();+ const report = foldRegionRead<UsageReport, UsageReport | null>(usageRead, {loading: () => null,ready: (data) => data,unread: () => null,- // A stale report is still the last true one; it stays on screen under the- // failure strip rather than being replaced by an empty state that would read- // as "nothing was ever metered".degraded: (staleData) => staleData,});- const options = React.useMemo(- () => USAGE_WINDOW_OPTIONS.map((option) => ({ id: String(option), label: t('settings.models.usage.window.option', { days: option }) as string })),- [t],+ const [sourceIds, setSourceIds] = React.useState<string[]>([]);+ const [modelKeys, setModelKeys] = React.useState<string[]>([]);+ const [metric, setMetric] = React.useState<UsageMetric>('tokens');+ const [group, setGroup] = React.useState<UsageGroup>('type');+ const [tableGroup, setTableGroup] = React.useState<'model' | 'source'>('model');+ const [sortAscending, setSortAscending] = React.useState(false);+ const [pinnedKey, setPinnedKey] = React.useState<string | null>(null);+ const scopeKey = JSON.stringify([windowKey, sourceIds, modelKeys, metric, group]);++ React.useEffect(() => {+ setSourceIds([]);+ setModelKeys([]);+ setPinnedKey(null);+ }, [windowKey]);++ React.useEffect(() => {+ setPinnedKey(null);+ }, [scopeKey]);++ React.useEffect(() => {+ if (report !== null && pinnedKey !== null && !report.buckets.some((bucket) => bucket.key === pinnedKey)) {+ setPinnedKey(null);+ }+ }, [report, pinnedKey]);++ if (report === null) {+ return (+ <div className="model-hub-usage-analytics">+ <UsageHeading report={null} windowKey={windowKey} onWindowChange={onWindowChange} />+ {regionFailed(usageRead) ? (+ <FailureState onRetry={onRetry} />+ ) : (+ <div className="model-hub-usage-loading" role="status">+ <LoaderCircle className="size-4 animate-spin" />+ {t('common.loading')}+ </div>+ )}+ </div>+ );+ }++ const allRows = filteredRows(report, { sourceIds: [], modelKeys: [] });+ const unknownModelLabel = t('settings.models.usage.unknownModel');+ const labelContext = usageLabelContext(report, allRows, unknownModelLabel);+ const sourceOptions: FilterOption[] = report.sources.map((source) => ({+ key: source.source_id,+ label: sourceIdentityLabel(report, source.source_id, labelContext),+ }));+ const modelOptions = [...new Map(+ allRows.map((row) => {+ const key = pairKey(row.source_id, row.model_id);+ const identity = {+ key,+ sourceId: row.source_id,+ modelId: row.model_id,+ sourceLabel: sourceLabel(report, row.source_id),+ modelLabel: modelLabel(report, row.source_id, row.model_id),+ } satisfies UsageIdentity;+ return [key, {+ key,+ label: identityDisplayLabel(identity, unknownModelLabel, labelContext),+ detail: identity.modelLabel ? undefined : unknownModelLabel,+ }];+ }),+ ).values()];+ const filter: UsageFilter = { sourceIds, modelKeys };+ const scopedRows = filteredRows(report, filter);+ const totals = aggregateCounters(scopedRows);+ const partialHistory = reportHasPartialHistory(report, filter);+ const reportEmpty = usageIsEmpty(report);+ const filteredEmpty = !reportEmpty && scopedRows.length === 0 && !partialHistory;+ const historyOnlyUnknown = partialHistory && scopedRows.length === 0;+ const pinnedBucket = pinnedKey === null+ ? null+ : report.buckets.find((bucket) => bucket.key === pinnedKey) ?? null;+ const activePinnedKey = pinnedBucket?.key ?? null;+ const rows = tableRows(report, filter, tableGroup, activePinnedKey, unknownModelLabel);+ const sortValue = (row: TableRow): number => usageMetricValue(row.counters, metric) ?? -1;+ const sortedRows = [...rows].sort((left, right) => (sortValue(right) - sortValue(left)) * (sortAscending ? -1 : 1));+ const tableTotal = aggregateCounters(+ (activePinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === activePinnedKey))+ .flatMap((bucket) => filterBucketRows(bucket, filter)),);- const pickWindow = (id: string) => {- const next = USAGE_WINDOW_OPTIONS.find((option) => String(option) === id);- if (next !== undefined) onWindowChange(next);+ const metricText = (counters: UsageCounters, selectedMetric = metric) =>+ tokenText(counters, selectedMetric, count, t('settings.models.usage.blank') as string);+ const partialHistoryNote = String(t('settings.models.usage.partialHistory'));+ const unknownTokensNote = String(t('settings.models.usage.unknownTokens'));+ const allReportedNote = String(t('settings.models.usage.stats.allReported'));++ const exportCsv = () => {+ const csv = buildUsageCsv(report, filter, activePinnedKey, {+ bucketKey: t('settings.models.usage.csv.bucketKey') as string,+ startAt: t('settings.models.usage.csv.startAt') as string,+ endAt: t('settings.models.usage.csv.endAt') as string,+ historyComplete: t('settings.models.usage.csv.historyComplete') as string,+ sourceId: t('settings.models.usage.csv.sourceId') as string,+ modelId: t('settings.models.usage.csv.modelId') as string,+ ledgerKey: t('settings.models.usage.csv.ledgerKey') as string,+ sourceLabel: t('settings.models.usage.csv.sourceLabel') as string,+ modelLabel: t('settings.models.usage.csv.modelLabel') as string,+ requests: t('settings.models.usage.table.requests') as string,+ tokenReports: t('settings.models.usage.csv.tokenReports') as string,+ inputTokens: t('settings.models.usage.csv.inputTokens') as string,+ nonCachedInputTokens: t('settings.models.usage.csv.nonCachedInputTokens') as string,+ cachedInputTokens: t('settings.models.usage.csv.cachedInputTokens') as string,+ outputTokens: t('settings.models.usage.csv.outputTokens') as string,+ totalTokens: t('settings.models.usage.csv.totalTokens') as string,+ }, t('settings.models.usage.unknownModel') as string);+ const url = URL.createObjectURL(new Blob([`\ufeff${csv}`], { type: 'text/csv;charset=utf-8' }));+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = `model-usage-${report.window_key}.csv`;+ anchor.click();+ window.setTimeout(() => URL.revokeObjectURL(url), 0);};- const day = (value: string) => formatLocalDay(value, i18n.language);return (- <div className="model-hub-usage">- <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.usage.title')}</h2>- <p className="model-hub-usage-note truncate">- {summary === null- ? t('settings.models.usage.detail')- : t('settings.models.usage.range', { from: day(summary.from_day), to: day(summary.to_day), days: summary.window_days })}- </p>- </div>- <SegmentedRadio- value={String(windowDays)}- onChange={pickWindow}- options={options}- ariaLabel={t('settings.models.usage.window.label') as string}- className="shrink-0 sm:w-auto"+ <div className="model-hub-usage-analytics">+ <UsageHeading report={report} windowKey={windowKey} onWindowChange={onWindowChange} />+ {regionFailed(usageRead) && <FailureState onRetry={onRetry} />}+ <div className="model-hub-usage-filter-bar">+ <Filter aria-hidden className="size-3.5 text-muted" />+ <MultiFilter+ label={t('settings.models.usage.filters.source') as string}+ icon={<Network aria-hidden className="size-3.5" />}+ options={sourceOptions}+ selected={sourceIds}+ onChange={setSourceIds}/>- </div>- {regionFailed(usageRead) && (- <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>+ <MultiFilter+ label={t('settings.models.usage.filters.model') as string}+ icon={<Cpu aria-hidden className="size-3.5" />}+ options={modelOptions}+ selected={modelKeys}+ onChange={setModelKeys}+ />+ <div className="model-hub-usage-select">+ <Zap aria-hidden className="size-3.5" />+ <select+ aria-label={t('settings.models.usage.metric.label') as string}+ value={metric}+ onChange={(event) => {+ const next = event.target.value as UsageMetric;+ setMetric(next);+ if (next === 'requests' && group === 'type') setGroup('total');+ }}+ >+ {metricKeys.map((key) => <option value={key} key={key}>{metricLabel(key, t)}</option>)}+ </select>+ <ChevronDown aria-hidden className="size-3" /></div>+ {(sourceIds.length > 0 || modelKeys.length > 0 || metric !== 'tokens') && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="model-hub-usage-reset"+ onClick={() => { setSourceIds([]); setModelKeys([]); setMetric('tokens'); setGroup('type'); }}+ >+ <X aria-hidden className="size-3" />+ {t('settings.models.usage.filters.reset')}+ </Button>+ )}+ <span className="model-hub-usage-filter-context">+ {sourceIds.length > 0 ? t('settings.models.usage.filters.sourceCount', { count: sourceIds.length }) : t('settings.models.usage.filters.allSources')}+ <span>·</span>+ {modelKeys.length > 0 ? t('settings.models.usage.filters.modelCount', { count: modelKeys.length }) : t('settings.models.usage.filters.allModels')}+ </span>+ </div>++ {reportEmpty ? (+ <EmptyState kind="report" />+ ) : filteredEmpty ? (+ <EmptyState kind="filter" onReset={() => { setSourceIds([]); setModelKeys([]); }} />+ ) : (+ <>+ <div className="model-hub-usage-stat-grid">+ <StatCard+ label={t('settings.models.usage.stats.tokens')}+ value={historyOnlyUnknown ? t('settings.models.usage.blank') : metricText(totals, 'tokens')}+ note={!historyOnlyUnknown && usageTokensAreKnown(totals)+ ? t('settings.models.usage.stats.tokenSplit', { input: count(totals.input_tokens), output: count(totals.output_tokens) })+ : historyOnlyUnknown ? partialHistoryNote : unknownTokensNote}+ />+ <StatCard+ label={t('settings.models.usage.stats.requests')}+ value={historyOnlyUnknown ? t('settings.models.usage.blank') : count(totals.requests)}+ note={!historyOnlyUnknown && usageReportShortfall(totals) > 0+ ? t('settings.models.usage.stats.shortfall', { count: usageReportShortfall(totals) })+ : historyOnlyUnknown ? partialHistoryNote : allReportedNote}+ />+ <StatCard+ label={t('settings.models.usage.stats.cached')}+ value={historyOnlyUnknown || usageCachedInputShare(totals) === null ? t('settings.models.usage.blank') : formatPercent(usageCachedInputShare(totals) ?? 0, i18n.language, 1)}+ note={historyOnlyUnknown || usageCachedInputShare(totals) === null+ ? t('settings.models.usage.stats.cacheUnknown')+ : t('settings.models.usage.stats.cacheSplit', { cached: count(totals.cached_input_tokens), input: count(totals.input_tokens) })}+ />+ </div>+ {(partialHistory || reportHasUnknownTokens(report, filter)) && (+ <div className="model-hub-usage-notice" role="status">+ <CircleHelp aria-hidden className="size-3.5 shrink-0" />+ <span>+ {partialHistory && t(report.granularity === 'hour'+ ? 'settings.models.usage.historicalHourly'+ : 'settings.models.usage.partialHistory')}+ {partialHistory && reportHasUnknownTokens(report, filter) && ' '}+ {reportHasUnknownTokens(report, filter) && t('settings.models.usage.unknownTokens')}+ </span>+ </div>+ )}+ <section className="model-hub-usage-card" aria-labelledby="model-hub-usage-chart-title">+ <div className="model-hub-usage-card-header">+ <div>+ <h3 id="model-hub-usage-chart-title">{t('settings.models.usage.chart.title')} <span>{t(`settings.models.usage.granularity.${report.granularity}`)}</span></h3>+ <p>{t('settings.models.usage.chart.subtitle')}</p>+ </div>+ <div className="model-hub-usage-group-control">+ <span>{t('settings.models.usage.group.label')}</span>+ <div role="group" aria-label={t('settings.models.usage.group.label') as string}>+ {groupKeys.map((key) => (+ <button+ type="button"+ key={key}+ aria-pressed={group === key}+ disabled={key === 'type' && metric === 'requests'}+ className={cn(group === key && 'is-selected')}+ onClick={() => setGroup(key)}+ >+ {t(`settings.models.usage.group.${key}`)}+ </button>+ ))}+ </div>+ </div>+ </div>+ <UsageChart+ report={report}+ filter={filter}+ metric={metric}+ group={group}+ pinnedKey={activePinnedKey}+ scopeKey={scopeKey}+ onPin={setPinnedKey}+ />+ </section>+ <section className="model-hub-usage-card model-hub-usage-details" aria-labelledby="model-hub-usage-details-title">+ <div className="model-hub-usage-card-header model-hub-usage-details-header">+ <div>+ <h3 id="model-hub-usage-details-title">{t('settings.models.usage.table.title')} <span>{sortedRows.length}</span></h3>+ <p>{activePinnedKey === null+ ? t('settings.models.usage.table.range')+ : t('settings.models.usage.table.bucket', { bucket: formatBucketLabel(pinnedBucket!, i18n.language) })}</p>+ </div>+ <div className="model-hub-usage-details-actions">+ {activePinnedKey !== null && <Button type="button" variant="ghost" size="sm" onClick={() => setPinnedKey(null)}><X aria-hidden className="size-3" />{t('settings.models.usage.table.allBuckets')}</Button>}+ <div className="model-hub-usage-table-group" role="group" aria-label={t('settings.models.usage.table.group') as string}>+ <button type="button" className={tableGroup === 'model' ? 'is-selected' : ''} aria-pressed={tableGroup === 'model'} onClick={() => setTableGroup('model')}>{t('settings.models.usage.table.byModel')}</button>+ <button type="button" className={tableGroup === 'source' ? 'is-selected' : ''} aria-pressed={tableGroup === 'source'} onClick={() => setTableGroup('source')}>{t('settings.models.usage.table.bySource')}</button>+ </div>+ <Button type="button" variant="outline" size="sm" onClick={exportCsv}><ArrowDownToLine aria-hidden className="size-3.5" />{t('settings.models.usage.table.export')}</Button>+ </div>+ </div>+ <div className="model-hub-usage-table-scroll">+ <table>+ <thead>+ <tr>+ <th scope="col">{t('settings.models.usage.table.identity')}</th>+ <th scope="col">{t('settings.models.usage.table.requests')}</th>+ <th scope="col">{t('settings.models.usage.table.input')}</th>+ <th scope="col">{t('settings.models.usage.table.nonCache')}</th>+ <th scope="col">{t('settings.models.usage.table.cache')}</th>+ <th scope="col">{t('settings.models.usage.table.output')}</th>+ <th scope="col" aria-sort={sortAscending ? 'ascending' : 'descending'}>+ <button+ type="button"+ aria-label={t(`settings.models.usage.table.${sortAscending ? 'sortAscending' : 'sortDescending'}`, { metric: metricLabel(metric, t) })}+ onClick={() => setSortAscending((value) => !value)}+ >+ {metricLabel(metric, t)} <ArrowDown aria-hidden className={cn('size-3', sortAscending && 'rotate-180')} />+ </button>+ </th>+ <th scope="col">{t('settings.models.usage.table.share')}</th>+ </tr>+ </thead>+ <tbody>+ {sortedRows.map((row) => {+ const value = usageMetricValue(row.counters, metric);+ const totalValue = usageMetricValue(tableTotal, metric);+ const share = value === null || totalValue === null || totalValue === 0 ? null : value / totalValue;+ return (+ <tr key={row.key}>+ <th scope="row">+ <span className="model-hub-usage-row-name">{row.label}</span>+ {row.detail && <span className="model-hub-usage-row-detail">{row.detail}</span>}+ </th>+ <td>{count(row.counters.requests)}</td>+ <td>{tokenText(row.counters, 'input', count, t('settings.models.usage.blank') as string)}</td>+ <td>{usageTokensAreKnown(row.counters) ? count(usageNonCachedInput(row.counters)) : t('settings.models.usage.blank')}</td>+ <td>{tokenText(row.counters, 'cache', count, t('settings.models.usage.blank') as string)}</td>+ <td>{tokenText(row.counters, 'output', count, t('settings.models.usage.blank') as string)}</td>+ <td className="model-hub-usage-table-total">{value === null ? t('settings.models.usage.blank') : count(value)}</td>+ <td>{share === null ? t('settings.models.usage.blank') : formatPercent(share, i18n.language, 1)}</td>+ </tr>+ );+ })}+ {sortedRows.length === 0 && <tr><td colSpan={8} className="model-hub-usage-table-empty">{t('settings.models.usage.table.empty')}</td></tr>}+ </tbody>+ {sortedRows.length > 0 && (+ <tfoot>+ <tr>+ <th scope="row">{t('settings.models.usage.table.total')}</th>+ <td>{count(tableTotal.requests)}</td>+ <td>{tokenText(tableTotal, 'input', count, t('settings.models.usage.blank') as string)}</td>+ <td>{usageTokensAreKnown(tableTotal) ? count(usageNonCachedInput(tableTotal)) : t('settings.models.usage.blank')}</td>+ <td>{tokenText(tableTotal, 'cache', count, t('settings.models.usage.blank') as string)}</td>+ <td>{tokenText(tableTotal, 'output', count, t('settings.models.usage.blank') as string)}</td>+ <td>{metricText(tableTotal)}</td>+ <td>{(() => {+ const totalValue = usageMetricValue(tableTotal, metric);+ return totalValue === null || totalValue === 0+ ? t('settings.models.usage.blank')+ : formatPercent(1, i18n.language);+ })()}</td>+ </tr>+ </tfoot>+ )}+ </table>+ </div>+ <div className="model-hub-usage-table-foot">+ <CircleHelp aria-hidden className="size-3.5 shrink-0" />+ {t('settings.models.usage.table.accounting')}+ </div>+ </section>+ </>)}- {summary === null- ? usageRead.kind === 'loading' && <p className="model-hub-usage-pending text-muted">{t('common.loading')}</p>- : usageIsEmpty(summary)- ? <p className="model-hub-usage-empty rounded-xl border border-border bg-background text-center text-muted">{t('settings.models.usage.empty')}</p>- : <>- <StatGrid summary={summary} />- <BySourcePanel summary={summary} />- <ByDayPanel summary={summary} />- </>}</div>);};++function UsageHeading({+ report,+ windowKey,+ onWindowChange,+}: {+ report: UsageReport | null;+ windowKey: UsageWindowKey;+ onWindowChange: (window: UsageWindowKey) => void;+}) {+ const { t, i18n } = useUsageTranslation();+ return (+ <div className="model-hub-usage-heading">+ <div>+ <h2>{t('settings.models.usage.title')}</h2>+ <p>+ {report+ ? formatBucketRange({ start_at: report.from_at, end_at: report.to_at, key: report.from_at, history_complete: true, rows: [] }, i18n.language, true)+ : t('settings.models.usage.detail')}+ </p>+ </div>+ <SegmentedRadio+ value={windowKey}+ onChange={onWindowChange}+ options={USAGE_WINDOW_OPTIONS.map((key) => ({ id: key, label: t(`settings.models.usage.window.${key}`) as string }))}+ ariaLabel={t('settings.models.usage.window.label') as string}+ className="model-hub-usage-window"+ />+ </div>+ );+}++function FailureState({ onRetry }: { onRetry?: () => void | Promise<void> }) {+ const { t } = useUsageTranslation();+ return (+ <div className="model-hub-usage-failure" role="alert">+ <span>{t('settings.models.usage.failure')}</span>+ <button type="button" onClick={() => void onRetry?.()}>{t('settings.models.usage.retry')}</button>+ </div>+ );+}++function EmptyState({ kind, onReset }: { kind: 'report' | 'filter'; onReset?: () => void }) {+ const { t } = useUsageTranslation();+ return (+ <div className="model-hub-usage-empty-state">+ <Search aria-hidden className="size-7" />+ <h3>{t(`settings.models.usage.empty.${kind}.title`)}</h3>+ <p>{t(`settings.models.usage.empty.${kind}.body`)}</p>+ {onReset && <Button type="button" variant="outline" onClick={onReset}>{t('settings.models.usage.filters.reset')}</Button>}+ </div>+ );+}diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.tsindex ebd4de7d8..947eb8552 100644--- a/ui/src/components/settings/models/format.ts+++ b/ui/src/components/settings/models/format.ts@@ -45,9 +45,13 @@ export function formatTokensCompact(value: number | null): string {.format(Math.floor(value));}-/** A ratio in [0, 1] as a whole-percent string — 「65%」. */-export function formatPercent(ratio: number, locale: string): string {- return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }).format(ratio);+/** A ratio in [0, 1] in the reader's notation, with the caller's display precision. */+export function formatPercent(ratio: number, locale: string, fractionDigits = 0): string {+ return new Intl.NumberFormat(locale, {+ style: 'percent',+ minimumFractionDigits: fractionDigits,+ maximumFractionDigits: fractionDigits,+ }).format(ratio);}/**diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex 01f97e42f..46b030de5 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -2207,6 +2207,667 @@text-align: center;}+/* Modern Model Hub usage analytics. The report is dense and interactive, so+ * this surface owns its layout while reusing the shell's neutral and accent+ * tokens. The tooltip is kept in one stable corner: changing the bucket must+ * not move the pin target away from the pointer. */+.model-hub-usage-analytics {+ --model-hub-usage-unknown: var(--gold);+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 14px;+}++.model-hub-usage-heading,+.model-hub-usage-filter-bar,+.model-hub-usage-card-header,+.model-hub-usage-details-actions,+.model-hub-usage-tooltip-head,+.model-hub-usage-tooltip-actions,+.model-hub-usage-chart-foot {+ display: flex;+ align-items: center;+}++.model-hub-usage-heading {+ justify-content: space-between;+ gap: 16px;+}++.model-hub-usage-heading h2 {+ color: var(--foreground);+ font-size: 19px;+ font-weight: 700;+ line-height: 1.2;+}++.model-hub-usage-heading p,+.model-hub-usage-card-header p {+ margin-top: 4px;+ color: var(--model-hub-muted-b3);+ font-size: var(--model-hub-usage-note-size);+ line-height: 1.45;+}++.model-hub-usage-window {+ flex: none;+}++.model-hub-usage-filter-bar {+ min-width: 0;+ flex-wrap: wrap;+ gap: 8px;+ padding: 10px 12px;+ border: 1px solid var(--border);+ border-radius: 10px;+ background: var(--model-hub-wash-03);+}++.model-hub-usage-filter {+ position: relative;+}++.model-hub-usage-filter-trigger {+ max-width: min(230px, 42vw);+}++.model-hub-usage-filter-trigger.is-filtered {+ border-color: var(--model-hub-mint-4d);+ background: var(--model-hub-mint-14);+}++.model-hub-usage-filter-menu {+ position: absolute;+ z-index: 30;+ top: calc(100% + 6px);+ left: 0;+ display: flex;+ width: min(310px, calc(100vw - 36px));+ max-height: 360px;+ flex-direction: column;+ gap: 3px;+ overflow: auto;+ padding: 7px;+ border: 1px solid var(--border-strong);+ border-radius: 10px;+ background: var(--surface);+ box-shadow: var(--model-hub-menu-shadow);+}++.model-hub-usage-filter-search {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 7px 8px;+ border: 1px solid var(--input);+ border-radius: 7px;+ color: var(--muted);+}++.model-hub-usage-filter-search input {+ min-width: 0;+ flex: 1;+ border: 0;+ outline: 0;+ background: transparent;+ color: var(--foreground);+ font-size: 12px;+}++.model-hub-usage-filter-option {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: 8px;+ padding: 7px 8px;+ border-radius: 7px;+ color: var(--foreground);+ font-size: 12px;+ text-align: left;+}++.model-hub-usage-filter-option:hover,+.model-hub-usage-filter-option[aria-selected="true"] {+ background: var(--model-hub-wash-08);+}++.model-hub-usage-filter-divider {+ height: 1px;+ margin: 3px 0;+ background: var(--border);+}++.model-hub-usage-filter-empty,+.model-hub-usage-filter-foot {+ margin: 5px 8px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+}++.model-hub-usage-filter-context {+ display: inline-flex;+ min-width: 0;+ align-items: center;+ gap: 7px;+ margin-left: auto;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+ white-space: nowrap;+}++.model-hub-usage-select {+ position: relative;+ display: inline-flex;+ min-width: 132px;+ align-items: center;+ gap: 7px;+ padding: 6px 28px 6px 9px;+ border: 1px solid var(--border);+ border-radius: 7px;+ color: var(--foreground);+ background: var(--surface);+}++.model-hub-usage-select select {+ min-width: 0;+ appearance: none;+ border: 0;+ outline: 0;+ background: transparent;+ color: inherit;+ font-size: 12px;+}++.model-hub-usage-select > svg:last-child {+ position: absolute;+ right: 8px;+ pointer-events: none;+}++.model-hub-usage-reset {+ color: var(--destructive-ink);+}++.model-hub-usage-loading,+.model-hub-usage-failure,+.model-hub-usage-empty-state,+.model-hub-usage-notice {+ display: flex;+ align-items: center;+ gap: 8px;+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 14px;+ color: var(--model-hub-ink-73);+ font-size: 12px;+}++.model-hub-usage-failure {+ justify-content: space-between;+ border-color: var(--model-hub-danger-border);+ background: var(--model-hub-danger-fill);+ color: var(--model-hub-danger-ink);+}++.model-hub-usage-failure button {+ color: var(--destructive-ink);+ font-weight: 600;+}++.model-hub-usage-empty-state {+ min-height: 180px;+ flex-direction: column;+ justify-content: center;+ text-align: center;+}++.model-hub-usage-empty-state h3 {+ color: var(--foreground);+ font-size: 14px;+ font-weight: 650;+}++.model-hub-usage-empty-state p {+ max-width: 480px;+ color: var(--model-hub-muted-b3);+ font-size: 12px;+}++.model-hub-usage-stat-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 10px;+}++.model-hub-usage-stat-card {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 5px;+ padding: 13px 15px;+ border: 1px solid var(--border);+ border-radius: 10px;+ background: var(--model-hub-wash-03);+}++.model-hub-usage-analytics .model-hub-usage-stat-label {+ color: var(--model-hub-ink-73);+ font-size: 10.5px;+}++.model-hub-usage-analytics .model-hub-usage-stat-value {+ color: var(--foreground);+ font-size: 20px;+ font-variant-numeric: tabular-nums;+ line-height: 1.15;+}++.model-hub-usage-analytics .model-hub-usage-stat-note {+ min-height: 15px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+ line-height: 1.4;+}++.model-hub-usage-notice {+ border-color: var(--model-hub-gold-4d);+ background: var(--model-hub-gold-14);+ color: var(--model-hub-gold-ink);+}++.model-hub-usage-card {+ min-width: 0;+ overflow: visible;+ border: 1px solid var(--border);+ border-radius: 12px;+ background: var(--surface);+}++.model-hub-usage-card-header {+ justify-content: space-between;+ gap: 16px;+ padding: 14px 16px 11px;+ border-bottom: 1px solid var(--border);+}++.model-hub-usage-card-header h3 {+ color: var(--foreground);+ font-size: 13px;+ font-weight: 650;+}++.model-hub-usage-card-header h3 span {+ margin-left: 5px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+ font-weight: 500;+}++.model-hub-usage-group-control {+ display: flex;+ flex: none;+ align-items: center;+ gap: 7px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+}++.model-hub-usage-group-control > div,+.model-hub-usage-table-group {+ display: inline-flex;+ gap: 2px;+ padding: 2px;+ border: 1px solid var(--border);+ border-radius: 7px;+ background: var(--model-hub-wash-03);+}++.model-hub-usage-group-control button,+.model-hub-usage-table-group button {+ padding: 4px 7px;+ border-radius: 5px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+}++.model-hub-usage-group-control button.is-selected,+.model-hub-usage-table-group button.is-selected,+.model-hub-usage-group-control button:hover,+.model-hub-usage-table-group button:hover {+ background: var(--model-hub-wash-14);+ color: var(--foreground);+}++.model-hub-usage-group-control button:disabled {+ cursor: not-allowed;+ opacity: .45;+}++.model-hub-usage-chart-content {+ min-width: 0;+ padding: 12px 16px 13px;+}++.model-hub-usage-legend {+ display: flex;+ min-width: 0;+ flex-wrap: wrap;+ gap: 5px 8px;+ margin-bottom: 6px;+}++.model-hub-usage-legend-item {+ display: inline-flex;+ min-width: 0;+ align-items: center;+ gap: 5px;+ padding: 4px 6px;+ border-radius: 6px;+ color: var(--model-hub-ink-73);+ font-size: 10.5px;+}++.model-hub-usage-legend-item:hover,+.model-hub-usage-legend-item[aria-pressed="false"] {+ background: var(--model-hub-wash-05);+}++.model-hub-usage-legend-item.is-hidden {+ opacity: .42;+}++.model-hub-usage-legend-swatch {+ width: 7px;+ height: 7px;+ flex: none;+ border-radius: 999px;+}++.model-hub-usage-legend-item strong {+ margin-left: 2px;+ color: var(--foreground);+ font-variant-numeric: tabular-nums;+}++.model-hub-usage-chart-wrap {+ position: relative;+ min-width: 0;+ min-height: 236px;+}++.model-hub-usage-svg {+ display: block;+ width: 100%;+ height: auto;+ min-height: 236px;+ overflow: visible;+ touch-action: pan-y;+}++.model-hub-usage-grid {+ stroke: var(--border);+ opacity: .8;+}++.model-hub-usage-tick {+ fill: var(--model-hub-muted-b3);+ font-size: 10px;+}++.model-hub-usage-highlight {+ fill: var(--model-hub-wash-08);+}++.model-hub-usage-crosshair {+ stroke: var(--model-hub-gold);+ stroke-dasharray: 3 4;+ stroke-width: 1;+ opacity: .75;+}++.model-hub-usage-hit-area {+ cursor: crosshair;+ fill: transparent;+ outline: none;+}++.model-hub-usage-hit-area:focus-visible {+ fill: var(--model-hub-mint-14);+ stroke: var(--mint);+ stroke-width: 1;+}++.model-hub-usage-unknown-point {+ fill: var(--model-hub-usage-unknown);+ stroke: var(--background);+ stroke-width: 1.5;+}++.model-hub-usage-tooltip {+ position: absolute;+ z-index: 10;+ top: 10px;+ right: 10px;+ width: min(340px, calc(100% - 20px));+ pointer-events: auto;+ padding: 10px 11px;+ border: 1px solid var(--model-hub-gold-4d);+ border-radius: 9px;+ background: color-mix(in srgb, var(--surface) 96%, var(--gold) 4%);+ box-shadow: var(--model-hub-menu-shadow);+ color: var(--foreground);+}++.model-hub-usage-tooltip.is-pinned {+ border-color: var(--model-hub-mint-4d);+ background: color-mix(in srgb, var(--surface) 96%, var(--mint) 4%);+}++.model-hub-usage-tooltip-head {+ justify-content: space-between;+ gap: 10px;+ color: var(--model-hub-ink-73);+ font-size: 10.5px;+ line-height: 1.35;+}++.model-hub-usage-tooltip-actions {+ flex: none;+ gap: 6px;+ color: var(--model-hub-mint-ink);+}++.model-hub-usage-pin {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 25px;+ height: 25px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: var(--model-hub-wash-08);+ color: var(--foreground);+}++.model-hub-usage-pin:hover,+.model-hub-usage-pin:focus-visible {+ border-color: var(--model-hub-mint-4d);+ color: var(--mint-ink);+}++.model-hub-usage-tooltip-total {+ display: flex;+ align-items: baseline;+ gap: 7px;+ margin-top: 8px;+}++.model-hub-usage-tooltip-total strong {+ font-size: 18px;+ font-variant-numeric: tabular-nums;+}++.model-hub-usage-tooltip-total span,+.model-hub-usage-tooltip-foot {+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+}++.model-hub-usage-tooltip-lines {+ display: grid;+ gap: 4px;+ margin-top: 8px;+ padding-top: 8px;+ border-top: 1px solid var(--border);+}++.model-hub-usage-tooltip-lines > div,+.model-hub-usage-tooltip-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}++.model-hub-usage-tooltip-lines span {+ display: inline-flex;+ min-width: 0;+ align-items: center;+ gap: 5px;+ color: var(--model-hub-ink-73);+ font-size: 10.5px;+}++.model-hub-usage-tooltip-lines i {+ width: 6px;+ height: 6px;+ flex: none;+ border-radius: 999px;+}++.model-hub-usage-tooltip-lines b {+ flex: none;+ font-size: 10.5px;+ font-variant-numeric: tabular-nums;+}++.model-hub-usage-tooltip-foot {+ margin-top: 8px;+}++.model-hub-usage-chart-foot {+ justify-content: space-between;+ gap: 10px;+ margin-top: 5px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+}++.model-hub-usage-details {+ overflow: hidden;+}++.model-hub-usage-details-header {+ flex-wrap: wrap;+}++.model-hub-usage-details-actions {+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: 7px;+}++.model-hub-usage-table-scroll {+ overflow-x: auto;+}++.model-hub-usage-table-scroll table {+ width: 100%;+ min-width: 760px;+ border-collapse: collapse;+ font-size: 11px;+}++.model-hub-usage-table-scroll th,+.model-hub-usage-table-scroll td {+ padding: 9px 11px;+ border-bottom: 1px solid var(--border);+ text-align: right;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.model-hub-usage-table-scroll th:first-child,+.model-hub-usage-table-scroll td:first-child {+ min-width: 190px;+ text-align: left;+}++.model-hub-usage-table-scroll thead th {+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+ font-weight: 550;+}++.model-hub-usage-table-scroll thead button {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: inherit;+}++.model-hub-usage-table-scroll tbody th {+ color: var(--foreground);+ font-weight: 550;+}++.model-hub-usage-table-scroll tbody tr:hover {+ background: var(--model-hub-wash-03);+}++.model-hub-usage-row-name,+.model-hub-usage-row-detail {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+}++.model-hub-usage-row-detail {+ margin-top: 3px;+ color: var(--model-hub-muted-b3);+ font-size: 10px;+ font-weight: 450;+}++.model-hub-usage-table-total {+ color: var(--mint-ink);+ font-weight: 650;+}++.model-hub-usage-table-empty {+ padding: 22px 12px !important;+ color: var(--model-hub-muted-b3);+ text-align: center !important;+}++.model-hub-usage-table-scroll tfoot th,+.model-hub-usage-table-scroll tfoot td {+ border-bottom: 0;+ color: var(--foreground);+ font-weight: 650;+}++.model-hub-usage-table-foot {+ display: flex;+ align-items: flex-start;+ gap: 7px;+ padding: 10px 14px;+ color: var(--model-hub-muted-b3);+ font-size: 10.5px;+ line-height: 1.45;+}+/* 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. */@@ -2390,6 +3051,16 @@/* 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; }+ .model-hub-usage-heading { align-items: flex-start; flex-direction: column; }+ .model-hub-usage-window { width: 100%; }+ .model-hub-usage-filter-context { width: 100%; margin-left: 0; }+ .model-hub-usage-stat-grid { grid-template-columns: 1fr; }+ .model-hub-usage-card-header { align-items: flex-start; flex-direction: column; }+ .model-hub-usage-group-control { width: 100%; align-items: flex-start; flex-direction: column; }+ .model-hub-usage-group-control > div { width: 100%; }+ .model-hub-usage-group-control button { flex: 1; }+ .model-hub-usage-details-actions { width: 100%; justify-content: flex-start; }+ .model-hub-usage-tooltip { top: 5px; right: 5px; width: calc(100% - 10px); }/* 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; }diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex a4274fef1..c483e1175 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -41,10 +41,11 @@ import type {SourceRepaired,SupplyChannel,SupplyGap,+ UsageReport,+ UsageWindowKey,QuotaSummary,- UsageSummary,} from './types';-import { USAGE_DEFAULT_WINDOW_DAYS } from './types';+import { USAGE_DEFAULT_WINDOW } from './types';/** Add-time Route placement returned by both source-creation paths. */export type Adoption = { added_to: AddedTo[]; adopted_by: AdoptedBy[] };@@ -160,10 +161,8 @@ export type ModelsApi = {applyMigration(itemIds: string[], cleanApiKeys?: boolean): Promise<MigrationApplyResult>;/** `before` is an event id cursor (「查看全部」 pagination). */listEvents(limit?: number, before?: string): Promise<ResolutionEvent[]>;- /** Metered token report over a trailing local-day window. `days` is a REQUEST:- * 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>;+ /** Usage analytics over the explicit modern window selector. */+ getUsageSummary(window?: UsageWindowKey): Promise<UsageReport>;/** 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). */@@ -649,8 +648,8 @@ export const modelsApi: ModelsApi = {call<{ events: ResolutionEvent[] }>(`/api/models/events?limit=${limit}${before ? `&before=${encodeURIComponent(before)}` : ''}`,).then((r) => r.events),- getUsageSummary: (days = USAGE_DEFAULT_WINDOW_DAYS) =>- call<{ usage: UsageSummary }>(`/api/models/usage?days=${days}`).then((r) => r.usage),+ getUsageSummary: (window = USAGE_DEFAULT_WINDOW) =>+ call<{ usage: UsageReport }>(`/api/models/usage?window=${window}`).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),diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 440f82d65..9768866c3 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -818,11 +818,36 @@ export type UsageSummary = {days: UsageByDay[];};+export type UsageWindowKey = '24h' | '7d' | '30d' | '60d';++export type UsageBucketRow = UsageCounters & {+ source_id: string;+ model_id: string;+};++export type UsageBucket = {+ key: string;+ start_at: string;+ end_at: string;+ history_complete: boolean;+ rows: UsageBucketRow[];+};++/** The modern temporal report consumed by the Model Hub analytics surface. */+export type UsageReport = UsageSummary & {+ window_key: UsageWindowKey;+ granularity: 'hour' | 'day';+ from_at: string;+ to_at: string;+ buckets: UsageBucket[];+};+/** `window_days` bounds from the schema. The offered options live in* `usageProjection` and are gated against these. */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;+export const USAGE_DEFAULT_WINDOW: UsageWindowKey = '24h';/** `quota-summary.schema.json` — a subscription's own rate-limit windows. A* report, like usage: nothing in routing reads it. Money is deliberately absent;diff --git a/ui/src/components/settings/models/usageCsv.ts b/ui/src/components/settings/models/usageCsv.tsnew file mode 100644index 000000000..d3771cf7b--- /dev/null+++ b/ui/src/components/settings/models/usageCsv.ts@@ -0,0 +1,108 @@+import type { UsageBucketRow, UsageReport } from './types';+import {+ filterBucketRows,+ emptyCounters,+ modelLabel,+ pairKey,+ sourceIdentityLabel,+ sourceLabel,+ usageLabelContext,+ usageNonCachedInput,+ usageTokensAreKnown,+ usageTotalTokens,+ type UsageFilter,+ type UsageIdentity,+} from './usageProjection';++export function csvCell(value: string | number): string {+ if (typeof value === 'number') return String(value);+ let text = value;+ if (/^[=+\-@]/.test(text) || /^[\t\r]/.test(text)) text = `'${text}`;+ return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;+}++export type UsageCsvHeaders = {+ bucketKey: string;+ startAt: string;+ endAt: string;+ historyComplete: string;+ sourceId: string;+ modelId: string;+ ledgerKey: string;+ sourceLabel: string;+ modelLabel: string;+ requests: string;+ tokenReports: string;+ inputTokens: string;+ nonCachedInputTokens: string;+ cachedInputTokens: string;+ outputTokens: string;+ totalTokens: string;+};++export function buildUsageCsv(+ report: UsageReport,+ filter: UsageFilter,+ pinnedKey: string | null,+ headers: UsageCsvHeaders,+ unknownModel: string,+): string {+ const labelContext = usageLabelContext(report, report.buckets.flatMap((bucket) => bucket.rows), unknownModel);+ const buckets = pinnedKey === null+ ? report.buckets+ : report.buckets.filter((bucket) => bucket.key === pinnedKey);+ const lines = buckets.flatMap((bucket) => {+ const rows = filterBucketRows(bucket, filter);+ const exportRows: Array<UsageBucketRow | null> = rows.length > 0 ? rows : [null];+ return exportRows.map((row) => {+ const counters = row ?? (bucket.history_complete ? emptyCounters() : null);+ const knownTokens = counters !== null && usageTokensAreKnown(counters);+ const identity = row === null ? null : {+ key: pairKey(row.source_id, row.model_id),+ sourceId: row.source_id,+ modelId: row.model_id,+ sourceLabel: sourceLabel(report, row.source_id),+ modelLabel: modelLabel(report, row.source_id, row.model_id),+ } satisfies UsageIdentity;+ return [+ bucket.key,+ bucket.start_at,+ bucket.end_at,+ String(bucket.history_complete),+ row?.source_id ?? '',+ identity?.modelLabel ?? '',+ row?.model_id ?? '',+ row === null ? '' : sourceIdentityLabel(report, row.source_id, labelContext),+ row === null ? '' : identity?.modelLabel || unknownModel,+ row?.requests ?? (bucket.history_complete ? 0 : ''),+ row?.token_reports ?? (bucket.history_complete ? 0 : ''),+ knownTokens ? counters.input_tokens : '',+ knownTokens ? usageNonCachedInput(counters) : '',+ knownTokens ? counters.cached_input_tokens : '',+ knownTokens ? counters.output_tokens : '',+ knownTokens ? usageTotalTokens(counters) : '',+ ] as Array<string | number>;+ });+ });+ const headerLine = [+ headers.bucketKey,+ headers.startAt,+ headers.endAt,+ headers.historyComplete,+ headers.sourceId,+ headers.modelId,+ headers.ledgerKey,+ headers.sourceLabel,+ headers.modelLabel,+ headers.requests,+ headers.tokenReports,+ headers.inputTokens,+ headers.nonCachedInputTokens,+ headers.cachedInputTokens,+ headers.outputTokens,+ headers.totalTokens,+ ];+ return [headerLine, ...lines]+ .map((line) => line.map(csvCell).join(','))+ .join('\r\n');+}diff --git a/ui/src/components/settings/models/usageProjection.test.ts b/ui/src/components/settings/models/usageProjection.test.tsindex fc6dedca0..53dfec9bb 100644--- a/ui/src/components/settings/models/usageProjection.test.ts+++ b/ui/src/components/settings/models/usageProjection.test.ts@@ -1,304 +1,212 @@import { describe, expect, it } from 'vitest';-import { USAGE_WINDOW_MAX_DAYS, USAGE_WINDOW_MIN_DAYS, type UsageByModel, type UsageBySource, type UsageCounters, type UsageSummary } from './types';+import type { UsageBucket, UsageBucketRow, UsageCounters, UsageReport } from './types';import {- USAGE_WINDOW_OPTIONS,- formatLocalDay,- modelIdentity,- parseLocalDay,- sourceIdentity,- usageCachedInputShare,- usageDayColumns,- usageDayIsMetered,+ formatBucketAxisLabel,+ formatBucketRange,+ identityLabel,+ pairKey,+ reportHasPartialHistory,+ seriesFor,+ sourceIdentityLabel,+ usageLabelContext,usageIsEmpty,- usageReportShortfall,- usageTokensAreKnown,- usageTokensAreReported,+ usageNonCachedInput,usageTotalTokens,} from './usageProjection';const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({- requests: 0,- token_reports: 0,- input_tokens: 0,- cached_input_tokens: 0,- output_tokens: 0,+ requests: 2,+ token_reports: 2,+ input_tokens: 100,+ cached_input_tokens: 25,+ output_tokens: 40,...over,});-const model = (over: Partial<UsageByModel> = {}): UsageByModel => ({- ...counters(),- model_id: 'claude-opus-4-6',- label: 'claude-opus-4-6',- ...over,-});--const source = (over: Partial<UsageBySource> = {}): UsageBySource => ({- ...counters(),- source_id: 'src_conform001',- label: 'Contract source',- last_metered_at: null,- models: [model()],- ...over,-});--const summary = (over: Partial<UsageSummary> = {}): UsageSummary => ({- window_days: 30,- from_day: '2026-07-20',- to_day: '2026-08-18',+const reportWith = (buckets: UsageBucket[]): UsageReport => ({+ window_days: 1,+ from_day: '2026-09-24',+ to_day: '2026-09-24',totals: counters(),- sources: [],+ sources: [{+ source_id: 'source-a',+ label: 'Supplier',+ last_metered_at: null,+ ...counters(),+ models: [{ model_id: 'model-a', label: 'Model', ...counters() }],+ }],days: [],- ...over,-});--describe('USAGE_WINDOW_OPTIONS', () => {- // The reason this file exists: an option outside the contract bounds is a- // number on screen the report never covered.- it('offers only windows the contract can serve', () => {- expect(USAGE_WINDOW_OPTIONS.length).toBeGreaterThan(0);- for (const option of USAGE_WINDOW_OPTIONS) {- expect(Number.isInteger(option)).toBe(true);- expect(option).toBeGreaterThanOrEqual(USAGE_WINDOW_MIN_DAYS);- expect(option).toBeLessThanOrEqual(USAGE_WINDOW_MAX_DAYS);- }- });-- it('offers each window once, shortest first', () => {- const options = [...USAGE_WINDOW_OPTIONS];- expect(new Set(options).size).toBe(options.length);- expect(options).toEqual([...options].sort((left, right) => left - right));- });-});--describe('usageTotalTokens', () => {- it('adds input and output without subtracting the cached subset', () => {- expect(usageTotalTokens(counters({ input_tokens: 148_230, cached_input_tokens: 96_010, output_tokens: 4_120 }))).toBe(152_350);- });-});--describe('usageReportShortfall', () => {- it('counts the requests that carried no token report', () => {- expect(usageReportShortfall(counters({ requests: 12, token_reports: 9 }))).toBe(3);- expect(usageReportShortfall(counters({ requests: 12, token_reports: 12 }))).toBe(0);- });-- it('never reports a negative shortfall, whatever the payload claims', () => {- expect(usageReportShortfall(counters({ requests: 4, token_reports: 9 }))).toBe(0);- });-});--describe('usageTokensAreReported', () => {- // The same rendered zero, three payloads apart. Only `token_reports` says- // whether it is a measurement, which is why no caller may read the total.- it('separates a reported zero from calls nobody reported', () => {- expect(usageTokensAreReported(counters({ requests: 4, token_reports: 4 }))).toBe(true);- expect(usageTokensAreReported(counters({ requests: 4, token_reports: 0 }))).toBe(false);- expect(usageTokensAreReported(counters())).toBe(false);- });-- it('asks about coverage and never about size', () => {- expect(usageTokensAreReported(counters({ requests: 1, token_reports: 1, input_tokens: 900_000 }))).toBe(true);- expect(usageTokensAreReported(counters({ requests: 1, token_reports: 0, input_tokens: 900_000 }))).toBe(false);- });-});--describe('usageTokensAreKnown', () => {- // Wider than reported by exactly one case, and that case is the honest one:- // nothing ran, so nothing was spent, and our own request counter is the evidence.- // Refusing it would trade an unreported cost read as free for an idle window read- // as unknowable.- it('prints the zero nothing ran to earn, and refuses the one nobody costed', () => {- expect(usageTokensAreKnown(counters({ requests: 0, token_reports: 0 }))).toBe(true);- expect(usageTokensAreKnown(counters({ requests: 4, token_reports: 0 }))).toBe(false);- expect(usageTokensAreKnown(counters({ requests: 4, token_reports: 4 }))).toBe(true);- });-- // A partial report is a real measurement of the calls it covered; the calls it- // did not cover are the shortfall's sentence to say, not this figure's.- it('treats a partial report as a measurement and leaves the gap to the shortfall', () => {- const partial = counters({ requests: 12, token_reports: 9, input_tokens: 400 });- expect(usageTokensAreKnown(partial)).toBe(true);- expect(usageReportShortfall(partial)).toBe(3);- });-});--describe('usageCachedInputShare', () => {- it('is the cached share of reported input', () => {- expect(usageCachedInputShare(counters({ input_tokens: 200, cached_input_tokens: 50 }))).toBe(0.25);- });-- it('has no share to report when nothing was input', () => {- expect(usageCachedInputShare(counters({ input_tokens: 0, cached_input_tokens: 0 }))).toBeNull();- expect(usageCachedInputShare(counters({ input_tokens: 0, cached_input_tokens: 90 }))).toBeNull();- });-- it('stays a share even when the payload breaks the subset promise', () => {- expect(usageCachedInputShare(counters({ input_tokens: 100, cached_input_tokens: 400 }))).toBe(1);- expect(usageCachedInputShare(counters({ input_tokens: 100, cached_input_tokens: -40 }))).toBe(0);- });+ window_key: '24h',+ granularity: 'hour',+ from_at: '2026-09-24T00:00:00+08:00',+ to_at: '2026-09-24T02:00:00+08:00',+ buckets,});-describe('usageIsEmpty', () => {- it('is empty exactly when no Source was metered', () => {- expect(usageIsEmpty(summary())).toBe(true);- expect(usageIsEmpty(summary({ sources: [source()] }))).toBe(false);- });-});--describe('parseLocalDay', () => {- it('accepts a contract LocalDay and rejects anything else', () => {- expect(parseLocalDay('2026-08-18')).toBe(Date.UTC(2026, 7, 18));- for (const rejected of ['', '2026-8-18', '2026-08-18T00:00:00Z', 'yesterday', '20260818']) {- expect(parseLocalDay(rejected)).toBeNull();- }- });-- // `Date.parse` rolls these forward instead of refusing them, so a day that- // survives must read back identical rather than merely parse.- it('rejects a day the calendar does not have', () => {- for (const rolled of ['2026-02-30', '2026-13-01', '2026-04-31', '2026-00-10', '2026-01-32']) {- expect(parseLocalDay(rolled)).toBeNull();- }- });-- it('round-trips every day of the widest window it will plot', () => {- const first = parseLocalDay('2026-01-01');- expect(first).not.toBeNull();- for (let index = 0; index < USAGE_WINDOW_MAX_DAYS; index += 1) {- const day = new Date((first as number) + index * 86_400_000).toISOString().slice(0, 10);- expect(parseLocalDay(day)).not.toBeNull();- }- });+const row = (over: Partial<UsageBucketRow> = {}): UsageBucketRow => ({+ ...counters(),+ source_id: 'source-a',+ model_id: 'model-a',+ ...over,});-describe('formatLocalDay', () => {- it('keeps the labelled day when read back, in either locale', () => {- expect(formatLocalDay('2026-08-18', 'en-US')).toContain('18');- expect(formatLocalDay('2026-08-18', 'en-US')).toContain('2026');- expect(formatLocalDay('2026-08-18', 'zh-CN')).toContain('18');- expect(formatLocalDay('2026-08-18', 'zh-CN')).toContain('2026');- });-- it('renders an unparseable day verbatim rather than inventing one', () => {- expect(formatLocalDay('not-a-day', 'en-US')).toBe('not-a-day');- });+const bucket = (key: string, rows: UsageBucketRow[], history_complete = true): UsageBucket => ({+ key,+ start_at: `2026-09-24T${key}:00:00+08:00`,+ end_at: `2026-09-24T${String(Number(key) + 1).padStart(2, '0')}:00:00+08:00`,+ history_complete,+ rows,});-describe('usageDayColumns', () => {- // A reported day exists because a call was metered on it, so it carries one- // unless the case is about a day that carried several. Tokens imply the report- // they were summed from — the server only totals what an upstream told it — so- // the coverage counter follows the tokens unless a case sets it apart.- const day = (value: string, tokens: number, requests = 1, token_reports = tokens > 0 ? requests : 0) => ({- ...counters({ requests, token_reports, input_tokens: tokens }),- day: value,- });-- it('spans the whole window and zero-fills the days that carried no turn', () => {- const columns = usageDayColumns(summary({ from_day: '2026-08-14', to_day: '2026-08-18', days: [day('2026-08-16', 40)] }));- expect(columns.map((column) => column.day)).toEqual(['2026-08-14', '2026-08-15', '2026-08-16', '2026-08-17', '2026-08-18']);- expect(columns.map((column) => column.tokens)).toEqual([0, 0, 40, 0, 0]);- });-- // The property, not a case list: whatever the reported set is, every reported- // day keeps its own tokens and nothing else gains any.- it('carries the tokens of every reported day through unchanged', () => {- const reported = [day('2026-08-14', 10), day('2026-08-16', 40), day('2026-08-18', 25)];- const columns = usageDayColumns(summary({ from_day: '2026-08-14', to_day: '2026-08-18', days: reported }));- const byDay = new Map(columns.map((column) => [column.day, column.tokens]));- for (const entry of reported) expect(byDay.get(entry.day)).toBe(usageTotalTokens(entry));- const total = columns.reduce((sum, column) => sum + column.tokens, 0);- expect(total).toBe(reported.reduce((sum, entry) => sum + usageTotalTokens(entry), 0));- });-- // Both counters travel, because they answer different questions: what a day- // cost, and whether it ran at all.- it('carries the calls of every reported day through, and gives a filled-in day none', () => {- const columns = usageDayColumns(summary({ from_day: '2026-08-14', to_day: '2026-08-16', days: [day('2026-08-15', 40, 3)] }));- expect(columns.map((column) => column.requests)).toEqual([0, 3, 0]);- });-- // And so does coverage, for the same reason one step further in: four calls that- // were measured at nothing and four whose upstreams said nothing carry identical- // tokens and identical requests. Only this counter tells the series apart, so a- // column that lost it could not be drawn or described honestly at any zero.- it('carries the token reports of every reported day through, and gives a filled-in day none', () => {- const columns = usageDayColumns(summary({- from_day: '2026-08-14',- to_day: '2026-08-16',- days: [day('2026-08-14', 0, 4, 4), day('2026-08-16', 0, 4, 0)],- }));- expect(columns.map((column) => column.tokens)).toEqual([0, 0, 0]);- expect(columns.map((column) => column.requests)).toEqual([4, 0, 4]);- expect(columns.map((column) => column.token_reports)).toEqual([4, 0, 0]);- // Three identical zeroes, three different facts — a measured nothing, a day- // nobody used, and a day nobody costed.- expect(columns.map(usageTokensAreReported)).toEqual([true, false, false]);- expect(columns.map(usageTokensAreKnown)).toEqual([true, true, false]);- });-- // The distinction the whole series exists to draw. A day whose upstreams never- // reported their tokens still served the calls the user made, so it is a metered- // day with nothing to scale — not an idle one.- it('reads a day of calls with no token report as metered rather than idle', () => {- const columns = usageDayColumns(summary({ from_day: '2026-08-17', to_day: '2026-08-18', days: [day('2026-08-18', 0, 4)] }));- expect(columns.map(usageDayIsMetered)).toEqual([false, true]);- expect(columns.map((column) => column.tokens)).toEqual([0, 0]);- });-- it('scales every bar against the busiest day on screen', () => {- const columns = usageDayColumns(summary({ from_day: '2026-08-17', to_day: '2026-08-18', days: [day('2026-08-17', 25), day('2026-08-18', 100)] }));- expect(columns.map((column) => column.ratio)).toEqual([0.25, 1]);- });-- it('gives a silent window flat bars rather than a division by zero', () => {- const columns = usageDayColumns(summary({ from_day: '2026-08-17', to_day: '2026-08-18' }));- expect(columns.map((column) => column.ratio)).toEqual([0, 0]);- });-- it('falls back to the reported days when the window bounds are unusable', () => {- // Reversed, malformed, and wider than retention all mean the same thing: the- // span is not ours to trust, so plot what was actually reported.- for (const window of [- { from_day: '2026-08-18', to_day: '2026-08-14' },- { from_day: 'nope', to_day: '2026-08-18' },- { from_day: '2020-01-01', to_day: '2026-08-18' },- ]) {- const columns = usageDayColumns(summary({ ...window, days: [day('2026-08-16', 40)] }));- expect(columns.map((column) => column.day)).toEqual(['2026-08-16']);- expect(columns[0].tokens).toBe(40);- }- });-- it('never plots more columns than the maximum window the contract allows', () => {- const columns = usageDayColumns(summary({ from_day: '2026-06-18', to_day: '2026-08-18' }));- expect(columns.length).toBeLessThanOrEqual(USAGE_WINDOW_MAX_DAYS);- });-});--describe('usage row identity', () => {- it('shows the joined label while there is one', () => {- expect(sourceIdentity(source({ label: 'Contract source' }))).toEqual({ kind: 'label', text: 'Contract source' });- expect(modelIdentity(model({ label: 'claude-opus-4-6' }))).toEqual({ kind: 'label', text: 'claude-opus-4-6' });- });-- it('treats a blank label as no label at all', () => {- expect(sourceIdentity(source({ label: ' ' })).kind).toBe('gone');- expect(modelIdentity(model({ label: '' })).kind).toBe('gone');- });-- it('keeps a gone Source addressable by its canonical id', () => {- expect(sourceIdentity(source({ label: null, source_id: 'src_gone' }))).toEqual({ kind: 'gone', id: 'src_gone' });- });-- // The contract's rule, as a property: `model_id` is a head plus a digest for- // any long identifier, so it is never a string this UI may display.- it('never offers the ledger key of a gone model as something to display', () => {- for (const key of ['claude-opus-4-6', 'anthropic/claude-opus-4-6-2026#9f2a1c', 'x'.repeat(200)]) {- const identity = modelIdentity(model({ label: null, model_id: key }));- expect(identity).toEqual({ kind: 'gone', id: null });- expect(JSON.stringify(identity)).not.toContain(key);- }+describe('usageProjection', () => {+ it('counts input and output once while exposing the cached subset', () => {+ const value = counters({ input_tokens: 148_230, cached_input_tokens: 96_010, output_tokens: 4_120 });+ expect(usageTotalTokens(value)).toBe(152_350);+ expect(usageNonCachedInput(value)).toBe(52_220);+ });++ it('keeps source/model identity separate even when labels match', () => {+ const value = reportWith([+ bucket('00', [row()]),+ bucket('01', [row({ source_id: 'source-b' })]),+ ]);+ value.sources.push({+ source_id: 'source-b',+ label: 'Supplier',+ last_metered_at: null,+ ...counters(),+ models: [{ model_id: 'model-a', label: 'Model', ...counters() }],+ });+ const series = seriesFor(value, { sourceIds: [], modelKeys: [] }, 'model', 'tokens', 'Unknown model');+ expect(series.map((item) => item.key)).toEqual([pairKey('source-a', 'model-a'), pairKey('source-b', 'model-a')]);+ expect(series.map((item) => item.label)).toEqual([+ 'Supplier · Model · source-a',+ 'Supplier · Model · source-b',+ ]);+ });++ it('localizes an unknown model in model-grouped series', () => {+ const value = reportWith([bucket('00', [row({ model_id: 'removed-model' })])]);+ expect(seriesFor(value, { sourceIds: [], modelKeys: [] }, 'model', 'tokens', '未知模型')[0]?.label).toBe('Supplier · 未知模型');+ expect(identityLabel({+ key: pairKey('source-a', 'removed-model'),+ sourceId: 'source-a',+ modelId: 'removed-model',+ sourceLabel: 'Supplier',+ modelLabel: null,+ }, '未知模型')).toBe('Supplier · 未知模型');+ });++ it('disambiguates localized unknown-model collisions', () => {+ const value = reportWith([bucket('00', [+ row({ model_id: 'removed-model' }),+ row({ model_id: 'model-a' }),+ ])]);+ value.sources[0]!.models = [+ { model_id: 'model-a', label: '未知模型', ...counters() },+ ];++ expect(seriesFor(value, { sourceIds: [], modelKeys: [] }, 'model', 'tokens', '未知模型').map((item) => item.label)).toEqual([+ 'Supplier · 未知模型 · source-a · removed-model',+ 'Supplier · 未知模型 · source-a · model-a',+ ]);+ });++ it('keeps final source labels unique when a suffix collides with a literal label', () => {+ const value = reportWith([+ bucket('00', [+ row({ source_id: 'source-a' }),+ row({ source_id: 'source-b' }),+ row({ source_id: 'source-c' }),+ ]),+ ]);+ value.sources = [+ { source_id: 'source-a', label: 'Provider', last_metered_at: null, ...counters(), models: [] },+ { source_id: 'source-b', label: 'Provider', last_metered_at: null, ...counters(), models: [] },+ { source_id: 'source-c', label: 'Provider · source-a', last_metered_at: null, ...counters(), models: [] },+ ];+ const context = usageLabelContext(value, value.buckets.flatMap((bucket) => bucket.rows), 'Unknown model');+ const labels = ['source-a', 'source-b', 'source-c'].map((sourceId) => (+ sourceIdentityLabel(value, sourceId, context)+ ));++ expect(new Set(labels).size).toBe(labels.length);+ expect(labels.every((label) => label.length > 0)).toBe(true);+ });++ it('keeps final identity labels unique after collision suffixes are added', () => {+ const value = reportWith([+ bucket('00', [+ row({ model_id: 'old-a' }),+ row({ model_id: 'old-b' }),+ row({ source_id: 'source-b', model_id: 'literal-model' }),+ ]),+ ]);+ value.sources = [+ {+ source_id: 'source-a',+ label: 'Supplier',+ last_metered_at: null,+ ...counters(),+ models: [],+ },+ {+ source_id: 'source-b',+ label: 'Supplier',+ last_metered_at: null,+ ...counters(),+ models: [{+ model_id: 'literal-model',+ label: 'Unknown model · source-a · old-a',+ ...counters(),+ }],+ },+ ];++ const labels = seriesFor(+ value,+ { sourceIds: [], modelKeys: [] },+ 'model',+ 'tokens',+ 'Unknown model',+ ).map((series) => series.label);++ expect(new Set(labels).size).toBe(labels.length);+ expect(labels).toContain('Supplier · Unknown model · source-a · old-a');+ });++ it('renders incomplete empty buckets as unavailable gaps, not zero', () => {+ const value = reportWith([bucket('00', [], false), bucket('01', [], false)]);+ const series = seriesFor(value, { sourceIds: [], modelKeys: [] }, 'total', 'tokens', 'Unknown model');+ expect(series[0]?.values).toEqual([null, null]);+ expect(usageIsEmpty(value)).toBe(false);+ expect(reportHasPartialHistory(value, { sourceIds: [], modelKeys: [] })).toBe(true);+ });++ it('includes both explicit offsets when formatting a bucket range', () => {+ const base = bucket('00', []);+ expect(formatBucketRange({+ ...base,+ start_at: '2026-11-01T01:00:00-04:00',+ end_at: '2026-11-01T01:00:00-05:00',+ }, 'en-US', true)).toContain('UTC-04:00');+ expect(formatBucketRange({+ ...base,+ start_at: '2026-11-01T01:00:00-04:00',+ end_at: '2026-11-01T01:00:00-05:00',+ }, 'en-US', true)).toContain('UTC-05:00');+ });++ it('keeps axis labels compact while detail labels remain full', () => {+ const hourly = bucket('00', []);+ expect(formatBucketAxisLabel(hourly, 'en-US')).toBe('00:00');+ expect(formatBucketAxisLabel({+ ...hourly,+ key: '2026-09-24',+ start_at: '2026-09-24T00:00:00+08:00',+ end_at: '2026-09-25T00:00:00+08:00',+ }, 'en-US')).toBe('Sep 24');+ expect(formatBucketRange(hourly, 'en-US')).toContain('Sep 24, 2026');});});diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.tsindex 76deb90fa..a5854d491 100644--- a/ui/src/components/settings/models/usageProjection.ts+++ b/ui/src/components/settings/models/usageProjection.ts@@ -1,223 +1,442 @@-// Pure projections over `usage-summary.schema.json` for the 用量 tab.-//-// Everything here is a derivation the tab could get WRONG, kept out of JSX so it-// can be asserted as a property: what the window spans, what a row is allowed to-// display, and how a sparse trend becomes a dense one. Layout and copy stay in-// the component; this module never translates.-//-// It owns the trailing local-day window — `YYYY-MM-DD` labels in and out.-// `localCalendar.ts` answers a different question (is this INSTANT today?) over a-// different input type, so the two are deliberately not merged: an instant needs-// a timezone to become a day, and these strings already are days.-import { USAGE_WINDOW_MAX_DAYS, USAGE_WINDOW_MIN_DAYS, type UsageByDay, type UsageByModel, type UsageBySource, type UsageCounters, type UsageSummary } from './types';--/**- * The windows the tab offers.- *- * Bounded by the schema rather than by the design, which offers 7/30/90: the- * server clamps `days` to retention and answers with what it served, so a 「90- * 天」 option would put a number on screen the report never covered. The gate is- * mechanical — `usageProjection.test.ts` fails if an option leaves the contract- * bounds — so the next person to add one cannot reintroduce the lie by hand.- */-export const USAGE_WINDOW_OPTIONS = [7, 30, 60] as const;-export type UsageWindowOption = (typeof USAGE_WINDOW_OPTIONS)[number];--const DAY_MS = 86_400_000;-const LOCAL_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;--const toLocalDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10);--/**- * A `LocalDay` as the UTC instant of its midnight, or null when it is not one.- *- * UTC is the arithmetic frame on purpose. The string is already a local calendar- * day, so re-deriving it through the host's zone would let a DST boundary or an- * offset change move a labelled day by one; stepping in fixed 86 400 s units and- * reading the label straight back cannot.- *- * The pattern alone does not decide it. `Date.parse` rolls an out-of-range day- * FORWARD rather than refusing it — `2026-02-30` becomes March 2 — and a rolled- * day silently stops matching the label it was keyed by. Reading the day back out- * and requiring it unchanged is a check against our own output, so no calendar- * quirk of the host parser can pass through it.- */-export function parseLocalDay(day: string): number | null {- if (!LOCAL_DAY_PATTERN.test(day)) return null;- const ms = Date.parse(`${day}T00:00:00Z`);- return Number.isNaN(ms) || toLocalDay(ms) !== day ? null : ms;-}--/** A `LocalDay` in the reader's own date order — 「2026年7月20日」/「Jul 20, 2026」.- * Formatted in UTC for the same reason the arithmetic is: the label must survive- * the round trip unshifted. Unparseable input renders verbatim rather than as an- * invented date. */-export function formatLocalDay(day: string, locale: string): string {- const ms = parseLocalDay(day);- if (ms === null) return day;- return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(ms);-}--/** Tokens the window actually moved. Cache is NOT subtracted: a cached input- * token was still composed into the request, and `cached_input_tokens` is a- * subset of `input_tokens` reported separately so a view can qualify the total- * without double-counting it. */+import type {+ UsageBucket,+ UsageBucketRow,+ UsageCounters,+ UsageReport,+ UsageWindowKey,+} from './types';++export const USAGE_WINDOW_OPTIONS = ['24h', '7d', '30d', '60d'] as const satisfies readonly UsageWindowKey[];+export type UsageWindowOption = UsageWindowKey;++export type UsageMetric = 'tokens' | 'input' | 'output' | 'cache' | 'requests';+export type UsageGroup = 'total' | 'type' | 'model' | 'source';+export type UsageFilter = {+ sourceIds: readonly string[];+ modelKeys: readonly string[];+};++export type UsageIdentity = {+ sourceId: string;+ modelId: string;+ sourceLabel: string;+ modelLabel: string | null;+ key: string;+};++export type UsageLabelContext = {+ sourceCollisionLabels: ReadonlySet<string>;+ sourceDisplayLabels: ReadonlyMap<string, string>;+ identityCollisionLabels: ReadonlySet<string>;+ identityModelCollisionKeys: ReadonlySet<string>;+ identityDisplayLabels: ReadonlyMap<string, string>;+};++export type UsageSeries = {+ key: string;+ label: string;+ colorIndex: number;+ values: Array<number | null>;+};++export const PAIR_SEPARATOR = '\u0000';++export const pairKey = (sourceId: string, modelId: string): string =>+ `${sourceId}${PAIR_SEPARATOR}${modelId}`;++export const emptyCounters = (): UsageCounters => ({+ requests: 0,+ token_reports: 0,+ input_tokens: 0,+ cached_input_tokens: 0,+ output_tokens: 0,+});++export function aggregateCounters(rows: readonly UsageCounters[]): UsageCounters {+ return rows.reduce((total, row) => ({+ requests: total.requests + row.requests,+ token_reports: total.token_reports + row.token_reports,+ input_tokens: total.input_tokens + row.input_tokens,+ cached_input_tokens: total.cached_input_tokens + row.cached_input_tokens,+ output_tokens: total.output_tokens + row.output_tokens,+ }), emptyCounters());+}+export function usageTotalTokens(counters: UsageCounters): number {return counters.input_tokens + counters.output_tokens;}-/**- * Requests whose upstream response carried no token report.- *- * The schema guarantees `token_reports <= requests`, and this floors at zero- * anyway: both numbers arrive over the wire, and a view that renders 「-3 次未回- * 报」 has turned a payload bug into a claim about the user's usage. The honest- * reading of a shortfall is missing reports, never unused capacity — which is- * why the caller's copy says so.- */+export function usageNonCachedInput(counters: UsageCounters): number {+ return Math.max(0, counters.input_tokens - counters.cached_input_tokens);+}+export function usageReportShortfall(counters: UsageCounters): number {return Math.max(0, counters.requests - counters.token_reports);}-/**- * Whether an upstream said what anything in this bucket cost.- *- * Three independent facts share one payload, and only one counter answers each:- * `requests` says calls happened, `token_reports` says an upstream told us what- * they cost, and the token counts say how much. A total of zero is therefore- * several different readings, and only this counter can find the one where a cost- * was actually reported — which is the only reading allowed to speak for the- * report, as a peak or as a claim about what the reports said.- */+export function usageTokensAreKnown(counters: Pick<UsageCounters, 'requests' | 'token_reports'>): boolean {+ return counters.token_reports > 0 || counters.requests === 0;+}+export function usageTokensAreReported(counters: Pick<UsageCounters, 'token_reports'>): boolean {return counters.token_reports > 0;}-/**- * Whether the token counts are a measurement, and so printable as a number.- *- * Wider than `usageTokensAreReported` by exactly one case, and it is not a- * concession: a bucket where nothing ran cost nothing, and that zero is measured- * by our own request counter rather than promised by an upstream. Blanking it- * would trade the defect this answers — an unreported cost read as free — for its- * mirror image, an idle day read as unknowable.- *- * So the two questions stay apart. Every token figure the tab prints asks this- * one; whether the report itself has anything to say about tokens is the other.- */-export function usageTokensAreKnown(counters: Pick<UsageCounters, 'requests' | 'token_reports'>): boolean {- return usageTokensAreReported(counters) || counters.requests === 0;+export function usageMetricValue(counters: UsageCounters, metric: UsageMetric): number | null {+ if (metric === 'requests') return counters.requests;+ if (!usageTokensAreKnown(counters)) return null;+ if (metric === 'tokens') return usageTotalTokens(counters);+ if (metric === 'input') return counters.input_tokens;+ if (metric === 'output') return counters.output_tokens;+ return counters.cached_input_tokens;}-/** Share of input tokens served from cache, or null when there is no input to- * take a share of. Clamped to [0, 1] because the subset relation is the- * server's promise, not something this view can verify. */export function usageCachedInputShare(counters: UsageCounters): number | null {- if (counters.input_tokens <= 0) return null;+ if (counters.input_tokens <= 0 || !usageTokensAreKnown(counters)) return null;return Math.min(1, Math.max(0, counters.cached_input_tokens / counters.input_tokens));}-/** Nothing was metered in the window. `sources` is the gate because it is what- * the table renders, and a Source enters it only once it has a metered turn. */-export function usageIsEmpty(summary: UsageSummary): boolean {- return summary.sources.length === 0;+export function usageIsEmpty(report: UsageReport): boolean {+ return report.buckets.every((bucket) => bucket.history_complete && bucket.rows.length === 0);}-export type UsageDayColumn = {- day: string;- /** Calls metered on this day, whether or not their tokens came back. */- requests: number;- /** Calls whose upstream said what they cost — what makes `tokens` a measurement. */- token_reports: number;- tokens: number;- /** Height against the busiest rendered day, in [0, 1]. */- ratio: number;-};+export function formatRfc3339(value: string, locale: string, includeOffset = false): string {+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);+ if (!match) return value;+ const [, year, month, day, hour, minute] = match;+ const suffix = includeOffset ? ` ${formatOffset(value)}` : '';+ if (locale.startsWith('zh')) return `${year}年${Number(month)}月${Number(day)}日 ${hour}:${minute}${suffix}`;+ const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));+ const monthLabel = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' }).format(date);+ return `${monthLabel} ${Number(day)}, ${year}, ${hour}:${minute}${suffix}`;+}++export function formatOffset(value: string): string {+ const match = value.match(/(Z|[+-]\d{2}:\d{2})$/);+ if (!match || match[1] === 'Z') return 'UTC';+ return `UTC${match[1]}`;+}++export function formatBucketLabel(bucket: UsageBucket, locale: string): string {+ if (bucket.key.match(/^\d{4}-\d{2}-\d{2}$/)) {+ const [year, month, day] = bucket.key.split('-').map(Number);+ if (locale.startsWith('zh')) return `${year}年${month}月${day}日`;+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' })+ .format(new Date(Date.UTC(year, month - 1, day)));+ }+ return formatRfc3339(bucket.start_at, locale);+}++export function formatBucketAxisLabel(bucket: UsageBucket, locale: string): string {+ if (bucket.key.match(/^\d{4}-\d{2}-\d{2}$/)) {+ const [year, month, day] = bucket.key.split('-').map(Number);+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' })+ .format(new Date(Date.UTC(year, month - 1, day)));+ }+ const match = bucket.start_at.match(/T\d{2}:(\d{2})/);+ if (match) {+ const hour = bucket.start_at.slice(11, 13);+ return `${hour}:${match[1]}`;+ }+ return formatBucketLabel(bucket, locale);+}-/**- * Whether a day carried a metered call at all.- *- * A day's activity is its request counter, never its token total. An upstream- * that answered without a token report still served a call the user made, so a- * day of those is a day that ran — and drawing it at zero height, or folding it- * into 「没有任何一天有计量数据」, reports our own missing evidence as the user's- * idleness. That is the rule the requests card states as a shortfall, applied per- * day, and it lives here so the series has one place to ask rather than one- * `tokens > 0` per thing it draws.- */-export function usageDayIsMetered(column: UsageDayColumn): boolean {- return column.requests > 0;-}--/**- * Every day of the window, oldest first, with the days that carried no turn- * filled in at zero.- *- * `days[]` is sparse by contract — a quiet day is absent, not reported as zero —- * and a chart drawn straight from it would silently close the gaps and read as- * continuous traffic. Densifying from `from_day`/`to_day` is what makes an idle- * stretch visible as an idle stretch.- *- * The span comes from the dates rather than from `window_days` so a payload- * whose two disagree still plots its real dates, and it is refused outright past- * the contract's own maximum: the bound is ours, measured against the schema, so- * a `from_day` far in the past cannot ask this for a million columns. A refused- * span falls back to exactly the days reported — fewer bars, no invention.- */-export function usageDayColumns(summary: UsageSummary): UsageDayColumn[] {- const reportedByDay = new Map(summary.days.map((day: UsageByDay) => [day.day, day]));- const span = windowSpan(summary.from_day, summary.to_day);- const days = span ?? summary.days.map((day) => day.day);- // All three counters travel, because tokens alone cannot tell a day nobody- // used from a day whose upstream never said what it cost — nor either of those- // from a day that really did cost nothing. Dropping `token_reports` here is- // what made a rendered 0 ambiguous no matter how carefully the copy was worded.- const counted = days.map((day) => {- const reported = reportedByDay.get(day);+export function formatBucketRange(bucket: UsageBucket, locale: string, includeOffsets = false): string {+ return `${formatRfc3339(bucket.start_at, locale, includeOffsets)} – ${formatRfc3339(bucket.end_at, locale, includeOffsets)}`;+}++export function sourceLabel(report: UsageReport, sourceId: string): string {+ const source = report.sources.find((candidate) => candidate.source_id === sourceId);+ return source?.label?.trim() || sourceId;+}++export function modelLabel(report: UsageReport, sourceId: string, modelId: string): string | null {+ const source = report.sources.find((candidate) => candidate.source_id === sourceId);+ const model = source?.models.find((candidate) => candidate.model_id === modelId);+ return model?.label?.trim() || null;+}++export function usageIdentities(report: UsageReport, rows: readonly UsageBucketRow[]): UsageIdentity[] {+ const keys = new Set(rows.map((row) => pairKey(row.source_id, row.model_id)));+ return [...keys].map((key) => {+ const separator = key.indexOf(PAIR_SEPARATOR);+ const sourceId = key.slice(0, separator);+ const modelId = key.slice(separator + 1);return {- day,- requests: reported?.requests ?? 0,- token_reports: reported?.token_reports ?? 0,- tokens: reported ? usageTotalTokens(reported) : 0,+ key,+ sourceId,+ modelId,+ sourceLabel: sourceLabel(report, sourceId),+ modelLabel: modelLabel(report, sourceId, modelId),};});- // Scaled against the days on screen, not every day reported: a stray row- // outside the window would otherwise flatten every bar the user can see.- const peak = counted.reduce((max, column) => Math.max(max, column.tokens), 0);- return counted.map((column) => ({ ...column, ratio: peak > 0 ? column.tokens / peak : 0 }));-}--const windowSpan = (fromDay: string, toDay: string): string[] | null => {- const from = parseLocalDay(fromDay);- const to = parseLocalDay(toDay);- if (from === null || to === null || to < from) return null;- const length = (to - from) / DAY_MS + 1;- if (!Number.isInteger(length) || length < USAGE_WINDOW_MIN_DAYS || length > USAGE_WINDOW_MAX_DAYS) return null;- return Array.from({ length }, (_, index) => toLocalDay(from + index * DAY_MS));+}++export function identityLabel(identity: UsageIdentity, unknownModelLabel: string): string {+ const model = identity.modelLabel || unknownModelLabel;+ return `${identity.sourceLabel} · ${model}`;+}++export function usageLabelContext(+ report: UsageReport,+ rows: readonly UsageBucketRow[],+ unknownModelLabel: string,+): UsageLabelContext {+ const sourceIds = [...new Set([+ ...report.sources.map((source) => source.source_id),+ ...rows.map((row) => row.source_id),+ ])];+ const sourceLabels = new Map(+ sourceIds.map((sourceId) => [sourceId, sourceLabel(report, sourceId)] as const),+ );+ const sourceLabelCounts = new Map<string, number>();+ for (const label of sourceLabels.values()) {+ sourceLabelCounts.set(label, (sourceLabelCounts.get(label) ?? 0) + 1);+ }+ const sourceCollisionLabels = new Set(+ [...sourceLabelCounts.entries()]+ .filter(([, count]) => count > 1)+ .map(([label]) => label),+ );+ const sourceDisplayLabels = new Map(+ [...sourceLabels.entries()].map(([sourceId, label]) => [+ sourceId,+ sourceCollisionLabels.has(label) ? `${label} · ${sourceId}` : label,+ ]),+ );+ for (;;) {+ const displayCounts = new Map<string, number>();+ for (const label of sourceDisplayLabels.values()) {+ displayCounts.set(label, (displayCounts.get(label) ?? 0) + 1);+ }+ const collisions = [...displayCounts.entries()]+ .filter(([, count]) => count > 1)+ .map(([label]) => label);+ if (collisions.length === 0) break;+ for (const [sourceId, label] of sourceDisplayLabels) {+ if (collisions.includes(label)) {+ sourceDisplayLabels.set(sourceId, `${label} · ${sourceId}`);+ }+ }+ }++ const identityLabelCounts = new Map<string, number>();+ const identities = usageIdentities(report, rows);+ for (const identity of identities) {+ const label = identityLabel(identity, unknownModelLabel);+ identityLabelCounts.set(label, (identityLabelCounts.get(label) ?? 0) + 1);+ }+ const sourceQualifiedIdentityCounts = new Map<string, number>();+ for (const identity of identities) {+ const label = identityLabel(identity, unknownModelLabel);+ if (identityLabelCounts.get(label) === 1) continue;+ const qualifiedLabel = `${label} · ${identity.sourceId}`;+ sourceQualifiedIdentityCounts.set(qualifiedLabel, (sourceQualifiedIdentityCounts.get(qualifiedLabel) ?? 0) + 1);+ }++ const identityCollisionLabels = new Set(+ [...identityLabelCounts.entries()]+ .filter(([, count]) => count > 1)+ .map(([label]) => label),+ );+ const identityByKey = new Map(identities.map((identity) => [identity.key, identity] as const));+ const identityCandidates = new Map(+ identities.map((identity) => {+ const label = identityLabel(identity, unknownModelLabel);+ const modelSuffix = (+ (sourceQualifiedIdentityCounts.get(`${label} · ${identity.sourceId}`) ?? 0) > 1+ ) ? ` · ${identity.modelId}` : '';+ const candidate = identityCollisionLabels.has(label)+ ? `${label} · ${identity.sourceId}${modelSuffix}`+ : label;+ return [identity.key, candidate] as const;+ }),+ );+ const identityDisplayLabels = new Map<string, string>();+ const usedIdentityLabels = new Set<string>();+ for (const [key, candidate] of identityCandidates) {+ const identity = identityByKey.get(key)!;+ let displayLabel = candidate;+ let suffix = 0;+ while (usedIdentityLabels.has(displayLabel)) {+ suffix += 1;+ const identitySuffix = ` · ${identity.sourceId} · ${identity.modelId}`;+ displayLabel = `${candidate}${identitySuffix}${suffix > 1 ? ` (${suffix})` : ''}`;+ }+ usedIdentityLabels.add(displayLabel);+ identityDisplayLabels.set(key, displayLabel);+ }+ return {+ sourceCollisionLabels,+ sourceDisplayLabels,+ identityCollisionLabels,+ identityModelCollisionKeys: new Set(+ identities+ .filter((identity) => {+ const label = identityLabel(identity, unknownModelLabel);+ return identityCollisionLabels.has(label)+ && (sourceQualifiedIdentityCounts.get(`${label} · ${identity.sourceId}`) ?? 0) > 1;+ })+ .map((identity) => identity.key),+ ),+ identityDisplayLabels,+ };+}++export function sourceIdentityLabel(+ report: UsageReport,+ sourceId: string,+ context: UsageLabelContext,+): string {+ const label = sourceLabel(report, sourceId);+ return context.sourceDisplayLabels.get(sourceId)+ ?? (context.sourceCollisionLabels.has(label) ? `${label} · ${sourceId}` : label);+}++export function identityDisplayLabel(+ identity: UsageIdentity,+ unknownModelLabel: string,+ context?: UsageLabelContext,+): string {+ const displayLabel = context?.identityDisplayLabels.get(identity.key);+ if (displayLabel) return displayLabel;+ const label = identityLabel(identity, unknownModelLabel);+ if (!context?.identityCollisionLabels.has(label)) return label;+ const modelSuffix = context.identityModelCollisionKeys.has(identity.key) ? ` · ${identity.modelId}` : '';+ return `${label} · ${identity.sourceId}${modelSuffix}`;+}++export function filterBucketRows(bucket: UsageBucket, filter: UsageFilter): UsageBucketRow[] {+ return bucket.rows.filter((row) => (+ (filter.sourceIds.length === 0 || filter.sourceIds.includes(row.source_id))+ && (filter.modelKeys.length === 0 || filter.modelKeys.includes(pairKey(row.source_id, row.model_id)))+ ));+}++export function filteredRows(report: UsageReport, filter: UsageFilter): UsageBucketRow[] {+ return report.buckets.flatMap((bucket) => filterBucketRows(bucket, filter));+}++const typeSeries = (+ rows: UsageBucketRow[],+ metric: UsageMetric,+ historyComplete: boolean,+): Array<[string, number | null]> => {+ if (!historyComplete && rows.length === 0) {+ if (metric === 'requests') return [['requests', null]];+ if (metric === 'output') return [['output', null]];+ if (metric === 'cache') return [['cache', null]];+ if (metric === 'input') return [['input', null], ['cache', null]];+ return [['input', null], ['cache', null], ['output', null]];+ }+ const counters = aggregateCounters(rows);+ if (metric === 'requests') return [['requests', counters.requests]];+ if (!usageTokensAreKnown(counters)) return metric === 'output'+ ? [['output', null]]+ : metric === 'cache'+ ? [['cache', null]]+ : metric === 'input'+ ? [['input', null], ['cache', null]]+ : [['input', null], ['cache', null], ['output', null]];+ if (metric === 'output') return [['output', counters.output_tokens]];+ if (metric === 'cache') return [['cache', counters.cached_input_tokens]];+ if (metric === 'input') return [['input', usageNonCachedInput(counters)], ['cache', counters.cached_input_tokens]];+ return [+ ['input', usageNonCachedInput(counters)],+ ['cache', counters.cached_input_tokens],+ ['output', counters.output_tokens],+ ];};-/**- * What a usage row may put on screen for its own identity.- *- * `gone` carries an id only where one is safe to show. A Source keeps its- * canonical `src_*` id, which is a string the user could have seen elsewhere. A- * model's ledger key is a head plus a digest for any long identifier — a string- * nobody typed — so a vanished model has NO displayable identity and gets a bare- * marker. That asymmetry is the reason both live behind one type instead of two- * `label ?? id` expressions in JSX.- */-export type UsageIdentity = { kind: 'label'; text: string } | { kind: 'gone'; id: string | null };--const identify = (label: string | null, fallbackId: string | null): UsageIdentity => {- const text = label?.trim();- // A blank label is as unrenderable as a missing one, and the schema permits it.- return text ? { kind: 'label', text } : { kind: 'gone', id: fallbackId };+const bucketMetricValue = (+ bucket: UsageBucket,+ rows: UsageBucketRow[],+ metric: UsageMetric,+): number | null => {+ if (!bucket.history_complete && rows.length === 0) return null;+ return usageMetricValue(aggregateCounters(rows), metric);};-export function sourceIdentity(source: UsageBySource): UsageIdentity {- return identify(source.label, source.source_id);+export function seriesFor(+ report: UsageReport,+ filter: UsageFilter,+ group: UsageGroup,+ metric: UsageMetric,+ unknownModelLabel: string,+): UsageSeries[] {+ const rows = filteredRows(report, filter);+ if (group === 'type') {+ const valuesByKey = new Map<string, Array<number | null>>();+ for (const bucket of report.buckets) {+ for (const [key, value] of typeSeries(filterBucketRows(bucket, filter), metric, bucket.history_complete)) {+ valuesByKey.set(key, [...(valuesByKey.get(key) ?? []), value]);+ }+ }+ const labels: Record<string, string> = {+ input: 'Input (non-cache)',+ cache: 'Cache reads',+ output: 'Output',+ requests: 'Requests',+ };+ return [...valuesByKey.entries()].map(([key, values], index) => ({+ key,+ label: labels[key],+ colorIndex: index,+ values,+ }));+ }++ if (group === 'total') {+ return [{+ key: 'total',+ label: metric,+ colorIndex: 0,+ values: report.buckets.map((bucket) => bucketMetricValue(+ bucket,+ filterBucketRows(bucket, filter),+ metric,+ )),+ }];+ }++ if (group === 'source') {+ const labelContext = usageLabelContext(report, rows, unknownModelLabel);+ const sourceIds = [...new Set(rows.map((row) => row.source_id))];+ return sourceIds.map((sourceId, index) => ({+ key: sourceId,+ label: sourceIdentityLabel(report, sourceId, labelContext),+ colorIndex: index,+ values: report.buckets.map((bucket) => {+ const rowsForSource = filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId);+ return bucketMetricValue(bucket, rowsForSource, metric);+ }),+ }));+ }++ const identities = usageIdentities(report, rows);+ const labelContext = usageLabelContext(report, rows, unknownModelLabel);+ return identities.map((identity, index) => ({+ key: identity.key,+ label: identityDisplayLabel(identity, unknownModelLabel, labelContext),+ colorIndex: index,+ values: report.buckets.map((bucket) => {+ const rowsForIdentity = filterBucketRows(bucket, filter).filter((row) => (+ row.source_id === identity.sourceId && row.model_id === identity.modelId+ ));+ return bucketMetricValue(bucket, rowsForIdentity, metric);+ }),+ }));}-export function modelIdentity(model: UsageByModel): UsageIdentity {- return identify(model.label, null);+export function reportHasPartialHistory(report: UsageReport, filter: UsageFilter): boolean {+ void filter;+ return report.buckets.some((bucket) => !bucket.history_complete);+}++export function reportHasUnknownTokens(report: UsageReport, filter: UsageFilter): boolean {+ return report.buckets.some((bucket) => {+ const rows = filterBucketRows(bucket, filter);+ const counters = aggregateCounters(rows);+ return rows.length > 0 && !usageTokensAreKnown(counters);+ });}diff --git a/ui/src/context/ToastProvider.test.tsx b/ui/src/context/ToastProvider.test.tsxindex 831bdb106..5dd5e5104 100644--- a/ui/src/context/ToastProvider.test.tsx+++ b/ui/src/context/ToastProvider.test.tsx@@ -17,6 +17,18 @@ const Trigger = () => {return <button type="button" onClick={() => showToast('Saved')}>Save</button>;};+const ActionTrigger = () => {+ const { showToast } = useToast();+ return (+ <button+ type="button"+ onClick={() => showToast('Saved', 'success', { label: 'Undo', onClick: () => {} })}+ >+ Save+ </button>+ );+};+describe('ToastProvider', () => {it('announces toast messages through a polite status region', async () => {render(@@ -50,4 +62,40 @@ describe('ToastProvider', () => {act(() => vi.advanceTimersByTime(1));expect(screen.queryByRole('status')).toBeNull();});++ it('clears actionable auto-dismiss timers when the provider unmounts', () => {+ vi.useFakeTimers();+ const rendered = render(+ <ToastProvider>+ <ActionTrigger />+ </ToastProvider>,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ expect(vi.getTimerCount()).toBe(1);++ rendered.unmount();++ expect(vi.getTimerCount()).toBe(0);+ act(() => vi.advanceTimersByTime(6000));+ });++ it('clears dedupe timers when the provider unmounts', () => {+ vi.useFakeTimers();+ const rendered = render(+ <ToastProvider>+ <Trigger />+ </ToastProvider>,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ act(() => vi.advanceTimersByTime(2500));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ expect(vi.getTimerCount()).toBe(1);++ rendered.unmount();++ expect(vi.getTimerCount()).toBe(0);+ act(() => vi.advanceTimersByTime(3000));+ });});diff --git a/ui/src/context/ToastProvider.tsx b/ui/src/context/ToastProvider.tsxindex 8ecc02aaa..d44b62ccb 100644--- a/ui/src/context/ToastProvider.tsx+++ b/ui/src/context/ToastProvider.tsx@@ -1,4 +1,4 @@-import React, { useState, useCallback, useMemo, useRef } from 'react';+import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';import { AlertTriangle, CheckCircle, XCircle, X } from 'lucide-react';import { ToastContext, type ToastType } from './ToastContext';@@ -34,6 +34,28 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre// Ref so dedupe lookups don't rerender. Maps message -> {id, expiresAt}// for currently-visible toasts; we evict on auto-dismiss.const recentRef = useRef<Map<string, RecentToast>>(new Map());+ const timersRef = useRef<Set<ToastTimer>>(new Set());++ const scheduleTimer = useCallback((callback: () => void, delay: number): ToastTimer => {+ let timer = 0;+ timer = window.setTimeout(() => {+ timersRef.current.delete(timer);+ callback();+ }, delay);+ timersRef.current.add(timer);+ return timer;+ }, []);++ const cancelTimer = useCallback((timer: ToastTimer) => {+ window.clearTimeout(timer);+ timersRef.current.delete(timer);+ }, []);++ useEffect(() => () => {+ for (const timer of timersRef.current) window.clearTimeout(timer);+ timersRef.current.clear();+ recentRef.current.clear();+ }, []);const showToast = useCallback((message: string, type: ToastType = 'success', action?: ToastAction) => {@@ -44,11 +66,11 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childreconst now = Date.now();const existing = recentRef.current.get(message);if (shouldCoalesceToast(!!action, existing, now)) {- window.clearTimeout(existing!.timer);+ cancelTimer(existing!.timer);setToasts((prev) =>prev.map((t) => (t.id === existing!.id ? { ...t, repeats: t.repeats + 1, type } : t)),);- const timer = window.setTimeout(() => {+ const timer = scheduleTimer(() => {setToasts((prev) => prev.filter((t) => t.id !== existing!.id));const tracked = recentRef.current.get(message);if (tracked && tracked.id === existing!.id) recentRef.current.delete(message);@@ -65,7 +87,7 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childresetToasts((prev) => [...prev, { id, message, type, repeats: 0, action }]);// Auto dismiss (longer for actionable toasts so undo is reachable).- const timer = window.setTimeout(() => {+ const timer = scheduleTimer(() => {setToasts((prev) => prev.filter((t) => t.id !== id));// Best-effort cleanup of the dedupe map — the entry may have been// re-issued under a different id during the window.@@ -78,18 +100,18 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childretimer,});},- [],+ [cancelTimer, scheduleTimer],);const dismissToast = useCallback((id: number) => {setToasts((prev) => prev.filter((t) => t.id !== id));for (const [message, tracked] of recentRef.current) {if (tracked.id !== id) continue;- window.clearTimeout(tracked.timer);+ cancelTimer(tracked.timer);recentRef.current.delete(message);break;}- }, []);+ }, [cancelTimer]);// Stable value identity so the ~34 consumers of useToast don't re-render every// time a toast is added/removed/auto-dismissed (which re-renders this provider):diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 3eb115e3c..5ad1a0343 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1415,7 +1415,11 @@"detail": "Metered tokens from the turns the gateway proxied, by local day.","window": {"label": "Window",- "option": "{{days}}d"+ "option": "{{days}}d",+ "24h": "24 hours",+ "7d": "7 days",+ "30d": "30 days",+ "60d": "60 days"},"range": "{{from}} – {{to}} · trailing {{days}} days","empty": "Nothing metered yet. A window fills once a gateway source serves a request.",@@ -1427,6 +1431,7 @@},"requests": {"label": "Requests",+ "unit": "requests","reported": "Every request reported its tokens","shortfall_one": "{{count}} request came back with no token report","shortfall_other": "{{count}} requests came back with no token report"@@ -1460,7 +1465,136 @@"quiet": "No day in this window carried a metered turn","unreported": "Requests ran, but no day reported its tokens","zero": "Every day that reported its tokens reported zero"- }+ },+ "metric": {+ "label": "Metric",+ "tokens": "All tokens",+ "input": "Input (including cache)",+ "output": "Output",+ "cache": "Cache reads",+ "requests": "Requests"+ },+ "filters": {+ "source": "Source",+ "model": "Model",+ "all": "All {{label}}",+ "selected_one": "{{label}} · {{count}} selected",+ "selected_other": "{{label}} · {{count}} selected",+ "search": "Search {{label}}",+ "noMatch": "No matching options",+ "hint": "Multi-select updates the report",+ "reset": "Reset filters",+ "allSources": "All sources",+ "allModels": "All models",+ "sourceCount_one": "{{count}} source",+ "sourceCount_other": "{{count}} sources",+ "modelCount_one": "{{count}} model",+ "modelCount_other": "{{count}} models"+ },+ "stats": {+ "tokens": "All tokens",+ "requests": "Requests",+ "cached": "Cached input share",+ "tokenSplit": "{{input}} input · {{output}} output",+ "shortfall_one": "{{count}} request has no token report",+ "shortfall_other": "{{count}} requests have no token report",+ "allReported": "Every request reported tokens",+ "cacheUnknown": "No measured input available",+ "cacheSplit": "{{cached}} cached of {{input}} input"+ },+ "unknownTokens": "Some requests have no token report; token values are unavailable",+ "partialHistory": "Some buckets have incomplete history",+ "historicalHourly": "Includes historical usage without hourly time",+ "unknownModel": "Unknown model",+ "granularity": {+ "hour": "hourly",+ "day": "daily"+ },+ "group": {+ "label": "Group",+ "total": "Total",+ "type": "Token type",+ "model": "Model",+ "source": "Source"+ },+ "series": {+ "input": "Input (non-cache)",+ "cache": "Cache reads",+ "output": "Output",+ "requests": "Requests"+ },+ "chart": {+ "title": "Usage trend",+ "subtitle": "Exact counts by the selected time bucket",+ "aria": "{{kind}} usage trend",+ "lines": "line",+ "bars": "stacked bar",+ "bucket": "Usage bucket {{bucket}}",+ "detail": "Usage bucket details",+ "legend": "Chart legend",+ "pin": "Pin this bucket",+ "unpin": "Unpin this bucket",+ "pinned": "Pinned",+ "currentPartial": "Current partial hour",+ "complete": "History complete",+ "partial": "Partial history",+ "points_one": "{{count}} {{granularity}} point",+ "points_other": "{{count}} {{granularity}} points",+ "legendOnly": "Legend visibility only changes the chart",+ "interaction": "Hover or focus a bucket · click for details"+ },+ "table": {+ "title": "Exact usage details",+ "range": "The table uses the same filters as the chart",+ "bucket": "Showing {{bucket}}",+ "allBuckets": "View all buckets",+ "group": "Table grouping",+ "byModel": "By model",+ "bySource": "By source",+ "export": "Export CSV",+ "identity": "Model / source",+ "requests": "Requests",+ "input": "Input",+ "nonCache": "Non-cache input",+ "cache": "Cache reads",+ "output": "Output",+ "tokens": "All tokens",+ "share": "Share",+ "sortAscending": "{{metric}}: Sorted ascending",+ "sortDescending": "{{metric}}: Sorted descending",+ "total": "Total",+ "empty": "No matching usage",+ "accounting": "All tokens = input + output. Cache reads are included in input and shown separately."+ },+ "csv": {+ "bucketKey": "Bucket key",+ "startAt": "Start at",+ "endAt": "End at",+ "historyComplete": "History complete",+ "sourceId": "Source ID",+ "modelId": "Model ID",+ "ledgerKey": "Internal ledger key",+ "sourceLabel": "Source",+ "modelLabel": "Model",+ "tokenReports": "Token reports",+ "inputTokens": "Input tokens",+ "nonCachedInputTokens": "Non-cache input tokens",+ "cachedInputTokens": "Cached input tokens",+ "outputTokens": "Output tokens",+ "totalTokens": "Total tokens"+ },+ "empty": {+ "report": {+ "title": "No usage in this window",+ "body": "The gateway has not recorded a request in the selected time range."+ },+ "filter": {+ "title": "No matching usage",+ "body": "Try another Source or model, or reset the filters."+ }+ },+ "failure": "The usage report could not be read.",+ "retry": "Retry"},"supplyTooltip": {"label": "Supplies: "diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 791a1e58c..b4f137ea0 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1415,7 +1415,11 @@"detail": "模型网关代理的对话所计量的 token,按本地日期汇总。","window": {"label": "区间",- "option": "{{days}} 天"+ "option": "{{days}} 天",+ "24h": "24 小时",+ "7d": "7 天",+ "30d": "30 天",+ "60d": "60 天"},"range": "{{from}} – {{to}} · 近 {{days}} 天","empty": "还没有计量数据。模型网关完成请求后,这里就会有内容。",@@ -1427,6 +1431,7 @@},"requests": {"label": "请求数",+ "unit": "次请求","reported": "每次请求都回报了 token","shortfall_one": "{{count}} 次请求没有回报 token","shortfall_other": "{{count}} 次请求没有回报 token"@@ -1460,7 +1465,136 @@"quiet": "这个区间没有任何一天有计量数据","unreported": "有请求,但没有任何一天回报了 token","zero": "有回报 token 的日子,回报的都是 0"- }+ },+ "metric": {+ "label": "指标",+ "tokens": "全部 Tokens",+ "input": "输入(含缓存)",+ "output": "输出",+ "cache": "缓存读取",+ "requests": "请求数"+ },+ "filters": {+ "source": "供应商",+ "model": "模型",+ "all": "全部{{label}}",+ "selected_one": "{{label}} · 已选 {{count}} 个",+ "selected_other": "{{label}} · 已选 {{count}} 个",+ "search": "搜索{{label}}",+ "noMatch": "没有匹配项",+ "hint": "多选会同步更新整份报表",+ "reset": "重置筛选",+ "allSources": "全部供应商",+ "allModels": "全部模型",+ "sourceCount_one": "{{count}} 个供应商",+ "sourceCount_other": "{{count}} 个供应商",+ "modelCount_one": "{{count}} 个模型",+ "modelCount_other": "{{count}} 个模型"+ },+ "stats": {+ "tokens": "全部 Tokens",+ "requests": "请求数",+ "cached": "输入缓存占比",+ "tokenSplit": "输入 {{input}} · 输出 {{output}}",+ "shortfall_one": "{{count}} 次请求没有回报 token",+ "shortfall_other": "{{count}} 次请求没有回报 token",+ "allReported": "每次请求都回报了 token",+ "cacheUnknown": "暂无已知输入 token",+ "cacheSplit": "输入 {{input}} 中有 {{cached}} 来自缓存"+ },+ "unknownTokens": "部分请求没有回报 token,相关 token 数值不可用",+ "partialHistory": "部分时间桶的历史记录不完整",+ "historicalHourly": "含无具体小时记录的历史用量",+ "unknownModel": "未知模型",+ "granularity": {+ "hour": "按小时",+ "day": "按天"+ },+ "group": {+ "label": "分组",+ "total": "总量",+ "type": "Token 类型",+ "model": "模型",+ "source": "供应商"+ },+ "series": {+ "input": "输入(非缓存)",+ "cache": "缓存读取",+ "output": "输出",+ "requests": "请求数"+ },+ "chart": {+ "title": "用量趋势",+ "subtitle": "按所选时间桶显示精确数量",+ "aria": "{{kind}}用量趋势",+ "lines": "折线",+ "bars": "堆叠柱状图",+ "bucket": "用量时间桶 {{bucket}}",+ "detail": "时间桶用量详情",+ "legend": "图表图例",+ "pin": "固定这个时间桶",+ "unpin": "取消固定时间桶",+ "pinned": "已固定",+ "currentPartial": "当前小时未结束",+ "complete": "历史完整",+ "partial": "历史不完整",+ "points_one": "{{count}} 个{{granularity}}数据点",+ "points_other": "{{count}} 个{{granularity}}数据点",+ "legendOnly": "图例显隐只影响图表",+ "interaction": "悬停或聚焦时间桶 · 点击查看详情"+ },+ "table": {+ "title": "精确用量明细",+ "range": "明细表与图表使用相同筛选条件",+ "bucket": "正在显示 {{bucket}}",+ "allBuckets": "查看全部时间桶",+ "group": "明细分组",+ "byModel": "按模型",+ "bySource": "按供应商",+ "export": "导出 CSV",+ "identity": "模型 / 供应商",+ "requests": "请求数",+ "input": "输入",+ "nonCache": "非缓存输入",+ "cache": "缓存读取",+ "output": "输出",+ "tokens": "全部 Tokens",+ "share": "占比",+ "sortAscending": "{{metric}}:升序排列",+ "sortDescending": "{{metric}}:降序排列",+ "total": "合计",+ "empty": "没有符合条件的用量",+ "accounting": "全部 Tokens = 输入 + 输出。缓存读取已包含在输入中,同时单独列出。"+ },+ "csv": {+ "bucketKey": "时间桶键",+ "startAt": "开始时间",+ "endAt": "结束时间",+ "historyComplete": "历史完整",+ "sourceId": "供应商 ID",+ "modelId": "模型 ID",+ "ledgerKey": "内部账本键",+ "sourceLabel": "供应商",+ "modelLabel": "模型",+ "tokenReports": "Token 报告数",+ "inputTokens": "输入 token",+ "nonCachedInputTokens": "非缓存输入 token",+ "cachedInputTokens": "缓存输入 token",+ "outputTokens": "输出 token",+ "totalTokens": "总 token"+ },+ "empty": {+ "report": {+ "title": "这个区间没有用量",+ "body": "模型网关在所选时间范围内还没有记录请求。"+ },+ "filter": {+ "title": "没有符合条件的用量",+ "body": "试试其他供应商或模型,或重置筛选。"+ }+ },+ "failure": "暂时没能读取用量报表。",+ "retry": "重试"},"supplyTooltip": {"label": "使用:"diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 51d5aaa85..d668c6a9b 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -273,11 +273,23 @@ class ModelHubRemoteService:def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:return _rpc_sync("list_events", {"limit": limit, "before": before})- async def usage_summary(self, *, days: int = USAGE_DEFAULT_WINDOW_DAYS) -> dict:+ async def usage_summary(+ self,+ *,+ days: Optional[int] = None,+ window: Optional[str] = None,+ ) -> dict:# Async, unlike the other reads here: this one blocks on the lock the# ledger's writers hold across an fsync, so a sync call would hold a UI# worker for as long as the disk takes. See `usage.BoundedUsageLedger`.- return await _rpc("usage_summary", {"days": days})+ payload: dict[str, Any] = {}+ if days is not None:+ payload["days"] = days+ if window is not None:+ payload["window"] = window+ if not payload:+ payload["days"] = USAGE_DEFAULT_WINDOW_DAYS+ return await _rpc("usage_summary", payload)async def quota_summary(self, *, force: bool = False) -> dict:return await _rpc("quota_summary", {"force": force})diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex fab5f3b70..bce71d834 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4925,14 +4925,26 @@ async def model_hub_usage_get(starlette_request: FastAPIRequest):# `rpc.py`, which keeps the read off the event loop there.async def handler():from core.handlers.model_hub import ModelHubError- from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS+ from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS, USAGE_WINDOW_KEYStry:- days = int(starlette_request.query_params.get("days") or USAGE_DEFAULT_WINDOW_DAYS)- except (TypeError, ValueError):- days = USAGE_DEFAULT_WINDOW_DAYS- try:- usage = await _model_hub_service().usage_summary(days=days)+ query = starlette_request.query_params+ has_days = "days" in query+ has_window = "window" in query+ if has_days and has_window:+ raise ModelHubError("invalid_parameter", status=400)+ if has_window:+ windows = query.getlist("window")+ window = windows[0]+ if window not in USAGE_WINDOW_KEYS or any(value != window for value in windows):+ raise ModelHubError("invalid_parameter", status=400)+ usage = await _model_hub_service().usage_summary(window=window)+ else:+ try:+ days = int(query.get("days") or USAGE_DEFAULT_WINDOW_DAYS)+ except (TypeError, ValueError):+ days = USAGE_DEFAULT_WINDOW_DAYS+ usage = await _model_hub_service().usage_summary(days=days)return _model_hub_success(usage=usage)except ModelHubError as exc:return _model_hub_error(exc)