Skip to content

fix(usage): harden statistics aggregation, chart geometry, and telemetry - #2353

Open
chaos-cl wants to merge 8 commits into
GCWing:usage-statistics-pagefrom
chaos-cl:usage-statistics-page
Open

fix(usage): harden statistics aggregation, chart geometry, and telemetry#2353
chaos-cl wants to merge 8 commits into
GCWing:usage-statistics-pagefrom
chaos-cl:usage-statistics-page

Conversation

@chaos-cl

Copy link
Copy Markdown

Critical/Major/Minor/Nit risk remediation from the usage-statistics-page code review. All 16 findings fixed; scope is limited to the usage statistics feature. See commit message for the full breakdown. Verification: cargo check + cargo test (16 tests passed), pnpm tsc --noEmit + vitest (3507 passed).

chaos added 8 commits August 17, 2026 12:33
Add a settings page showing historical model call statistics (requests,
tokens, estimated cost) broken down by model, provider group, and
endpoint, with a token usage trend chart.

- services-core: pure aggregation module with unit tests
- core: attribution resolver (config + models.dev catalog) and
  get_statistics on the token usage service
- desktop: get_token_usage_statistics Tauri command
- web-ui: UsageStatisticsConfig settings tab + i18n (en/zh-CN/zh-TW)
- services-core: remove price estimation; UsageStatisticsEntry now carries
  cacheHitRate (cached / reported input); UsageStatistics gains
  totalCacheReportedInputTokens for the overall hit rate
- core: resolver no longer resolves prices
- web-ui: summary cards show requests/tokens/cached tokens/hit rate; tables
  show model/group/endpoint, requests, tokens, cache hit rate; fix table
  header layout (min column widths + no-wrap) that squeezed Chinese labels;
  drop cost columns and footnote
- i18n: update en/zh-CN/zh-TW copy
…splay

- move cache hit rate out of the distribution tables into a dedicated
  per-model card with a ratio bar
- display hit rates truncated to two decimals (never rounded up); only a
  true 100% hit (cached == reported input, exact in the backend) shows as
  100%
- trend chart now spans the full row; distribution tables revert to
  name / requests / tokens
The image understanding tool calls AIClient directly, bypassing the round
executor, so its consumption never reached the token usage store and
multimodal models were missing from the usage statistics page. Persist the
response usage through a global TokenUsageService reference installed by
the desktop runtime.
Dynamic var() string building (--bf-appearance-token-${name}) is invisible to
the theme color audit, which flagged an unresolved required CSS var and broke
the CI Frontend Build job. Replace every token reference with a literal var()
so the audit resolves them statically.
The appearance contract audit (part of build:web) requires every
data-bf-component to match a registered descriptor id and every data-bf-part
to be a string literal declared on the same node as its component. Align the
usage statistics page: component id 'usage-statistics-config', literal parts
on root/filters/summary/distributions/modelHitRate/trendPanel/empty, and drop
appearance attributes from internal chart components.
Critical/Major/Minor/Nit risk remediation from the usage-statistics-page
code review. All 16 findings fixed; scope is limited to the usage
statistics feature.

Critical (2)
- DonutChart SVG geometry: full-ring (100%) slice no longer paints a
  visible gap; zero-token slices are skipped instead of rendering a full
  stroke; cumulative arc length avoids floating-point drift.
- Aggregation now validates each record for plausibility (non-saturating
  token counts, non-empty model/session identifiers) and skips garbage.

Major (5)
- analyze_image persists cache_write_tokens via token_details, and its
  record_token_usage is now fire-and-forget (tokio::spawn) so the I/O
  no longer blocks the user-visible response.
- token_usage_api enforces a maximum custom range span to guard against
  pathological queries.
- provider_endpoint_path matches the provider key exactly rather than by
  substring, preventing a 'claude' provider from matching 'anthropic-claude'.
- Trend chart tooltip geometry clamps coordinates inside the plot rect.
- services-core no longer relies on a tracing dependency for warn logs;
  uses log::warn! instead.

Minor (6)
- endpoint_from_base_url refactored into join_endpoint + a known-suffix
  table; avoids duplicated /v1 segments and duplicated chat-completions.
- truncateName uses Intl.Segmenter (grapheme) with Array.from fallback so
  Chinese/emoji are never sliced mid-codepoint.
- formatBucketLabel parses the ISO bucket string directly via regex instead
  of constructing a Date and re-formatting it.
- aggregate_statistics receives &[&TokenUsageRecord] so the trend builder
  can share the already-filtered list without re-scanning.
- Empty session_id/turn_id in analyze_image now synthesise a UUID-based
  key per call so per-session aggregates remain meaningful.
- formatHitRate only reports 100% when Number.isInteger(value) && value===1,
  so 0.9999... no longer rounds up to 100%.

Nit (5)
- DonutChart no longer re-runs entries.filter inside the render loop;
  visible slices are pre-computed once in useMemo.
- niceMax uses a NICE_MAX_TABLE loop instead of nested ternaries and
  adds a Number.isFinite guard.
- TREND_SERIES key type extracted to TrendSeriesKey for readability.
- cache_write_tokens JSON parsing extracted into extract_cache_write_tokens.
- Frontend load() catch block now logs the error via console.error.

Verification
- cargo check -p bitfun-services-core --features local-storage
- cargo check -p bitfun-core --features 'local-storage,workspace-runtime,process-runtime,agent-runtime'
- cargo check -p bitfun-desktop
- cargo test -p bitfun-services-core --features local-storage token_usage::statistics (8 passed)
- cargo test -p bitfun-core --features '...agent-runtime' service::token_usage (8 passed)
- pnpm exec tsc --noEmit -p tsconfig.json
- pnpm run test:run (3507 passed, 485 files)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant