feat(webui): show the full token-usage picture in settings (#6638)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-12 18:13:06 +08:00
1 parent b49218b6a3
commit e6b23c7356
42 files changed
+1116 -342

No files matched your search

+3 -1
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import threading import threading
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any, Literal
from loguru import logger from loguru import logger
@@ -61,11 +61,13 @@ def record_llm_call(call: LLMCallRecord) -> None:
def llm_usage_payload( def llm_usage_payload(
*, *,
days: int = 371, days: int = 371,
view: Literal["history", "overview", "models"] = "history",
timezone_name: str | None = None, timezone_name: str | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
try: try:
return get_llm_usage_store().usage_payload( return get_llm_usage_store().usage_payload(
days=days, days=days,
view=view,
timezone_name=timezone_name, timezone_name=timezone_name,
) )
except Exception: except Exception:
+103 -82
View File
@@ -1,5 +1,7 @@
from __future__ import annotations from __future__ import annotations
import hashlib
import json
import os import os
import sqlite3 import sqlite3
import threading import threading
@@ -8,7 +10,7 @@ from collections.abc import Iterable
from copy import deepcopy from copy import deepcopy
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
from typing import Any, cast from typing import Any, Literal, cast
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from nanobot.llm_usage.models import LLMCallRecord from nanobot.llm_usage.models import LLMCallRecord
@@ -52,6 +54,8 @@ _USAGE_COLUMNS = (
"cache_write_tokens", "cache_write_tokens",
"cache_read_observed_input_tokens", "cache_read_observed_input_tokens",
"cache_write_observed_input_tokens", "cache_write_observed_input_tokens",
"cache_miss_tokens",
"cache_unknown_tokens",
"total_tokens", "total_tokens",
"reported_tokens", "reported_tokens",
"estimated_tokens", "estimated_tokens",
@@ -78,6 +82,16 @@ _AGGREGATE_SQL = """
COALESCE(SUM( COALESCE(SUM(
CASE WHEN cache_write_tokens IS NOT NULL THEN input_tokens ELSE 0 END CASE WHEN cache_write_tokens IS NOT NULL THEN input_tokens ELSE 0 END
), 0) AS cache_write_observed_input_tokens, ), 0) AS cache_write_observed_input_tokens,
COALESCE(SUM(
CASE WHEN cache_read_tokens IS NOT NULL
THEN input_tokens - cache_read_tokens - COALESCE(cache_write_tokens, 0)
ELSE 0 END
), 0) AS cache_miss_tokens,
COALESCE(SUM(
CASE WHEN cache_read_tokens IS NULL
THEN input_tokens - COALESCE(cache_write_tokens, 0)
ELSE 0 END
), 0) AS cache_unknown_tokens,
COALESCE(SUM(total_tokens), 0) AS total_tokens, COALESCE(SUM(total_tokens), 0) AS total_tokens,
COALESCE(SUM(reported_tokens), 0) AS reported_tokens, COALESCE(SUM(reported_tokens), 0) AS reported_tokens,
COALESCE(SUM(estimated_tokens), 0) AS estimated_tokens, COALESCE(SUM(estimated_tokens), 0) AS estimated_tokens,
@@ -165,8 +179,9 @@ class LLMUsageStore:
self._last_prune_utc_day: int | None = None self._last_prune_utc_day: int | None = None
self._writes_since_size_prune = 0 self._writes_since_size_prune = 0
self._write_version = 0 self._write_version = 0
self._cached_payload_key: tuple[int, str, str, int, int] | None = None self._cached_payloads: dict[
self._cached_payload: dict[str, Any] | None = None str, tuple[tuple[int, str, str, int, int], dict[str, Any]]
] = {}
def _connect(self) -> sqlite3.Connection: def _connect(self) -> sqlite3.Connection:
pid = os.getpid() pid = os.getpid()
@@ -174,8 +189,7 @@ class LLMUsageStore:
return self._connection return self._connection
if self._connection is not None: if self._connection is not None:
self._connection.close() self._connection.close()
self._cached_payload_key = None self._cached_payloads.clear()
self._cached_payload = None
self.path.parent.mkdir(parents=True, exist_ok=True) self.path.parent.mkdir(parents=True, exist_ok=True)
connection = sqlite3.connect( connection = sqlite3.connect(
self.path, self.path,
@@ -251,8 +265,7 @@ class LLMUsageStore:
self._connection.close() self._connection.close()
self._connection = None self._connection = None
self._connection_pid = None self._connection_pid = None
self._cached_payload_key = None self._cached_payloads.clear()
self._cached_payload = None
def record(self, call: LLMCallRecord) -> None: def record(self, call: LLMCallRecord) -> None:
usage = call.usage usage = call.usage
@@ -301,8 +314,7 @@ class LLMUsageStore:
values, values,
) )
self._write_version += 1 self._write_version += 1
self._cached_payload_key = None self._cached_payloads.clear()
self._cached_payload = None
self._prune_if_due(connection) self._prune_if_due(connection)
def _prune_if_due(self, connection: sqlite3.Connection) -> None: def _prune_if_due(self, connection: sqlite3.Connection) -> None:
@@ -392,6 +404,7 @@ class LLMUsageStore:
self, self,
*, *,
days: int = 371, days: int = 371,
view: Literal["history", "overview", "models"] = "history",
timezone_name: str | None = None, timezone_name: str | None = None,
now: datetime | None = None, now: datetime | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
@@ -400,7 +413,7 @@ class LLMUsageStore:
if current.tzinfo is None: if current.tzinfo is None:
current = current.replace(tzinfo=timezone.utc) current = current.replace(tzinfo=timezone.utc)
today = current.astimezone(zone).date() today = current.astimezone(zone).date()
safe_days = max(1, days) safe_days = max(1, days) if view == "history" else 30
zone_name = getattr(zone, "key", "UTC") zone_name = getattr(zone, "key", "UTC")
with self._lock: with self._lock:
@@ -414,14 +427,16 @@ class LLMUsageStore:
write_version, write_version,
data_version, data_version,
) )
if self._cached_payload_key == cache_key and self._cached_payload is not None: cached = self._cached_payloads.get(view)
return deepcopy(self._cached_payload) if cached is not None and cached[0] == cache_key:
return deepcopy(cached[1])
connection = self._read_connection() connection = self._read_connection()
try: try:
connection.execute("BEGIN") connection.execute("BEGIN")
end_ms = self._midnight_ms(today + timedelta(days=1), zone) end_ms = self._midnight_ms(today + timedelta(days=1), zone)
retained_start = today - timedelta(days=MAX_DAYS_RETAINED - 1) retained_days = MAX_DAYS_RETAINED if view == "history" else 30
retained_start = today - timedelta(days=retained_days - 1)
retained_start_ms = self._midnight_ms(retained_start, zone) retained_start_ms = self._midnight_ms(retained_start, zone)
daily = self._daily_rows( daily = self._daily_rows(
connection=connection, connection=connection,
@@ -435,16 +450,11 @@ class LLMUsageStore:
last_30_start_ms = self._midnight_ms(today - timedelta(days=29), zone) last_30_start_ms = self._midnight_ms(today - timedelta(days=29), zone)
last_30_date = (today - timedelta(days=29)).isoformat() last_30_date = (today - timedelta(days=29)).isoformat()
last_365_date = (today - timedelta(days=364)).isoformat()
all_totals = _sum_rows(daily)
totals_30 = _sum_rows(row for row in daily if row["date"] >= last_30_date)
totals_365 = _sum_rows(row for row in daily if row["date"] >= last_365_date)
provider_rows = self._aggregate( provider_rows = self._aggregate(
connection=connection, connection=connection,
start_ms=last_30_start_ms, start_ms=last_30_start_ms,
end_ms=end_ms, end_ms=end_ms,
) ) if view != "overview" else []
providers_30d = [ providers_30d = [
{ {
"provider": str(row["provider"]), "provider": str(row["provider"]),
@@ -459,11 +469,19 @@ class LLMUsageStore:
"provider": str(row["provider"]), "provider": str(row["provider"]),
"model": str(row["model"]), "model": str(row["model"]),
"total_tokens": int(row["total_tokens"]), "total_tokens": int(row["total_tokens"]),
"measured_output_tokens": int(row["measured_output_tokens"]),
"generation_ms": int(row["generation_ms"]),
"ttft_ms": int(row["ttft_ms"]),
"timed_requests": int(row["timed_requests"]),
"cache_read_tokens": int(row["cache_read_tokens"]),
"cache_read_observed_input_tokens": int(
row["cache_read_observed_input_tokens"]
),
} }
for row in connection.execute( for row in connection.execute(
""" f"""
SELECT llm_usage_local_day(started_at_ms, ?) AS date, provider, model, SELECT llm_usage_local_day(started_at_ms, ?) AS date, provider, model,
COALESCE(SUM(total_tokens), 0) AS total_tokens {_AGGREGATE_SQL}
FROM llm_calls FROM llm_calls
WHERE started_at_ms >= ? AND started_at_ms < ? WHERE started_at_ms >= ? AND started_at_ms < ?
GROUP BY date, provider, model GROUP BY date, provider, model
@@ -472,66 +490,70 @@ class LLMUsageStore:
""", """,
(zone_name, last_30_start_ms, end_ms), (zone_name, last_30_start_ms, end_ms),
) )
] ] if view != "overview" else []
active_dates = { if view == "history":
date.fromisoformat(row["date"]) for row in daily if row["total_tokens"] > 0 totals_30 = _sum_rows(row for row in daily if row["date"] >= last_30_date)
} last_365_date = (today - timedelta(days=364)).isoformat()
current_streak = 0 totals_365 = _sum_rows(row for row in daily if row["date"] >= last_365_date)
cursor = today active_dates = {
while cursor in active_dates: date.fromisoformat(row["date"]) for row in daily if row["total_tokens"] > 0
current_streak += 1 }
cursor -= timedelta(days=1) current_streak = 0
longest_streak = 0 cursor = today
running_streak = 0 while cursor in active_dates:
previous: date | None = None current_streak += 1
for cursor in sorted(active_dates): cursor -= timedelta(days=1)
running_streak = running_streak + 1 if previous == cursor - timedelta(days=1) else 1 longest_streak = 0
longest_streak = max(longest_streak, running_streak) running_streak = 0
previous = cursor previous: date | None = None
for cursor in sorted(active_dates):
latest = ( running_streak = running_streak + 1 if previous == cursor - timedelta(days=1) else 1
connection longest_streak = max(longest_streak, running_streak)
.execute("SELECT MAX(started_at_ms) AS updated_at_ms FROM llm_calls") previous = cursor
.fetchone() latest = connection.execute(
) "SELECT MAX(started_at_ms) AS updated_at_ms FROM llm_calls"
updated_at_ms = int(latest["updated_at_ms"] or 0) if latest is not None else 0 ).fetchone()
denominator = totals_30["cache_read_observed_input_tokens"] updated_at_ms = int(latest["updated_at_ms"] or 0) if latest is not None else 0
payload = { denominator = totals_30["cache_read_observed_input_tokens"]
"days": visible_days, payload = {
"total_tokens": all_totals["total_tokens"], "days": visible_days,
"total_tokens_30d": totals_30["total_tokens"], "total_tokens": _sum_rows(daily)["total_tokens"],
"total_tokens_365d": totals_365["total_tokens"], "total_tokens_30d": totals_30["total_tokens"],
"reported_tokens_30d": totals_30["reported_tokens"], "total_tokens_365d": totals_365["total_tokens"],
"estimated_tokens_30d": totals_30["estimated_tokens"], "reported_tokens_30d": totals_30["reported_tokens"],
"cache_read_tokens_30d": totals_30["cache_read_tokens"], "estimated_tokens_30d": totals_30["estimated_tokens"],
"cache_read_observed_input_tokens_30d": denominator, "cache_read_tokens_30d": totals_30["cache_read_tokens"],
"cache_read_rate_30d": ( "cache_read_observed_input_tokens_30d": denominator,
totals_30["cache_read_tokens"] / denominator if denominator else None "cache_read_rate_30d": (
), totals_30["cache_read_tokens"] / denominator if denominator else None
"peak_day_tokens": max( ),
(int(row["total_tokens"]) for row in daily), "peak_day_tokens": max((int(row["total_tokens"]) for row in daily), default=0),
default=0, "current_streak_days": current_streak,
), "longest_streak_days": longest_streak,
"current_streak_days": current_streak, "active_days_30d": sum(
"longest_streak_days": longest_streak, 1 for row in daily if row["date"] >= last_30_date and row["total_tokens"] > 0
"active_days_30d": sum( ),
1 "requests_30d": totals_30["requests"],
for row in daily "failed_requests_30d": totals_30["failed_requests"],
if row["date"] >= last_30_date and row["total_tokens"] > 0 "providers_30d": providers_30d,
), "model_days_30d": model_days_30d,
"requests_30d": totals_30["requests"], "updated_at": (
"failed_requests_30d": totals_30["failed_requests"], datetime.fromtimestamp(updated_at_ms / 1000, timezone.utc)
"providers_30d": providers_30d, .isoformat().replace("+00:00", "Z") if updated_at_ms else None
"model_days_30d": model_days_30d, ),
"updated_at": ( }
datetime.fromtimestamp(updated_at_ms / 1000, timezone.utc) else:
.isoformat() payload = {
.replace("+00:00", "Z") "days": visible_days,
if updated_at_ms "range_start": last_30_date,
else None "range_end": today.isoformat(),
), **({"providers_30d": providers_30d, "model_days_30d": model_days_30d}
} if view == "models" else {}),
}
payload["revision"] = hashlib.sha256(
json.dumps(payload, sort_keys=True).encode("utf-8")
).hexdigest()
finally: finally:
connection.close() connection.close()
@@ -543,8 +565,7 @@ class LLMUsageStore:
else 0 else 0
) )
if self._write_version == write_version and latest_data_version == data_version: if self._write_version == write_version and latest_data_version == data_version:
self._cached_payload_key = cache_key self._cached_payloads[view] = (cache_key, payload)
self._cached_payload = payload
return deepcopy(payload) return deepcopy(payload)
def recent_calls(self, *, limit: int = 100) -> list[dict[str, Any]]: def recent_calls(self, *, limit: int = 100) -> list[dict[str, Any]]:
+5 -3
View File
@@ -161,7 +161,7 @@ def settings_payload(
restart_required_sections: list[str] | None = None, restart_required_sections: list[str] | None = None,
apply_state: dict[str, Any] | None = None, apply_state: dict[str, Any] | None = None,
config_path: Path | None = None, config_path: Path | None = None,
include_usage: bool = True, include_usage: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
config = _load_settings_config(config_path) config = _load_settings_config(config_path)
payload: dict[str, Any] = { payload: dict[str, Any] = {
@@ -190,8 +190,10 @@ def settings_payload(
) )
def settings_usage_payload(*, config_path: Path | None = None) -> dict[str, Any]: def settings_usage_payload(
return system.settings_usage_payload(_load_settings_config(config_path)) *, config_path: Path | None = None, details: bool = False,
) -> dict[str, Any]:
return system.settings_usage_payload(_load_settings_config(config_path), details=details)
def update_agent_settings( def update_agent_settings(
+21 -3
View File
@@ -21,6 +21,7 @@ from nanobot.webui import settings_contracts as contracts
from nanobot.webui import settings_models as model_domain from nanobot.webui import settings_models as model_domain
from nanobot.webui import settings_system as system_domain from nanobot.webui import settings_system as system_domain
from nanobot.webui.cli_apps_api import cli_apps_action, cli_apps_payload from nanobot.webui.cli_apps_api import cli_apps_action, cli_apps_payload
from nanobot.webui.http_utils import http_json_response
from nanobot.webui.http_utils import http_response as _http_response from nanobot.webui.http_utils import http_response as _http_response
from nanobot.webui.http_utils import is_local_browser_request as _is_local_browser_request from nanobot.webui.http_utils import is_local_browser_request as _is_local_browser_request
from nanobot.webui.mcp_oauth_api import McpOAuthManager from nanobot.webui.mcp_oauth_api import McpOAuthManager
@@ -312,7 +313,7 @@ class WebUISettingsRouter:
if route == ("root", "settings"): if route == ("root", "settings"):
return await asyncio.to_thread(self._handle_settings) return await asyncio.to_thread(self._handle_settings)
if route == ("root", "usage"): if route == ("root", "usage"):
return await asyncio.to_thread(self._handle_settings_usage) return await asyncio.to_thread(self._handle_settings_usage, request)
domain, action = route domain, action = route
if action.startswith("update-") and self._runtime_surface == "native": if action.startswith("update-") and self._runtime_surface == "native":
@@ -500,8 +501,25 @@ class WebUISettingsRouter:
) )
) )
def _handle_settings_usage(self) -> Response: def _handle_settings_usage(self, request: WsRequest) -> Response:
return self._json_response(self.settings.read(settings_usage_payload)) details = contracts.query_first(self._parse_query(request.path), "details")
if details not in (None, "true", "false"):
return self._error_response(400, "details must be true or false")
payload = self.settings.read(settings_usage_payload, details=details == "true")
revision = payload.get("revision")
headers = [("Cache-Control", "private, no-cache")]
if revision:
etag = f'W/"{revision}"'
headers.append(("ETag", etag))
if request.headers.get("If-None-Match") == etag:
return _http_response(
b"", status=304, extra_headers=[*headers, ("Vary", "Accept-Encoding")],
)
return http_json_response(
payload,
accept_encoding=request.headers.get("Accept-Encoding", ""),
extra_headers=headers,
)
def _model_operations(self) -> model_domain.ModelSettingsOperations: def _model_operations(self) -> model_domain.ModelSettingsOperations:
return model_domain.ModelSettingsOperations( return model_domain.ModelSettingsOperations(
+6 -3
View File
@@ -185,9 +185,12 @@ def system_settings_payload(
return payload return payload
def settings_usage_payload(config: Config) -> dict[str, Any]: def settings_usage_payload(config: Config, *, details: bool = False) -> dict[str, Any]:
"""Return the lightweight token usage slice for Overview refreshes.""" """Return only the 30-day usage projection currently displayed."""
return llm_usage_payload(timezone_name=config.agents.defaults.timezone) return llm_usage_payload(
timezone_name=config.agents.defaults.timezone,
view="models" if details else "overview",
)
def update_agent_system_settings(config: Config, query: QueryParams) -> tuple[bool, bool]: def update_agent_system_settings(config: Config, query: QueryParams) -> tuple[bool, bool]:
+109 -3
View File
@@ -89,7 +89,10 @@ def test_usage_payload_aggregates_cache_coverage_sources_and_failures(tmp_path:
_call( _call(
"2026-06-03T01:00:00+00:00", "2026-06-03T01:00:00+00:00",
source="api", source="api",
usage=LLMUsage.reported(input_tokens=50, output_tokens=5), usage=LLMUsage.reported(input_tokens=50, output_tokens=5).with_timing(
generation_ms=2500,
ttft_ms=200,
),
), ),
_call( _call(
"2026-06-03T02:00:00+00:00", "2026-06-03T02:00:00+00:00",
@@ -122,8 +125,30 @@ def test_usage_payload_aggregates_cache_coverage_sources_and_failures(tmp_path:
assert payload["cache_read_observed_input_tokens_30d"] == 100 assert payload["cache_read_observed_input_tokens_30d"] == 100
assert payload["cache_read_rate_30d"] == 0.4 assert payload["cache_read_rate_30d"] == 0.4
assert payload["model_days_30d"] == [ assert payload["model_days_30d"] == [
{"date": "2026-06-03", "provider": "anthropic", "model": "claude-sonnet-4", "total_tokens": 40}, {
{"date": "2026-06-03", "provider": "openai", "model": "gpt-5", "total_tokens": 175}, "date": "2026-06-03",
"provider": "anthropic",
"model": "claude-sonnet-4",
"total_tokens": 40,
"measured_output_tokens": 0,
"generation_ms": 0,
"ttft_ms": 0,
"timed_requests": 0,
"cache_read_tokens": 0,
"cache_read_observed_input_tokens": 0,
},
{
"date": "2026-06-03",
"provider": "openai",
"model": "gpt-5",
"total_tokens": 175,
"measured_output_tokens": 5,
"generation_ms": 2500,
"ttft_ms": 200,
"timed_requests": 1,
"cache_read_tokens": 40,
"cache_read_observed_input_tokens": 100,
},
] ]
day = payload["days"][0] day = payload["days"][0]
@@ -131,6 +156,8 @@ def test_usage_payload_aggregates_cache_coverage_sources_and_failures(tmp_path:
assert day["requests"] == 4 assert day["requests"] == 4
assert day["reported_requests"] == 2 assert day["reported_requests"] == 2
assert day["estimated_requests"] == 1 assert day["estimated_requests"] == 1
assert day["cache_miss_tokens"] == 50
assert day["cache_unknown_tokens"] == 80
assert day["sources"]["api"]["cache_read_observed_input_tokens"] == 0 assert day["sources"]["api"]["cache_read_observed_input_tokens"] == 0
assert day["sources"]["user"]["cache_read_observed_input_tokens"] == 100 assert day["sources"]["user"]["cache_read_observed_input_tokens"] == 100
assert {(row["provider"], row["model"]) for row in payload["providers_30d"]} == { assert {(row["provider"], row["model"]) for row in payload["providers_30d"]} == {
@@ -139,6 +166,38 @@ def test_usage_payload_aggregates_cache_coverage_sources_and_failures(tmp_path:
} }
@pytest.mark.parametrize("with_read_call", [False, True], ids=["write-only", "mixed-observation"])
def test_usage_payload_partitions_cache_tokens_before_aggregation(
tmp_path: Path, with_read_call: bool,
) -> None:
store = LLMUsageStore(tmp_path / "llm_usage.sqlite3")
store.record(_call(
"2026-06-03T00:00:00+00:00",
usage=LLMUsage.reported(
input_tokens=100, output_tokens=20, cache_write_tokens=100,
),
))
if with_read_call:
store.record(_call(
"2026-06-03T00:01:00+00:00",
usage=LLMUsage.reported(
input_tokens=100, output_tokens=20,
cache_read_tokens=100, cache_write_tokens=0,
),
))
payload = store.usage_payload(now=datetime(2026, 6, 3, 12, tzinfo=timezone.utc))
day = payload["days"][0]
assert day["cache_write_tokens"] == 100
assert day["cache_read_tokens"] == (100 if with_read_call else 0)
assert day["cache_miss_tokens"] == 0
assert day["cache_unknown_tokens"] == 0
assert sum(day[key] for key in (
"cache_read_tokens", "cache_write_tokens", "cache_miss_tokens",
"cache_unknown_tokens", "output_tokens",
)) == day["total_tokens"]
def test_usage_payload_preserves_zero_cache_observation(tmp_path: Path) -> None: def test_usage_payload_preserves_zero_cache_observation(tmp_path: Path) -> None:
store = LLMUsageStore(tmp_path / "llm_usage.sqlite3") store = LLMUsageStore(tmp_path / "llm_usage.sqlite3")
store.record( store.record(
@@ -275,3 +334,50 @@ def test_usage_query_does_not_hold_writer_lock(
assert not query_thread.is_alive() assert not query_thread.is_alive()
assert not record_thread.is_alive() assert not record_thread.is_alive()
def test_dashboard_views_are_bounded_and_cached_independently(tmp_path, monkeypatch) -> None:
path = tmp_path / "llm_usage.sqlite3"
store = LLMUsageStore(path)
store.record_many([
_call("2026-05-04T12:00:00+00:00", usage=LLMUsage.reported(input_tokens=100, output_tokens=0)),
_call("2026-06-03T12:00:00+00:00", usage=LLMUsage.reported(input_tokens=10, output_tokens=2)),
])
queries = []
daily_rows = store._daily_rows
def count_daily_rows(**kwargs):
queries.append((kwargs["start_ms"], kwargs["end_ms"]))
return daily_rows(**kwargs)
monkeypatch.setattr(store, "_daily_rows", count_daily_rows)
kwargs = {"now": datetime(2026, 6, 3, 23, tzinfo=timezone.utc), "timezone_name": "UTC"}
overview = store.usage_payload(view="overview", **kwargs)
models = store.usage_payload(view="models", **kwargs)
assert overview["range_start"] == "2026-05-05"
assert overview["range_end"] == "2026-06-03"
assert sum(day["total_tokens"] for day in overview["days"]) == 12
assert set(overview) == {"days", "range_start", "range_end", "revision"}
assert models["days"] == overview["days"]
assert models["providers_30d"][0]["total_tokens"] == 12
assert models["model_days_30d"][0]["total_tokens"] == 12
assert models["revision"] != overview["revision"]
assert store.usage_payload(view="overview", **kwargs) == overview
assert store.usage_payload(view="models", **kwargs) == models
assert queries == [(_timestamp("2026-05-05T00:00:00+00:00"),
_timestamp("2026-06-04T00:00:00+00:00"))] * 2
# Another gateway writer must invalidate both projections, not just the last read view.
other = LLMUsageStore(path)
other.record(_call("2026-06-03T13:00:00+00:00", usage=LLMUsage.reported(input_tokens=5, output_tokens=0)))
other.close()
refreshed = store.usage_payload(view="overview", **kwargs)
assert sum(day["total_tokens"] for day in refreshed["days"]) == 17
assert refreshed["revision"] != overview["revision"]
assert store.usage_payload(view="models", **kwargs)["providers_30d"][0]["total_tokens"] == 17
next_day = store.usage_payload(view="overview", timezone_name="UTC",
now=datetime(2026, 6, 4, 1, tzinfo=timezone.utc))
assert next_day["days"] == refreshed["days"]
assert next_day["range_end"] == "2026-06-04"
assert next_day["revision"] != refreshed["revision"]
+15 -5
View File
@@ -5,6 +5,7 @@ import json
import time import time
from datetime import date from datetime import date
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import patch
import httpx import httpx
import pytest import pytest
@@ -1753,7 +1754,7 @@ def test_update_transcription_settings_validates_language(
update_transcription_settings({"language": ["en-US"]}) update_transcription_settings({"language": ["en-US"]})
def test_settings_payload_includes_token_usage_summary( def test_settings_payload_includes_token_usage_only_when_requested(
tmp_path, tmp_path,
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> None:
@@ -1774,7 +1775,12 @@ def test_settings_payload_includes_token_usage_summary(
) )
) )
payload = settings_payload() store = get_llm_usage_store()
with patch.object(store, "usage_payload", wraps=store.usage_payload) as aggregate:
assert "usage" not in settings_payload()
aggregate.assert_not_called()
payload = settings_payload(include_usage=True)
aggregate.assert_called_once()
assert payload["usage"]["total_tokens_30d"] == 15 assert payload["usage"]["total_tokens_30d"] == 15
assert payload["usage"]["total_tokens"] == 15 assert payload["usage"]["total_tokens"] == 15
@@ -1808,9 +1814,13 @@ def test_settings_usage_payload_returns_lightweight_token_usage(
payload = settings_usage_payload() payload = settings_usage_payload()
assert payload["total_tokens"] == 22 assert sum(day["total_tokens"] for day in payload["days"]) == 22
assert payload["requests_30d"] == 1 assert sum(day["requests"] for day in payload["days"]) == 1
assert "agent" not in payload assert set(payload) == {"days", "range_start", "range_end", "revision"}
details = settings_usage_payload(details=True)
assert details["days"] == payload["days"]
assert details["providers_30d"][0]["total_tokens"] == 22
assert details["model_days_30d"][0]["total_tokens"] == 22
def test_update_network_safety_settings_writes_local_service_flag( def test_update_network_safety_settings_writes_local_service_flag(
+34
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import gzip
import json import json
import threading import threading
from collections.abc import Awaitable, Callable, Mapping from collections.abc import Awaitable, Callable, Mapping
@@ -1181,3 +1182,36 @@ async def test_mcp_proxy_mutation_persists_reloads_and_keeps_oauth_credentials(
reload.assert_awaited_once() reload.assert_awaited_once()
finally: finally:
await gateway.http.settings_routes.close() await gateway.http.settings_routes.close()
@pytest.mark.asyncio
async def test_usage_query_supports_lazy_details_and_conditional_compressed_responses(monkeypatch):
calls = []
payload = {"days": [{"date": "2026-06-03", "total_tokens": 12}] * 100, "revision": "overview"}
def usage_payload(**kwargs):
calls.append(kwargs["details"])
return {**payload, "revision": "models" if kwargs["details"] else "overview"}
monkeypatch.setattr("nanobot.webui.settings_routes.settings_usage_payload", usage_payload)
router = _router()
path = "/api/settings/usage"
request = SimpleNamespace(path=path, headers=Headers({"Accept-Encoding": "gzip"}))
first = await router.dispatch(None, request, path)
assert first.status_code == 200
assert first.headers["Content-Encoding"] == "gzip"
assert json.loads(gzip.decompress(first.body)) == payload
assert first.headers["ETag"] == 'W/"overview"'
request.headers["If-None-Match"] = first.headers["ETag"]
unchanged = await router.dispatch(None, request, path)
assert unchanged.status_code == 304
assert unchanged.body == b""
request.path = f"{path}?details=true"
detailed = await router.dispatch(None, request, path)
assert detailed.status_code == 200
assert detailed.headers["ETag"] == 'W/"models"'
assert calls == [False, False, True]
request.path = f"{path}?details=invalid"
assert (await router.dispatch(None, request, path)).status_code == 400
unauthorized = _router(authorized=False)
assert (await unauthorized.dispatch(None, request, path)).status_code == 401
+2 -1
View File
@@ -66,7 +66,8 @@ export function installSkeletonPreviewApi() {
return detailState === "error" ? Response.json({ error: "Preview read failed" }, { status: 503 }) : Response.json(skill); return detailState === "error" ? Response.json({ error: "Preview read failed" }, { status: 503 }) : Response.json(skill);
} }
const bodies: Record<string, unknown> = { const bodies: Record<string, unknown> = {
"/api/settings": previewSettings, "/api/settings/usage": { usage: null }, "/api/settings": previewSettings,
"/api/settings/usage": { days: [] } satisfies NonNullable<SettingsPayload["usage"]>,
"/api/webui/automations": { jobs }, "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false }, "/api/webui/automations": { jobs }, "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false },
"/api/settings/cli-apps": { apps: [], installed_count: 0 }, "/api/settings/mcp-presets": { presets: [], installed_count: 0 }, "/api/settings/cli-apps": { apps: [], installed_count: 0 }, "/api/settings/mcp-presets": { presets: [], installed_count: 0 },
}; };
+10 -3
View File
@@ -942,6 +942,9 @@ function Shell({
const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken); const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken);
const [settingsSnapshot, setSettingsSnapshot] = useState<SettingsPayload | null>(null); const [settingsSnapshot, setSettingsSnapshot] = useState<SettingsPayload | null>(null);
const [settingsLoading, setSettingsLoading] = useState(true); const [settingsLoading, setSettingsLoading] = useState(true);
const settingsSnapshotRef = useRef(settingsSnapshot);
settingsSnapshotRef.current = settingsSnapshot;
const settingsOwnsSnapshot = view !== "chat" && view !== "remote";
const settingsRefreshGenerationRef = useRef(0); const settingsRefreshGenerationRef = useRef(0);
const [pendingAutomationMessage, setPendingAutomationMessage] = useState<{ const [pendingAutomationMessage, setPendingAutomationMessage] = useState<{
id: string; id: string;
@@ -1082,10 +1085,14 @@ function Shell({
}, [client]); }, [client]);
useEffect(() => { useEffect(() => {
if (settingsOwnsSnapshot || settingsSnapshotRef.current !== null) {
setSettingsLoading(false);
return;
}
let cancelled = false; let cancelled = false;
const requestGeneration = settingsRefreshGenerationRef.current; const requestGeneration = settingsRefreshGenerationRef.current;
setSettingsLoading(true); setSettingsLoading(true);
fetchSettings(getToken()) fetchSettings(getToken(), "", client)
.then((payload) => { .then((payload) => {
if (!cancelled && requestGeneration === settingsRefreshGenerationRef.current) { if (!cancelled && requestGeneration === settingsRefreshGenerationRef.current) {
setSettingsSnapshot(payload); setSettingsSnapshot(payload);
@@ -1102,7 +1109,7 @@ function Shell({
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [getToken]); }, [client, getToken, settingsOwnsSnapshot]);
useEffect(() => { useEffect(() => {
try { try {
@@ -1925,7 +1932,7 @@ function Shell({
let cancelled = false; let cancelled = false;
let retryTimer: number | undefined; let retryTimer: number | undefined;
const refreshSettings = (generation: number, attempt = 0): void => { const refreshSettings = (generation: number, attempt = 0): void => {
void fetchSettings(getToken()) void fetchSettings(getToken(), "", client)
.then((payload) => { .then((payload) => {
if (!cancelled && generation === settingsRefreshGenerationRef.current) { if (!cancelled && generation === settingsRefreshGenerationRef.current) {
setSettingsSnapshot(payload); setSettingsSnapshot(payload);
@@ -25,6 +25,7 @@ import {
} from "@/components/settings/models/ProviderSettings"; } from "@/components/settings/models/ProviderSettings";
import { providerFormFromRow } from "@/components/settings/models/providerForm"; import { providerFormFromRow } from "@/components/settings/models/providerForm";
import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings"; import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings";
import { TokenUsageOverview } from "@/components/settings/TokenUsageOverview";
import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings"; import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings";
import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar"; import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar";
import { import {
@@ -270,6 +271,7 @@ export function SettingsPage({
settings={settings} settings={settings}
showBrandLogos={localPrefs.brandLogos} showBrandLogos={localPrefs.brandLogos}
onSelectSection={selectSection} onSelectSection={selectSection}
usageCard={<TokenUsageOverview initialUsage={settings.usage} timeZone={settings.agent.timezone} />}
/> />
); );
case "about": case "about":
@@ -2,27 +2,33 @@ import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { SettingsPayload } from "@/lib/types"; import type { SettingsPayload } from "@/lib/types";
import { usageFormats } from "@/lib/usage-number";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { TokenUsageDetails } from "@/components/settings/TokenUsageDetails"; import { TokenUsageDetails } from "@/components/settings/TokenUsageDetails";
import { UsageAxis, UsageDateAxis, usageAxisTicks, usagePeakCenter } from "@/components/settings/usage-chart";
import { SettingsHint } from "@/components/settings/shared/SettingsHint"; import { SettingsHint } from "@/components/settings/shared/SettingsHint";
type Usage = NonNullable<SettingsPayload["usage"]>; type Usage = NonNullable<SettingsPayload["usage"]>;
const SOURCE_KEYS = ["user", "api", "cron", "dream", "system"] as const; const SOURCE_KEYS = ["user", "api", "cron", "dream", "system"] as const;
const SEGMENT_CLASSES = [ const SEGMENT_CLASSES = [
"bg-orange-100 text-orange-500 dark:bg-orange-400/15 dark:text-orange-400", "bg-orange-100 text-orange-500 dark:bg-orange-400/15 dark:text-orange-400",
"bg-neutral-300 dark:bg-neutral-500", "bg-orange-300 dark:bg-orange-400/40",
"bg-neutral-400 dark:bg-neutral-500",
"bg-neutral-200 dark:bg-neutral-700", "bg-neutral-200 dark:bg-neutral-700",
"bg-orange-500 dark:bg-orange-400", "bg-neutral-700 dark:bg-neutral-200",
"bg-neutral-500 dark:bg-neutral-300", "bg-neutral-500 dark:bg-neutral-300",
]; ];
const CACHE_PATTERN = { backgroundImage: "repeating-linear-gradient(135deg, transparent, transparent 3px, currentColor 3px, currentColor 4px)" }; const CACHE_PATTERN = { backgroundImage: "repeating-linear-gradient(135deg, transparent, transparent 3px, currentColor 3px, currentColor 4px)" };
function tokenSegments(day?: Usage["days"][number]): number[] { function tokenSegments(day?: Usage["days"][number]): number[] {
if (!day) return [0, 0, 0, 0, 0]; if (!day) return [0, 0, 0, 0, 0, 0];
const observed = day.cache_read_observed_input_tokens; const observed = day.cache_read_observed_input_tokens;
return [day.cache_read_tokens, observed - day.cache_read_tokens, // Older backends cannot locate writes within the read-observed and unknown pools.
day.input_tokens - observed, const input = day.cache_miss_tokens !== undefined && day.cache_unknown_tokens !== undefined
day.output_tokens, Math.max(0, day.total_tokens - day.input_tokens - day.output_tokens)]; ? [day.cache_read_tokens, day.cache_write_tokens, day.cache_miss_tokens, day.cache_unknown_tokens]
: [day.cache_read_tokens, 0, observed - day.cache_read_tokens, day.input_tokens - observed];
return [...input, day.output_tokens,
Math.max(0, day.total_tokens - day.input_tokens - day.output_tokens)];
} }
function todayInTimeZone(timeZone?: string): string { function todayInTimeZone(timeZone?: string): string {
@@ -42,7 +48,12 @@ function todayInTimeZone(timeZone?: string): string {
return now.toISOString().slice(0, 10); return now.toISOString().slice(0, 10);
} }
export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?: string }) { export function TokenUsageCard({ usage, timeZone, onDetailsOpenChange, detailsLoading }: {
usage?: Usage;
timeZone?: string;
detailsLoading?: boolean;
onDetailsOpenChange?: (open: boolean) => void;
}) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const today = todayInTimeZone(timeZone); const today = todayInTimeZone(timeZone);
const byDate = new Map(usage?.days.map(day => [day.date, day])); const byDate = new Map(usage?.days.map(day => [day.date, day]));
@@ -53,20 +64,29 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
return { date: key, usage: byDate.get(key) }; return { date: key, usage: byDate.get(key) };
}); });
const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0); const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0);
const peak = Math.max(0, ...days.map(day => day.usage?.total_tokens ?? 0)); const values = days.map(day => day.usage?.total_tokens ?? 0);
const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 }); const average = total / values.length;
const exact = new Intl.NumberFormat(i18n.language); const peak = Math.max(0, ...values);
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }); const peakDay = days.reduce<(typeof days)[number] | undefined>(
const dateFormat = new Intl.DateTimeFormat(i18n.language, { month: "short", day: "numeric", timeZone: "UTC" }); (best, day) => ((day.usage?.total_tokens ?? 0) > (best?.usage?.total_tokens ?? 0) ? day : best),
const formatDate = (date: string) => dateFormat.format(new Date(`${date}T00:00:00Z`)); undefined,
);
const peakIndex = peak > 0 ? values.indexOf(peak) : -1;
const peakCenter = usagePeakCenter(values.length, peakIndex);
const ticks = usageAxisTicks(peak, average);
const { display, exact, compact, percent, date: formatDate } = usageFormats(i18n.language);
const segmentLabels = [ const segmentLabels = [
t("settings.usage.cachedInput", { defaultValue: "Cached input" }), t("settings.usage.cachedInput", { defaultValue: "Cached input" }),
t("settings.usage.cacheWrite", { defaultValue: "Cache write" }),
t("settings.usage.cacheMiss", { defaultValue: "Cache miss" }), t("settings.usage.cacheMiss", { defaultValue: "Cache miss" }),
t("settings.usage.cacheUnknown", { defaultValue: "Cache status unknown" }), t("settings.usage.cacheUnknown", { defaultValue: "Cache status unknown" }),
t("settings.usage.outputTokens", { defaultValue: "Output" }), t("settings.usage.outputTokens", { defaultValue: "Output" }),
t("settings.usage.otherTokens", { defaultValue: "Other tokens" }), t("settings.usage.otherTokens", { defaultValue: "Other tokens" }),
]; ];
const hasOtherTokens = days.some(day => tokenSegments(day.usage)[4] > 0); const segmentTotals = days.reduce<number[]>(
(sums, day) => tokenSegments(day.usage).map((value, index) => sums[index] + value),
[0, 0, 0, 0, 0, 0],
);
const sourceLabels: Record<string, string> = { const sourceLabels: Record<string, string> = {
user: t("settings.usage.sources.user", { defaultValue: "Chat" }), user: t("settings.usage.sources.user", { defaultValue: "Chat" }),
api: t("settings.usage.sources.api", { defaultValue: "API" }), api: t("settings.usage.sources.api", { defaultValue: "API" }),
@@ -92,12 +112,15 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
<div className="min-w-0 space-y-5"> <div className="min-w-0 space-y-5">
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-4">
<div> <div>
<h3 className="text-sm font-medium">{t("settings.usage.shortTitle", { defaultValue: "Token usage" })}</h3> <h3 className="flex items-baseline gap-2 text-sm font-medium">
<p className="mt-2 text-3xl font-semibold tracking-tight tabular-nums" aria-label={usage ? `${exact.format(total)} tokens` : undefined}> {t("settings.usage.shortTitle", { defaultValue: "Token usage" })}
{usage ? compact.format(total) : "—"} {usage && <span className="text-[11px] font-normal leading-none text-muted-foreground">{t("settings.usage.last30Days", { defaultValue: "Last 30 days" })}</span>}
</h3>
<p className="mt-2 text-3xl font-semibold tracking-tight tabular-nums" aria-label={usage ? `${exact(total)} tokens in the last 30 days` : undefined}>
{usage ? compact(total) : "—"}
</p> </p>
</div> </div>
{usage && <TokenUsageDetails days={days} models={usage.providers_30d} modelDays={usage.model_days_30d} />} {usage && <TokenUsageDetails days={days} models={usage.providers_30d} modelDays={usage.model_days_30d} onOpenChange={onDetailsOpenChange} loading={detailsLoading} />}
</div> </div>
{!usage || total === 0 ? ( {!usage || total === 0 ? (
@@ -109,61 +132,63 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
) : ( ) : (
<> <>
<div> <div>
<div className="mb-2 text-right text-[11px] tabular-nums text-muted-foreground" aria-hidden>{compact.format(peak)}</div> <div className="relative pl-11">
<div className="relative"> <div className="relative h-28">
<div className="pointer-events-none absolute inset-0 flex flex-col justify-between" aria-hidden> <UsageAxis ticks={ticks} format={compact} gridlineAttribute="data-usage-gridline" />
{[0, 1, 2].map(line => <div key={line} className="border-t border-border/40" />)} <div className="relative grid h-full grid-cols-[repeat(30,minmax(0,1fr))]" role="group" aria-label={t("settings.usage.dailyTrend", { defaultValue: "Daily token usage" })}>
</div> <TooltipProvider delayDuration={0} disableHoverableContent>
<div className="relative grid h-28 grid-cols-[repeat(30,minmax(0,1fr))] gap-1" role="group" aria-label={t("settings.usage.dailyTrend", { defaultValue: "Daily token usage" })}> {days.map(day => {
<TooltipProvider> const tokens = day.usage?.total_tokens ?? 0;
{days.map(day => { const segments = tokenSegments(day.usage);
const tokens = day.usage?.total_tokens ?? 0; const label = t("settings.usage.cellTitle", {
const segments = tokenSegments(day.usage); defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests",
const label = t("settings.usage.cellTitle", { date: day.date, tokens: exact(tokens), requests: day.usage?.requests ?? 0,
defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests", });
date: day.date, tokens: exact.format(tokens), requests: day.usage?.requests ?? 0, if (tokens === 0) return <span key={day.date} role="img" aria-label={label} />;
}); return (
if (tokens === 0) return <span key={day.date} role="img" aria-label={label} />; <Tooltip key={day.date}>
return ( <TooltipTrigger asChild>
<Tooltip key={day.date}> <span tabIndex={0} role="img" aria-label={`${label}; ${segments.map((value, index) => `${segmentLabels[index]}: ${exact(value)}`).join(", ")}`} className="group flex h-full min-w-0 items-end pr-1 rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 dark:focus-visible:outline-orange-400">
<TooltipTrigger asChild> <span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm group-hover:brightness-95" style={{ height: `${tokens / peak * 100}%` }}>
<span tabIndex={0} role="img" aria-label={`${label}; ${segments.map((value, index) => `${segmentLabels[index]}: ${exact.format(value)}`).join(", ")}`} className="group flex h-full min-w-0 items-end rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 dark:focus-visible:outline-orange-400"> {segments.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", SEGMENT_CLASSES[index])} style={{ height: `${value / tokens * 100}%`, ...(index === 0 ? CACHE_PATTERN : {}) }} />)}
<span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm group-hover:brightness-95" style={{ height: `${tokens / peak * 100}%` }}> </span>
{segments.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", SEGMENT_CLASSES[index])} style={{ height: `${value / tokens * 100}%`, ...(index === 0 ? CACHE_PATTERN : {}) }} />)} </span>
</span> </TooltipTrigger>
</span> <TooltipContent className="min-w-56 p-3">
</TooltipTrigger> <div className="mb-2 flex justify-between gap-6 font-medium tabular-nums"><span>{day.date}</span><span title={exact(tokens)}>{display(tokens)}</span></div>
<TooltipContent className="min-w-56 p-3"> <dl className="space-y-1.5">
<div className="mb-2 flex justify-between gap-6 font-medium tabular-nums"><span>{day.date}</span><span>{exact.format(tokens)}</span></div> {segments.map((value, index) => (index < 5 || value > 0) && <div key={index} className="flex items-center justify-between gap-6">
<dl className="space-y-1.5"> <dt className="flex items-center gap-2 text-muted-foreground"><span aria-hidden className={cn("size-2.5 shrink-0 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} /><span>{segmentLabels[index]}</span></dt>
{segments.map((value, index) => (index < 4 || value > 0) && <div key={index} className="flex items-center justify-between gap-6"> <dd className="tabular-nums" title={exact(value)}>{display(value)}</dd>
<dt className="flex items-center text-muted-foreground"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} /><span className="sr-only">{segmentLabels[index]}</span></dt> </div>)}
<dd className="tabular-nums">{exact.format(value)}</dd> <div className="flex justify-between gap-6 border-t border-border/50 pt-2">
</div>)} <dt className="text-muted-foreground">{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}</dt>
<div className="flex justify-between gap-6 border-t border-border/50 pt-2"> <dd className="tabular-nums">{day.usage?.cache_read_observed_input_tokens ? percent(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}</dd>
<dt className="text-muted-foreground">{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}</dt> </div>
<dd className="tabular-nums">{day.usage?.cache_read_observed_input_tokens ? percent.format(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}</dd> <div className="flex justify-between gap-6">
</div> <dt className="text-muted-foreground">{t("settings.usage.requests", { defaultValue: "Requests" })}</dt>
</dl> <dd className="tabular-nums">
</TooltipContent> {display(day.usage?.requests ?? 0)}
</Tooltip> {(day.usage?.failed_requests ?? 0) > 0 && <span className="text-muted-foreground"> ({t("settings.usage.failedRequests", { defaultValue: "{{count}} failed", count: display(day.usage?.failed_requests ?? 0) })})</span>}
); </dd>
})} </div>
</TooltipProvider> </dl>
</div> </TooltipContent>
</div> </Tooltip>
<div className="mt-2 flex justify-between text-[11px] text-muted-foreground" aria-hidden> );
<span>{formatDate(days[0].date)}</span> })}
<span>{formatDate(days[14].date)}</span> </TooltipProvider>
<span>{formatDate(today)}</span> </div>
</div>
<UsageDateAxis start={days[0].date} end={today} peak={peakDay?.date ?? days[0].date} peakCenter={peakCenter} format={formatDate} />
</div> </div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-2 text-[11px] text-muted-foreground"> <div className="mt-3 flex flex-wrap gap-x-4 gap-y-2 text-[11px] text-muted-foreground">
{segmentLabels.map((label, index) => (index < 4 || hasOtherTokens) && <span key={label} className="flex items-center gap-1.5"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} />{label}</span>)} {segmentLabels.map((label, index) => segmentTotals[index] > 0 && <span key={label} className="flex items-center gap-1.5"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} />{label}</span>)}
</div> </div>
</div> </div>
<dl className="grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-3" aria-label={t("settings.usage.bySource", { defaultValue: "Usage by source" })}> <dl className="flex flex-wrap gap-x-8 gap-y-2 text-xs" aria-label={t("settings.usage.bySource", { defaultValue: "Usage by source" })}>
{breakdown.map(([source, tokens]) => ( {breakdown.map(([source, tokens]) => (
<div key={source} className="flex min-w-0 items-center justify-between gap-2"> <div key={source} className="flex min-w-0 items-baseline gap-2">
<dt className="min-w-0 break-words text-muted-foreground"> <dt className="min-w-0 break-words text-muted-foreground">
{source === "system" ? ( {source === "system" ? (
<SettingsHint description={t("settings.usage.systemHelp", { <SettingsHint description={t("settings.usage.systemHelp", {
@@ -171,7 +196,7 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
})}>{sourceLabels[source]}</SettingsHint> })}>{sourceLabels[source]}</SettingsHint>
) : sourceLabels[source]} ) : sourceLabels[source]}
</dt> </dt>
<dd className="shrink-0 tabular-nums" title={`${exact.format(tokens)} tokens`}>{new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }).format(tokens / total)}</dd> <dd className="shrink-0 tabular-nums" title={`${exact(tokens)} tokens`}>{tokens / total < 0.001 ? `<${percent(0.001)}` : percent(tokens / total)}</dd>
</div> </div>
))} ))}
</dl> </dl>
@@ -2,44 +2,48 @@ import { ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogLayoutContext, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogLayoutContext, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import type { SettingsPayload } from "@/lib/types"; import type { SettingsPayload } from "@/lib/types";
import { usageFormats } from "@/lib/usage-number";
import { TokenUsageModelTrend } from "@/components/settings/TokenUsageModelTrend"; import { TokenUsageModelTrend } from "@/components/settings/TokenUsageModelTrend";
type Usage = NonNullable<SettingsPayload["usage"]>; type Usage = NonNullable<SettingsPayload["usage"]>;
type DayTotal = NonNullable<Usage["days"][number]>;
export function TokenUsageDetails({ days, models, modelDays }: { export function TokenUsageDetails({ days, models, modelDays, onOpenChange, loading }: {
days: { date: string; usage?: Usage["days"][number] }[]; days: { date: string; usage?: DayTotal }[];
models?: Usage["providers_30d"]; models?: Usage["providers_30d"];
modelDays?: Usage["model_days_30d"]; modelDays?: Usage["model_days_30d"];
onOpenChange?: (open: boolean) => void;
loading?: boolean;
}) { }) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 0 }); const percent = usageFormats(i18n.language).percent;
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }); const sum = (key: "total_tokens" | "estimated_tokens") =>
const sum = (key: "total_tokens" | "requests" | "cache_read_tokens" | "cache_read_observed_input_tokens") =>
days.reduce((total, day) => total + (day.usage?.[key] ?? 0), 0); days.reduce((total, day) => total + (day.usage?.[key] ?? 0), 0);
const total = sum("total_tokens"); const total = sum("total_tokens");
const observed = sum("cache_read_observed_input_tokens"); const estimated = sum("estimated_tokens");
const metrics = [
[t("settings.usage.totalTokens"), number.format(total)],
[t("settings.usage.requests"), number.format(sum("requests"))],
[t("settings.usage.cacheHitRate"), observed ? percent.format(sum("cache_read_tokens") / observed) : "—"],
];
return ( return (
<DialogLayoutContext.Provider value={null}> <DialogLayoutContext.Provider value={null}>
<Dialog> <Dialog onOpenChange={onOpenChange}>
<DialogTrigger asChild> <DialogTrigger asChild>
<button type="button" className="settings-hover flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-xs text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"> <button type="button" className="settings-hover flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-xs text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">
{t("settings.usage.viewDetails")}<ChevronRight className="size-3.5" aria-hidden /> {t("settings.usage.viewDetails")}<ChevronRight className="size-3.5" aria-hidden />
</button> </button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="w-[min(1100px,calc(100vw-32px))] max-w-none gap-5 p-5 pt-10 sm:p-7 sm:pt-10" aria-describedby={undefined}> <DialogContent className="w-[min(1100px,calc(100vw-32px))] max-w-none gap-5 p-5 pt-10 sm:p-7 sm:pt-10" aria-describedby={undefined}>
<DialogTitle className="sr-only">{t("settings.usage.shortTitle")}</DialogTitle> <div className="flex items-baseline justify-between gap-4 pr-8">
<dl className="grid grid-cols-3 gap-3"> <DialogTitle className="text-sm font-medium">{t("settings.usage.shortTitle")}</DialogTitle>
{metrics.map(([label, value], index) => <div key={label} title={index === 2 ? t("settings.usage.cacheRateHelp") : undefined}> <span className="text-[11px] text-muted-foreground">{t("settings.usage.last30Days", { defaultValue: "Last 30 days" })}</span>
<dt className="text-xs text-muted-foreground">{label}</dt> </div>
<dd className="mt-1 text-lg font-medium tabular-nums sm:text-2xl">{value}</dd> {estimated > 0 && total > 0 && (
</div>)} <p className="text-[11px] text-muted-foreground">
</dl> {t("settings.usage.estimatedShare", {
{modelDays?.length ? <TokenUsageModelTrend days={days} modelDays={modelDays} models={models} /> : <p className="text-sm text-muted-foreground">{t("settings.usage.modelsUnavailable")}</p>} defaultValue: "{{percent}} of tokens are estimated",
percent: percent(estimated / total),
})}
</p>
)}
{modelDays?.length ? <TokenUsageModelTrend days={days} modelDays={modelDays} models={models} /> : <p className="text-sm text-muted-foreground">{t(loading ? "common.loading" : "settings.usage.modelsUnavailable")}</p>}
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</DialogLayoutContext.Provider> </DialogLayoutContext.Provider>
@@ -1,10 +1,14 @@
import { Fragment } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { SettingsPayload } from "@/lib/types"; import type { SettingsPayload } from "@/lib/types";
import { usageFormats, usageSpeed } from "@/lib/usage-number";
import { normalizeUsageModel } from "@/lib/usage-model";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { UsageAxis, UsageDateAxis, usageAxisTicks, usagePeakCenter } from "@/components/settings/usage-chart";
type Usage = NonNullable<SettingsPayload["usage"]>; type Usage = NonNullable<SettingsPayload["usage"]>;
const COLORS = ["bg-orange-500", "bg-amber-500", "bg-stone-500", "bg-orange-300", "bg-zinc-400", "bg-neutral-200 dark:bg-neutral-600"]; const COLORS = ["bg-orange-600 dark:bg-orange-500", "bg-amber-300 dark:bg-amber-300", "bg-stone-700 dark:bg-stone-300", "bg-orange-300 dark:bg-orange-200", "bg-zinc-500 dark:bg-neutral-500", "bg-neutral-400 dark:bg-neutral-600"];
export function TokenUsageModelTrend({ days, modelDays, models }: { export function TokenUsageModelTrend({ days, modelDays, models }: {
days: { date: string; usage?: Usage["days"][number] }[]; days: { date: string; usage?: Usage["days"][number] }[];
@@ -12,31 +16,57 @@ export function TokenUsageModelTrend({ days, modelDays, models }: {
models?: Usage["providers_30d"]; models?: Usage["providers_30d"];
}) { }) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const number = new Intl.NumberFormat(i18n.language); const { display, exact, compact, percent, seconds, date: formatDay } = usageFormats(i18n.language);
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0); const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0);
const modelUsage = new Map((models ?? []).map(model => [JSON.stringify([model.provider, model.model]), model])); // Group by provider and normalized model, so one model is never split across
const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 }); // `openai-codex/…` and bare ids.
const modelKey = (provider: string, model: string) => JSON.stringify([provider, normalizeUsageModel(provider, model)]);
const modelUsage = new Map<string, { cache_read_tokens: number; cache_read_observed_input_tokens: number }>();
for (const model of models ?? []) {
const key = modelKey(model.provider, model.model);
const entry = modelUsage.get(key) ?? { cache_read_tokens: 0, cache_read_observed_input_tokens: 0 };
entry.cache_read_tokens += model.cache_read_tokens ?? 0;
entry.cache_read_observed_input_tokens += model.cache_read_observed_input_tokens ?? 0;
modelUsage.set(key, entry);
}
const dates = new Set(days.map(day => day.date)); const dates = new Set(days.map(day => day.date));
const totals = new Map<string, { label: string; total: number }>(); const totals = new Map<string, { label: string; total: number }>();
const daily = new Map<string, Map<string, number>>(); const daily = new Map<string, Map<string, { tokens: number; measured: number; generationMs: number; ttftMs: number; timed: number; cacheRead: number; cacheObserved: number }>>();
for (const row of modelDays) { for (const row of modelDays) {
if (!dates.has(row.date) || row.total_tokens <= 0) continue; if (!dates.has(row.date) || row.total_tokens <= 0) continue;
const key = JSON.stringify([row.provider, row.model]); const label = normalizeUsageModel(row.provider, row.model);
const item = totals.get(key) ?? { label: row.model, total: 0 }; const key = JSON.stringify([row.provider, label]);
const item = totals.get(key) ?? { label, total: 0 };
item.total += row.total_tokens; item.total += row.total_tokens;
totals.set(key, item); totals.set(key, item);
const bucket = daily.get(row.date) ?? new Map<string, number>(); type Bucket = { tokens: number; measured: number; generationMs: number; ttftMs: number; timed: number; cacheRead: number; cacheObserved: number };
bucket.set(key, (bucket.get(key) ?? 0) + row.total_tokens); const bucket = daily.get(row.date) ?? new Map<string, Bucket>();
const entry = bucket.get(key) ?? { tokens: 0, measured: 0, generationMs: 0, ttftMs: 0, timed: 0, cacheRead: 0, cacheObserved: 0 };
entry.tokens += row.total_tokens;
entry.measured += row.measured_output_tokens ?? 0;
entry.generationMs += row.generation_ms ?? 0;
entry.ttftMs += row.ttft_ms ?? 0;
entry.timed += row.timed_requests ?? 0;
entry.cacheRead += row.cache_read_tokens ?? 0;
entry.cacheObserved += row.cache_read_observed_input_tokens ?? 0;
bucket.set(key, entry);
daily.set(row.date, bucket); daily.set(row.date, bucket);
} }
const series = [...totals].sort((a, b) => b[1].total - a[1].total).slice(0, 5); const series = [...totals].sort((a, b) => b[1].total - a[1].total).slice(0, 5);
const otherLabel = t("settings.usage.otherModels", { defaultValue: "Other / unattributed" }); const otherLabel = t("settings.usage.otherModels", { defaultValue: "Other / unattributed" });
const columns = days.map(day => { const columns = days.map(day => {
const bucket = daily.get(day.date); const bucket = daily.get(day.date);
const values = series.map(([key]) => bucket?.get(key) ?? 0); const values = series.map(([key]) => bucket?.get(key)?.tokens ?? 0);
const stats = series.map(([key]) => {
const entry = bucket?.get(key);
return {
speed: entry ? usageSpeed(entry.measured, entry.generationMs) : null,
ttft: entry && entry.timed > 0 ? entry.ttftMs / entry.timed : null,
hit: entry && entry.cacheObserved > 0 ? entry.cacheRead / entry.cacheObserved : null,
};
});
const total = day.usage?.total_tokens ?? 0; const total = day.usage?.total_tokens ?? 0;
return { date: day.date, total, requests: day.usage?.requests ?? 0, values: [...values, Math.max(0, total - values.reduce((a, b) => a + b, 0))] }; return { date: day.date, total, requests: day.usage?.requests ?? 0, values: [...values, Math.max(0, total - values.reduce((a, b) => a + b, 0))], stats: [...stats, { speed: null, ttft: null, hit: null }] };
}); });
const peak = Math.max(0, ...columns.map(column => column.total)); const peak = Math.max(0, ...columns.map(column => column.total));
if (!peak || !series.length) return null; if (!peak || !series.length) return null;
@@ -44,53 +74,70 @@ export function TokenUsageModelTrend({ days, modelDays, models }: {
const color = (index: number) => index === series.length ? COLORS[5] : COLORS[index]; const color = (index: number) => index === series.length ? COLORS[5] : COLORS[index];
const hasOther = columns.some(column => column.values[series.length] > 0); const hasOther = columns.some(column => column.values[series.length] > 0);
const title = t("settings.usage.modelTrend", { defaultValue: "Model usage over time" }); const title = t("settings.usage.modelTrend", { defaultValue: "Model usage over time" });
const average = total / columns.length;
const peakIndex = columns.findIndex(column => column.total === peak);
const peakCenter = usagePeakCenter(columns.length, peakIndex);
const ticks = usageAxisTicks(peak, average);
// Missing telemetry reads as `—`; 0 tok/s would look like a stall. Value and
// unit stay in separate columns so both line up down the tooltip.
const speed = (value: number | null): [string, string] =>
value == null ? ["—", ""] : [display(Math.round(value)), "tok/s"];
const firstToken = (value: number | null): [string, string] =>
value == null ? ["—", ""] : [seconds(value), "s"];
const spoken = (stats: { speed: number | null; ttft: number | null; hit: number | null }) =>
`${stats.speed == null ? "" : `, ${Math.round(stats.speed)} tok/s`}${stats.ttft == null ? "" : `, ${seconds(stats.ttft)}s to first token`}${stats.hit == null ? "" : `, ${percent(stats.hit)} cache hit`}`;
return <section className="mt-2"> return <section className="mt-2">
<h3 className="mb-4 text-sm font-medium">{title}</h3> <div className="relative pl-11">
<div className="relative pl-9">
<div className="relative h-[clamp(144px,30vh,280px)]" data-model-usage-plot> <div className="relative h-[clamp(144px,30vh,280px)]" data-model-usage-plot>
<div className="pointer-events-none absolute inset-y-0 -left-9 right-0" aria-hidden> <UsageAxis ticks={ticks} format={compact} gridlineAttribute="data-model-usage-gridline" />
{[peak, peak / 2, 0].map((value, index) => <div key={index} className="absolute inset-x-0 flex items-center gap-2" style={{ top: `${index * 50}%` }}> <div role="group" aria-label={title} className="relative grid h-full grid-cols-[repeat(30,minmax(0,1fr))]">
<span className="absolute top-0 w-7 -translate-y-1/2 text-right text-[10px] tabular-nums text-muted-foreground">{compact.format(value)}</span> <TooltipProvider delayDuration={0} disableHoverableContent>
<span className="ml-9 flex-1 border-t border-border/40" data-model-usage-gridline={index} />
</div>)}
</div>
<div role="group" aria-label={title} className="relative grid h-full grid-cols-[repeat(30,minmax(0,1fr))] gap-px">
<TooltipProvider>
{columns.map(column => column.total === 0 ? ( {columns.map(column => column.total === 0 ? (
<span key={column.date} role="img" aria-label={`${column.date}: ${number.format(0)} tokens`} /> <span key={column.date} role="img" aria-label={`${column.date}: ${exact(0)} tokens`} />
) : <Tooltip key={column.date}> ) : <Tooltip key={column.date}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<span role="img" tabIndex={0} aria-label={`${column.date}: ${number.format(column.total)} tokens; ${column.values.map((value, index) => `${labels[index]}: ${number.format(value)}`).join(", ")}`} className="flex min-w-0 items-end focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500"> <span role="img" tabIndex={0} aria-label={`${column.date}: ${exact(column.total)} tokens; ${column.values.map((value, index) => `${labels[index]}: ${exact(value)}${spoken(column.stats[index])}`).join(", ")}`} className="flex min-w-0 items-end pr-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500">
<span className="flex w-full flex-col-reverse" style={{ height: `${column.total / peak * 100}%` }}> <span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm" style={{ height: `${column.total / peak * 100}%` }}>
{column.values.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", color(index))} style={{ height: `${value / column.total * 100}%` }} />)} {column.values.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", color(index))} style={{ height: `${value / column.total * 100}%` }} />)}
</span> </span>
</span> </span>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent className="w-72 max-w-[85vw] p-3"> <TooltipContent className="w-[27rem] max-w-[90vw] p-3">
<p className="mb-2 text-xs font-medium">{column.date}</p> <dl className="grid grid-cols-[minmax(0,1fr)_auto_auto_auto_auto_auto_auto] items-baseline gap-x-2 gap-y-2 text-xs">
<dl className="space-y-2"> <dt className="whitespace-nowrap text-xs font-medium">{column.date}</dt>
{column.values.map((value, index) => ({ value, index })).filter(item => item.value > 0).sort((a, b) => b.value - a.value).map(({ value, index }) => <div key={index} className="flex items-start justify-between gap-3 text-xs"> <dd />
<dt className="flex min-w-0 items-start gap-2"><span aria-hidden className={cn("mt-0.5 h-3 w-1 shrink-0 rounded-full", color(index))} /><span className="break-words">{labels[index]}</span></dt><dd className="shrink-0 tabular-nums">{number.format(value)}</dd> <dd className="text-[11px] text-muted-foreground">tok/s</dd>
</div>)} <dd className="text-right text-[11px] text-muted-foreground">TTFT</dd>
<div className="flex justify-between border-t border-border/50 pt-2 text-xs font-medium"><dt>{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}</dt><dd className="tabular-nums">{number.format(column.total)}</dd></div> <dd className="text-[11px] text-muted-foreground">s</dd>
<div className="flex justify-between text-xs text-muted-foreground"><dt>{t("settings.usage.requests")}</dt><dd className="tabular-nums">{number.format(column.requests)}</dd></div> <dd className="text-right text-[11px] text-muted-foreground">{t("settings.usage.cacheHitRate")}</dd>
<dd className="text-right text-[11px] text-muted-foreground">tokens</dd>
{column.values.map((value, index) => ({ value, index })).filter(item => item.value > 0).sort((a, b) => b.value - a.value).map(({ value, index }) => {
const [speedValue, speedUnit] = speed(column.stats[index].speed);
const [ttftValue, ttftUnit] = firstToken(column.stats[index].ttft);
const hit = column.stats[index].hit;
return <Fragment key={index}>
<dt className="flex min-w-0 items-start gap-2"><span aria-hidden className={cn("mt-0.5 h-3 w-1 shrink-0 rounded-full", color(index))} /><span className="break-words">{labels[index]}</span></dt><dd className="text-right tabular-nums">{speedValue}</dd><dd className="w-8 tabular-nums">{speedUnit}</dd><dd className="text-right tabular-nums">{ttftValue}</dd><dd className="w-2 tabular-nums">{ttftUnit}</dd><dd className="text-right tabular-nums">{hit == null ? "—" : percent(hit)}</dd><dd className="text-right tabular-nums">{display(value)}</dd>
</Fragment>;
})}
<dt className="col-span-6 border-t border-border/50 pt-2 font-medium">{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}</dt><dd className="border-t border-border/50 pt-2 text-right font-medium tabular-nums">{display(column.total)}</dd>
<dt className="col-span-6 text-muted-foreground">{t("settings.usage.requests")}</dt><dd className="text-right tabular-nums text-muted-foreground">{display(column.requests)}</dd>
</dl> </dl>
</TooltipContent> </TooltipContent>
</Tooltip>)} </Tooltip>)}
</TooltipProvider> </TooltipProvider>
</div> </div>
</div> </div>
<div className="relative mt-2 flex justify-between text-[10px] tabular-nums text-muted-foreground"><span>{days[0].date.slice(5)}</span><span>{days[14].date.slice(5)}</span><span>{days[days.length - 1].date.slice(5)}</span></div> <UsageDateAxis start={days[0].date} end={days[days.length - 1].date} peak={days[peakIndex].date} peakCenter={peakCenter} format={formatDay} />
</div> </div>
<TooltipProvider> <TooltipProvider delayDuration={0} disableHoverableContent>
<div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-[11px] text-muted-foreground sm:grid-cols-3"> <div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-[11px] text-muted-foreground sm:grid-cols-3">
{labels.map((label, index) => { {labels.map((label, index) => {
if (index === series.length && !hasOther) return null; if (index === series.length && !hasOther) return null;
const model = index < series.length ? modelUsage.get(series[index][0]) : undefined; const model = index < series.length ? modelUsage.get(series[index][0]) : undefined;
const tokens = columns.reduce((sum, column) => sum + column.values[index], 0); const tokens = columns.reduce((sum, column) => sum + column.values[index], 0);
const rate = model?.cache_read_observed_input_tokens ? percent.format(model.cache_read_tokens / model.cache_read_observed_input_tokens) : "—"; const rate = model?.cache_read_observed_input_tokens ? percent(model.cache_read_tokens / model.cache_read_observed_input_tokens) : "—";
const parts = [ const parts = [
[t("settings.usage.totalTokens"), `${number.format(tokens)} (${percent.format(tokens / total)})`], [t("settings.usage.totalTokens"), `${display(tokens)} (${percent(tokens / total)})`],
[t("settings.usage.cacheHitRate"), rate], [t("settings.usage.cacheHitRate"), rate],
]; ];
return <Tooltip key={index}> return <Tooltip key={index}>
@@ -0,0 +1,56 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { TokenUsageCard } from "@/components/settings/TokenUsageCard";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { fetchSettingsUsage } from "@/lib/api";
import type { SettingsPayload } from "@/lib/types";
import { useClient } from "@/providers/ClientProvider";
type Usage = NonNullable<SettingsPayload["usage"]>;
export function TokenUsageOverview({ initialUsage, timeZone }: { initialUsage?: Usage; timeZone?: string }) {
const { client, getToken } = useClient();
const pageVisible = usePageVisibility();
const [details, setDetails] = useState(false);
const [usage, setUsage] = useState(initialUsage);
const [modelsLoading, setModelsLoading] = useState(false);
const cache = useMemo<{ overview?: Usage; models?: Usage }>(() => ({ overview: initialUsage }), [client, initialUsage, timeZone]);
const previousDetails = useRef(false);
useEffect(() => setUsage(cache.overview), [cache]);
useEffect(() => {
const closingDetails = previousDetails.current && !details;
previousDetails.current = details;
if (!pageVisible) return;
if (details && cache.models) setUsage(cache.models);
const controller = new AbortController();
let refreshing = false;
const refresh = async () => {
if (refreshing) return;
refreshing = true;
const key = details ? "models" : "overview";
if (details) setModelsLoading(!cache.models);
try {
const next = await fetchSettingsUsage(getToken(), { details, cached: cache[key], signal: controller.signal });
if (!controller.signal.aborted) {
cache[key] = next;
setUsage(next);
}
} catch {
// Keep the last telemetry snapshot during transient failures.
} finally {
if (!controller.signal.aborted) setModelsLoading(false);
refreshing = false;
}
};
if (!closingDetails) void refresh();
const interval = window.setInterval(() => void refresh(), 5000);
window.addEventListener("focus", refresh);
return () => {
controller.abort();
window.clearInterval(interval);
window.removeEventListener("focus", refresh);
};
}, [cache, details, getToken, pageVisible]);
return <TokenUsageCard usage={usage} timeZone={timeZone} detailsLoading={modelsLoading} onDetailsOpenChange={setDetails} />;
}
@@ -4,7 +4,7 @@ import {
ImageGenerationIcon, ImageGenerationIcon,
VoiceIcon, VoiceIcon,
} from "@/components/icons/product-icons"; } from "@/components/icons/product-icons";
import { useContext, useEffect, type Dispatch, type SetStateAction } from "react"; import { useContext, useEffect, type Dispatch, type ReactNode, type SetStateAction } from "react";
import { import {
ChevronRight, ChevronRight,
type LucideIcon, type LucideIcon,
@@ -39,10 +39,12 @@ export function OverviewSettings({
settings, settings,
onSelectSection, onSelectSection,
showBrandLogos, showBrandLogos,
usageCard,
}: { }: {
settings: SettingsPayload; settings: SettingsPayload;
onSelectSection: (section: SettingsSectionKey) => void; onSelectSection: (section: SettingsSectionKey) => void;
showBrandLogos: boolean; showBrandLogos: boolean;
usageCard?: ReactNode;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
@@ -76,7 +78,7 @@ export function OverviewSettings({
return ( return (
<div className="settings-stack"> <div className="settings-stack">
<section className="rounded-panel bg-settings-surface p-6"> <section className="rounded-panel bg-settings-surface p-6">
<TokenUsageCard usage={settings.usage} timeZone={settings.agent.timezone} /> {usageCard ?? <TokenUsageCard usage={settings.usage} timeZone={settings.agent.timezone} />}
</section> </section>
<section> <section>
@@ -0,0 +1,67 @@
/**
* Shared chrome for the two usage charts: the peak/average axis and the date
* axis below the bars. Both charts draw 30 columns over the same window, so
* they must not drift apart in scale, ticks, or labels.
*/
export interface UsageAxisTick {
value: number;
top: number;
/** Stable identity for `data-*-gridline`, independent of which ticks render. */
gridline: 0 | 1 | 2;
}
/** Peak at the top, daily average as the reference line, zero as the baseline. */
export function usageAxisTicks(peak: number, average: number): UsageAxisTick[] {
if (peak <= 0) return [];
const meanTop = Math.min(100, (1 - average / peak) * 100);
const ticks: UsageAxisTick[] = [{ value: peak, top: 0, gridline: 0 }];
// A mean hugging the peak would print two labels on top of each other.
if (meanTop >= 12) ticks.push({ value: average, top: meanTop, gridline: 1 });
ticks.push({ value: 0, top: 100, gridline: 2 });
return ticks;
}
/** Horizontal center of the peak column, in percent of the plot width. */
export function usagePeakCenter(columns: number, peakIndex: number): number {
return columns ? ((peakIndex + 0.5) / columns) * 100 : 0;
}
export function UsageAxis({ ticks, format, gridlineAttribute }: {
ticks: UsageAxisTick[];
format: (value: number) => string;
gridlineAttribute: "data-usage-gridline" | "data-model-usage-gridline";
}) {
return (
<div className="pointer-events-none absolute inset-y-0 -left-11 right-0" aria-hidden>
{ticks.map(tick => (
<div key={tick.gridline} className="absolute inset-x-0 flex items-center gap-2" style={{ top: `${tick.top}%` }}>
{tick.value > 0 && <span className="absolute top-0 w-9 -translate-y-1/2 whitespace-nowrap text-right text-[10px] tabular-nums text-muted-foreground">{format(tick.value)}</span>}
<span className="ml-11 flex-1 border-t border-border/40" {...{ [gridlineAttribute]: tick.gridline }} />
</div>
))}
</div>
);
}
export function UsageDateAxis({ start, peak, end, peakCenter, format }: {
start: string;
peak: string;
end: string;
peakCenter: number;
format: (date: string) => string;
}) {
// Keep the peak label inside the plot instead of letting it hang off an edge.
const peakStyle = peakCenter < 17
? { left: 0 }
: peakCenter > 83
? { left: "100%", transform: "translateX(-100%)" }
: { left: `${peakCenter}%`, transform: "translateX(-50%)" };
return (
<div className="relative mt-2 h-4 text-[10px] tabular-nums text-muted-foreground" aria-hidden>
{peakCenter > 20 && <span className="absolute left-0 top-0">{format(start)}</span>}
{peakCenter < 80 && <span className="absolute right-0 top-0">{format(end)}</span>}
<span className="absolute top-0 whitespace-nowrap text-orange-500 dark:text-orange-400" style={peakStyle}>{format(peak)}</span>
</div>
);
}
@@ -36,7 +36,7 @@ import { useSystemSettingsState } from "@/components/settings/system/useSystemSe
import { getToolsCatalog } from "@/lib/tools-catalog-cache"; import { getToolsCatalog } from "@/lib/tools-catalog-cache";
import { usePageVisibility } from "@/hooks/usePageVisibility"; import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useEditCompletion } from "@/components/settings/shared/useEditCompletion"; import { useEditCompletion } from "@/components/settings/shared/useEditCompletion";
import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api"; import { cancelProviderOAuth, fetchSettings } from "@/lib/api";
import { import {
LOCAL_PREFS_CHANGED_EVENT, LOCAL_PREFS_CHANGED_EVENT,
readLocalPreferences, readLocalPreferences,
@@ -204,7 +204,7 @@ export function useSettingsController({
const requestInitialSettings = latestInitialSettingsRef.current; const requestInitialSettings = latestInitialSettingsRef.current;
const requestDrafts = draftsRef.current; const requestDrafts = draftsRef.current;
if (showLoading) setLoading(true); if (showLoading) setLoading(true);
fetchSettings(getToken()) fetchSettings(getToken(), "", client)
.then((payload) => { .then((payload) => {
if (!cancelled && latestInitialSettingsRef.current === requestInitialSettings) { if (!cancelled && latestInitialSettingsRef.current === requestInitialSettings) {
const current = draftsRef.current; const current = draftsRef.current;
@@ -228,37 +228,8 @@ export function useSettingsController({
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [applyPayload, getToken]); }, [applyPayload, client, getToken]);
const hasSettings = settings !== null;
useEffect(() => {
if (activeSection !== "overview" || !hasSettings || !pageVisible) return;
let cancelled = false;
let refreshing = false;
const refresh = async () => {
if (refreshing) return;
refreshing = true;
try {
const usage = await fetchSettingsUsage(getToken());
if (!cancelled) {
setSettings((current) => (current ? { ...current, usage } : current));
}
} catch {
// Usage is best-effort telemetry; the settings snapshot remains usable.
} finally {
refreshing = false;
}
};
void refresh();
const interval = window.setInterval(() => void refresh(), 5000);
const onFocus = () => void refresh();
window.addEventListener("focus", onFocus);
return () => {
cancelled = true;
window.clearInterval(interval);
window.removeEventListener("focus", onFocus);
};
}, [activeSection, getToken, hasSettings, pageVisible]);
const { refreshAutomations } = useSystemSettingsEffects({ const { refreshAutomations } = useSystemSettingsEffects({
state: systemState, state: systemState,
activeSection, activeSection,
@@ -363,7 +334,7 @@ export function useSettingsController({
const requestDrafts = draftsRef.current; const requestDrafts = draftsRef.current;
try { try {
const nextToken = await onNativeEngineRestart(); const nextToken = await onNativeEngineRestart();
const payload = await fetchSettings(nextToken); const payload = await fetchSettings(nextToken, "", client);
const current = draftsRef.current; const current = draftsRef.current;
applyPayload(payload, { applyPayload(payload, {
preserveAgentForm: current.form !== requestDrafts.form, preserveAgentForm: current.form !== requestDrafts.form,
@@ -399,7 +370,7 @@ export function useSettingsController({
setHostEngineApplying(true); setHostEngineApplying(true);
try { try {
const nextToken = await onNativeEngineRestart(); const nextToken = await onNativeEngineRestart();
const refreshed = await fetchSettings(nextToken); const refreshed = await fetchSettings(nextToken, "", client);
applyPayload(refreshed, { preserveAgentForm: true, preserveCapabilityForms: true }); applyPayload(refreshed, { preserveAgentForm: true, preserveCapabilityForms: true });
setPendingRestartSections(EMPTY_PENDING_RESTART_SECTIONS); setPendingRestartSections(EMPTY_PENDING_RESTART_SECTIONS);
setError(null); setError(null);
@@ -4,8 +4,11 @@ import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
function TooltipProvider(props: Omit<React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Provider>, "delayDuration" | "skipDelayDuration">) { function TooltipProvider({
return <TooltipPrimitive.Provider {...props} delayDuration={500} skipDelayDuration={0} />; delayDuration = 500,
...props
}: Omit<React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Provider>, "delayDuration" | "skipDelayDuration"> & { delayDuration?: number }) {
return <TooltipPrimitive.Provider {...props} delayDuration={delayDuration} skipDelayDuration={0} />;
} }
const Tooltip = TooltipPrimitive.Root; const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger; const TooltipTrigger = TooltipPrimitive.Trigger;
+9 -4
View File
@@ -220,10 +220,15 @@ const usage: Usage = (() => {
return { days, total_tokens: total, total_tokens_30d: total, total_tokens_365d: total, return { days, total_tokens: total, total_tokens_30d: total, total_tokens_365d: total,
peak_day_tokens: Math.max(...days.map((day) => day.total_tokens)), current_streak_days: 3, longest_streak_days: 6, peak_day_tokens: Math.max(...days.map((day) => day.total_tokens)), current_streak_days: 3, longest_streak_days: 6,
active_days_30d: days.filter((day) => day.total_tokens > 0).length, requests_30d: days.reduce((sum, day) => sum + day.requests, 0), active_days_30d: days.filter((day) => day.total_tokens > 0).length, requests_30d: days.reduce((sum, day) => sum + day.requests, 0),
model_days_30d: days.flatMap((day) => [ model_days_30d: days.flatMap((day, index) => [
{ date: day.date, provider: "openai", model: "gpt-5.4", total_tokens: day.total_tokens * 0.6 }, { provider: "openai", model: "gpt-5.4", share: 0.6, speed: 48 + index % 7 },
{ date: day.date, provider: "anthropic", model: "claude-sonnet-4", total_tokens: day.total_tokens * 0.4 }, { provider: "anthropic", model: "claude-sonnet-4", share: 0.4, speed: 33 + index % 5 },
]) }; ].map(({ provider, model, share, speed }) => {
const totalTokens = day.total_tokens * share;
const measured = Math.round(totalTokens * 0.4);
const generationMs = Math.round(measured / speed * 1000);
return { date: day.date, provider, model, total_tokens: totalTokens, measured_output_tokens: measured, generation_ms: generationMs, ttft_ms: Math.round(generationMs * 0.6), timed_requests: 1, cache_read_tokens: Math.round(totalTokens * 0.5), cache_read_observed_input_tokens: Math.round(totalTokens * 0.8) };
})) };
})(); })();
function UsagePreview() { function UsagePreview() {
+6 -3
View File
@@ -1323,17 +1323,18 @@
"shortTitle": "Token usage", "shortTitle": "Token usage",
"viewDetails": "View details", "viewDetails": "View details",
"cacheHitRate": "Cache hit rate", "cacheHitRate": "Cache hit rate",
"cacheRateHelp": "Cache hit rate excludes input with unknown cache status.",
"dailyTrend": "Daily tokens", "dailyTrend": "Daily tokens",
"bySource": "Usage by source", "bySource": "Usage by source",
"modelTrend": "Model trends", "modelTrend": "Model trends",
"modelsUnavailable": "No model breakdown available.", "modelsUnavailable": "No model breakdown available.",
"otherModels": "Other / unattributed", "otherModels": "Other models",
"unclassified": "Unclassified", "unclassified": "Unclassified",
"unavailable": "Usage data is unavailable.", "unavailable": "Usage data is unavailable.",
"noActivity": "No token usage in the last 30 days.", "noActivity": "No token usage in the last 30 days.",
"last30Days": "Last 30 days",
"cachedInput": "Cached input", "cachedInput": "Cached input",
"cacheMiss": "Cache miss", "cacheMiss": "Cache miss",
"cacheWrite": "Cache write",
"cacheUnknown": "Unknown status", "cacheUnknown": "Unknown status",
"outputTokens": "Output", "outputTokens": "Output",
"otherTokens": "Other tokens", "otherTokens": "Other tokens",
@@ -1347,7 +1348,9 @@
"dream": "Memory", "dream": "Memory",
"system": "Auxiliary calls" "system": "Auxiliary calls"
}, },
"systemHelp": "Includes internal tasks and calls without a recorded source." "systemHelp": "Includes internal tasks and calls without a recorded source.",
"failedRequests": "{{count}} failed",
"estimatedShare": "{{percent}} of tokens are estimated"
}, },
"providers": { "providers": {
"manageProviders": "Manage providers", "manageProviders": "Manage providers",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Uso de tokens", "shortTitle": "Uso de tokens",
"viewDetails": "Ver detalles", "viewDetails": "Ver detalles",
"cacheHitRate": "Tasa de aciertos de caché", "cacheHitRate": "Tasa de aciertos de caché",
"cacheRateHelp": "La tasa excluye las entradas cuyo estado de caché se desconoce.",
"dailyTrend": "Tokens diarios", "dailyTrend": "Tokens diarios",
"systemHelp": "Incluye tareas internas y llamadas sin origen registrado.", "systemHelp": "Incluye tareas internas y llamadas sin origen registrado.",
"bySource": "Uso por origen", "bySource": "Uso por origen",
"modelTrend": "Tendencias por modelo", "modelTrend": "Tendencias por modelo",
"modelsUnavailable": "Sin desglose por modelo.", "modelsUnavailable": "Sin desglose por modelo.",
"otherModels": "Otros / sin atribuir", "otherModels": "Otros modelos",
"unclassified": "Sin clasificar", "unclassified": "Sin clasificar",
"unavailable": "Los datos de uso no están disponibles.", "unavailable": "Los datos de uso no están disponibles.",
"noActivity": "Sin uso de tokens en los últimos 30 días.", "noActivity": "Sin uso de tokens en los últimos 30 días.",
"last30Days": "Últimos 30 días",
"cachedInput": "Entrada en caché", "cachedInput": "Entrada en caché",
"cacheMiss": "Fallo de caché", "cacheMiss": "Fallo de caché",
"cacheWrite": "Escritura de caché",
"cacheUnknown": "Estado desconocido", "cacheUnknown": "Estado desconocido",
"outputTokens": "Salida", "outputTokens": "Salida",
"otherTokens": "Otros tokens", "otherTokens": "Otros tokens",
@@ -959,7 +960,9 @@
"cron": "Automatizaciones", "cron": "Automatizaciones",
"dream": "Consolidación de memoria", "dream": "Consolidación de memoria",
"system": "Llamadas auxiliares" "system": "Llamadas auxiliares"
} },
"failedRequests": "{{count}} fallidas",
"estimatedShare": "El {{percent}} de los tokens es estimado"
}, },
"providers": { "providers": {
"manageProviders": "Gestionar proveedores", "manageProviders": "Gestionar proveedores",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Utilisation des tokens", "shortTitle": "Utilisation des tokens",
"viewDetails": "Voir les détails", "viewDetails": "Voir les détails",
"cacheHitRate": "Taux de réussite du cache", "cacheHitRate": "Taux de réussite du cache",
"cacheRateHelp": "Le taux exclut les entrées dont l’état du cache est inconnu.",
"dailyTrend": "Tokens quotidiens", "dailyTrend": "Tokens quotidiens",
"systemHelp": "Inclut les tâches internes et les appels sans source enregistrée.", "systemHelp": "Inclut les tâches internes et les appels sans source enregistrée.",
"bySource": "Utilisation par source", "bySource": "Utilisation par source",
"modelTrend": "Tendances des modèles", "modelTrend": "Tendances des modèles",
"modelsUnavailable": "Aucune ventilation par modèle disponible.", "modelsUnavailable": "Aucune ventilation par modèle disponible.",
"otherModels": "Autres / non attribués", "otherModels": "Autres modèles",
"unclassified": "Non classé", "unclassified": "Non classé",
"unavailable": "Les données d’utilisation sont indisponibles.", "unavailable": "Les données d’utilisation sont indisponibles.",
"noActivity": "Aucun token utilisé au cours des 30 derniers jours.", "noActivity": "Aucun token utilisé au cours des 30 derniers jours.",
"last30Days": "30 derniers jours",
"cachedInput": "Entrée en cache", "cachedInput": "Entrée en cache",
"cacheMiss": "Cache manqué", "cacheMiss": "Cache manqué",
"cacheWrite": "Écriture de cache",
"cacheUnknown": "État inconnu", "cacheUnknown": "État inconnu",
"outputTokens": "Sortie", "outputTokens": "Sortie",
"otherTokens": "Autres tokens", "otherTokens": "Autres tokens",
@@ -959,7 +960,9 @@
"cron": "Automatisations", "cron": "Automatisations",
"dream": "Consolidation de la mémoire", "dream": "Consolidation de la mémoire",
"system": "Appels auxiliaires" "system": "Appels auxiliaires"
} },
"failedRequests": "{{count}} échecs",
"estimatedShare": "{{percent}} des tokens sont estimés"
}, },
"providers": { "providers": {
"manageProviders": "Gérer les fournisseurs", "manageProviders": "Gérer les fournisseurs",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Penggunaan token", "shortTitle": "Penggunaan token",
"viewDetails": "Lihat detail", "viewDetails": "Lihat detail",
"cacheHitRate": "Rasio cache hit", "cacheHitRate": "Rasio cache hit",
"cacheRateHelp": "Rasio tidak mencakup input dengan status cache yang tidak diketahui.",
"dailyTrend": "Token harian", "dailyTrend": "Token harian",
"systemHelp": "Termasuk tugas internal dan panggilan tanpa sumber tercatat.", "systemHelp": "Termasuk tugas internal dan panggilan tanpa sumber tercatat.",
"bySource": "Penggunaan berdasarkan sumber", "bySource": "Penggunaan berdasarkan sumber",
"modelTrend": "Tren model", "modelTrend": "Tren model",
"modelsUnavailable": "Rincian per model tidak tersedia.", "modelsUnavailable": "Rincian per model tidak tersedia.",
"otherModels": "Lainnya / belum dikategorikan", "otherModels": "Model lain",
"unclassified": "Tidak dikategorikan", "unclassified": "Tidak dikategorikan",
"unavailable": "Data penggunaan tidak tersedia.", "unavailable": "Data penggunaan tidak tersedia.",
"noActivity": "Tidak ada penggunaan token dalam 30 hari terakhir.", "noActivity": "Tidak ada penggunaan token dalam 30 hari terakhir.",
"last30Days": "30 hari terakhir",
"cachedInput": "Input tersedia di cache", "cachedInput": "Input tersedia di cache",
"cacheMiss": "Cache tidak ditemukan", "cacheMiss": "Cache tidak ditemukan",
"cacheWrite": "Penulisan cache",
"cacheUnknown": "Status tidak diketahui", "cacheUnknown": "Status tidak diketahui",
"outputTokens": "Output", "outputTokens": "Output",
"otherTokens": "Token lainnya", "otherTokens": "Token lainnya",
@@ -959,7 +960,9 @@
"cron": "Otomasi", "cron": "Otomasi",
"dream": "Penataan memori", "dream": "Penataan memori",
"system": "Panggilan pendukung" "system": "Panggilan pendukung"
} },
"failedRequests": "{{count}} gagal",
"estimatedShare": "{{percent}} token diperkirakan"
}, },
"providers": { "providers": {
"manageProviders": "Kelola penyedia", "manageProviders": "Kelola penyedia",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "トークン使用量", "shortTitle": "トークン使用量",
"viewDetails": "詳細を見る", "viewDetails": "詳細を見る",
"cacheHitRate": "キャッシュヒット率", "cacheHitRate": "キャッシュヒット率",
"cacheRateHelp": "キャッシュ状態が不明な入力はヒット率の計算から除外します。",
"dailyTrend": "毎日の Token", "dailyTrend": "毎日の Token",
"systemHelp": "内部タスクと記録された送信元がない呼び出しを含みます。", "systemHelp": "内部タスクと記録された送信元がない呼び出しを含みます。",
"bySource": "利用元別の使用量", "bySource": "利用元別の使用量",
"modelTrend": "モデルの推移", "modelTrend": "モデルの推移",
"modelsUnavailable": "モデル別の内訳はありません。", "modelsUnavailable": "モデル別の内訳はありません。",
"otherModels": "その他 / 未分類", "otherModels": "その他のモデル",
"unclassified": "未分類", "unclassified": "未分類",
"unavailable": "使用量データを取得できません。", "unavailable": "使用量データを取得できません。",
"noActivity": "過去30日間のトークン使用はありません。", "noActivity": "過去30日間のトークン使用はありません。",
"last30Days": "過去 30 日間",
"cachedInput": "キャッシュヒット", "cachedInput": "キャッシュヒット",
"cacheMiss": "キャッシュ未使用", "cacheMiss": "キャッシュ未使用",
"cacheWrite": "キャッシュ書き込み",
"cacheUnknown": "状態不明", "cacheUnknown": "状態不明",
"outputTokens": "出力", "outputTokens": "出力",
"otherTokens": "その他のトークン", "otherTokens": "その他のトークン",
@@ -959,7 +960,9 @@
"cron": "自動タスク", "cron": "自動タスク",
"dream": "メモリ整理", "dream": "メモリ整理",
"system": "補助処理" "system": "補助処理"
} },
"failedRequests": "失敗 {{count}} 件",
"estimatedShare": "トークンの {{percent}} は推定値"
}, },
"providers": { "providers": {
"manageProviders": "プロバイダーを管理", "manageProviders": "プロバイダーを管理",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "토큰 사용량", "shortTitle": "토큰 사용량",
"viewDetails": "자세히 보기", "viewDetails": "자세히 보기",
"cacheHitRate": "캐시 적중률", "cacheHitRate": "캐시 적중률",
"cacheRateHelp": "캐시 상태가 알려진 입력만 적중률 계산에 포함됩니다.",
"dailyTrend": "일일 Token", "dailyTrend": "일일 Token",
"systemHelp": "내부 작업과 출처가 기록되지 않은 호출을 포함합니다.", "systemHelp": "내부 작업과 출처가 기록되지 않은 호출을 포함합니다.",
"bySource": "출처별 사용량", "bySource": "출처별 사용량",
"modelTrend": "모델 추이", "modelTrend": "모델 추이",
"modelsUnavailable": "모델별 내역이 없습니다.", "modelsUnavailable": "모델별 내역이 없습니다.",
"otherModels": "기타 / 미분류", "otherModels": "기타 모델",
"unclassified": "미분류", "unclassified": "미분류",
"unavailable": "사용량 데이터를 사용할 수 없습니다.", "unavailable": "사용량 데이터를 사용할 수 없습니다.",
"noActivity": "최근 30일 동안 토큰 사용량이 없습니다.", "noActivity": "최근 30일 동안 토큰 사용량이 없습니다.",
"last30Days": "최근 30일",
"cachedInput": "캐시 적중", "cachedInput": "캐시 적중",
"cacheMiss": "캐시 미스", "cacheMiss": "캐시 미스",
"cacheWrite": "캐시 쓰기",
"cacheUnknown": "상태 알 수 없음", "cacheUnknown": "상태 알 수 없음",
"outputTokens": "출력", "outputTokens": "출력",
"otherTokens": "기타 토큰", "otherTokens": "기타 토큰",
@@ -959,7 +960,9 @@
"cron": "자동화", "cron": "자동화",
"dream": "기억 정리", "dream": "기억 정리",
"system": "보조 호출" "system": "보조 호출"
} },
"failedRequests": "실패 {{count}}회",
"estimatedShare": "토큰의 {{percent}}가 추정치"
}, },
"providers": { "providers": {
"manageProviders": "제공업체 관리", "manageProviders": "제공업체 관리",
+6 -3
View File
@@ -1143,18 +1143,19 @@
"shortTitle": "Uso de tokens", "shortTitle": "Uso de tokens",
"viewDetails": "Ver detalhes", "viewDetails": "Ver detalhes",
"cacheHitRate": "Taxa de acertos de cache", "cacheHitRate": "Taxa de acertos de cache",
"cacheRateHelp": "A taxa exclui entradas com estado de cache desconhecido.",
"dailyTrend": "Tokens diários", "dailyTrend": "Tokens diários",
"systemHelp": "Inclui tarefas internas e chamadas sem origem registrada.", "systemHelp": "Inclui tarefas internas e chamadas sem origem registrada.",
"bySource": "Uso por origem", "bySource": "Uso por origem",
"modelTrend": "Tendências dos modelos", "modelTrend": "Tendências dos modelos",
"modelsUnavailable": "Sem detalhamento por modelo.", "modelsUnavailable": "Sem detalhamento por modelo.",
"otherModels": "Outros / não atribuídos", "otherModels": "Outros modelos",
"unclassified": "Não classificado", "unclassified": "Não classificado",
"unavailable": "Os dados de uso estão indisponíveis.", "unavailable": "Os dados de uso estão indisponíveis.",
"noActivity": "Nenhum token usado nos últimos 30 dias.", "noActivity": "Nenhum token usado nos últimos 30 dias.",
"last30Days": "Últimos 30 dias",
"cachedInput": "Entrada em cache", "cachedInput": "Entrada em cache",
"cacheMiss": "Falha de cache", "cacheMiss": "Falha de cache",
"cacheWrite": "Gravação de cache",
"cacheUnknown": "Status desconhecido", "cacheUnknown": "Status desconhecido",
"outputTokens": "Saída", "outputTokens": "Saída",
"otherTokens": "Outros tokens", "otherTokens": "Outros tokens",
@@ -1167,7 +1168,9 @@
"cron": "Automações", "cron": "Automações",
"dream": "Consolidação de memória", "dream": "Consolidação de memória",
"system": "Chamadas auxiliares" "system": "Chamadas auxiliares"
} },
"failedRequests": "{{count}} falhas",
"estimatedShare": "{{percent}} dos tokens são estimados"
}, },
"providers": { "providers": {
"manageProviders": "Gerenciar provedores", "manageProviders": "Gerenciar provedores",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Mức dùng token", "shortTitle": "Mức dùng token",
"viewDetails": "Xem chi tiết", "viewDetails": "Xem chi tiết",
"cacheHitRate": "Tỷ lệ trúng bộ nhớ đệm", "cacheHitRate": "Tỷ lệ trúng bộ nhớ đệm",
"cacheRateHelp": "Tỷ lệ không tính đầu vào có trạng thái bộ nhớ đệm không rõ.",
"dailyTrend": "Token mỗi ngày", "dailyTrend": "Token mỗi ngày",
"systemHelp": "Gồm tác vụ nội bộ và lệnh gọi chưa ghi nguồn.", "systemHelp": "Gồm tác vụ nội bộ và lệnh gọi chưa ghi nguồn.",
"bySource": "Mức dùng theo nguồn", "bySource": "Mức dùng theo nguồn",
"modelTrend": "Xu hướng mô hình", "modelTrend": "Xu hướng mô hình",
"modelsUnavailable": "Chưa có chi tiết theo mô hình.", "modelsUnavailable": "Chưa có chi tiết theo mô hình.",
"otherModels": "Khác / chưa phân loại", "otherModels": "Mô hình khác",
"unclassified": "Chưa phân loại", "unclassified": "Chưa phân loại",
"unavailable": "Không có dữ liệu sử dụng.", "unavailable": "Không có dữ liệu sử dụng.",
"noActivity": "Không có token nào được sử dụng trong 30 ngày qua.", "noActivity": "Không có token nào được sử dụng trong 30 ngày qua.",
"last30Days": "30 ngày qua",
"cachedInput": "Đầu vào có trong bộ nhớ đệm", "cachedInput": "Đầu vào có trong bộ nhớ đệm",
"cacheMiss": "Không khớp cache", "cacheMiss": "Không khớp cache",
"cacheWrite": "Ghi bộ nhớ đệm",
"cacheUnknown": "Trạng thái chưa rõ", "cacheUnknown": "Trạng thái chưa rõ",
"outputTokens": "Đầu ra", "outputTokens": "Đầu ra",
"otherTokens": "Token khác", "otherTokens": "Token khác",
@@ -959,7 +960,9 @@
"cron": "Tự động hóa", "cron": "Tự động hóa",
"dream": "Sắp xếp bộ nhớ", "dream": "Sắp xếp bộ nhớ",
"system": "Lượt gọi phụ trợ" "system": "Lượt gọi phụ trợ"
} },
"failedRequests": "{{count}} lần lỗi",
"estimatedShare": "{{percent}} token là ước tính"
}, },
"providers": { "providers": {
"manageProviders": "Quản lý nhà cung cấp", "manageProviders": "Quản lý nhà cung cấp",
+6 -3
View File
@@ -1323,17 +1323,18 @@
"shortTitle": "Token 用量", "shortTitle": "Token 用量",
"viewDetails": "查看详情", "viewDetails": "查看详情",
"cacheHitRate": "缓存命中率", "cacheHitRate": "缓存命中率",
"cacheRateHelp": "缓存命中率仅统计缓存状态已知的输入。",
"dailyTrend": "每日 Token", "dailyTrend": "每日 Token",
"bySource": "用量来源", "bySource": "用量来源",
"modelTrend": "模型趋势", "modelTrend": "模型趋势",
"modelsUnavailable": "暂无模型用量明细。", "modelsUnavailable": "暂无模型用量明细。",
"otherModels": "其他模型 / 未分类", "otherModels": "其他模型",
"unclassified": "未分类", "unclassified": "未分类",
"unavailable": "暂时无法获取用量数据。", "unavailable": "暂时无法获取用量数据。",
"noActivity": "近 30 天暂无 Token 用量。", "noActivity": "近 30 天暂无 Token 用量。",
"last30Days": "近 30 天",
"cachedInput": "缓存命中", "cachedInput": "缓存命中",
"cacheMiss": "未命中", "cacheMiss": "未命中",
"cacheWrite": "缓存写入",
"cacheUnknown": "状态未知", "cacheUnknown": "状态未知",
"outputTokens": "输出", "outputTokens": "输出",
"otherTokens": "其他 Token", "otherTokens": "其他 Token",
@@ -1347,7 +1348,9 @@
"dream": "记忆整理", "dream": "记忆整理",
"system": "辅助调用" "system": "辅助调用"
}, },
"systemHelp": "包括内部任务和未标注来源的调用" "systemHelp": "包括内部任务和未标注来源的调用",
"failedRequests": "{{count}} 次失败",
"estimatedShare": "{{percent}} 的 Token 为本地估算"
}, },
"providers": { "providers": {
"manageProviders": "管理提供商", "manageProviders": "管理提供商",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Token 用量", "shortTitle": "Token 用量",
"viewDetails": "查看詳情", "viewDetails": "查看詳情",
"cacheHitRate": "快取命中率", "cacheHitRate": "快取命中率",
"cacheRateHelp": "快取命中率僅統計快取狀態已知的輸入。",
"dailyTrend": "每日 Token", "dailyTrend": "每日 Token",
"systemHelp": "包括內部任務和未標註來源的呼叫", "systemHelp": "包括內部任務和未標註來源的呼叫",
"bySource": "用量來源", "bySource": "用量來源",
"modelTrend": "模型趨勢", "modelTrend": "模型趨勢",
"modelsUnavailable": "暫無模型用量明細。", "modelsUnavailable": "暫無模型用量明細。",
"otherModels": "其他模型 / 未歸類", "otherModels": "其他模型",
"unclassified": "未分類", "unclassified": "未分類",
"unavailable": "暫時無法取得用量資料。", "unavailable": "暫時無法取得用量資料。",
"noActivity": "近 30 天暫無 Token 用量。", "noActivity": "近 30 天暫無 Token 用量。",
"last30Days": "近 30 天",
"cachedInput": "快取命中", "cachedInput": "快取命中",
"cacheMiss": "未命中", "cacheMiss": "未命中",
"cacheWrite": "快取寫入",
"cacheUnknown": "狀態未知", "cacheUnknown": "狀態未知",
"outputTokens": "輸出", "outputTokens": "輸出",
"otherTokens": "其他 Token", "otherTokens": "其他 Token",
@@ -959,7 +960,9 @@
"cron": "自動任務", "cron": "自動任務",
"dream": "記憶整理", "dream": "記憶整理",
"system": "輔助呼叫" "system": "輔助呼叫"
} },
"failedRequests": "{{count}} 次失敗",
"estimatedShare": "{{percent}} 的 Token 為本地估算"
}, },
"providers": { "providers": {
"manageProviders": "管理提供商", "manageProviders": "管理提供商",
+26 -14
View File
@@ -842,28 +842,40 @@ export async function deleteSession(
); );
} }
export async function fetchSettings( const settingsReads = new WeakMap<WebUIMutationTransport, Map<string, Promise<SettingsPayload>>>();
export function fetchSettings(
token: string, token: string,
base: string = "", base: string = "",
scope?: WebUIMutationTransport,
): Promise<SettingsPayload> { ): Promise<SettingsPayload> {
return request<SettingsPayload>( const load = () => request<SettingsPayload>(`${base}/api/settings`, token, undefined, API_READ_TIMEOUT_MS);
`${base}/api/settings`, if (!scope) return load();
token, let reads = settingsReads.get(scope);
undefined, if (!reads) {
API_READ_TIMEOUT_MS, reads = new Map();
); settingsReads.set(scope, reads);
}
const key = JSON.stringify([base, token]);
const pending = reads.get(key);
if (pending) return pending;
const read = load().finally(() => reads.delete(key));
reads.set(key, read);
return read;
} }
export async function fetchSettingsUsage( export async function fetchSettingsUsage(
token: string, token: string,
base: string = "", options: { details?: boolean; cached?: NonNullable<SettingsPayload["usage"]>; signal?: AbortSignal } = {},
): Promise<NonNullable<SettingsPayload["usage"]>> { ): Promise<NonNullable<SettingsPayload["usage"]>> {
return request<NonNullable<SettingsPayload["usage"]>>( const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
`${base}/api/settings/usage`, if (options.cached?.revision) headers["If-None-Match"] = `W/"${options.cached.revision}"`;
token, const response = await fetchWithTimeout(`/api/settings/usage${options.details ? "?details=true" : ""}`, {
undefined, headers, credentials: "same-origin", cache: "no-store", signal: options.signal,
API_READ_TIMEOUT_MS, }, API_READ_TIMEOUT_MS);
); if (response.status === 304 && options.cached) return options.cached;
if (!response.ok) throw new ApiError(response.status, `HTTP ${response.status}`);
return await response.json() as NonNullable<SettingsPayload["usage"]>;
} }
export type UpdateChannel = "stable" | "preview"; export type UpdateChannel = "stable" | "preview";
+23 -8
View File
@@ -918,6 +918,8 @@ export interface SettingsPayload {
cache_write_tokens: number; cache_write_tokens: number;
cache_read_observed_input_tokens: number; cache_read_observed_input_tokens: number;
cache_write_observed_input_tokens: number; cache_write_observed_input_tokens: number;
cache_miss_tokens?: number;
cache_unknown_tokens?: number;
total_tokens: number; total_tokens: number;
reported_tokens?: number; reported_tokens?: number;
estimated_tokens?: number; estimated_tokens?: number;
@@ -940,6 +942,8 @@ export interface SettingsPayload {
cache_write_tokens: number; cache_write_tokens: number;
cache_read_observed_input_tokens: number; cache_read_observed_input_tokens: number;
cache_write_observed_input_tokens: number; cache_write_observed_input_tokens: number;
cache_miss_tokens?: number;
cache_unknown_tokens?: number;
total_tokens: number; total_tokens: number;
reported_tokens?: number; reported_tokens?: number;
estimated_tokens?: number; estimated_tokens?: number;
@@ -956,14 +960,17 @@ export interface SettingsPayload {
} }
>; >;
}>; }>;
total_tokens: number; revision?: string;
total_tokens_30d: number; range_start?: string;
total_tokens_365d: number; range_end?: string;
peak_day_tokens: number; total_tokens?: number;
current_streak_days: number; total_tokens_30d?: number;
longest_streak_days: number; total_tokens_365d?: number;
active_days_30d: number; peak_day_tokens?: number;
requests_30d: number; current_streak_days?: number;
longest_streak_days?: number;
active_days_30d?: number;
requests_30d?: number;
failed_requests_30d?: number; failed_requests_30d?: number;
reported_tokens_30d?: number; reported_tokens_30d?: number;
estimated_tokens_30d?: number; estimated_tokens_30d?: number;
@@ -979,6 +986,8 @@ export interface SettingsPayload {
cache_write_tokens: number; cache_write_tokens: number;
cache_read_observed_input_tokens: number; cache_read_observed_input_tokens: number;
cache_write_observed_input_tokens: number; cache_write_observed_input_tokens: number;
cache_miss_tokens?: number;
cache_unknown_tokens?: number;
total_tokens: number; total_tokens: number;
reported_tokens: number; reported_tokens: number;
estimated_tokens: number; estimated_tokens: number;
@@ -998,6 +1007,12 @@ export interface SettingsPayload {
provider: string; provider: string;
model: string; model: string;
total_tokens: number; total_tokens: number;
measured_output_tokens?: number;
generation_ms?: number;
ttft_ms?: number;
timed_requests?: number;
cache_read_tokens?: number;
cache_read_observed_input_tokens?: number;
}>; }>;
updated_at?: string | null; updated_at?: string | null;
}; };
+21
View File
@@ -0,0 +1,21 @@
/**
* Providers report the same model under different ids: the Codex backend
* answers with `openai-codex/gpt-6.1-sol` while other calls record the bare
* `gpt-6-astra`. Grouping stays per provider, but the model name has to be
* normalized first, otherwise one model shows up as several cards.
*/
const SEPARATORS = /[^a-z0-9]/g;
function identity(value: string): string {
return value.toLowerCase().replace(SEPARATORS, "");
}
export function normalizeUsageModel(provider: string, model: string): string {
const separator = model.indexOf("/");
if (separator <= 0) return model;
const prefix = identity(model.slice(0, separator));
const owner = identity(provider);
// Only strip a prefix that names the provider itself; `qwen/…` under a
// custom provider is part of the model name.
return prefix && owner.startsWith(prefix) ? model.slice(separator + 1) : model;
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Usage counters are routinely eight to eleven digits. Reading them requires
* locale units (`100.5亿`, `10B`), but the exact value still has to stay
* available for titles, accessible labels, and diagnostics.
*/
const COMPACT_THRESHOLD = 10_000;
export interface UsageNumberFormats {
/** Locale units for five-digit and larger values, exact digits below that. */
display: (value: number) => string;
/** Grouped exact digits. */
exact: (value: number) => string;
}
export interface UsageFormats extends UsageNumberFormats {
/** Locale units regardless of magnitude. */
compact: (value: number) => string;
/** Percentage with one fraction digit. */
percent: (value: number) => string;
/** Milliseconds as seconds with one fraction digit. */
seconds: (value: number) => string;
/** Short month and day for a `YYYY-MM-DD` key, in UTC. */
date: (date: string) => string;
}
const formatsByLocale = new Map<string, UsageFormats>();
/**
* `Intl` constructors are comparatively expensive and the usage panels
* re-render on every hover, so each locale's formatters are built once.
*/
export function usageFormats(locale: string): UsageFormats {
const cached = formatsByLocale.get(locale);
if (cached) return cached;
const compact = new Intl.NumberFormat(locale, { notation: "compact", maximumFractionDigits: 1 });
const exact = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });
const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 1 });
const seconds = new Intl.NumberFormat(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
const date = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone: "UTC" });
const formats: UsageFormats = {
display: (value) => (Math.abs(value) >= COMPACT_THRESHOLD ? compact.format(value) : exact.format(value)),
exact: (value) => exact.format(value),
compact: (value) => compact.format(value),
percent: (value) => percent.format(value),
seconds: (value) => seconds.format(value / 1000),
date: (value) => date.format(new Date(`${value}T00:00:00Z`)),
};
formatsByLocale.set(locale, formats);
return formats;
}
/** Output tokens per second, or `null` when no generation time was measured. */
export function usageSpeed(measuredOutputTokens: number, generationMs: number): number | null {
return generationMs > 0 ? measuredOutputTokens / (generationMs / 1000) : null;
}
+28
View File
@@ -707,6 +707,34 @@ describe("webui API helpers", () => {
); );
}); });
it("shares only pending settings reads within the same client", async () => {
const pending: ((response: Response) => void)[] = [];
vi.mocked(fetch).mockImplementation(() => new Promise<Response>((resolve) => pending.push(resolve)));
const first = fetchSettings("tok", "", mutationTransport);
expect(fetchSettings("tok", "", mutationTransport)).toBe(first);
const other = fetchSettings("tok", "", { requestMutation });
expect(fetch).toHaveBeenCalledTimes(2);
pending[0]({ ok: true, json: async () => ({ version: { current: "first" } }) } as Response);
pending[1]({ ok: true, json: async () => ({ version: { current: "other" } }) } as Response);
expect((await first).version?.current).toBe("first");
expect((await other).version?.current).toBe("other");
const refreshed = fetchSettings("tok", "", mutationTransport);
expect(fetch).toHaveBeenCalledTimes(3);
pending[2]({ ok: true, json: async () => ({ version: { current: "refreshed" } }) } as Response);
expect((await refreshed).version?.current).toBe("refreshed");
});
it("reuses unchanged usage and requests model details explicitly", async () => {
const cached = { days: [], revision: "models" };
const json = vi.fn();
vi.mocked(fetch).mockResolvedValue({ status: 304, json } as unknown as Response);
expect(await fetchSettingsUsage("tok", { details: true, cached })).toBe(cached);
expect(fetch).toHaveBeenCalledWith("/api/settings/usage?details=true", expect.objectContaining({
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"models"' },
}));
expect(json).not.toHaveBeenCalled();
});
it("serializes model configuration creation", async () => { it("serializes model configuration creation", async () => {
await createModelConfiguration(mutationTransport, { await createModelConfiguration(mutationTransport, {
name: "Fast writing", name: "Fast writing",
+14
View File
@@ -662,6 +662,20 @@ describe("App layout", () => {
expect(asideClassNames.some((cls) => cls.includes("lg:block"))).toBe(true); expect(asideClassNames.some((cls) => cls.includes("lg:block"))).toBe(true);
}); });
it("loads settings once when opening the overview directly", async () => {
window.location.hash = "#/settings";
mockFetchRoutes({ "/api/settings": baseSettingsPayload(), "/api/settings/usage": { days: [] } });
render(<App />);
await act(async () => { await import("@/components/settings/SettingsView"); });
expect(await screen.findByRole("navigation", { name: "Settings sections" })).toBeInTheDocument();
expect(await screen.findByText("Token usage")).toBeInTheDocument();
const reads = () => vi.mocked(fetch).mock.calls.filter(([url]) => String(url) === "/api/settings");
expect(reads()).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
await screen.findByRole("navigation", { name: "Sidebar navigation" });
expect(reads()).toHaveLength(1);
});
it("uses one main landmark and a page heading in desktop settings", async () => { it("uses one main landmark and a page heading in desktop settings", async () => {
mockFetchRoutes({ "/api/settings": baseSettingsPayload() }); mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
const { container } = render(<App />); const { container } = render(<App />);
@@ -569,13 +569,14 @@ describe("Settings capabilities", () => {
requestMutationMock.mockResolvedValueOnce(saved); requestMutationMock.mockResolvedValueOnce(saved);
let refreshParent!: (snapshot: SettingsPayload) => void; let refreshParent!: (snapshot: SettingsPayload) => void;
let parentSnapshot: SettingsPayload = payload; let parentSnapshot: SettingsPayload = payload;
const client = { requestMutation: requestMutationMock, status: "open",
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
} as never;
function Parent() { function Parent() {
const [snapshot, setSnapshot] = useState<SettingsPayload>(payload); const [snapshot, setSnapshot] = useState<SettingsPayload>(payload);
parentSnapshot = snapshot; parentSnapshot = snapshot;
refreshParent = setSnapshot; refreshParent = setSnapshot;
return <ClientProvider client={{ requestMutation: requestMutationMock, status: "open", return <ClientProvider client={client} token="tok">
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
} as never} token="tok">
<SettingsView themePreference="light" initialSection="voice" initialSettings={snapshot} <SettingsView themePreference="light" initialSection="voice" initialSettings={snapshot}
onSettingsChange={setSnapshot} onNativeEngineRestart={restart} onSettingsChange={setSnapshot} onNativeEngineRestart={restart}
onChangeTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} /> onChangeTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />
+2 -1
View File
@@ -386,6 +386,7 @@ describe("Settings overview and appearance", () => {
vi.fn(async (input: RequestInfo | URL) => { vi.fn(async (input: RequestInfo | URL) => {
const url = String(input); const url = String(input);
if (url === "/api/settings") return jsonResponse(payload); if (url === "/api/settings") return jsonResponse(payload);
if (url === "/api/settings/usage") return jsonResponse(payload.usage);
if (url === "/api/settings/cli-apps") { if (url === "/api/settings/cli-apps") {
return jsonResponse({ apps: [], installed_count: 0 }); return jsonResponse({ apps: [], installed_count: 0 });
} }
@@ -398,7 +399,7 @@ describe("Settings overview and appearance", () => {
renderSettingsView({ initialSection: "overview" }); renderSettingsView({ initialSection: "overview" });
expect(await screen.findByLabelText("1,500 tokens")).toBeInTheDocument(); expect(await screen.findByLabelText("1,500 tokens in the last 30 days")).toBeInTheDocument();
expect(screen.getByText("Token usage")).toBeInTheDocument(); expect(screen.getByText("Token usage")).toBeInTheDocument();
}); });
+89 -13
View File
@@ -11,7 +11,7 @@ function day(date: string, tokens: number): Usage["days"][number] {
cache_write_observed_input_tokens: 0, requests: 1 }; cache_write_observed_input_tokens: 0, requests: 1 };
} }
function usage(days: Usage["days"]): Usage { function usage(days: Usage["days"]): Usage {
return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 999999, return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 1_500_000,
peak_day_tokens: 999999, current_streak_days: 0, longest_streak_days: 0, peak_day_tokens: 999999, current_streak_days: 0, longest_streak_days: 0,
active_days_30d: 0, requests_30d: 0, updated_at: "2026-09-09T00:00:00Z" }; active_days_30d: 0, requests_30d: 0, updated_at: "2026-09-09T00:00:00Z" };
} }
@@ -33,7 +33,7 @@ describe("Token usage card", () => {
const baseline = container.querySelector<HTMLElement>('[data-model-usage-gridline="2"]')!; const baseline = container.querySelector<HTMLElement>('[data-model-usage-gridline="2"]')!;
expect(plot).toContainElement(baseline); expect(plot).toContainElement(baseline);
expect(baseline.parentElement).toHaveStyle({ top: "100%" }); expect(baseline.parentElement).toHaveStyle({ top: "100%" });
expect(plot).not.toContainElement(screen.getByText("09-01")); expect(plot).not.toContainElement(screen.getByText("Sep 1"));
expect(bars[0].firstElementChild).toHaveStyle({ height: "100%" }); expect(bars[0].firstElementChild).toHaveStyle({ height: "100%" });
expect(bars[0].firstElementChild?.children).toHaveLength(2); expect(bars[0].firstElementChild?.children).toHaveLength(2);
expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` }); expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` });
@@ -46,17 +46,17 @@ describe("Token usage card", () => {
afterEach(() => vi.useRealTimers()); afterEach(() => vi.useRealTimers());
it("uses one 30-day window for the total, chart and source percentages", () => { it("uses one 30-day window for the total, chart and source percentages", () => {
const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, estimated_tokens: 100, const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, cache_miss_tokens: 60, cache_unknown_tokens: 60, estimated_tokens: 100,
sources: { user: day("2026-09-09", 200) } }; sources: { user: day("2026-09-09", 200) } };
render(<TokenUsageCard timeZone="UTC" usage={usage([ render(<TokenUsageCard timeZone="UTC" usage={usage([
day("2026-08-10", 9000), day("2026-08-11", 100), today, day("2026-09-10", 9000), day("2026-08-10", 9000), day("2026-08-11", 100), today, day("2026-09-10", 9000),
])} />); ])} />);
expect(screen.getByLabelText("400 tokens")).toBeInTheDocument(); expect(screen.getByLabelText("400 tokens in the last 30 days")).toBeInTheDocument();
const bars = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img"); const bars = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img");
expect(bars).toHaveLength(30); expect(bars).toHaveLength(30);
expect(bars.filter((bar) => bar.tabIndex === 0)).toEqual([bars[0], bars[29]]); expect(bars.filter((bar) => bar.tabIndex === 0)).toEqual([bars[0], bars[29]]);
expect(bars[0]).toHaveAccessibleName(/2026-08-11: 100 tokens, 1 requests/); expect(bars[0]).toHaveAccessibleName(/2026-08-11: 100 tokens, 1 requests/);
expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache miss: 60, Unknown status: 60, Output: 60/); expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache write: 0, Cache miss: 60, Unknown status: 60, Output: 60/);
const segments = bars[29].firstElementChild?.children; const segments = bars[29].firstElementChild?.children;
expect(segments).toHaveLength(4); expect(segments).toHaveLength(4);
expect(segments?.[0]).toHaveStyle({ height: "40%" }); expect(segments?.[0]).toHaveStyle({ height: "40%" });
@@ -66,6 +66,43 @@ describe("Token usage card", () => {
expect(bars[0]).toHaveAccessibleName(/Cache miss: 0, Unknown status: 100/); expect(bars[0]).toHaveAccessibleName(/Cache miss: 0, Unknown status: 100/);
expect(screen.getAllByText("50%")).toHaveLength(2); expect(screen.getAllByText("50%")).toHaveLength(2);
expect(screen.getByText("Unclassified")).toBeInTheDocument(); expect(screen.getByText("Unclassified")).toBeInTheDocument();
expect(screen.getByText("13.3")).toBeInTheDocument();
expect(screen.getByText(/Sep 9/)).toBeInTheDocument();
});
it.each([0, 100])("partitions cache writes without overlap when cached input is %i", (read) => {
const output = read === 0 ? 20 : 40;
const total = read + 100 + output;
const today = { ...day("2026-09-09", total), input_tokens: read + 100, output_tokens: output,
cache_read_tokens: read, cache_write_tokens: 100,
cache_read_observed_input_tokens: read, cache_write_observed_input_tokens: read + 100,
cache_miss_tokens: 0, cache_unknown_tokens: 0 };
render(<TokenUsageCard usage={usage([today])} />);
const bar = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img")[29];
expect(bar).toHaveAccessibleName(new RegExp(`Cached input: ${read}, Cache write: 100, Cache miss: 0, Unknown status: 0, Output: ${output}`));
const segments = Array.from(bar.firstElementChild!.children);
const values = [read, 100, output].filter(value => value > 0);
expect(segments).toHaveLength(values.length);
segments.forEach((segment, index) => expect(segment).toHaveStyle({ height: `${values[index] / total * 100}%` }));
});
it("keeps the read-only breakdown for older backends without per-call partitions", () => {
render(<TokenUsageCard usage={usage([{ ...day("2026-09-09", 240), input_tokens: 200, output_tokens: 40,
cache_read_tokens: 100, cache_write_tokens: 100,
cache_read_observed_input_tokens: 100, cache_write_observed_input_tokens: 200 }])} />);
const bar = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img")[29];
expect(bar).toHaveAccessibleName(/Cached input: 100, Cache write: 0, Cache miss: 0, Unknown status: 100, Output: 40/);
expect(bar.firstElementChild?.children).toHaveLength(3);
expect(bar.firstElementChild?.children[1]).toHaveStyle({ height: `${100 / 240 * 100}%` });
});
it("hides a legend entry when that segment stays empty across the window", () => {
const today = { ...day("2026-09-09", 1000), cache_read_tokens: 200, cache_read_observed_input_tokens: 400 };
const { rerender } = render(<TokenUsageCard usage={usage([today])} />);
expect(screen.getByText("Cached input")).toBeInTheDocument();
expect(screen.queryByText("Cache write")).not.toBeInTheDocument();
rerender(<TokenUsageCard usage={usage([{ ...today, cache_write_tokens: 150, cache_write_observed_input_tokens: 400, cache_miss_tokens: 50, cache_unknown_tokens: 600 }])} />);
expect(screen.getByText("Cache write")).toBeInTheDocument();
}); });
it("shows an empty state for zero usage", () => { it("shows an empty state for zero usage", () => {
@@ -73,15 +110,11 @@ describe("Token usage card", () => {
expect(screen.getByRole("status")).toHaveTextContent("No token usage in the last 30 days."); expect(screen.getByRole("status")).toHaveTextContent("No token usage in the last 30 days.");
}); });
it("opens details and computes the weighted cache rate from observed input only", () => { it("flags the share of tokens that were estimated locally", () => {
render(<TokenUsageCard usage={usage([ render(<TokenUsageCard usage={usage([{ ...day("2026-09-09", 1000), estimated_tokens: 250 }])} />);
{ ...day("2026-09-08", 100), cache_read_tokens: 80, cache_read_observed_input_tokens: 100 },
{ ...day("2026-09-09", 900), cache_read_tokens: 20, cache_read_observed_input_tokens: 300 },
])} />);
fireEvent.click(screen.getByRole("button", { name: "View details" })); fireEvent.click(screen.getByRole("button", { name: "View details" }));
const details = screen.getByRole("dialog", { name: "Token usage" }); const details = screen.getByRole("dialog", { name: "Token usage" });
expect(within(details).getByText("25%")).toBeInTheDocument(); expect(within(details).getByText("25% of tokens are estimated")).toBeInTheDocument();
expect(within(details).getByTitle("Cache hit rate excludes input with unknown cache status.")).toBeInTheDocument();
}); });
it("does not misrepresent unavailable usage as zero", () => { it("does not misrepresent unavailable usage as zero", () => {
@@ -90,6 +123,49 @@ describe("Token usage card", () => {
expect(screen.getByText("—")).toBeInTheDocument(); expect(screen.getByText("—")).toBeInTheDocument();
}); });
it("merges one model recorded under a provider prefix and a bare id", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z");
date.setUTCDate(date.getUTCDate() - 29 + index);
const key = date.toISOString().slice(0, 10);
return { date: key, usage: day(key, index === 29 ? 1000 : 0) };
});
render(<TokenUsageModelTrend days={days} models={[
{ ...day("2026-09-09", 600), provider: "openai_codex", model: "openai-codex/gpt-6",
cache_read_tokens: 100, cache_read_observed_input_tokens: 200,
reported_tokens: 600, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
ttft_ms: 0, timed_requests: 0, duration_ms: 0 },
{ ...day("2026-09-09", 400), provider: "openai_codex", model: "gpt-6",
cache_read_tokens: 50, cache_read_observed_input_tokens: 100,
reported_tokens: 400, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
ttft_ms: 0, timed_requests: 0, duration_ms: 0 },
]} modelDays={[
{ date: "2026-09-09", provider: "openai_codex", model: "openai-codex/gpt-6", total_tokens: 600 },
{ date: "2026-09-09", provider: "openai_codex", model: "gpt-6", total_tokens: 400 },
]} />);
expect(screen.getAllByText("gpt-6")).toHaveLength(1);
expect(screen.getByLabelText("gpt-6: Total tokens: 1,000 (100%), Cache hit rate: 50%")).toBeInTheDocument();
});
it("reports per-model speed, first-token wait and cache hit rate where measured", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z");
date.setUTCDate(date.getUTCDate() - 29 + index);
const key = date.toISOString().slice(0, 10);
return { date: key, usage: day(key, index === 29 ? 1500 : 0) };
});
render(<TokenUsageModelTrend days={days} modelDays={[
{ date: "2026-09-09", provider: "openai", model: "fast", total_tokens: 1000, measured_output_tokens: 400, generation_ms: 8000, ttft_ms: 3200, timed_requests: 1, cache_read_tokens: 700, cache_read_observed_input_tokens: 1000 },
{ date: "2026-09-09", provider: "openai", model: "legacy", total_tokens: 500 },
]} />);
const column = screen.getAllByRole("img")[29];
const label = column.getAttribute("aria-label") ?? "";
expect(label).toContain("fast: 1,000, 50 tok/s, 3.2s to first token, 70% cache hit");
expect(label).toContain("legacy: 500, Other models");
});
it("keeps the five leading model series and reconciles the rest to the daily total", () => { it("keeps the five leading model series and reconciles the rest to the daily total", () => {
const days = Array.from({ length: 30 }, (_, index) => { const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z"); const date = new Date("2026-09-09T00:00:00Z");
@@ -108,7 +184,7 @@ describe("Token usage card", () => {
expect(screen.getAllByRole("img").filter((bar) => bar.tabIndex === 0)).toEqual([column]); expect(screen.getAllByRole("img").filter((bar) => bar.tabIndex === 0)).toEqual([column]);
expect(column).toHaveAccessibleName(/2026-09-09: 2,200 tokens/); expect(column).toHaveAccessibleName(/2026-09-09: 2,200 tokens/);
expect(column).toHaveAccessibleName(/model-5: 600/); expect(column).toHaveAccessibleName(/model-5: 600/);
expect(column).toHaveAccessibleName(/Other \/ unattributed: 200/); expect(column).toHaveAccessibleName(/Other models: 200/);
const legend = screen.getByLabelText("model-5: Total tokens: 600 (27.3%), Cache hit rate: 80%"); const legend = screen.getByLabelText("model-5: Total tokens: 600 (27.3%), Cache hit rate: 80%");
expect(legend).toHaveAttribute("tabindex", "0"); expect(legend).toHaveAttribute("tabindex", "0");
}); });
@@ -0,0 +1,90 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TokenUsageOverview } from "@/components/settings/TokenUsageOverview";
const client = {};
const getToken = () => "tok";
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client, getToken }) }));
const overview = { days: [], revision: "overview" };
const models = { ...overview, revision: "models", providers_30d: [], model_days_30d: [] };
const json = (value: unknown) => ({ ok: true, status: 200, json: async () => value }) as Response;
async function settle() {
await act(async () => {});
}
describe("Token usage loading", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-09-09T12:00:00Z"));
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it("polls conditionally and loads models only while details are open", async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
if ((init?.headers as Record<string, string>)["If-None-Match"]) {
return { status: 304 } as Response;
}
return json(String(_input).includes("details=true") ? models : overview);
});
vi.stubGlobal("fetch", fetchMock);
const { unmount } = render(<TokenUsageOverview />);
await settle();
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(["/api/settings/usage"]);
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage", expect.objectContaining({
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"overview"' },
}));
fireEvent.click(screen.getByRole("button", { name: "View details" }));
await settle();
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage?details=true", expect.anything());
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage?details=true", expect.objectContaining({
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"models"' },
}));
const beforeClose = fetchMock.mock.calls.length;
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
await settle();
expect(fetchMock).toHaveBeenCalledTimes(beforeClose);
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage", expect.anything());
const beforeLeave = fetchMock.mock.calls.length;
unmount();
await act(async () => vi.advanceTimersByTimeAsync(10000));
fireEvent(window, new Event("focus"));
expect(fetchMock).toHaveBeenCalledTimes(beforeLeave);
});
it("aborts a pending request when hidden and refreshes once when visible again", async () => {
let visibility = "visible";
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility as DocumentVisibilityState);
const signals: AbortSignal[] = [];
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
const signal = init!.signal!;
signals.push(signal);
signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
}));
vi.stubGlobal("fetch", fetchMock);
render(<TokenUsageOverview />);
await settle();
fireEvent(window, new Event("focus"));
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenCalledTimes(1);
visibility = "hidden";
fireEvent(document, new Event("visibilitychange"));
await settle();
expect(signals[0].aborted).toBe(true);
await act(async () => vi.advanceTimersByTimeAsync(10000));
expect(fetchMock).toHaveBeenCalledTimes(1);
visibility = "visible";
fireEvent(document, new Event("visibilitychange"));
await settle();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { normalizeUsageModel } from "@/lib/usage-model";
describe("usage model names", () => {
it("strips a prefix that repeats the provider", () => {
expect(normalizeUsageModel("openai_codex", "openai-codex/gpt-6.1-sol")).toBe("gpt-6.1-sol");
expect(normalizeUsageModel("openai_codex", "openai/gpt-6-astra")).toBe("gpt-6-astra");
expect(normalizeUsageModel("custom-ffsa", "custom/model")).toBe("model");
});
it("keeps prefixes that belong to the model name", () => {
expect(normalizeUsageModel("custom-ffsa", "qwen/qwen3.8-27b")).toBe("qwen/qwen3.8-27b");
expect(normalizeUsageModel("zhipu", "glm-5.3-flash")).toBe("glm-5.3-flash");
expect(normalizeUsageModel("openai_codex", "gpt-6-astra")).toBe("gpt-6-astra");
expect(normalizeUsageModel("acme", "/leading-slash")).toBe("/leading-slash");
});
});
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { usageFormats } from "@/lib/usage-number";
describe("usage number formats", () => {
it("switches to locale units once a count reaches five digits", () => {
const en = usageFormats("en");
const zh = usageFormats("zh-CN");
expect(en.display(10_046_620_708)).toBe("10B");
expect(en.display(69_134)).toBe("69.1K");
expect(en.display(3039)).toBe("3,039");
expect(zh.display(10_046_620_708)).toBe("100.5亿");
expect(zh.display(10_324)).toBe("1万");
expect(zh.display(3039)).toBe("3,039");
});
it("keeps exact digits for titles and accessible labels", () => {
const en = usageFormats("en");
expect(en.exact(10_046_620_708)).toBe("10,046,620,708");
expect(en.exact(0)).toBe("0");
});
it("builds one formatter set per locale", () => {
expect(usageFormats("en")).toBe(usageFormats("en"));
expect(usageFormats("en")).not.toBe(usageFormats("zh-CN"));
expect(usageFormats("en").percent(0.5)).toBe("50%");
expect(usageFormats("en").date("2026-10-27")).toBe("Oct 27");
});
});