From e6b23c7356f225709f7fc3d97748613a6f8839b1 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:13:06 +0800 Subject: [PATCH] feat(webui): show the full token-usage picture in settings (#6638) --- nanobot/llm_usage/service.py | 4 +- nanobot/llm_usage/store.py | 185 ++++++++++-------- nanobot/webui/settings_api.py | 8 +- nanobot/webui/settings_routes.py | 24 ++- nanobot/webui/settings_system.py | 9 +- tests/llm_usage/test_llm_usage_store.py | 112 ++++++++++- tests/webui/test_settings_api.py | 20 +- tests/webui/test_settings_routes.py | 34 ++++ webui/browser/skeleton-additions-fixture.tsx | 3 +- webui/src/App.tsx | 13 +- .../src/components/settings/SettingsPage.tsx | 2 + .../components/settings/TokenUsageCard.tsx | 163 ++++++++------- .../components/settings/TokenUsageDetails.tsx | 46 +++-- .../settings/TokenUsageModelTrend.tsx | 121 ++++++++---- .../settings/TokenUsageOverview.tsx | 56 ++++++ .../settings/overview/OverviewSettings.tsx | 6 +- webui/src/components/settings/usage-chart.tsx | 67 +++++++ .../settings/useSettingsController.ts | 39 +--- .../src/components/ui/tooltip-primitives.tsx | 7 +- webui/src/dev/gallery/settings.tsx | 13 +- webui/src/i18n/locales/en/common.json | 9 +- webui/src/i18n/locales/es/common.json | 9 +- webui/src/i18n/locales/fr/common.json | 9 +- webui/src/i18n/locales/id/common.json | 9 +- webui/src/i18n/locales/ja/common.json | 9 +- webui/src/i18n/locales/ko/common.json | 9 +- webui/src/i18n/locales/pt-BR/common.json | 9 +- webui/src/i18n/locales/vi/common.json | 9 +- webui/src/i18n/locales/zh-CN/common.json | 9 +- webui/src/i18n/locales/zh-TW/common.json | 9 +- webui/src/lib/api.ts | 40 ++-- webui/src/lib/types.ts | 31 ++- webui/src/lib/usage-model.ts | 21 ++ webui/src/lib/usage-number.ts | 55 ++++++ webui/src/tests/api.test.ts | 28 +++ webui/src/tests/app-layout.test.tsx | 14 ++ .../src/tests/settings-capabilities.test.tsx | 7 +- webui/src/tests/settings-overview.test.tsx | 3 +- webui/src/tests/token-usage-card.test.tsx | 102 ++++++++-- webui/src/tests/token-usage-overview.test.tsx | 90 +++++++++ webui/src/tests/usage-model.test.ts | 17 ++ webui/src/tests/usage-number.test.ts | 28 +++ 42 files changed, 1116 insertions(+), 342 deletions(-) create mode 100644 webui/src/components/settings/TokenUsageOverview.tsx create mode 100644 webui/src/components/settings/usage-chart.tsx create mode 100644 webui/src/lib/usage-model.ts create mode 100644 webui/src/lib/usage-number.ts create mode 100644 webui/src/tests/token-usage-overview.test.tsx create mode 100644 webui/src/tests/usage-model.test.ts create mode 100644 webui/src/tests/usage-number.test.ts diff --git a/nanobot/llm_usage/service.py b/nanobot/llm_usage/service.py index 16fa6b258..b19f97ff0 100644 --- a/nanobot/llm_usage/service.py +++ b/nanobot/llm_usage/service.py @@ -2,7 +2,7 @@ from __future__ import annotations import threading from pathlib import Path -from typing import Any +from typing import Any, Literal from loguru import logger @@ -61,11 +61,13 @@ def record_llm_call(call: LLMCallRecord) -> None: def llm_usage_payload( *, days: int = 371, + view: Literal["history", "overview", "models"] = "history", timezone_name: str | None = None, ) -> dict[str, Any]: try: return get_llm_usage_store().usage_payload( days=days, + view=view, timezone_name=timezone_name, ) except Exception: diff --git a/nanobot/llm_usage/store.py b/nanobot/llm_usage/store.py index 3151ec1b6..3cb549fb2 100644 --- a/nanobot/llm_usage/store.py +++ b/nanobot/llm_usage/store.py @@ -1,5 +1,7 @@ from __future__ import annotations +import hashlib +import json import os import sqlite3 import threading @@ -8,7 +10,7 @@ from collections.abc import Iterable from copy import deepcopy from datetime import date, datetime, timedelta, timezone from pathlib import Path -from typing import Any, cast +from typing import Any, Literal, cast from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from nanobot.llm_usage.models import LLMCallRecord @@ -52,6 +54,8 @@ _USAGE_COLUMNS = ( "cache_write_tokens", "cache_read_observed_input_tokens", "cache_write_observed_input_tokens", + "cache_miss_tokens", + "cache_unknown_tokens", "total_tokens", "reported_tokens", "estimated_tokens", @@ -78,6 +82,16 @@ _AGGREGATE_SQL = """ COALESCE(SUM( CASE WHEN cache_write_tokens IS NOT NULL THEN input_tokens ELSE 0 END ), 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(reported_tokens), 0) AS reported_tokens, COALESCE(SUM(estimated_tokens), 0) AS estimated_tokens, @@ -165,8 +179,9 @@ class LLMUsageStore: self._last_prune_utc_day: int | None = None self._writes_since_size_prune = 0 self._write_version = 0 - self._cached_payload_key: tuple[int, str, str, int, int] | None = None - self._cached_payload: dict[str, Any] | None = None + self._cached_payloads: dict[ + str, tuple[tuple[int, str, str, int, int], dict[str, Any]] + ] = {} def _connect(self) -> sqlite3.Connection: pid = os.getpid() @@ -174,8 +189,7 @@ class LLMUsageStore: return self._connection if self._connection is not None: self._connection.close() - self._cached_payload_key = None - self._cached_payload = None + self._cached_payloads.clear() self.path.parent.mkdir(parents=True, exist_ok=True) connection = sqlite3.connect( self.path, @@ -251,8 +265,7 @@ class LLMUsageStore: self._connection.close() self._connection = None self._connection_pid = None - self._cached_payload_key = None - self._cached_payload = None + self._cached_payloads.clear() def record(self, call: LLMCallRecord) -> None: usage = call.usage @@ -301,8 +314,7 @@ class LLMUsageStore: values, ) self._write_version += 1 - self._cached_payload_key = None - self._cached_payload = None + self._cached_payloads.clear() self._prune_if_due(connection) def _prune_if_due(self, connection: sqlite3.Connection) -> None: @@ -392,6 +404,7 @@ class LLMUsageStore: self, *, days: int = 371, + view: Literal["history", "overview", "models"] = "history", timezone_name: str | None = None, now: datetime | None = None, ) -> dict[str, Any]: @@ -400,7 +413,7 @@ class LLMUsageStore: if current.tzinfo is None: current = current.replace(tzinfo=timezone.utc) 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") with self._lock: @@ -414,14 +427,16 @@ class LLMUsageStore: write_version, data_version, ) - if self._cached_payload_key == cache_key and self._cached_payload is not None: - return deepcopy(self._cached_payload) + cached = self._cached_payloads.get(view) + if cached is not None and cached[0] == cache_key: + return deepcopy(cached[1]) connection = self._read_connection() try: connection.execute("BEGIN") 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) daily = self._daily_rows( connection=connection, @@ -435,16 +450,11 @@ class LLMUsageStore: last_30_start_ms = self._midnight_ms(today - timedelta(days=29), zone) 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( connection=connection, start_ms=last_30_start_ms, end_ms=end_ms, - ) + ) if view != "overview" else [] providers_30d = [ { "provider": str(row["provider"]), @@ -459,11 +469,19 @@ class LLMUsageStore: "provider": str(row["provider"]), "model": str(row["model"]), "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( - """ + f""" 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 WHERE started_at_ms >= ? AND started_at_ms < ? GROUP BY date, provider, model @@ -472,66 +490,70 @@ class LLMUsageStore: """, (zone_name, last_30_start_ms, end_ms), ) - ] + ] if view != "overview" else [] - active_dates = { - date.fromisoformat(row["date"]) for row in daily if row["total_tokens"] > 0 - } - current_streak = 0 - cursor = today - while cursor in active_dates: - current_streak += 1 - cursor -= timedelta(days=1) - longest_streak = 0 - running_streak = 0 - previous: date | None = None - for cursor in sorted(active_dates): - running_streak = running_streak + 1 if previous == cursor - timedelta(days=1) else 1 - longest_streak = max(longest_streak, running_streak) - previous = cursor - - latest = ( - connection - .execute("SELECT MAX(started_at_ms) AS updated_at_ms FROM llm_calls") - .fetchone() - ) - updated_at_ms = int(latest["updated_at_ms"] or 0) if latest is not None else 0 - denominator = totals_30["cache_read_observed_input_tokens"] - payload = { - "days": visible_days, - "total_tokens": all_totals["total_tokens"], - "total_tokens_30d": totals_30["total_tokens"], - "total_tokens_365d": totals_365["total_tokens"], - "reported_tokens_30d": totals_30["reported_tokens"], - "estimated_tokens_30d": totals_30["estimated_tokens"], - "cache_read_tokens_30d": totals_30["cache_read_tokens"], - "cache_read_observed_input_tokens_30d": denominator, - "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), - default=0, - ), - "current_streak_days": current_streak, - "longest_streak_days": longest_streak, - "active_days_30d": sum( - 1 - for row in daily - if row["date"] >= last_30_date and row["total_tokens"] > 0 - ), - "requests_30d": totals_30["requests"], - "failed_requests_30d": totals_30["failed_requests"], - "providers_30d": providers_30d, - "model_days_30d": model_days_30d, - "updated_at": ( - datetime.fromtimestamp(updated_at_ms / 1000, timezone.utc) - .isoformat() - .replace("+00:00", "Z") - if updated_at_ms - else None - ), - } + if view == "history": + totals_30 = _sum_rows(row for row in daily if row["date"] >= last_30_date) + last_365_date = (today - timedelta(days=364)).isoformat() + totals_365 = _sum_rows(row for row in daily if row["date"] >= last_365_date) + active_dates = { + date.fromisoformat(row["date"]) for row in daily if row["total_tokens"] > 0 + } + current_streak = 0 + cursor = today + while cursor in active_dates: + current_streak += 1 + cursor -= timedelta(days=1) + longest_streak = 0 + running_streak = 0 + previous: date | None = None + for cursor in sorted(active_dates): + running_streak = running_streak + 1 if previous == cursor - timedelta(days=1) else 1 + longest_streak = max(longest_streak, running_streak) + previous = cursor + latest = connection.execute( + "SELECT MAX(started_at_ms) AS updated_at_ms FROM llm_calls" + ).fetchone() + updated_at_ms = int(latest["updated_at_ms"] or 0) if latest is not None else 0 + denominator = totals_30["cache_read_observed_input_tokens"] + payload = { + "days": visible_days, + "total_tokens": _sum_rows(daily)["total_tokens"], + "total_tokens_30d": totals_30["total_tokens"], + "total_tokens_365d": totals_365["total_tokens"], + "reported_tokens_30d": totals_30["reported_tokens"], + "estimated_tokens_30d": totals_30["estimated_tokens"], + "cache_read_tokens_30d": totals_30["cache_read_tokens"], + "cache_read_observed_input_tokens_30d": denominator, + "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), default=0), + "current_streak_days": current_streak, + "longest_streak_days": longest_streak, + "active_days_30d": sum( + 1 for row in daily if row["date"] >= last_30_date and row["total_tokens"] > 0 + ), + "requests_30d": totals_30["requests"], + "failed_requests_30d": totals_30["failed_requests"], + "providers_30d": providers_30d, + "model_days_30d": model_days_30d, + "updated_at": ( + datetime.fromtimestamp(updated_at_ms / 1000, timezone.utc) + .isoformat().replace("+00:00", "Z") if updated_at_ms else None + ), + } + else: + payload = { + "days": visible_days, + "range_start": last_30_date, + "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: connection.close() @@ -543,8 +565,7 @@ class LLMUsageStore: else 0 ) if self._write_version == write_version and latest_data_version == data_version: - self._cached_payload_key = cache_key - self._cached_payload = payload + self._cached_payloads[view] = (cache_key, payload) return deepcopy(payload) def recent_calls(self, *, limit: int = 100) -> list[dict[str, Any]]: diff --git a/nanobot/webui/settings_api.py b/nanobot/webui/settings_api.py index 8ab0944c5..3e98423aa 100644 --- a/nanobot/webui/settings_api.py +++ b/nanobot/webui/settings_api.py @@ -161,7 +161,7 @@ def settings_payload( restart_required_sections: list[str] | None = None, apply_state: dict[str, Any] | None = None, config_path: Path | None = None, - include_usage: bool = True, + include_usage: bool = False, ) -> dict[str, Any]: config = _load_settings_config(config_path) payload: dict[str, Any] = { @@ -190,8 +190,10 @@ def settings_payload( ) -def settings_usage_payload(*, config_path: Path | None = None) -> dict[str, Any]: - return system.settings_usage_payload(_load_settings_config(config_path)) +def settings_usage_payload( + *, 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( diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.py index 31fb4d4d8..96b8d4d6f 100644 --- a/nanobot/webui/settings_routes.py +++ b/nanobot/webui/settings_routes.py @@ -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_system as system_domain 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 is_local_browser_request as _is_local_browser_request from nanobot.webui.mcp_oauth_api import McpOAuthManager @@ -312,7 +313,7 @@ class WebUISettingsRouter: if route == ("root", "settings"): return await asyncio.to_thread(self._handle_settings) 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 if action.startswith("update-") and self._runtime_surface == "native": @@ -500,8 +501,25 @@ class WebUISettingsRouter: ) ) - def _handle_settings_usage(self) -> Response: - return self._json_response(self.settings.read(settings_usage_payload)) + def _handle_settings_usage(self, request: WsRequest) -> Response: + 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: return model_domain.ModelSettingsOperations( diff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.py index b5fbefc6b..3e0c3dddf 100644 --- a/nanobot/webui/settings_system.py +++ b/nanobot/webui/settings_system.py @@ -185,9 +185,12 @@ def system_settings_payload( return payload -def settings_usage_payload(config: Config) -> dict[str, Any]: - """Return the lightweight token usage slice for Overview refreshes.""" - return llm_usage_payload(timezone_name=config.agents.defaults.timezone) +def settings_usage_payload(config: Config, *, details: bool = False) -> dict[str, Any]: + """Return only the 30-day usage projection currently displayed.""" + 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]: diff --git a/tests/llm_usage/test_llm_usage_store.py b/tests/llm_usage/test_llm_usage_store.py index 881dd2c5a..e8a27a621 100644 --- a/tests/llm_usage/test_llm_usage_store.py +++ b/tests/llm_usage/test_llm_usage_store.py @@ -89,7 +89,10 @@ def test_usage_payload_aggregates_cache_coverage_sources_and_failures(tmp_path: _call( "2026-06-03T01:00:00+00:00", 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( "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_rate_30d"] == 0.4 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] @@ -131,6 +156,8 @@ def test_usage_payload_aggregates_cache_coverage_sources_and_failures(tmp_path: assert day["requests"] == 4 assert day["reported_requests"] == 2 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"]["user"]["cache_read_observed_input_tokens"] == 100 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: store = LLMUsageStore(tmp_path / "llm_usage.sqlite3") store.record( @@ -275,3 +334,50 @@ def test_usage_query_does_not_hold_writer_lock( assert not query_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"] diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.py index 200e70cd9..f3d4d94c7 100644 --- a/tests/webui/test_settings_api.py +++ b/tests/webui/test_settings_api.py @@ -5,6 +5,7 @@ import json import time from datetime import date from types import SimpleNamespace +from unittest.mock import patch import httpx import pytest @@ -1753,7 +1754,7 @@ def test_update_transcription_settings_validates_language( 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, monkeypatch: pytest.MonkeyPatch, ) -> 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"] == 15 @@ -1808,9 +1814,13 @@ def test_settings_usage_payload_returns_lightweight_token_usage( payload = settings_usage_payload() - assert payload["total_tokens"] == 22 - assert payload["requests_30d"] == 1 - assert "agent" not in payload + assert sum(day["total_tokens"] for day in payload["days"]) == 22 + assert sum(day["requests"] for day in payload["days"]) == 1 + 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( diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.py index eba7772b0..83d667408 100644 --- a/tests/webui/test_settings_routes.py +++ b/tests/webui/test_settings_routes.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import gzip import json import threading 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() finally: 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 diff --git a/webui/browser/skeleton-additions-fixture.tsx b/webui/browser/skeleton-additions-fixture.tsx index fb9c3ade7..366090390 100644 --- a/webui/browser/skeleton-additions-fixture.tsx +++ b/webui/browser/skeleton-additions-fixture.tsx @@ -66,7 +66,8 @@ export function installSkeletonPreviewApi() { return detailState === "error" ? Response.json({ error: "Preview read failed" }, { status: 503 }) : Response.json(skill); } const bodies: Record = { - "/api/settings": previewSettings, "/api/settings/usage": { usage: null }, + "/api/settings": previewSettings, + "/api/settings/usage": { days: [] } satisfies NonNullable, "/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 }, }; diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 1d8617084..ddddfe6c8 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -942,6 +942,9 @@ function Shell({ const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken); const [settingsSnapshot, setSettingsSnapshot] = useState(null); const [settingsLoading, setSettingsLoading] = useState(true); + const settingsSnapshotRef = useRef(settingsSnapshot); + settingsSnapshotRef.current = settingsSnapshot; + const settingsOwnsSnapshot = view !== "chat" && view !== "remote"; const settingsRefreshGenerationRef = useRef(0); const [pendingAutomationMessage, setPendingAutomationMessage] = useState<{ id: string; @@ -1082,10 +1085,14 @@ function Shell({ }, [client]); useEffect(() => { + if (settingsOwnsSnapshot || settingsSnapshotRef.current !== null) { + setSettingsLoading(false); + return; + } let cancelled = false; const requestGeneration = settingsRefreshGenerationRef.current; setSettingsLoading(true); - fetchSettings(getToken()) + fetchSettings(getToken(), "", client) .then((payload) => { if (!cancelled && requestGeneration === settingsRefreshGenerationRef.current) { setSettingsSnapshot(payload); @@ -1102,7 +1109,7 @@ function Shell({ return () => { cancelled = true; }; - }, [getToken]); + }, [client, getToken, settingsOwnsSnapshot]); useEffect(() => { try { @@ -1925,7 +1932,7 @@ function Shell({ let cancelled = false; let retryTimer: number | undefined; const refreshSettings = (generation: number, attempt = 0): void => { - void fetchSettings(getToken()) + void fetchSettings(getToken(), "", client) .then((payload) => { if (!cancelled && generation === settingsRefreshGenerationRef.current) { setSettingsSnapshot(payload); diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index e8d0a3e1d..293f0c22c 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -25,6 +25,7 @@ import { } from "@/components/settings/models/ProviderSettings"; import { providerFormFromRow } from "@/components/settings/models/providerForm"; import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings"; +import { TokenUsageOverview } from "@/components/settings/TokenUsageOverview"; import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings"; import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar"; import { @@ -270,6 +271,7 @@ export function SettingsPage({ settings={settings} showBrandLogos={localPrefs.brandLogos} onSelectSection={selectSection} + usageCard={} /> ); case "about": diff --git a/webui/src/components/settings/TokenUsageCard.tsx b/webui/src/components/settings/TokenUsageCard.tsx index 9c9ef38af..5bc68ef0c 100644 --- a/webui/src/components/settings/TokenUsageCard.tsx +++ b/webui/src/components/settings/TokenUsageCard.tsx @@ -2,27 +2,33 @@ import { useTranslation } from "react-i18next"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import type { SettingsPayload } from "@/lib/types"; +import { usageFormats } from "@/lib/usage-number"; import { cn } from "@/lib/utils"; import { TokenUsageDetails } from "@/components/settings/TokenUsageDetails"; +import { UsageAxis, UsageDateAxis, usageAxisTicks, usagePeakCenter } from "@/components/settings/usage-chart"; import { SettingsHint } from "@/components/settings/shared/SettingsHint"; type Usage = NonNullable; const SOURCE_KEYS = ["user", "api", "cron", "dream", "system"] as const; const SEGMENT_CLASSES = [ "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-orange-500 dark:bg-orange-400", + "bg-neutral-700 dark:bg-neutral-200", "bg-neutral-500 dark:bg-neutral-300", ]; const CACHE_PATTERN = { backgroundImage: "repeating-linear-gradient(135deg, transparent, transparent 3px, currentColor 3px, currentColor 4px)" }; 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; - return [day.cache_read_tokens, observed - day.cache_read_tokens, - day.input_tokens - observed, - day.output_tokens, Math.max(0, day.total_tokens - day.input_tokens - day.output_tokens)]; + // Older backends cannot locate writes within the read-observed and unknown pools. + const input = day.cache_miss_tokens !== undefined && day.cache_unknown_tokens !== undefined + ? [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 { @@ -42,7 +48,12 @@ function todayInTimeZone(timeZone?: string): string { 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 today = todayInTimeZone(timeZone); 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) }; }); 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 compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 }); - const exact = new Intl.NumberFormat(i18n.language); - const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }); - const dateFormat = new Intl.DateTimeFormat(i18n.language, { month: "short", day: "numeric", timeZone: "UTC" }); - const formatDate = (date: string) => dateFormat.format(new Date(`${date}T00:00:00Z`)); + const values = days.map(day => day.usage?.total_tokens ?? 0); + const average = total / values.length; + const peak = Math.max(0, ...values); + const peakDay = days.reduce<(typeof days)[number] | undefined>( + (best, day) => ((day.usage?.total_tokens ?? 0) > (best?.usage?.total_tokens ?? 0) ? day : best), + 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 = [ t("settings.usage.cachedInput", { defaultValue: "Cached input" }), + t("settings.usage.cacheWrite", { defaultValue: "Cache write" }), t("settings.usage.cacheMiss", { defaultValue: "Cache miss" }), t("settings.usage.cacheUnknown", { defaultValue: "Cache status unknown" }), t("settings.usage.outputTokens", { defaultValue: "Output" }), t("settings.usage.otherTokens", { defaultValue: "Other tokens" }), ]; - const hasOtherTokens = days.some(day => tokenSegments(day.usage)[4] > 0); + const segmentTotals = days.reduce( + (sums, day) => tokenSegments(day.usage).map((value, index) => sums[index] + value), + [0, 0, 0, 0, 0, 0], + ); const sourceLabels: Record = { user: t("settings.usage.sources.user", { defaultValue: "Chat" }), api: t("settings.usage.sources.api", { defaultValue: "API" }), @@ -92,12 +112,15 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
-

{t("settings.usage.shortTitle", { defaultValue: "Token usage" })}

-

- {usage ? compact.format(total) : "—"} +

+ {t("settings.usage.shortTitle", { defaultValue: "Token usage" })} + {usage && {t("settings.usage.last30Days", { defaultValue: "Last 30 days" })}} +

+

+ {usage ? compact(total) : "—"}

- {usage && } + {usage && }
{!usage || total === 0 ? ( @@ -109,61 +132,63 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?: ) : ( <>
-
{compact.format(peak)}
-
-
- {[0, 1, 2].map(line =>
)} -
-
- - {days.map(day => { - const tokens = day.usage?.total_tokens ?? 0; - const segments = tokenSegments(day.usage); - const label = t("settings.usage.cellTitle", { - defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests", - date: day.date, tokens: exact.format(tokens), requests: day.usage?.requests ?? 0, - }); - if (tokens === 0) return ; - return ( - - - `${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 && )} - - - - -
{day.date}{exact.format(tokens)}
-
- {segments.map((value, index) => (index < 4 || value > 0) &&
-
{segmentLabels[index]}
-
{exact.format(value)}
-
)} -
-
{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}
-
{day.usage?.cache_read_observed_input_tokens ? percent.format(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}
-
-
-
-
- ); - })} -
-
-
-
- {formatDate(days[0].date)} - {formatDate(days[14].date)} - {formatDate(today)} +
+
+ +
+ + {days.map(day => { + const tokens = day.usage?.total_tokens ?? 0; + const segments = tokenSegments(day.usage); + const label = t("settings.usage.cellTitle", { + defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests", + date: day.date, tokens: exact(tokens), requests: day.usage?.requests ?? 0, + }); + if (tokens === 0) return ; + return ( + + + `${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"> + + {segments.map((value, index) => value > 0 && )} + + + + +
{day.date}{display(tokens)}
+
+ {segments.map((value, index) => (index < 5 || value > 0) &&
+
{segmentLabels[index]}
+
{display(value)}
+
)} +
+
{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}
+
{day.usage?.cache_read_observed_input_tokens ? percent(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}
+
+
+
{t("settings.usage.requests", { defaultValue: "Requests" })}
+
+ {display(day.usage?.requests ?? 0)} + {(day.usage?.failed_requests ?? 0) > 0 && ({t("settings.usage.failedRequests", { defaultValue: "{{count}} failed", count: display(day.usage?.failed_requests ?? 0) })})} +
+
+
+
+
+ ); + })} +
+
+
+
- {segmentLabels.map((label, index) => (index < 4 || hasOtherTokens) && {label})} + {segmentLabels.map((label, index) => segmentTotals[index] > 0 && {label})}
-
+
{breakdown.map(([source, tokens]) => ( -
+
{source === "system" ? ( {sourceLabels[source]} ) : sourceLabels[source]}
-
{new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }).format(tokens / total)}
+
{tokens / total < 0.001 ? `<${percent(0.001)}` : percent(tokens / total)}
))}
diff --git a/webui/src/components/settings/TokenUsageDetails.tsx b/webui/src/components/settings/TokenUsageDetails.tsx index d7304744c..42bfb3d97 100644 --- a/webui/src/components/settings/TokenUsageDetails.tsx +++ b/webui/src/components/settings/TokenUsageDetails.tsx @@ -2,44 +2,48 @@ import { ChevronRight } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Dialog, DialogContent, DialogLayoutContext, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import type { SettingsPayload } from "@/lib/types"; +import { usageFormats } from "@/lib/usage-number"; import { TokenUsageModelTrend } from "@/components/settings/TokenUsageModelTrend"; type Usage = NonNullable; +type DayTotal = NonNullable; -export function TokenUsageDetails({ days, models, modelDays }: { - days: { date: string; usage?: Usage["days"][number] }[]; +export function TokenUsageDetails({ days, models, modelDays, onOpenChange, loading }: { + days: { date: string; usage?: DayTotal }[]; models?: Usage["providers_30d"]; modelDays?: Usage["model_days_30d"]; + onOpenChange?: (open: boolean) => void; + loading?: boolean; }) { const { t, i18n } = useTranslation(); - const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 0 }); - const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }); - const sum = (key: "total_tokens" | "requests" | "cache_read_tokens" | "cache_read_observed_input_tokens") => + const percent = usageFormats(i18n.language).percent; + const sum = (key: "total_tokens" | "estimated_tokens") => days.reduce((total, day) => total + (day.usage?.[key] ?? 0), 0); const total = sum("total_tokens"); - const observed = sum("cache_read_observed_input_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) : "—"], - ]; + const estimated = sum("estimated_tokens"); + return ( - + - - {t("settings.usage.shortTitle")} -
- {metrics.map(([label, value], index) =>
-
{label}
-
{value}
-
)} -
- {modelDays?.length ? :

{t("settings.usage.modelsUnavailable")}

} +
+ {t("settings.usage.shortTitle")} + {t("settings.usage.last30Days", { defaultValue: "Last 30 days" })} +
+ {estimated > 0 && total > 0 && ( +

+ {t("settings.usage.estimatedShare", { + defaultValue: "{{percent}} of tokens are estimated", + percent: percent(estimated / total), + })} +

+ )} + {modelDays?.length ? :

{t(loading ? "common.loading" : "settings.usage.modelsUnavailable")}

}
diff --git a/webui/src/components/settings/TokenUsageModelTrend.tsx b/webui/src/components/settings/TokenUsageModelTrend.tsx index b7951869f..2b8452bc1 100644 --- a/webui/src/components/settings/TokenUsageModelTrend.tsx +++ b/webui/src/components/settings/TokenUsageModelTrend.tsx @@ -1,10 +1,14 @@ +import { Fragment } from "react"; import { useTranslation } from "react-i18next"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; 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 { UsageAxis, UsageDateAxis, usageAxisTicks, usagePeakCenter } from "@/components/settings/usage-chart"; type Usage = NonNullable; -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 }: { days: { date: string; usage?: Usage["days"][number] }[]; @@ -12,31 +16,57 @@ export function TokenUsageModelTrend({ days, modelDays, models }: { models?: Usage["providers_30d"]; }) { const { t, i18n } = useTranslation(); - const number = new Intl.NumberFormat(i18n.language); - const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }); + const { display, exact, compact, percent, seconds, date: formatDay } = usageFormats(i18n.language); 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])); - const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 }); + // Group by provider and normalized model, so one model is never split across + // `openai-codex/…` and bare ids. + const modelKey = (provider: string, model: string) => JSON.stringify([provider, normalizeUsageModel(provider, model)]); + const modelUsage = new Map(); + 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 totals = new Map(); - const daily = new Map>(); + const daily = new Map>(); for (const row of modelDays) { if (!dates.has(row.date) || row.total_tokens <= 0) continue; - const key = JSON.stringify([row.provider, row.model]); - const item = totals.get(key) ?? { label: row.model, total: 0 }; + const label = normalizeUsageModel(row.provider, row.model); + const key = JSON.stringify([row.provider, label]); + const item = totals.get(key) ?? { label, total: 0 }; item.total += row.total_tokens; totals.set(key, item); - const bucket = daily.get(row.date) ?? new Map(); - bucket.set(key, (bucket.get(key) ?? 0) + row.total_tokens); + type Bucket = { tokens: number; measured: number; generationMs: number; ttftMs: number; timed: number; cacheRead: number; cacheObserved: number }; + const bucket = daily.get(row.date) ?? new Map(); + 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); } 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 columns = days.map(day => { 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; - 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)); 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 hasOther = columns.some(column => column.values[series.length] > 0); 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
-

{title}

-
+
-
- {[peak, peak / 2, 0].map((value, index) =>
- {compact.format(value)} - -
)} -
-
- + +
+ {columns.map(column => column.total === 0 ? ( - + ) : - `${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"> - + `${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"> + {column.values.map((value, index) => value > 0 && )} - -

{column.date}

-
- {column.values.map((value, index) => ({ value, index })).filter(item => item.value > 0).sort((a, b) => b.value - a.value).map(({ value, index }) =>
-
{labels[index]}
{number.format(value)}
-
)} -
{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}
{number.format(column.total)}
-
{t("settings.usage.requests")}
{number.format(column.requests)}
+ +
+
{column.date}
+
+
tok/s
+
TTFT
+
s
+
{t("settings.usage.cacheHitRate")}
+
tokens
+ {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 +
{labels[index]}
{speedValue}
{speedUnit}
{ttftValue}
{ttftUnit}
{hit == null ? "—" : percent(hit)}
{display(value)}
+
; + })} +
{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}
{display(column.total)}
+
{t("settings.usage.requests")}
{display(column.requests)}
)}
-
{days[0].date.slice(5)}{days[14].date.slice(5)}{days[days.length - 1].date.slice(5)}
+
- +
{labels.map((label, index) => { if (index === series.length && !hasOther) return null; const model = index < series.length ? modelUsage.get(series[index][0]) : undefined; 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 = [ - [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], ]; return diff --git a/webui/src/components/settings/TokenUsageOverview.tsx b/webui/src/components/settings/TokenUsageOverview.tsx new file mode 100644 index 000000000..ea35b0d1e --- /dev/null +++ b/webui/src/components/settings/TokenUsageOverview.tsx @@ -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; + +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 ; +} diff --git a/webui/src/components/settings/overview/OverviewSettings.tsx b/webui/src/components/settings/overview/OverviewSettings.tsx index 1170fb821..b9a8e43c8 100644 --- a/webui/src/components/settings/overview/OverviewSettings.tsx +++ b/webui/src/components/settings/overview/OverviewSettings.tsx @@ -4,7 +4,7 @@ import { ImageGenerationIcon, VoiceIcon, } 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 { ChevronRight, type LucideIcon, @@ -39,10 +39,12 @@ export function OverviewSettings({ settings, onSelectSection, showBrandLogos, + usageCard, }: { settings: SettingsPayload; onSelectSection: (section: SettingsSectionKey) => void; showBrandLogos: boolean; + usageCard?: ReactNode; }) { const { t } = useTranslation(); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); @@ -76,7 +78,7 @@ export function OverviewSettings({ return (
- + {usageCard ?? }
diff --git a/webui/src/components/settings/usage-chart.tsx b/webui/src/components/settings/usage-chart.tsx new file mode 100644 index 000000000..4c6cfab26 --- /dev/null +++ b/webui/src/components/settings/usage-chart.tsx @@ -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 ( +
+ {ticks.map(tick => ( +
+ {tick.value > 0 && {format(tick.value)}} + +
+ ))} +
+ ); +} + +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 ( +
+ {peakCenter > 20 && {format(start)}} + {peakCenter < 80 && {format(end)}} + {format(peak)} +
+ ); +} diff --git a/webui/src/components/settings/useSettingsController.ts b/webui/src/components/settings/useSettingsController.ts index 134c21a31..d0b08a04c 100644 --- a/webui/src/components/settings/useSettingsController.ts +++ b/webui/src/components/settings/useSettingsController.ts @@ -36,7 +36,7 @@ import { useSystemSettingsState } from "@/components/settings/system/useSystemSe import { getToolsCatalog } from "@/lib/tools-catalog-cache"; import { usePageVisibility } from "@/hooks/usePageVisibility"; import { useEditCompletion } from "@/components/settings/shared/useEditCompletion"; -import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api"; +import { cancelProviderOAuth, fetchSettings } from "@/lib/api"; import { LOCAL_PREFS_CHANGED_EVENT, readLocalPreferences, @@ -204,7 +204,7 @@ export function useSettingsController({ const requestInitialSettings = latestInitialSettingsRef.current; const requestDrafts = draftsRef.current; if (showLoading) setLoading(true); - fetchSettings(getToken()) + fetchSettings(getToken(), "", client) .then((payload) => { if (!cancelled && latestInitialSettingsRef.current === requestInitialSettings) { const current = draftsRef.current; @@ -228,37 +228,8 @@ export function useSettingsController({ return () => { 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({ state: systemState, activeSection, @@ -363,7 +334,7 @@ export function useSettingsController({ const requestDrafts = draftsRef.current; try { const nextToken = await onNativeEngineRestart(); - const payload = await fetchSettings(nextToken); + const payload = await fetchSettings(nextToken, "", client); const current = draftsRef.current; applyPayload(payload, { preserveAgentForm: current.form !== requestDrafts.form, @@ -399,7 +370,7 @@ export function useSettingsController({ setHostEngineApplying(true); try { const nextToken = await onNativeEngineRestart(); - const refreshed = await fetchSettings(nextToken); + const refreshed = await fetchSettings(nextToken, "", client); applyPayload(refreshed, { preserveAgentForm: true, preserveCapabilityForms: true }); setPendingRestartSections(EMPTY_PENDING_RESTART_SECTIONS); setError(null); diff --git a/webui/src/components/ui/tooltip-primitives.tsx b/webui/src/components/ui/tooltip-primitives.tsx index 3b5f3cca6..3bbc2af3f 100644 --- a/webui/src/components/ui/tooltip-primitives.tsx +++ b/webui/src/components/ui/tooltip-primitives.tsx @@ -4,8 +4,11 @@ import * as TooltipPrimitive from "@radix-ui/react-tooltip"; import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; import { cn } from "@/lib/utils"; -function TooltipProvider(props: Omit, "delayDuration" | "skipDelayDuration">) { - return ; +function TooltipProvider({ + delayDuration = 500, + ...props +}: Omit, "delayDuration" | "skipDelayDuration"> & { delayDuration?: number }) { + return ; } const Tooltip = TooltipPrimitive.Root; const TooltipTrigger = TooltipPrimitive.Trigger; diff --git a/webui/src/dev/gallery/settings.tsx b/webui/src/dev/gallery/settings.tsx index 8ed5cdf54..85b822d49 100644 --- a/webui/src/dev/gallery/settings.tsx +++ b/webui/src/dev/gallery/settings.tsx @@ -220,10 +220,15 @@ const usage: Usage = (() => { 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, 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) => [ - { date: day.date, provider: "openai", model: "gpt-5.4", total_tokens: day.total_tokens * 0.6 }, - { date: day.date, provider: "anthropic", model: "claude-sonnet-4", total_tokens: day.total_tokens * 0.4 }, - ]) }; + model_days_30d: days.flatMap((day, index) => [ + { provider: "openai", model: "gpt-5.4", share: 0.6, speed: 48 + index % 7 }, + { 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() { diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index d8cc189c2..d5e4c4018 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1323,17 +1323,18 @@ "shortTitle": "Token usage", "viewDetails": "View details", "cacheHitRate": "Cache hit rate", - "cacheRateHelp": "Cache hit rate excludes input with unknown cache status.", "dailyTrend": "Daily tokens", "bySource": "Usage by source", "modelTrend": "Model trends", "modelsUnavailable": "No model breakdown available.", - "otherModels": "Other / unattributed", + "otherModels": "Other models", "unclassified": "Unclassified", "unavailable": "Usage data is unavailable.", "noActivity": "No token usage in the last 30 days.", + "last30Days": "Last 30 days", "cachedInput": "Cached input", "cacheMiss": "Cache miss", + "cacheWrite": "Cache write", "cacheUnknown": "Unknown status", "outputTokens": "Output", "otherTokens": "Other tokens", @@ -1347,7 +1348,9 @@ "dream": "Memory", "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": { "manageProviders": "Manage providers", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 7497eee56..501d5fc14 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -935,18 +935,19 @@ "shortTitle": "Uso de tokens", "viewDetails": "Ver detalles", "cacheHitRate": "Tasa de aciertos de caché", - "cacheRateHelp": "La tasa excluye las entradas cuyo estado de caché se desconoce.", "dailyTrend": "Tokens diarios", "systemHelp": "Incluye tareas internas y llamadas sin origen registrado.", "bySource": "Uso por origen", "modelTrend": "Tendencias por modelo", "modelsUnavailable": "Sin desglose por modelo.", - "otherModels": "Otros / sin atribuir", + "otherModels": "Otros modelos", "unclassified": "Sin clasificar", "unavailable": "Los datos de uso no están disponibles.", "noActivity": "Sin uso de tokens en los últimos 30 días.", + "last30Days": "Últimos 30 días", "cachedInput": "Entrada en caché", "cacheMiss": "Fallo de caché", + "cacheWrite": "Escritura de caché", "cacheUnknown": "Estado desconocido", "outputTokens": "Salida", "otherTokens": "Otros tokens", @@ -959,7 +960,9 @@ "cron": "Automatizaciones", "dream": "Consolidación de memoria", "system": "Llamadas auxiliares" - } + }, + "failedRequests": "{{count}} fallidas", + "estimatedShare": "El {{percent}} de los tokens es estimado" }, "providers": { "manageProviders": "Gestionar proveedores", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 3a0e0d0ed..1d7d49886 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -935,18 +935,19 @@ "shortTitle": "Utilisation des tokens", "viewDetails": "Voir les détails", "cacheHitRate": "Taux de réussite du cache", - "cacheRateHelp": "Le taux exclut les entrées dont l’état du cache est inconnu.", "dailyTrend": "Tokens quotidiens", "systemHelp": "Inclut les tâches internes et les appels sans source enregistrée.", "bySource": "Utilisation par source", "modelTrend": "Tendances des modèles", "modelsUnavailable": "Aucune ventilation par modèle disponible.", - "otherModels": "Autres / non attribués", + "otherModels": "Autres modèles", "unclassified": "Non classé", "unavailable": "Les données d’utilisation sont indisponibles.", "noActivity": "Aucun token utilisé au cours des 30 derniers jours.", + "last30Days": "30 derniers jours", "cachedInput": "Entrée en cache", "cacheMiss": "Cache manqué", + "cacheWrite": "Écriture de cache", "cacheUnknown": "État inconnu", "outputTokens": "Sortie", "otherTokens": "Autres tokens", @@ -959,7 +960,9 @@ "cron": "Automatisations", "dream": "Consolidation de la mémoire", "system": "Appels auxiliaires" - } + }, + "failedRequests": "{{count}} échecs", + "estimatedShare": "{{percent}} des tokens sont estimés" }, "providers": { "manageProviders": "Gérer les fournisseurs", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 003d1eea8..73e9e6ae3 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -935,18 +935,19 @@ "shortTitle": "Penggunaan token", "viewDetails": "Lihat detail", "cacheHitRate": "Rasio cache hit", - "cacheRateHelp": "Rasio tidak mencakup input dengan status cache yang tidak diketahui.", "dailyTrend": "Token harian", "systemHelp": "Termasuk tugas internal dan panggilan tanpa sumber tercatat.", "bySource": "Penggunaan berdasarkan sumber", "modelTrend": "Tren model", "modelsUnavailable": "Rincian per model tidak tersedia.", - "otherModels": "Lainnya / belum dikategorikan", + "otherModels": "Model lain", "unclassified": "Tidak dikategorikan", "unavailable": "Data penggunaan tidak tersedia.", "noActivity": "Tidak ada penggunaan token dalam 30 hari terakhir.", + "last30Days": "30 hari terakhir", "cachedInput": "Input tersedia di cache", "cacheMiss": "Cache tidak ditemukan", + "cacheWrite": "Penulisan cache", "cacheUnknown": "Status tidak diketahui", "outputTokens": "Output", "otherTokens": "Token lainnya", @@ -959,7 +960,9 @@ "cron": "Otomasi", "dream": "Penataan memori", "system": "Panggilan pendukung" - } + }, + "failedRequests": "{{count}} gagal", + "estimatedShare": "{{percent}} token diperkirakan" }, "providers": { "manageProviders": "Kelola penyedia", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index ee3249606..ce1fc2be8 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -935,18 +935,19 @@ "shortTitle": "トークン使用量", "viewDetails": "詳細を見る", "cacheHitRate": "キャッシュヒット率", - "cacheRateHelp": "キャッシュ状態が不明な入力はヒット率の計算から除外します。", "dailyTrend": "毎日の Token", "systemHelp": "内部タスクと記録された送信元がない呼び出しを含みます。", "bySource": "利用元別の使用量", "modelTrend": "モデルの推移", "modelsUnavailable": "モデル別の内訳はありません。", - "otherModels": "その他 / 未分類", + "otherModels": "その他のモデル", "unclassified": "未分類", "unavailable": "使用量データを取得できません。", "noActivity": "過去30日間のトークン使用はありません。", + "last30Days": "過去 30 日間", "cachedInput": "キャッシュヒット", "cacheMiss": "キャッシュ未使用", + "cacheWrite": "キャッシュ書き込み", "cacheUnknown": "状態不明", "outputTokens": "出力", "otherTokens": "その他のトークン", @@ -959,7 +960,9 @@ "cron": "自動タスク", "dream": "メモリ整理", "system": "補助処理" - } + }, + "failedRequests": "失敗 {{count}} 件", + "estimatedShare": "トークンの {{percent}} は推定値" }, "providers": { "manageProviders": "プロバイダーを管理", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index c3be9eafb..0a32f6183 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -935,18 +935,19 @@ "shortTitle": "토큰 사용량", "viewDetails": "자세히 보기", "cacheHitRate": "캐시 적중률", - "cacheRateHelp": "캐시 상태가 알려진 입력만 적중률 계산에 포함됩니다.", "dailyTrend": "일일 Token", "systemHelp": "내부 작업과 출처가 기록되지 않은 호출을 포함합니다.", "bySource": "출처별 사용량", "modelTrend": "모델 추이", "modelsUnavailable": "모델별 내역이 없습니다.", - "otherModels": "기타 / 미분류", + "otherModels": "기타 모델", "unclassified": "미분류", "unavailable": "사용량 데이터를 사용할 수 없습니다.", "noActivity": "최근 30일 동안 토큰 사용량이 없습니다.", + "last30Days": "최근 30일", "cachedInput": "캐시 적중", "cacheMiss": "캐시 미스", + "cacheWrite": "캐시 쓰기", "cacheUnknown": "상태 알 수 없음", "outputTokens": "출력", "otherTokens": "기타 토큰", @@ -959,7 +960,9 @@ "cron": "자동화", "dream": "기억 정리", "system": "보조 호출" - } + }, + "failedRequests": "실패 {{count}}회", + "estimatedShare": "토큰의 {{percent}}가 추정치" }, "providers": { "manageProviders": "제공업체 관리", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 7b878befe..7d80b95fd 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1143,18 +1143,19 @@ "shortTitle": "Uso de tokens", "viewDetails": "Ver detalhes", "cacheHitRate": "Taxa de acertos de cache", - "cacheRateHelp": "A taxa exclui entradas com estado de cache desconhecido.", "dailyTrend": "Tokens diários", "systemHelp": "Inclui tarefas internas e chamadas sem origem registrada.", "bySource": "Uso por origem", "modelTrend": "Tendências dos modelos", "modelsUnavailable": "Sem detalhamento por modelo.", - "otherModels": "Outros / não atribuídos", + "otherModels": "Outros modelos", "unclassified": "Não classificado", "unavailable": "Os dados de uso estão indisponíveis.", "noActivity": "Nenhum token usado nos últimos 30 dias.", + "last30Days": "Últimos 30 dias", "cachedInput": "Entrada em cache", "cacheMiss": "Falha de cache", + "cacheWrite": "Gravação de cache", "cacheUnknown": "Status desconhecido", "outputTokens": "Saída", "otherTokens": "Outros tokens", @@ -1167,7 +1168,9 @@ "cron": "Automações", "dream": "Consolidação de memória", "system": "Chamadas auxiliares" - } + }, + "failedRequests": "{{count}} falhas", + "estimatedShare": "{{percent}} dos tokens são estimados" }, "providers": { "manageProviders": "Gerenciar provedores", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 723d7f979..6733bab60 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -935,18 +935,19 @@ "shortTitle": "Mức dùng token", "viewDetails": "Xem chi tiết", "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", "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", "modelTrend": "Xu hướng 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", "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.", + "last30Days": "30 ngày qua", "cachedInput": "Đầu vào có trong bộ nhớ đệm", "cacheMiss": "Không khớp cache", + "cacheWrite": "Ghi bộ nhớ đệm", "cacheUnknown": "Trạng thái chưa rõ", "outputTokens": "Đầu ra", "otherTokens": "Token khác", @@ -959,7 +960,9 @@ "cron": "Tự động hóa", "dream": "Sắp xếp bộ nhớ", "system": "Lượt gọi phụ trợ" - } + }, + "failedRequests": "{{count}} lần lỗi", + "estimatedShare": "{{percent}} token là ước tính" }, "providers": { "manageProviders": "Quản lý nhà cung cấp", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 5c13765f7..de7a4d703 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1323,17 +1323,18 @@ "shortTitle": "Token 用量", "viewDetails": "查看详情", "cacheHitRate": "缓存命中率", - "cacheRateHelp": "缓存命中率仅统计缓存状态已知的输入。", "dailyTrend": "每日 Token", "bySource": "用量来源", "modelTrend": "模型趋势", "modelsUnavailable": "暂无模型用量明细。", - "otherModels": "其他模型 / 未分类", + "otherModels": "其他模型", "unclassified": "未分类", "unavailable": "暂时无法获取用量数据。", "noActivity": "近 30 天暂无 Token 用量。", + "last30Days": "近 30 天", "cachedInput": "缓存命中", "cacheMiss": "未命中", + "cacheWrite": "缓存写入", "cacheUnknown": "状态未知", "outputTokens": "输出", "otherTokens": "其他 Token", @@ -1347,7 +1348,9 @@ "dream": "记忆整理", "system": "辅助调用" }, - "systemHelp": "包括内部任务和未标注来源的调用" + "systemHelp": "包括内部任务和未标注来源的调用", + "failedRequests": "{{count}} 次失败", + "estimatedShare": "{{percent}} 的 Token 为本地估算" }, "providers": { "manageProviders": "管理提供商", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 9d269a9c3..7bb997226 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -935,18 +935,19 @@ "shortTitle": "Token 用量", "viewDetails": "查看詳情", "cacheHitRate": "快取命中率", - "cacheRateHelp": "快取命中率僅統計快取狀態已知的輸入。", "dailyTrend": "每日 Token", "systemHelp": "包括內部任務和未標註來源的呼叫", "bySource": "用量來源", "modelTrend": "模型趨勢", "modelsUnavailable": "暫無模型用量明細。", - "otherModels": "其他模型 / 未歸類", + "otherModels": "其他模型", "unclassified": "未分類", "unavailable": "暫時無法取得用量資料。", "noActivity": "近 30 天暫無 Token 用量。", + "last30Days": "近 30 天", "cachedInput": "快取命中", "cacheMiss": "未命中", + "cacheWrite": "快取寫入", "cacheUnknown": "狀態未知", "outputTokens": "輸出", "otherTokens": "其他 Token", @@ -959,7 +960,9 @@ "cron": "自動任務", "dream": "記憶整理", "system": "輔助呼叫" - } + }, + "failedRequests": "{{count}} 次失敗", + "estimatedShare": "{{percent}} 的 Token 為本地估算" }, "providers": { "manageProviders": "管理提供商", diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index 3ea87cc7d..a12356a60 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -842,28 +842,40 @@ export async function deleteSession( ); } -export async function fetchSettings( +const settingsReads = new WeakMap>>(); + +export function fetchSettings( token: string, base: string = "", + scope?: WebUIMutationTransport, ): Promise { - return request( - `${base}/api/settings`, - token, - undefined, - API_READ_TIMEOUT_MS, - ); + const load = () => request(`${base}/api/settings`, token, undefined, API_READ_TIMEOUT_MS); + if (!scope) return load(); + let reads = settingsReads.get(scope); + if (!reads) { + 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( token: string, - base: string = "", + options: { details?: boolean; cached?: NonNullable; signal?: AbortSignal } = {}, ): Promise> { - return request>( - `${base}/api/settings/usage`, - token, - undefined, - API_READ_TIMEOUT_MS, - ); + const headers: Record = { Authorization: `Bearer ${token}` }; + if (options.cached?.revision) headers["If-None-Match"] = `W/"${options.cached.revision}"`; + const response = await fetchWithTimeout(`/api/settings/usage${options.details ? "?details=true" : ""}`, { + headers, credentials: "same-origin", cache: "no-store", signal: options.signal, + }, 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; } export type UpdateChannel = "stable" | "preview"; diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 3160690bd..bf7c5ef0f 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -918,6 +918,8 @@ export interface SettingsPayload { cache_write_tokens: number; cache_read_observed_input_tokens: number; cache_write_observed_input_tokens: number; + cache_miss_tokens?: number; + cache_unknown_tokens?: number; total_tokens: number; reported_tokens?: number; estimated_tokens?: number; @@ -940,6 +942,8 @@ export interface SettingsPayload { cache_write_tokens: number; cache_read_observed_input_tokens: number; cache_write_observed_input_tokens: number; + cache_miss_tokens?: number; + cache_unknown_tokens?: number; total_tokens: number; reported_tokens?: number; estimated_tokens?: number; @@ -956,14 +960,17 @@ export interface SettingsPayload { } >; }>; - total_tokens: number; - total_tokens_30d: number; - total_tokens_365d: number; - peak_day_tokens: number; - current_streak_days: number; - longest_streak_days: number; - active_days_30d: number; - requests_30d: number; + revision?: string; + range_start?: string; + range_end?: string; + total_tokens?: number; + total_tokens_30d?: number; + total_tokens_365d?: number; + peak_day_tokens?: number; + current_streak_days?: number; + longest_streak_days?: number; + active_days_30d?: number; + requests_30d?: number; failed_requests_30d?: number; reported_tokens_30d?: number; estimated_tokens_30d?: number; @@ -979,6 +986,8 @@ export interface SettingsPayload { cache_write_tokens: number; cache_read_observed_input_tokens: number; cache_write_observed_input_tokens: number; + cache_miss_tokens?: number; + cache_unknown_tokens?: number; total_tokens: number; reported_tokens: number; estimated_tokens: number; @@ -998,6 +1007,12 @@ export interface SettingsPayload { provider: string; model: string; 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; }; diff --git a/webui/src/lib/usage-model.ts b/webui/src/lib/usage-model.ts new file mode 100644 index 000000000..f70090b18 --- /dev/null +++ b/webui/src/lib/usage-model.ts @@ -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; +} diff --git a/webui/src/lib/usage-number.ts b/webui/src/lib/usage-number.ts new file mode 100644 index 000000000..702189074 --- /dev/null +++ b/webui/src/lib/usage-number.ts @@ -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(); + +/** + * `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; +} diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index 5676d7b57..c8e39dc18 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -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((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 () => { await createModelConfiguration(mutationTransport, { name: "Fast writing", diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index c1e4cfed4..061b13428 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -662,6 +662,20 @@ describe("App layout", () => { 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(); + 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 () => { mockFetchRoutes({ "/api/settings": baseSettingsPayload() }); const { container } = render(); diff --git a/webui/src/tests/settings-capabilities.test.tsx b/webui/src/tests/settings-capabilities.test.tsx index d2b778f51..230e97499 100644 --- a/webui/src/tests/settings-capabilities.test.tsx +++ b/webui/src/tests/settings-capabilities.test.tsx @@ -569,13 +569,14 @@ describe("Settings capabilities", () => { requestMutationMock.mockResolvedValueOnce(saved); let refreshParent!: (snapshot: SettingsPayload) => void; let parentSnapshot: SettingsPayload = payload; + const client = { requestMutation: requestMutationMock, status: "open", + onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; }, + } as never; function Parent() { const [snapshot, setSnapshot] = useState(payload); parentSnapshot = snapshot; refreshParent = setSnapshot; - return void) => { handler("open"); return () => {}; }, - } as never} token="tok"> + return {}} onBackToChat={() => {}} onModelNameChange={() => {}} /> diff --git a/webui/src/tests/settings-overview.test.tsx b/webui/src/tests/settings-overview.test.tsx index 7e551afe1..ecead5121 100644 --- a/webui/src/tests/settings-overview.test.tsx +++ b/webui/src/tests/settings-overview.test.tsx @@ -386,6 +386,7 @@ describe("Settings overview and appearance", () => { vi.fn(async (input: RequestInfo | URL) => { const url = String(input); if (url === "/api/settings") return jsonResponse(payload); + if (url === "/api/settings/usage") return jsonResponse(payload.usage); if (url === "/api/settings/cli-apps") { return jsonResponse({ apps: [], installed_count: 0 }); } @@ -398,7 +399,7 @@ describe("Settings overview and appearance", () => { 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(); }); diff --git a/webui/src/tests/token-usage-card.test.tsx b/webui/src/tests/token-usage-card.test.tsx index 5ca049205..f424ea3cb 100644 --- a/webui/src/tests/token-usage-card.test.tsx +++ b/webui/src/tests/token-usage-card.test.tsx @@ -11,7 +11,7 @@ function day(date: string, tokens: number): Usage["days"][number] { cache_write_observed_input_tokens: 0, requests: 1 }; } 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, 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('[data-model-usage-gridline="2"]')!; expect(plot).toContainElement(baseline); 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?.children).toHaveLength(2); expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` }); @@ -46,17 +46,17 @@ describe("Token usage card", () => { afterEach(() => vi.useRealTimers()); 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) } }; render(); - 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"); expect(bars).toHaveLength(30); 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[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; expect(segments).toHaveLength(4); 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(screen.getAllByText("50%")).toHaveLength(2); 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(); + 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(); + 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(); + expect(screen.getByText("Cached input")).toBeInTheDocument(); + expect(screen.queryByText("Cache write")).not.toBeInTheDocument(); + rerender(); + expect(screen.getByText("Cache write")).toBeInTheDocument(); }); 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."); }); - it("opens details and computes the weighted cache rate from observed input only", () => { - render(); + it("flags the share of tokens that were estimated locally", () => { + render(); fireEvent.click(screen.getByRole("button", { name: "View details" })); const details = screen.getByRole("dialog", { name: "Token usage" }); - expect(within(details).getByText("25%")).toBeInTheDocument(); - expect(within(details).getByTitle("Cache hit rate excludes input with unknown cache status.")).toBeInTheDocument(); + expect(within(details).getByText("25% of tokens are estimated")).toBeInTheDocument(); }); it("does not misrepresent unavailable usage as zero", () => { @@ -90,6 +123,49 @@ describe("Token usage card", () => { 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(); + 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(); + 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", () => { const days = Array.from({ length: 30 }, (_, index) => { 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(column).toHaveAccessibleName(/2026-09-09: 2,200 tokens/); 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%"); expect(legend).toHaveAttribute("tabindex", "0"); }); diff --git a/webui/src/tests/token-usage-overview.test.tsx b/webui/src/tests/token-usage-overview.test.tsx new file mode 100644 index 000000000..f6771e1bb --- /dev/null +++ b/webui/src/tests/token-usage-overview.test.tsx @@ -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)["If-None-Match"]) { + return { status: 304 } as Response; + } + return json(String(_input).includes("details=true") ? models : overview); + }); + vi.stubGlobal("fetch", fetchMock); + const { unmount } = render(); + 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((_resolve, reject) => { + const signal = init!.signal!; + signals.push(signal); + signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true }); + })); + vi.stubGlobal("fetch", fetchMock); + render(); + 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); + }); +}); diff --git a/webui/src/tests/usage-model.test.ts b/webui/src/tests/usage-model.test.ts new file mode 100644 index 000000000..473234e96 --- /dev/null +++ b/webui/src/tests/usage-model.test.ts @@ -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"); + }); +}); diff --git a/webui/src/tests/usage-number.test.ts b/webui/src/tests/usage-number.test.ts new file mode 100644 index 000000000..1ba720b33 --- /dev/null +++ b/webui/src/tests/usage-number.test.ts @@ -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"); + }); +});