Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(model-hub): say prices are coming, never 「≥ $0」, and follow Claude plan changes (#2213)

Call White300ef295481c
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 0bfc0682b..bf7dc8206 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -572,7 +572,9 @@ class EngineAdapter(Protocol):
The engine makes the model-free account call with the bound grant; only
the parsed ``{plan, windows}`` crosses this boundary, never the grant or
- the raw body. Raise ``SubscriptionQuotaError`` with a sanitized reason
+ the raw body. ``plan`` is the plan this read named, one without a built-in
+ fee included, or None when it could not name one; only None keeps the
+ last known plan. Raise ``SubscriptionQuotaError`` with a sanitized reason
(``auth_expired``, ``rate_limited``, ``unsupported``, ``unavailable`` or
``malformed``) on every failure. A report only: never feeds resolution.
"""
diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.py
index 3ead15e43..cfe4819c0 100644
--- a/core/handlers/model_hub/pricing.py
+++ b/core/handlers/model_hub/pricing.py
@@ -229,8 +229,11 @@ class PriceTable:
vendor_map: Mapping[str, Any],
overrides: Mapping[str, Any],
price_table_date: Optional[str],
+ pending: bool = False,
):
self.price_table_date = price_table_date
+ # No models.dev table yet, and a first fetch is running that should land.
+ self.pending = pending
self._catalog = catalog
self._vendor_map = vendor_map
self._model_overrides: dict[str, Mapping[str, Any]] = {}
@@ -305,6 +308,14 @@ class PriceTable:
return None
return model_price(entry.get("cost"))
+ def fields(self) -> dict[str, Any]:
+ """The table's own part of every priced block: currency, date, and a first fetch still running."""
+
+ fields: dict[str, Any] = {"currency": CURRENCY, "price_table_date": self.price_table_date}
+ if self.pending:
+ fields["pending"] = True
+ return fields
+
def source_plan(self, source_id: str) -> SourcePlan:
return self._sources.get(source_id, SourcePlan())
@@ -424,10 +435,15 @@ def _read_overrides(path: Path) -> dict[str, Any]:
def load_price_table(
state_dir: Path,
*,
- catalog_loader: Optional[Callable[[], tuple[Mapping[str, Any], Optional[float]]]] = None,
+ catalog_loader: Optional[Callable[[], tuple[Mapping[str, Any], Optional[float], bool]]] = None,
vendor_map_loader: Optional[Callable[[], Mapping[str, Any]]] = None,
) -> PriceTable:
- """Build the current table. A missing catalog leaves only the overrides to price with."""
+ """Build the current table. A missing catalog leaves only the overrides to price with.
+
+ The loader answers the catalog, when it was fetched, and whether a first copy
+ is on its way; the last makes the table `pending`, so a reader can say the
+ prices are being fetched rather than that there are none.
+ """
if catalog_loader is None or vendor_map_loader is None:
from vibe import models_dev_catalog
@@ -435,10 +451,10 @@ def load_price_table(
catalog_loader = catalog_loader or models_dev_catalog.load_models_dev_catalog_with_date
vendor_map_loader = vendor_map_loader or models_dev_catalog.load_model_vendor_map
try:
- catalog, fetched_at = catalog_loader()
+ catalog, fetched_at, fetching = catalog_loader()
except Exception as exc: # noqa: BLE001 - an optional valuation never fails a read
logger.info("Model Hub pricing has no models.dev catalog: %s", type(exc).__name__)
- catalog, fetched_at = {}, None
+ catalog, fetched_at, fetching = {}, None, False
try:
vendor_map = vendor_map_loader()
except Exception: # noqa: BLE001
@@ -448,6 +464,7 @@ def load_price_table(
vendor_map=vendor_map if isinstance(vendor_map, Mapping) else {},
overrides=_read_overrides(state_dir / PRICE_OVERRIDE_FILENAME),
price_table_date=_local_day(fetched_at) if catalog else None,
+ pending=fetching is True and not catalog,
)
@@ -490,8 +507,7 @@ def quota_values(
fee = prices.fee(key)
multiple = round(period.api_cost_usd / fee, 4) if fee else None
source["value"] = {
- "currency": CURRENCY,
- "price_table_date": prices.price_table_date,
+ **prices.fields(),
"plan_key": key,
"fee_usd": fee,
"multiple": multiple,
@@ -510,8 +526,7 @@ def quota_values(
period_fee += fee
period_sources += 1
return {
- "currency": CURRENCY,
- "price_table_date": prices.price_table_date,
+ **prices.fields(),
"week": week_total.fields(),
"period": (
{
diff --git a/core/handlers/model_hub/quota.py b/core/handlers/model_hub/quota.py
index 0f384712f..9168db0c4 100644
--- a/core/handlers/model_hub/quota.py
+++ b/core/handlers/model_hub/quota.py
@@ -288,11 +288,13 @@ _CLAUDE_MAX_TIER_PLANS: Final[Mapping[str, str]] = {
def parse_claude_plan(body: object) -> Optional[str]:
- """Read the plan from `GET https://api.anthropic.com/api/oauth/profile`, or None.
+ """Read the plan from `GET https://api.anthropic.com/api/oauth/profile`; None when unreadable.
- Best effort by design: the plan only prices a fee comparison, so a body we
- cannot read, or a product without a built-in fee (Team, Enterprise, an
- unknown Max tier), yields no plan rather than a failure.
+ A readable profile always names the product, so a plan read from it replaces
+ the last one even when it carries no built-in fee: Team and Enterprise are
+ named as themselves, and a Max tier this table does not know is plain `max`.
+ None means the read told us nothing — a body we cannot read — and the caller
+ keeps the plan it last knew.
"""
try:
@@ -302,14 +304,14 @@ def parse_claude_plan(body: object) -> Optional[str]:
organization = payload.get("organization")
if not isinstance(organization, dict):
return None
- kind = organization.get("organization_type")
- kind = kind.strip().lower() if isinstance(kind, str) else ""
- if kind == "claude_pro":
- return "pro"
- if kind != "claude_max":
+ kind = _label(organization.get("organization_type"))
+ if kind is None:
return None
+ kind = kind.lower()
+ if kind != "claude_max":
+ return kind.removeprefix("claude_") or None
tier = organization.get("rate_limit_tier")
- return _CLAUDE_MAX_TIER_PLANS.get(tier.strip().lower()) if isinstance(tier, str) else None
+ return _CLAUDE_MAX_TIER_PLANS.get(tier.strip().lower(), "max") if isinstance(tier, str) else "max"
def _codex_kind(seconds: Optional[int]) -> QuotaWindowKind:
@@ -582,7 +584,9 @@ class SubscriptionQuotaCache:
return
plan = parsed.get("plan")
if plan is None and entry.snapshot is not None:
- # The plan is a best-effort second read; one miss must not blank it.
+ # No plan means this read could not name one — Claude's is a best-effort
+ # second read — so it must not blank the last. A named plan, one without
+ # a built-in fee included, replaces it.
plan = entry.snapshot["plan"]
entry.snapshot = {"plan": plan, "windows": windows}
entry.fetched_at = self._now()
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 778d91266..409aa7844 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -40,7 +40,7 @@ from pathlib import Path
from typing import Callable, Final, Mapping, Optional, Sequence
from .identifiers import persisted_ledger_key, usage_ledger_key
-from .pricing import CURRENCY, Cost, ModelPrice, PriceTable, row_cost
+from .pricing import Cost, ModelPrice, PriceTable, row_cost
from .state_file import write_state_document
from .stream_wire import ProtocolUsageReport
@@ -1641,7 +1641,7 @@ class BoundedUsageLedger:
"days": [with_cost(by_day[day]) for day in sorted(by_day)],
}
if prices is not None:
- summary["pricing"] = {"currency": CURRENCY, "price_table_date": prices.price_table_date}
+ summary["pricing"] = prices.fields()
return summary
def report(
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 0bfc0682b..bf7dc8206 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -572,7 +572,9 @@ class EngineAdapter(Protocol):
The engine makes the model-free account call with the bound grant; only
the parsed ``{plan, windows}`` crosses this boundary, never the grant or
- the raw body. Raise ``SubscriptionQuotaError`` with a sanitized reason
+ the raw body. ``plan`` is the plan this read named, one without a built-in
+ fee included, or None when it could not name one; only None keeps the
+ last known plan. Raise ``SubscriptionQuotaError`` with a sanitized reason
(``auth_expired``, ``rate_limited``, ``unsupported``, ``unavailable`` or
``malformed``) on every failure. A report only: never feeds resolution.
"""
diff --git a/docs/plans/model-hub-contracts/quota-summary.schema.json b/docs/plans/model-hub-contracts/quota-summary.schema.json
index 1d14cedde..a5b702eaf 100644
--- a/docs/plans/model-hub-contracts/quota-summary.schema.json
+++ b/docs/plans/model-hub-contracts/quota-summary.schema.json
@@ -68,7 +68,7 @@
]
},
"plan": {
- "description": "Plan name the vendor reported, when it reports one.",
+ "description": "Plan the vendor last reported, whether or not it has a built-in fee (Claude's `team` and `enterprise` have none, nor does a Max tier the fee table does not know, reported as `max`). A read that names a plan replaces this one; a read that names none keeps it. Null until any read names one.",
"type": [
"string",
"null"
@@ -334,6 +334,10 @@
}
]
},
+ "pending": {
+ "description": "Present (true) when no models.dev price table has been read yet and a first fetch is running that is expected to land; the cost fields then cover only what local overrides price. A client may re-read shortly and say prices are being fetched rather than that there are none. Absent means no fetch is awaited: a table is in hand, or the last fetch failed.",
+ "const": true
+ },
"plan_key": {
"description": "Fee-table key the plan resolved to (built-in: claude_pro, claude_max_5x, claude_max_20x, chatgpt_plus, chatgpt_pro_5x, chatgpt_pro; or a key the local override file defines), or null when the plan is unknown.",
"type": [
@@ -398,6 +402,10 @@
}
]
},
+ "pending": {
+ "description": "Present (true) when no models.dev price table has been read yet and a first fetch is running that is expected to land; the cost fields then cover only what local overrides price. A client may re-read shortly and say prices are being fetched rather than that there are none. Absent means no fetch is awaited: a table is in hand, or the last fetch failed.",
+ "const": true
+ },
"week": {
"$ref": "#/definitions/PricedUsage",
"description": "Every valued Source."
diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.json
index 83c14ad30..aae72f61d 100644
--- a/docs/plans/model-hub-contracts/usage-summary.schema.json
+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json
@@ -498,6 +498,10 @@
"type": "null"
}
]
+ },
+ "pending": {
+ "description": "Present (true) when no models.dev price table has been read yet and a first fetch is running that is expected to land; the cost fields then cover only what local overrides price. A client may re-read shortly and say prices are being fetched rather than that there are none. Absent means no fetch is awaited: a table is in hand, or the last fetch failed.",
+ "const": true
}
}
}
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 8249a43a6..d3592d1a2 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -722,6 +722,14 @@ scenarios:
related_tests:
- ui/src/components/settings/models/format.test.ts::MH-USAGE-032
- ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-024
+ - id: MH-USAGE-033
+ name: A cost with nothing priced reads no price on every usage and quota surface, a partly priced one 「≥」, and a fully priced one exact
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-033
+ related_tests:
+ - ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-024
- id: MH-USAGE-BACKEND-001
name: Modern usage reports keep dense hourly buckets and distinct Unicode Source/model identities
status: covered
@@ -905,7 +913,7 @@ scenarios:
related_tests:
- tests/test_model_hub_quota.py::test_claude_plan_ignores_an_unreadable_profile
- tests/test_model_hub_quota.py::test_adapter_adds_the_claude_plan_from_the_profile_and_never_fails_on_it
- - tests/test_model_hub_quota.py::test_a_missing_plan_on_one_read_keeps_the_last_known_plan
+ - tests/test_model_hub_quota.py::test_a_readable_claude_profile_replaces_the_plan_and_an_unreadable_one_keeps_it
- id: MH-QUOTA-020
name: A quota read past the page deadline is named pending, and the page re-reads it soon a bounded number of times until it lands
status: covered
@@ -970,6 +978,16 @@ scenarios:
test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-029
related_tests:
- ui/e2e/model-catalog/quota-layout.spec.ts
+ - id: MH-QUOTA-030
+ name: A Claude account that moves to Team, Enterprise, a lower Max tier, or Pro shows its new plan and fee, while an unreadable profile keeps the old plan
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_quota.py::test_a_readable_claude_profile_replaces_the_plan_and_an_unreadable_one_keeps_it
+ related_tests:
+ - tests/test_model_hub_quota.py::test_claude_plan_is_read_from_the_oauth_profile_organization
+ - tests/test_model_hub_pricing.py::test_reported_plans_resolve_to_fee_table_keys
+ - ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-027
- id: MH-PRICE-001
name: A models.dev price fills a missing cache price from input and a one-hour cache write from twice input
status: covered
@@ -1065,6 +1083,17 @@ scenarios:
kind: recovery
layer: unit
test: tests/test_model_hub_pricing.py::test_an_invalid_override_entry_is_ignored_and_the_rest_still_apply
+ - id: MH-PRICE-014
+ name: Before the first price table lands, usage and quota say prices are being fetched, the page re-reads a bounded number of times, and one fetch runs at a time
+ status: covered
+ kind: recovery
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py::test_mh_price_014_a_first_read_before_any_price_table_says_prices_are_on_their_way
+ related_tests:
+ - tests/test_models_dev_catalog.py::test_first_catalog_read_reports_one_fetch_in_flight_until_it_fails
+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-PRICE-014
+ - ui/src/components/settings/models/UsageTab.test.tsx::MH-PRICE-014
+ - ui/src/components/settings/models/QuotaTab.test.tsx::MH-PRICE-014
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py b/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
index 650f4a00a..2241ba5a9 100644
--- a/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
@@ -17,7 +17,7 @@ import pytest
from jsonschema import Draft7Validator, FormatChecker
from referencing import Registry, Resource
-from core.handlers.model_hub.pricing import PriceTable
+from core.handlers.model_hub.pricing import PriceTable, load_price_table
from core.handlers.model_hub.stream_wire import extract_protocol_usage
from tests.scenario_harness.model_hub import (
MemoryModelHubStore,
@@ -124,3 +124,37 @@ def test_mh_price_scenario_001_a_metered_stream_is_valued_through_usage_and_quot
assert value["period"]["api_cost_lower_bound"] is True
assert quota["value"]["period"]["api_cost_lower_bound"] is True
assert "cred_" not in json.dumps(quota)
+
+
+def test_mh_price_014_a_first_read_before_any_price_table_says_prices_are_on_their_way(tmp_path):
+ """MH-PRICE-014: With no models.dev copy yet and a fetch running, usage and quota both say pricing is pending."""
+
+ service = _service(tmp_path)
+ report = extract_protocol_usage("anthropic", MESSAGE_START).merge(
+ extract_protocol_usage("anthropic", MESSAGE_DELTA)
+ )
+
+ async def meter() -> None:
+ service.usage_writer.record(source_id="src_max", model_id="claude-opus-5", usage=report, at=NOW)
+ assert await service.usage_writer.drain(timeout=5) == 0
+
+ asyncio.run(meter())
+ # The first two loads find no copy while the first fetch runs; the next two find it landed.
+ loads = iter([({}, None, True), ({}, None, True), (CATALOG, NOW.timestamp(), False), (CATALOG, NOW.timestamp(), False)])
+ service.price_table = lambda: load_price_table(
+ tmp_path, catalog_loader=lambda: next(loads), vendor_map_loader=lambda: VENDOR_MAP
+ )
+
+ usage = service.usage_summary(window="24h")
+ _assert_valid("usage-summary.schema.json", usage)
+ assert usage["pricing"] == {"currency": "USD", "price_table_date": None, "pending": True}
+ assert usage["totals"]["api_cost_usd"] == 0 and usage["totals"]["excluded_tokens"] > 0
+ quota = asyncio.run(service.quota_summary())
+ _assert_valid("quota-summary.schema.json", quota)
+ assert quota["value"]["pending"] is True and quota["sources"][0]["value"]["pending"] is True
+
+ # Once the table lands, the same reads price the usage and drop the flag.
+ usage = service.usage_summary(window="24h")
+ assert "pending" not in usage["pricing"] and usage["totals"]["api_cost_usd"] > 0
+ quota = asyncio.run(service.quota_summary())
+ assert "pending" not in quota["value"] and "pending" not in quota["sources"][0]["value"]
diff --git a/tests/test_model_hub_pricing.py b/tests/test_model_hub_pricing.py
index ecfcde673..9ed7515ea 100644
--- a/tests/test_model_hub_pricing.py
+++ b/tests/test_model_hub_pricing.py
@@ -153,7 +153,7 @@ def test_price_table_reads_the_override_file_and_survives_a_bad_one(tmp_path):
def load():
return load_price_table(
tmp_path,
- catalog_loader=lambda: (CATALOG, FETCHED_AT),
+ catalog_loader=lambda: (CATALOG, FETCHED_AT, False),
vendor_map_loader=lambda: VENDOR_MAP,
)
@@ -284,6 +284,10 @@ def test_rows_written_before_cache_writes_read_as_uncaptured(tmp_path):
("openai", "prolite", "chatgpt_pro_5x"),
("codex", "ProLite", "chatgpt_pro_5x"),
("openai", "team", None),
+ # A Claude product the profile names without a built-in fee (MH-QUOTA-030).
+ ("anthropic", "team", None),
+ ("anthropic", "enterprise", None),
+ ("anthropic", "max", None),
("codex", "pro", "chatgpt_pro"),
("gemini", "pro", None),
("xai", "plus", None),
@@ -337,7 +341,7 @@ def test_an_invalid_override_entry_is_ignored_and_the_rest_still_apply(tmp_path)
}),
encoding="utf-8",
)
- table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT), vendor_map_loader=lambda: VENDOR_MAP)
+ table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT, False), vendor_map_loader=lambda: VENDOR_MAP)
# Rejected entries fall through to models.dev, as an absent override would.
assert table.price("claude-opus-5").input == 5
@@ -362,7 +366,7 @@ def test_an_integer_past_the_json_digit_limit_is_ignored_alone(tmp_path):
' "plans": {"claude_max_20x": {"fee_usd": %s}, "team_seat": {"fee_usd": 30}}}' % (digits, digits),
encoding="utf-8",
)
- table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT), vendor_map_loader=lambda: VENDOR_MAP)
+ table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT, False), vendor_map_loader=lambda: VENDOR_MAP)
assert table.price("claude-opus-5").input == 5
assert table.price("claude-fable-5-1").input == 7
assert table.fee("claude_max_20x") == 200
@@ -386,7 +390,7 @@ def test_an_integer_past_a_lowered_interpreter_digit_limit_is_ignored_alone(tmp_
% ("9" * 700),
encoding="utf-8",
)
- table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT), vendor_map_loader=lambda: VENDOR_MAP)
+ table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT, False), vendor_map_loader=lambda: VENDOR_MAP)
finally:
sys.set_int_max_str_digits(previous)
assert table.price("claude-opus-5").input == 5
diff --git a/tests/test_model_hub_quota.py b/tests/test_model_hub_quota.py
index 8be4d3c45..0467a4e33 100644
--- a/tests/test_model_hub_quota.py
+++ b/tests/test_model_hub_quota.py
@@ -691,14 +691,16 @@ CLAUDE_PROFILE = {
({}, "max_20x"),
({"rate_limit_tier": "default_claude_max_5x"}, "max_5x"),
({"organization_type": "claude_pro", "rate_limit_tier": "default_claude_ai"}, "pro"),
- ({"organization_type": "claude_team", "rate_limit_tier": "default_claude_max_5x"}, None),
- ({"organization_type": "claude_enterprise", "rate_limit_tier": "default_claude_max_20x"}, None),
- ({"rate_limit_tier": "something_new"}, None),
- ({"rate_limit_tier": None}, None),
+ ({"organization_type": "claude_team", "rate_limit_tier": "default_claude_max_5x"}, "team"),
+ ({"organization_type": "Claude_Enterprise", "rate_limit_tier": "default_claude_max_20x"}, "enterprise"),
+ ({"rate_limit_tier": "something_new"}, "max"),
+ ({"rate_limit_tier": None}, "max"),
+ ({"organization_type": " "}, None),
+ ({"organization_type": None}, None),
],
)
def test_claude_plan_is_read_from_the_oauth_profile_organization(organization, plan):
- """MH-QUOTA-019: The product comes from organization_type, the Max tier from rate_limit_tier; anything else is no plan."""
+ """MH-QUOTA-019, MH-QUOTA-030: organization_type names the product and rate_limit_tier the Max tier; a profile naming no product is no plan."""
from core.handlers.model_hub.quota import parse_claude_plan
@@ -736,19 +738,36 @@ async def test_adapter_adds_the_claude_plan_from_the_profile_and_never_fails_on_
assert parsed["plan"] is None and parsed["windows"]
-async def test_a_missing_plan_on_one_read_keeps_the_last_known_plan():
- """MH-QUOTA-019: A plan read that misses once does not blank the plan the page prices against."""
+async def test_a_readable_claude_profile_replaces_the_plan_and_an_unreadable_one_keeps_it():
+ """MH-QUOTA-019, MH-QUOTA-030: Only a failed plan read keeps the last plan; a readable one replaces it, fee or none."""
- plans = iter(["max_20x", None])
+ usage = {"status_code": 200, "header": {}, "body": json.dumps(CLAUDE_LEGACY)}
+
+ def profile(**organization):
+ body = {**CLAUDE_PROFILE, "organization": {**CLAUDE_PROFILE["organization"], **organization}}
+ return {"status_code": 200, "body": json.dumps(body)}
+
+ profiles = {_PROFILE_URL: profile()}
+ adapter, _client = _adapter(usage, _METADATA, profiles)
moment = [datetime(2026, 9, 1, tzinfo=timezone.utc)]
+ cache = SubscriptionQuotaCache(adapter.subscription_quota, now=lambda: moment[0])
- async def fetch(source_id, vendor, credential_ref):
- return {"plan": next(plans), "windows": []}
+ async def plan_after(answer):
+ profiles[_PROFILE_URL] = answer
+ moment[0] += timedelta(minutes=6)
+ source = (await cache.summary([_CLAUDE]))["sources"][0]
+ assert source["state"] == "ok" and source["windows"]
+ return source["plan"]
- cache = SubscriptionQuotaCache(fetch, now=lambda: moment[0])
- assert (await cache.summary([_CLAUDE]))["sources"][0]["plan"] == "max_20x"
- moment[0] += timedelta(minutes=6)
assert (await cache.summary([_CLAUDE]))["sources"][0]["plan"] == "max_20x"
+ for failure in ({"status_code": 500, "body": "{}"}, {"status_code": 200, "body": "<html>"}):
+ assert await plan_after(failure) == "max_20x"
+ # Moving to a Team seat names Team, which has no built-in fee to compare with.
+ assert await plan_after(profile(organization_type="claude_team")) == "team"
+ assert await plan_after(profile(organization_type="claude_max", rate_limit_tier="default_claude_max_5x")) == "max_5x"
+ assert await plan_after(profile(organization_type="claude_pro", rate_limit_tier="default_claude_ai")) == "pro"
+ # A Max tier the fee table does not know is still Max, never the last known tier.
+ assert await plan_after(profile(organization_type="claude_max", rate_limit_tier="default_claude_max_40x")) == "max"
@pytest.mark.parametrize(
diff --git a/tests/test_models_dev_catalog.py b/tests/test_models_dev_catalog.py
index d4028a8c6..8cd7e3da2 100644
--- a/tests/test_models_dev_catalog.py
+++ b/tests/test_models_dev_catalog.py
@@ -373,3 +373,35 @@ def test_exact_models_dev_matches_never_borrow_a_neighbour():
# no substrings.
assert set(matches) == {"gpt-target", "openrouter/gpt-target", "relay/gpt-target-mini"}
assert models_dev_catalog.exact_models_dev_matches(["gpt-target"], {}) == {}
+
+
+def test_first_catalog_read_reports_one_fetch_in_flight_until_it_fails(monkeypatch, tmp_path):
+ """MH-PRICE-014: With no cached copy, readers start one fetch and say one is coming; after a failure they do not."""
+
+ import threading
+
+ monkeypatch.setattr(models_dev_catalog, "_cache_path", lambda: tmp_path / "models_dev_catalog.json")
+ monkeypatch.setattr(models_dev_catalog, "_refresh_in_flight", False, raising=False)
+ monkeypatch.setattr(models_dev_catalog, "_last_refresh_failed", False, raising=False)
+ release = threading.Event()
+ fetches = []
+
+ def fetch(_previous):
+ fetches.append(threading.current_thread().name)
+ release.wait(timeout=5)
+ raise OSError("offline")
+
+ monkeypatch.setattr(models_dev_catalog, "_fetch_catalog", fetch)
+ readers = [threading.Thread(target=models_dev_catalog.load_models_dev_catalog_with_date) for _ in range(8)]
+ for reader in readers:
+ reader.start()
+ for reader in readers:
+ reader.join(timeout=5)
+ assert models_dev_catalog.load_models_dev_catalog_with_date() == ({}, None, True)
+ release.set()
+ for thread in threading.enumerate():
+ if thread.name == "models-dev-refresh":
+ thread.join(timeout=5)
+ assert fetches == ["models-dev-refresh"]
+ # The fetch failed: the next read retries it, but no longer promises prices.
+ assert models_dev_catalog.load_models_dev_catalog_with_date() == ({}, None, False)
diff --git a/ui/src/components/settings/models/QuotaTab.test.tsx b/ui/src/components/settings/models/QuotaTab.test.tsx
index 4b7dfc956..1c2da1fba 100644
--- a/ui/src/components/settings/models/QuotaTab.test.tsx
+++ b/ui/src/components/settings/models/QuotaTab.test.tsx
@@ -314,6 +314,10 @@ describe('QuotaTab', () => {
expect(badge('openai', 'business')).toBe('Business');
expect(badge('anthropic', 'claude_max_20x')).toBe('Max 20x');
expect(badge('anthropic', 'max-5x')).toBe('Max 5x');
+ // A Claude product the profile names without a built-in fee still reads as itself (MH-QUOTA-030).
+ expect(badge('anthropic', 'team')).toBe('Team');
+ expect(badge('anthropic', 'enterprise')).toBe('Enterprise');
+ expect(badge('anthropic', 'max')).toBe('Max');
// An id another vendor's table names is not borrowed; an unknown id reads as words.
expect(badge('anthropic', 'prolite')).toBe('Prolite');
expect(badge('anthropic', 'chatgpt_pro')).toBe('Chatgpt Pro');
@@ -516,6 +520,17 @@ describe('QuotaTab', () => {
expect(card.textContent).toContain('12,000 tokens 暂无价格,未计入');
expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('暂无价格');
cleanup();
+ // Nothing priced in the period: the payback card says no price, never 「≥ 0.0 倍」 (MH-USAGE-033).
+ const none = priced(0, { excluded_tokens: 12_000, api_cost_lower_bound: true });
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(0, 200, { week: none, period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...none } }) })],
+ totals(0, { cost: 0, fee: 200 }, { week: none, period: { sources: 1, fee_usd: 200, multiple: 0, ...none } }),
+ )));
+ const stats = document.querySelector('.model-hub-quota-stats')!.textContent;
+ expect(stats).not.toContain('0.0 倍');
+ expect(stats).not.toContain('$0.00');
+ expect(stats!.match(/暂无价格/g)?.length).toBeGreaterThanOrEqual(2);
+ cleanup();
// Partly priced: the figure stands and the leftover is named; a lower bound says ≥.
draw(readyRegion(valued(
[claude({ value: sourceValue(40, 200, { week: priced(40, { excluded_tokens: 500, api_cost_lower_bound: true }) }) })],
@@ -560,6 +575,19 @@ describe('QuotaTab', () => {
expect(document.body.textContent).not.toContain('还差');
});
+ it('MH-PRICE-014: while the first price table is being fetched, the value surfaces say so rather than no price', () => {
+ const none = priced(0, { excluded_tokens: 12_000, api_cost_lower_bound: true });
+ const fetching = { price_table_date: null, pending: true as const };
+ draw(readyRegion(valued(
+ [claude({ value: sourceValue(0, 200, { ...fetching, week: none, period: { basis: 'billing_cycle', from_day: '2026-09-05', to_day: '2026-09-25', renews_on: '2026-10-05', ...none } }) })],
+ totals(0, { cost: 0, fee: 200 }, { ...fetching, week: none, period: { sources: 1, fee_usd: 200, multiple: 0, ...none } }),
+ )));
+ expect(within(screen.getByRole('article')).getAllByText('正在获取价格…').length).toBe(2);
+ expect(document.querySelector('.model-hub-quota-stats')!.textContent).toContain('正在获取价格…');
+ expect(document.querySelector('.model-hub-quota-foot')!.textContent).toContain('正在获取价格表…');
+ expect(document.body.textContent).not.toContain('暂无价格');
+ });
+
it('MH-QUOTA-025: a Source still being read shows a loading line instead of 「暂时读不到」', () => {
const unread = claude({ state: 'error', error_key: 'models.quota.error.unavailable', windows: [], fetched_at: null, plan: null });
draw(readyRegion({ ...summary([unread]), pending: ['src_claude'] }));
diff --git a/ui/src/components/settings/models/QuotaTab.tsx b/ui/src/components/settings/models/QuotaTab.tsx
index 02d3f0a86..519436caf 100644
--- a/ui/src/components/settings/models/QuotaTab.tsx
+++ b/ui/src/components/settings/models/QuotaTab.tsx
@@ -17,7 +17,7 @@ import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { atLeast, formatCost, formatCount, formatUsd } from './format';
import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
-import type { PricedUsage, QuotaSummary, QuotaWindow, SourceQuota, SourceQuotaValue } from './types';
+import type { PricedUsage, QuotaSummary, QuotaWindow, SourceQuota, SourceQuotaValue, UsagePricing } from './types';
import { TimeHint } from './TimeHint';
import { VendorGlyph } from './vendorGlyph';
import {
@@ -215,10 +215,16 @@ const calendarDaysBetween = (from: string, to: string) => Math.round((Date.parse
/** Whether every priced token of a span belongs to a model with no price. */
const unpriced = (value: PricedUsage) => value.api_cost_usd === 0 && value.excluded_tokens > 0;
+/** The copy for a span with nothing priced: prices on their way while a first fetch runs, else none. */
+const noPriceKey = (pricing: UsagePricing) => (pricing.pending
+ ? 'settings.models.quota.value.fetching' as const
+ : 'settings.models.quota.value.noPrice' as const);
+
/** The account's API-price value: its week, its period against the fee, and the renewal. */
const ValueStrip: React.FC<{ value: SourceQuotaValue; text: QuotaText }> = ({ value, text }) => {
const { t } = useTranslation();
- const payback = value.fee_usd !== null ? quotaPayback(value.period.api_cost_usd, value.fee_usd) : null;
+ // A period with nothing priced has no verdict to give; its figure already says why.
+ const payback = value.fee_usd !== null && !unpriced(value.period) ? quotaPayback(value.period.api_cost_usd, value.fee_usd) : null;
// A floor can prove a payback but never size a shortfall.
const floor = value.period.api_cost_lower_bound;
// Both days are host-calendar days, so count between them, not from the browser's clock.
@@ -231,12 +237,12 @@ const ValueStrip: React.FC<{ value: SourceQuotaValue; text: QuotaText }> = ({ va
<div className="model-hub-quota-value" data-quota-value>
<div>
<span>{t('settings.models.quota.value.week')}</span>
- <b>{unpriced(value.week) ? t('settings.models.quota.value.noPrice') : text.usd(value.week)}</b>
+ <b>{unpriced(value.week) ? t(noPriceKey(value)) : text.usd(value.week)}</b>
</div>
<div>
<span>{t(`settings.models.quota.value.period.${value.period.basis}`)}</span>
<b>
- {unpriced(value.period) ? t('settings.models.quota.value.noPrice') : text.usd(value.period)}
+ {unpriced(value.period) ? t(noPriceKey(value)) : text.usd(value.period)}
{payback !== null && (
<em className={cn(payback.kind !== 'short' && 'is-good')} data-quota-payback={payback.kind}>
{/* 「刚好回本」 sizes the value against the fee; a floor there only proves it is at least paid back. */}
@@ -260,7 +266,7 @@ const ValueStrip: React.FC<{ value: SourceQuotaValue; text: QuotaText }> = ({ va
</div>
)}
</div>
- {excluded > 0 && (
+ {excluded > 0 && !value.pending && (
<p className="model-hub-quota-value-note">{t('settings.models.quota.value.excluded', { tokens: text.tokens(excluded) })}</p>
)}
</>
@@ -481,11 +487,11 @@ export const QuotaTab: React.FC<{
label={t('settings.models.quota.stat.weekValue')}
icon={<CircleDollarSign className="size-[15px]" aria-hidden />}
value={unpriced(value.week)
- ? t('settings.models.quota.value.noPrice')
+ ? t(noPriceKey(value))
: <>{text.usd(value.week)}<small className="model-hub-quota-stat-unit">USD</small></>}
note={[
t('settings.models.quota.stat.weekValueNote'),
- value.week.excluded_tokens > 0 && !unpriced(value.week)
+ value.week.excluded_tokens > 0 && !unpriced(value.week) && !value.pending
? t('settings.models.quota.value.excluded', { tokens: text.tokens(value.week.excluded_tokens) })
: null,
].filter(Boolean).join(' · ')}
@@ -496,11 +502,13 @@ export const QuotaTab: React.FC<{
label={t('settings.models.quota.stat.payback')}
icon={<TrendingUp className="size-[15px]" aria-hidden />}
value={value.period && periodPayback
- ? <>{t('settings.models.quota.stat.paybackMultiple', { multiple: atLeast(text.multiple(periodPayback.multiple), value.period.api_cost_lower_bound) })}<small className="model-hub-quota-stat-unit">{t('settings.models.quota.stat.paybackUnit')}</small></>
+ ? unpriced(value.period)
+ ? t(noPriceKey(value))
+ : <>{t('settings.models.quota.stat.paybackMultiple', { multiple: atLeast(text.multiple(periodPayback.multiple), value.period.api_cost_lower_bound) })}<small className="model-hub-quota-stat-unit">{t('settings.models.quota.stat.paybackUnit')}</small></>
: '—'}
note={value.period && periodPayback
? [
- periodPayback.kind === 'short'
+ unpriced(value.period) ? null : periodPayback.kind === 'short'
? value.period.api_cost_lower_bound
? t('settings.models.quota.stat.paybackShortUnknown')
: t('settings.models.quota.stat.paybackShort', { amount: text.dollars(periodPayback.shortfallUsd) })
@@ -544,7 +552,9 @@ export const QuotaTab: React.FC<{
{value && <>{' '}{t('settings.models.quota.footnoteValue')}</>}
{value && <>{' '}{value.price_table_date
? t('settings.models.quota.priceTableDate', { date: value.price_table_date })
- : t('settings.models.quota.priceTableUnknown')}</>}
+ : value.pending
+ ? t('settings.models.quota.priceTableFetching')
+ : t('settings.models.quota.priceTableUnknown')}</>}
</span>
</p>
</>}
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 34676df26..7421b8f47 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -2393,6 +2393,51 @@ describe('SettingsModelsPage usage region', () => {
await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
});
+ // A fresh install has no price table until its first fetch lands: the report
+ // says pricing is pending, and the tab re-reads soon, on the quota's bounded
+ // cadence, so the prices appear without a manual refresh.
+ it('MH-PRICE-014: re-reads the usage report while its prices are pending and stops once they land', async () => {
+ const timeouts = vi.spyOn(window, 'setTimeout');
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getUsageSummary);
+ const pending = { ...usageSummary, pricing: { currency: 'USD' as const, price_table_date: null, pending: true as const } };
+ read
+ .mockResolvedValueOnce(pending)
+ .mockResolvedValueOnce(pending)
+ .mockResolvedValue({ ...usageSummary, pricing: { currency: 'USD' as const, price_table_date: '2026-08-18' } });
+ await openUsage();
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
+ const rereads = () => timeouts.mock.calls.filter(([, delay]) => delay === QUOTA_PENDING_REREAD_MS);
+ // A reading that lands still pending re-arms the timer.
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
+ await waitFor(() => expect(rereads()).toHaveLength(attempt));
+ await act(async () => { (rereads()[attempt - 1][0] as () => void)(); });
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(attempt + 1));
+ }
+ expect(read.mock.calls.map(([window]) => window)).toEqual(['24h', '24h', '24h']);
+ // Priced: no further re-read is scheduled.
+ await act(async () => { await Promise.resolve(); });
+ expect(rereads()).toHaveLength(2);
+ });
+
+ it('MH-PRICE-014: gives up re-reading the usage report after a bounded number of tries while prices stay pending', async () => {
+ const timeouts = vi.spyOn(window, 'setTimeout');
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getUsageSummary);
+ read.mockResolvedValue({ ...usageSummary, pricing: { currency: 'USD', price_table_date: null, pending: true } });
+ await openUsage();
+ const rereads = () => timeouts.mock.calls.filter(([, delay]) => delay === QUOTA_PENDING_REREAD_MS);
+ for (let attempt = 1; attempt <= QUOTA_PENDING_REREADS; attempt += 1) {
+ await waitFor(() => expect(rereads()).toHaveLength(attempt));
+ await act(async () => { (rereads()[attempt - 1][0] as () => void)(); });
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(attempt + 1));
+ }
+ await act(async () => { await Promise.resolve(); });
+ expect(rereads()).toHaveLength(QUOTA_PENDING_REREADS);
+ });
+
it('retries the read the tab failed on, at the same span', async () => {
renderPage([retainedSource]);
const read = vi.mocked(modelsApi.getUsageSummary);
@@ -2468,6 +2513,29 @@ describe('SettingsModelsPage quota region', () => {
expect(rereads()).toHaveLength(1);
});
+ it('MH-PRICE-014: re-reads quota while its prices are pending, even with every Source read', async () => {
+ const timeouts = vi.spyOn(window, 'setTimeout');
+ const priced = { api_cost_usd: 0, excluded_tokens: 0, api_cost_lower_bound: false };
+ const value = (pending: boolean) => ({
+ currency: 'USD' as const, price_table_date: pending ? null : '2026-08-18', ...(pending ? { pending: true as const } : {}),
+ week: priced, period: null,
+ });
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getQuota);
+ read
+ .mockResolvedValueOnce({ refresh_interval_seconds: 300, sources: [], value: value(true) })
+ .mockResolvedValue({ refresh_interval_seconds: 300, sources: [], value: value(false) });
+ await openQuota();
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
+ const rereads = () => timeouts.mock.calls.filter(([, delay]) => delay === QUOTA_PENDING_REREAD_MS);
+ await waitFor(() => expect(rereads()).toHaveLength(1));
+ await act(async () => { (rereads()[0][0] as () => void)(); });
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ await act(async () => { await Promise.resolve(); });
+ expect(rereads()).toHaveLength(1);
+ });
+
it('MH-QUOTA-020: gives up re-reading after a bounded number of tries while a Source stays pending', async () => {
const timeouts = vi.spyOn(window, 'setTimeout');
const stuck = {
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 80332c4ec..38a139b20 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -299,6 +299,32 @@ const QUOTA_POLL_MS = 5 * 60_000;
export const QUOTA_PENDING_REREAD_MS = 5_000;
export const QUOTA_PENDING_REREADS = 3;
+/**
+ * Re-read a report whose reading the service says is still landing — a quota
+ * read past its deadline, or prices whose first fetch is running — soon, a
+ * bounded number of times in a row. `pendingKey` is null while no settled
+ * reading is on screen and '' when nothing is pending; `settled` counts settled
+ * reads, so one that lands still pending re-arms the timer. Returns the reset a
+ * fresh open or a manual refresh calls.
+ */
+function usePendingRereads(active: boolean, pendingKey: string | null, settled: number, reread: () => void) {
+ const rereads = React.useRef(0);
+ React.useEffect(() => {
+ if (!active || pendingKey === null) return undefined;
+ if (pendingKey === '') {
+ rereads.current = 0;
+ return undefined;
+ }
+ if (rereads.current >= QUOTA_PENDING_REREADS) return undefined;
+ const timer = window.setTimeout(() => {
+ rereads.current += 1;
+ reread();
+ }, QUOTA_PENDING_REREAD_MS);
+ return () => window.clearTimeout(timer);
+ }, [active, pendingKey, settled, reread]);
+ return React.useCallback(() => { rereads.current = 0; }, []);
+}
+
/** Back to the re-login button of a quota card, or to the selected tab once a refresh has removed it. */
const focusQuotaOpener = (opener: HTMLElement) =>
(opener.isConnected ? opener : document.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'))?.focus();
@@ -662,9 +688,11 @@ export const SettingsModelsPage: React.FC = () => {
});
}));
+ const [usageSettled, setUsageSettled] = React.useState(0);
const [usageReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<UsageReport>>((incoming) => {
if (!aliveRef.current) return;
setUsageRead((previous) => settleRegionRead(previous, incoming));
+ setUsageSettled((count) => count + 1);
}));
const refreshUsage = React.useCallback(async (window: UsageWindowKey) => {
@@ -684,16 +712,27 @@ export const SettingsModelsPage: React.FC = () => {
* change is the same read with a different span, which is why one effect owns
* both.
*/
+ /** A first install has no price table yet: while its fetch runs, re-read so the prices land on screen. */
+ const usagePendingKey = foldRegionRead<UsageReport, string | null>(usageRead, {
+ loading: () => null,
+ ready: (data) => (data.pricing?.pending ? 'pricing' : ''),
+ unread: () => null,
+ degraded: () => null,
+ });
+ const rereadUsage = React.useCallback(() => { void refreshUsage(usageWindow); }, [refreshUsage, usageWindow]);
+ const resetUsageRereads = usePendingRereads(tab === 'usage', usagePendingKey, usageSettled, rereadUsage);
+
React.useEffect(() => {
if (tab !== 'usage') return;
+ resetUsageRereads();
void refreshUsage(usageWindow);
- }, [tab, usageWindow, refreshUsage]);
+ }, [tab, usageWindow, refreshUsage, resetUsageRereads]);
const retryUsage = React.useCallback(async () => {
+ resetUsageRereads();
await refreshUsage(usageWindow);
- }, [refreshUsage, usageWindow]);
+ }, [refreshUsage, resetUsageRereads, usageWindow]);
- const quotaPendingRereads = React.useRef(0);
// Counts settled reads, so a re-read that lands with the same pending set
// still re-arms the timer below.
const [quotaSettled, setQuotaSettled] = React.useState(0);
@@ -715,48 +754,37 @@ export const SettingsModelsPage: React.FC = () => {
* service caches per Source, so an interval tick costs a vendor call only
* when that Source's reading is actually due.
*/
- React.useEffect(() => {
- if (tab !== 'quota') return undefined;
- quotaPendingRereads.current = 0;
- void readQuota(false);
- const timer = window.setInterval(() => { void readQuota(false); }, QUOTA_POLL_MS);
- return () => window.clearInterval(timer);
- }, [tab, readQuota]);
-
/**
- * The Sources the service named as still reading: null while no settled
- * reading is on screen, '' when none is pending. Each settled reading that
- * still names one re-arms the timer once.
+ * What the service named as still landing: the Sources still reading, and
+ * prices whose first fetch is running. Null while no settled reading is on
+ * screen, '' when nothing is pending.
*/
const quotaPendingKey = foldRegionRead<QuotaSummary, string | null>(quotaRead, {
loading: () => null,
- ready: (data) => (data.pending ?? []).join('\u0000'),
+ ready: (data) => [...(data.pending ?? []), ...(data.value?.pending ? ['\u0001pricing'] : [])].join('\u0000'),
unread: () => null,
degraded: () => null,
});
+ const rereadQuota = React.useCallback(() => { void readQuota(false); }, [readQuota]);
+ const resetQuotaRereads = usePendingRereads(tab === 'quota', quotaPendingKey, quotaSettled, rereadQuota);
+
React.useEffect(() => {
- if (tab !== 'quota' || quotaPendingKey === null) return undefined;
- if (quotaPendingKey === '') {
- quotaPendingRereads.current = 0;
- return undefined;
- }
- if (quotaPendingRereads.current >= QUOTA_PENDING_REREADS) return undefined;
- const timer = window.setTimeout(() => {
- quotaPendingRereads.current += 1;
- void readQuota(false);
- }, QUOTA_PENDING_REREAD_MS);
- return () => window.clearTimeout(timer);
- }, [tab, quotaPendingKey, quotaSettled, readQuota]);
+ if (tab !== 'quota') return undefined;
+ resetQuotaRereads();
+ void readQuota(false);
+ const timer = window.setInterval(() => { void readQuota(false); }, QUOTA_POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [tab, readQuota, resetQuotaRereads]);
const refreshQuotaNow = React.useCallback(async () => {
- quotaPendingRereads.current = 0;
+ resetQuotaRereads();
setRefreshingQuota(true);
try {
await readQuota(true);
} finally {
if (aliveRef.current) setRefreshingQuota(false);
}
- }, [readQuota]);
+ }, [readQuota, resetQuotaRereads]);
const retryQuota = React.useCallback(async () => {
await readQuota(false);
diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsx
index e9ec022d7..2657e553d 100644
--- a/ui/src/components/settings/models/UsageTab.test.tsx
+++ b/ui/src/components/settings/models/UsageTab.test.tsx
@@ -430,6 +430,64 @@ describe('UsageTab', () => {
expect(detail().textContent).not.toContain('≥');
});
+ it('MH-USAGE-033: a cost with nothing priced reads no price on every surface, a partial one 「≥」, a full one exact', async () => {
+ const cost = (usd: number, excluded: number, floor: boolean) => ({ api_cost_usd: usd, excluded_tokens: excluded, api_cost_lower_bound: floor });
+ // Bucket 00 has only an unpriced model; bucket 01 a priced one beside it; bucket 02 is fully priced.
+ const relay = (over: Partial<UsageBucketRow>) => row({ source_id: 'source-b', model_id: 'relay-model', ...cost(0, 140, true), ...over });
+ const value = pricedReport();
+ value.buckets = [
+ bucket('00', [relay({})]),
+ bucket('01', [row(cost(0.5, 0, false)), relay({})]),
+ bucket('02', [row(cost(0.25, 0, false))]),
+ ];
+ const { container } = draw(value);
+ await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Metric' }), 'cost');
+ await userEvent.click(screen.getByRole('button', { name: 'Model' }));
+ const legend = () => container.querySelector('.model-hub-usage-legend')!;
+ // The unpriced model's legend total is no price, never 「≥ $0.00」; the priced one's is exact.
+ expect(legend().textContent).toContain('No price yet');
+ expect(legend().textContent).toContain('$0.75');
+ expect(legend().textContent).not.toContain('$0.00');
+
+ const buckets = screen.getAllByRole('button', { name: /Usage bucket/ });
+ const detail = () => screen.getByRole('dialog', { name: 'Usage bucket details' });
+ fireEvent.pointerEnter(buckets[0]);
+ const relayLine = () => within(detail().querySelector('.model-hub-usage-tooltip-lines') as HTMLElement)
+ .getByText('Relay · Relay model').closest('div')!.textContent;
+ expect(detail().querySelector('.model-hub-usage-tooltip-total')!.textContent).toBe('No price yetAt API price');
+ expect(relayLine()).toContain('No price yet');
+ fireEvent.pointerEnter(buckets[1]);
+ await screen.findByText('≥ $0.50', { selector: '.model-hub-usage-tooltip-total strong' });
+ // Within a partly priced bucket, the line with nothing priced still says so.
+ expect(relayLine()).toContain('No price yet');
+ fireEvent.pointerEnter(buckets[2]);
+ await screen.findByText('$0.25', { selector: '.model-hub-usage-tooltip-total strong' });
+
+ // Pinned to the unpriced bucket, the table total has nothing priced either.
+ fireEvent.pointerEnter(buckets[0]);
+ await userEvent.click(screen.getByRole('button', { name: 'Pin this bucket' }));
+ const table = container.querySelector('.model-hub-usage-table-scroll')!;
+ expect(table.querySelector('tbody')!.textContent).toContain('No price yet');
+ expect(table.querySelector('tfoot .model-hub-usage-table-total, tfoot td:nth-last-child(2)')!.textContent).toBe('No price yet');
+ expect(table.textContent).not.toContain('$0.00');
+ });
+
+ it('MH-PRICE-014: while the first price table is still being fetched, says so rather than no price', async () => {
+ const value = pricedReport();
+ value.pricing = { currency: 'USD', price_table_date: null, pending: true };
+ value.totals = { ...value.totals, api_cost_usd: 0, excluded_tokens: 280, api_cost_lower_bound: true };
+ value.buckets = value.buckets.map((item) => ({ ...item, rows: item.rows.map((entry) => ({ ...entry, api_cost_usd: 0, excluded_tokens: 140, api_cost_lower_bound: true })) }));
+ const { container } = draw(value);
+ const stats = container.querySelector('.model-hub-usage-stat-grid--priced')!;
+ expect(stats.textContent).toContain('Fetching prices…');
+ expect(stats.textContent).toContain('Fetching the price table…');
+ expect(stats.textContent).not.toContain('No price yet');
+ await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Metric' }), 'cost');
+ expect(container.querySelector('.model-hub-usage-legend')!.textContent).toContain('Fetching prices…');
+ expect(container.querySelector('.model-hub-usage-table-scroll')!.textContent).toContain('Fetching prices…');
+ expect(container.textContent).not.toContain('No price yet');
+ });
+
it('MH-USAGE-031: reads the API-price value in Chinese as a conversion, not a charge', async () => {
await i18n.addResourceBundle('zh', 'translation', zh, true, true);
await i18n.changeLanguage('zh');
diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsx
index 9cb1f89d3..bca68f9c7 100644
--- a/ui/src/components/settings/models/UsageTab.tsx
+++ b/ui/src/components/settings/models/UsageTab.tsx
@@ -26,6 +26,7 @@ import type { UsageCounters, UsageReport, UsageWindowKey } from './types';
import {
aggregateCounters,
costIsFloor,
+ costIsUnpriced,
filterBucketRows,
filteredRows,
formatBucketAxisLabel,
@@ -45,6 +46,7 @@ import {
usageCachedInputShare,
usageIsEmpty,
usageIsPriced,
+ usageHasNoPrice,
usageMetricValue,
usageNonCachedInput,
usageReportShortfall,
@@ -111,9 +113,10 @@ const tokenText = (
return value === null ? blank : count(value);
};
-/** Every priced token of these counters belongs to a model with no known price. */
-const usageHasNoPrice = (counters: UsageCounters): boolean =>
- usageIsPriced(counters) && (counters.excluded_tokens ?? 0) > 0 && (counters.api_cost_usd ?? 0) === 0;
+/** What a cost with nothing priced in it reads as: prices on their way while a first fetch runs, else none. */
+const noPriceText = (report: UsageReport, t: UsageTranslate): string => (report.pricing?.pending
+ ? t('settings.models.usage.cost.fetching')
+ : t('settings.models.usage.cost.noPrice'));
const metricLabel = (metric: UsageMetric, t: UsageTranslate): string =>
t(`settings.models.usage.metric.${metric}`);
@@ -246,15 +249,18 @@ const ChartLegend: React.FC<{
labels: Map<string, string>;
count: (value: number) => string;
blank: string;
+ noPrice: string;
ariaLabel: string;
/** The plot's left edge, which the first swatch lines up with. */
inset: number;
-}> = ({ series, hidden, onToggle, labels, count, blank, ariaLabel, inset }) => (
+}> = ({ series, hidden, onToggle, labels, count, blank, noPrice, ariaLabel, inset }) => (
<div className="model-hub-usage-legend" aria-label={ariaLabel} style={{ marginLeft: Math.max(0, inset - LEGEND_SWATCH_OFFSET) }}>
{series.map((item) => {
const values = item.values.filter((value): value is number => value !== null);
const total = values.reduce((sum, value) => sum + value, 0);
const floor = item.floors.some(Boolean);
+ // Costs are never negative, so a zero total with an unpriced bucket has nothing priced in it.
+ const unpriced = total === 0 && item.unpriced.some(Boolean);
const isHidden = hidden.includes(item.key);
return (
<button
@@ -266,7 +272,7 @@ const ChartLegend: React.FC<{
>
<span className="model-hub-usage-legend-swatch" style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />
<span>{labels.get(item.key) ?? item.label}</span>
- <strong>{values.length === 0 ? blank : atLeast(count(total), floor)}</strong>
+ <strong>{values.length === 0 ? blank : unpriced ? noPrice : atLeast(count(total), floor)}</strong>
</button>
);
})}
@@ -715,6 +721,7 @@ function UsageChart({
labels={labels}
count={format}
blank={t('settings.models.usage.blank') as string}
+ noPrice={noPriceText(report, t)}
ariaLabel={t('settings.models.usage.chart.legend') as string}
inset={left}
/>
@@ -851,7 +858,11 @@ function UsageChart({
</div>
</div>
<div className="model-hub-usage-tooltip-total">
- <strong>{activeValue === null ? t('settings.models.usage.blank') : atLeast(format(activeValue), costIsFloor(bucketRows, metric))}</strong>
+ <strong>{activeValue === null
+ ? t('settings.models.usage.blank')
+ : costIsUnpriced(bucketRows, metric)
+ ? noPriceText(report, t)
+ : atLeast(format(activeValue), costIsFloor(bucketRows, metric))}</strong>
<span>{metricLabel(metric, t)}</span>
</div>
<div className="model-hub-usage-tooltip-lines">
@@ -860,7 +871,9 @@ function UsageChart({
<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')
- : atLeast(format(item.values[activeIndex as number] ?? 0), item.floors[activeIndex as number])}</b>
+ : item.unpriced[activeIndex as number]
+ ? noPriceText(report, t)
+ : atLeast(format(item.values[activeIndex as number] ?? 0), item.floors[activeIndex as number])}</b>
</div>
))}
</div>
@@ -1162,16 +1175,18 @@ export const UsageTab: React.FC<{
value={historyOnlyUnknown || !usageIsPriced(totals)
? t('settings.models.usage.blank')
: usageHasNoPrice(totals)
- ? t('settings.models.usage.cost.noPrice')
+ ? noPriceText(report, t)
: formatCost(totals.api_cost_usd ?? 0, totals.api_cost_lower_bound, i18n.language)}
note={[
t('settings.models.usage.cost.notBilled'),
- (totals.excluded_tokens ?? 0) > 0 && !usageHasNoPrice(totals)
+ (totals.excluded_tokens ?? 0) > 0 && !usageHasNoPrice(totals) && !report.pricing?.pending
? t('settings.models.usage.cost.excluded', { count: totals.excluded_tokens ?? 0, tokens: count(totals.excluded_tokens ?? 0) })
: null,
report.pricing?.price_table_date
? t('settings.models.usage.cost.tableDate', { date: report.pricing.price_table_date })
- : t('settings.models.usage.cost.tableDateUnknown'),
+ : report.pricing?.pending
+ ? t('settings.models.usage.cost.tableFetching')
+ : t('settings.models.usage.cost.tableDateUnknown'),
].filter(Boolean).join(' · ')}
/>
)}
@@ -1281,7 +1296,7 @@ export const UsageTab: React.FC<{
<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">{metric === 'cost' && usageHasNoPrice(row.counters)
- ? t('settings.models.usage.cost.noPrice')
+ ? noPriceText(report, t)
: metricText(row.counters)}</td>
<td>{share === null ? t('settings.models.usage.blank') : formatPercent(share, i18n.language, 1)}</td>
</tr>
@@ -1298,7 +1313,9 @@ export const UsageTab: React.FC<{
<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>{metric === 'cost' && usageHasNoPrice(tableTotal)
+ ? noPriceText(report, t)
+ : metricText(tableTotal)}</td>
<td>{(() => {
const totalValue = usageMetricValue(tableTotal, metric);
return totalValue === null || totalValue === 0
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 662277d81..44ab97731 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -815,6 +815,9 @@ export type UsagePricing = {
currency: 'USD';
/** Local date the price table was fetched; null when only overrides priced. */
price_table_date: string | null;
+ /** No price table yet and a first fetch is running; re-read soon, and say
+ * prices are being fetched rather than that there are none. */
+ pending?: true;
};
export type UsageByModel = UsageCounters & {
@@ -918,6 +921,8 @@ export type SourceQuota = {
vendor: string;
display_name: string;
account_label: string | null;
+ /** Plan the vendor last named, with or without a built-in fee (Claude's
+ * `team` and `enterprise` have none); null until a read names one. */
plan: string | null;
fetched_at: string | null;
state: QuotaSourceState;
diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.ts
index a85eda631..02257272a 100644
--- a/ui/src/components/settings/models/usageProjection.ts
+++ b/ui/src/components/settings/models/usageProjection.ts
@@ -40,6 +40,8 @@ export type UsageSeries = {
values: Array<number | null>;
/** Per bucket, whether the value is only a floor (`api_cost_lower_bound`); cost only. */
floors: boolean[];
+ /** Per bucket, whether nothing in the value is priced, so it reads as no price, never $0; cost only. */
+ unpriced: boolean[];
};
export const PAIR_SEPARATOR = '\u0000';
@@ -75,6 +77,10 @@ export function aggregateCounters(rows: readonly UsageCounters[]): UsageCounters
/** Whether the server priced these counters at API prices. */
export const usageIsPriced = (counters: UsageCounters): boolean => typeof counters.api_cost_usd === 'number';
+/** Every priced token of these counters belongs to a model with no known price. */
+export const usageHasNoPrice = (counters: UsageCounters): boolean =>
+ usageIsPriced(counters) && (counters.excluded_tokens ?? 0) > 0 && (counters.api_cost_usd ?? 0) === 0;
+
/** Whether the report carries API-price value at all: a server that predates it never does. */
export const reportIsPriced = (report: UsageSummary): boolean => report.pricing !== undefined;
@@ -427,6 +433,11 @@ export const costIsFloor = (rows: readonly UsageCounters[], metric: UsageMetric)
metric === 'cost' && aggregateCounters(rows).api_cost_lower_bound === true
);
+/** Whether these rows' cost has nothing priced in it, as opposed to a floor of some priced part. */
+export const costIsUnpriced = (rows: readonly UsageCounters[], metric: UsageMetric): boolean => (
+ metric === 'cost' && usageHasNoPrice(aggregateCounters(rows))
+);
+
const bucketMetricValue = (
bucket: UsageBucket,
rows: UsageBucketRow[],
@@ -459,12 +470,14 @@ export function seriesFor(
cost: 'API price',
};
const floors = report.buckets.map((bucket) => costIsFloor(filterBucketRows(bucket, filter), metric));
+ const unpriced = report.buckets.map((bucket) => costIsUnpriced(filterBucketRows(bucket, filter), metric));
return [...valuesByKey.entries()].map(([key, values], index) => ({
key,
label: labels[key],
colorIndex: index,
values,
floors,
+ unpriced,
}));
}
@@ -479,6 +492,7 @@ export function seriesFor(
metric,
)),
floors: report.buckets.map((bucket) => costIsFloor(filterBucketRows(bucket, filter), metric)),
+ unpriced: report.buckets.map((bucket) => costIsUnpriced(filterBucketRows(bucket, filter), metric)),
}];
}
@@ -497,6 +511,10 @@ export function seriesFor(
filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId),
metric,
)),
+ unpriced: report.buckets.map((bucket) => costIsUnpriced(
+ filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId),
+ metric,
+ )),
}));
}
@@ -518,6 +536,12 @@ export function seriesFor(
)),
metric,
)),
+ unpriced: report.buckets.map((bucket) => costIsUnpriced(
+ filterBucketRows(bucket, filter).filter((row) => (
+ row.source_id === identity.sourceId && row.model_id === identity.modelId
+ )),
+ metric,
+ )),
}));
}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e0604bc52..071d14e55 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1420,6 +1420,7 @@
"footnoteValue": "“At API price” is what the same use would cost at the vendor’s published API price — a way to judge the plan, not a charge.",
"priceTableDate": "Price table from {{date}}.",
"priceTableUnknown": "Price table date unknown.",
+ "priceTableFetching": "Fetching the price table…",
"value": {
"week": "Last 7 days at API price",
"period": {
@@ -1427,6 +1428,7 @@
"rolling_30d": "Last 30 days at API price"
},
"noPrice": "No price yet",
+ "fetching": "Fetching prices…",
"paid": "Paid back {{multiple}}×",
"even": "Just paid back",
"short": "{{amount}} to pay back",
@@ -1647,10 +1649,12 @@
"cost": {
"notBilled": "At published API prices, not a charge",
"noPrice": "No price yet",
+ "fetching": "Fetching prices…",
"excluded_one": "{{tokens}} token has no price and is left out",
"excluded_other": "{{tokens}} tokens have no price and are left out",
"tableDate": "Price table from {{date}}",
- "tableDateUnknown": "Price table date unknown"
+ "tableDateUnknown": "Price table date unknown",
+ "tableFetching": "Fetching the price table…"
}
},
"supplyTooltip": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4bae19617..cde2f974a 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1420,6 +1420,7 @@
"footnoteValue": "“按 API 价格”指同样的用量按官方 API 标价要花多少钱,用来看订阅值不值,不是实际扣费。",
"priceTableDate": "价格表日期 {{date}}。",
"priceTableUnknown": "暂无价格表日期。",
+ "priceTableFetching": "正在获取价格表…",
"value": {
"week": "近 7 天按 API 价格",
"period": {
@@ -1427,6 +1428,7 @@
"rolling_30d": "近 30 天按 API 价格"
},
"noPrice": "暂无价格",
+ "fetching": "正在获取价格…",
"paid": "回本 {{multiple}} 倍",
"even": "刚好回本",
"short": "还差 {{amount}} 回本",
@@ -1647,10 +1649,12 @@
"cost": {
"notBilled": "按官方 API 标价折算,不是实际扣费",
"noPrice": "暂无价格",
+ "fetching": "正在获取价格…",
"excluded_one": "{{tokens}} tokens 暂无价格,未计入",
"excluded_other": "{{tokens}} tokens 暂无价格,未计入",
"tableDate": "价格表日期 {{date}}",
- "tableDateUnknown": "暂无价格表日期"
+ "tableDateUnknown": "暂无价格表日期",
+ "tableFetching": "正在获取价格表…"
}
},
"supplyTooltip": {
diff --git a/vibe/models_dev_catalog.py b/vibe/models_dev_catalog.py
index 79b9e3aa1..cbfee2f57 100644
--- a/vibe/models_dev_catalog.py
+++ b/vibe/models_dev_catalog.py
@@ -204,36 +204,64 @@ def load_models_dev_catalog() -> dict[str, Any]:
raise RuntimeError("models.dev catalog is unavailable") from None
-_REFRESH_IN_FLIGHT = threading.Event()
+# One background fetch at a time. The claim and the answer to "will one land"
+# are read under one lock, so two readers cannot both start a fetch and no
+# reader can miss one that finished in between.
+_REFRESH_LOCK = threading.Lock()
+_refresh_in_flight = False
+_last_refresh_failed = False
-def _refresh_in_background() -> None:
+def _refresh_in_background() -> bool:
+ """Start a background fetch unless one is running; whether a fetch is expected to land.
+
+ A fetch retried after a failed one is not expected to: the reader says "no
+ price" rather than "fetching" for as long as the network keeps failing.
+ """
+
+ global _refresh_in_flight
+
def refresh() -> None:
+ global _refresh_in_flight, _last_refresh_failed
+ failed = True
try:
# Only the read is locked: request-path readers must not wait on the
# network, and the write is atomic on its own.
with _CACHE_LOCK:
cached = _read_cache()
_fetch_catalog(cached)
+ failed = False
except Exception: # noqa: BLE001 - a background refresh has no one to report to
logger.debug("models.dev background refresh failed", exc_info=True)
finally:
- _REFRESH_IN_FLIGHT.clear()
-
- if _REFRESH_IN_FLIGHT.is_set():
- return
- _REFRESH_IN_FLIGHT.set()
- threading.Thread(target=refresh, name="models-dev-refresh", daemon=True).start()
-
-
-def load_models_dev_catalog_with_date() -> tuple[dict[str, Any], float | None]:
- """The catalog and when it was fetched, without waiting on the network when a copy exists.
-
- For readers on a request path, such as usage valuation: a stale cached copy is
- returned at once and refreshed in the background, since a day-old price table
- is still the best one there is and the reader shows its date. With no cached
- copy at all it starts that fetch and returns an empty catalog, so the first
- read reports nothing as priced rather than holding a page on the network.
+ with _REFRESH_LOCK:
+ _refresh_in_flight = False
+ _last_refresh_failed = failed
+
+ with _REFRESH_LOCK:
+ expected = not _last_refresh_failed
+ if _refresh_in_flight:
+ return expected
+ _refresh_in_flight = True
+ try:
+ threading.Thread(target=refresh, name="models-dev-refresh", daemon=True).start()
+ except RuntimeError: # no thread to be had: release the claim, or no fetch ever runs again
+ with _REFRESH_LOCK:
+ _refresh_in_flight = False
+ return False
+ return expected
+
+
+def load_models_dev_catalog_with_date() -> tuple[dict[str, Any], float | None, bool]:
+ """The catalog, when it was fetched, and whether a first copy is on its way.
+
+ For readers on a request path, such as usage valuation, which never wait on
+ the network when a copy exists: a stale cached copy is returned at once and
+ refreshed in the background, since a day-old price table is still the best
+ one there is and the reader shows its date. With no cached copy at all it
+ starts that fetch and returns an empty catalog, so the first read reports
+ nothing as priced rather than holding a page on the network; the third value
+ says a fetch is running that should land, so the reader can read again soon.
"""
with _CACHE_LOCK:
@@ -245,9 +273,8 @@ def load_models_dev_catalog_with_date() -> tuple[dict[str, Any], float | None]:
age = time.time() - fetched if fetched is not None else None
if age is None or not 0 <= age < MODELS_DEV_CACHE_TTL_SECONDS:
_refresh_in_background()
- return catalog, fetched
- _refresh_in_background()
- return {}, None
+ return catalog, fetched, False
+ return {}, None, _refresh_in_background()
def _search_tokens(query: str) -> tuple[str, ...]: