openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(cost): add settings cost dashboard with global tracker, dashboard RPCs, and charts

Open YellowSnnowmann opened this issue 6 months ago • 1 comments

Summary

  • Added a new Settings → Cost Dashboard page with 7-day cost and token visualizations, budget summary, model breakdown table, loading/error/empty states, and manual + polling refresh.

  • Introduced new core JSON-RPC controllers: openhuman.cost_get_dashboard, openhuman.cost_get_daily_history, and openhuman.cost_get_summary.

  • Activated a process-global CostTracker at core bootstrap and wired provider usage recording from the agent turn loop so dashboard data is populated automatically.

  • Extended cost domain types/tracker logic to support daily buckets (gap-filled), monthly pace projection, budget utilization/status thresholds, and per-model aggregation/sorting.

  • Expanded configuration with dashboard settings (cost.dashboard.*) and set cost.enabled default to true so telemetry is captured by default.

  • Added comprehensive frontend + Rust tests for dashboard rendering, formatting, hook polling, tracker aggregation, history windowing, and budget-state edge cases; added i18n strings across supported locales.

Problem

  • Cost data was tracked in isolation and not surfaced in a dedicated dashboard experience for users.

  • Reviewers and users lacked a single place to inspect short-term spend trends, token usage shape, and per-model contribution.

  • Dashboard RPC reads could race bootstrap and fail if no tracker instance was ready.

  • The prior cost.enabled behavior made observability weaker when enforcement was off, reducing visibility into usage trends.

Solution

  • Implemented a full dashboard UI in the Settings surface using reusable components (BudgetSummary, CostBarChart, TokenUsageChart, ModelCostTable) and a polling hook (useCostDashboard) backed by core RPC.

  • Added a global singleton CostTracker initialized during bootstrap_core_runtime, with fallback tracker resolution in dashboard RPC handlers for resilience.

  • Wired agent usage events into cost tracking (record_provider_usage) so records are persisted continuously from real provider responses.

  • Added new cost domain DTOs and aggregation logic for:

  • daily history (1..366 day clamp, zero-fill gaps),

  • budget utilization/status (normal/warning/exceeded),

  • projected monthly pace and per-model totals.

  • Kept tracking non-blocking and fault-tolerant (cost tracking errors are logged and never break turn execution).

Submission Checklist

  • If a section does not apply to this change, mark the item as N/A with a one-line reason. Do not delete items.

  • Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy

  • Diff coverage ≥ 80% — changed lines (Vitest + cargo-llvm-cov merged via diff-cover) meet the gate enforced by .github/workflows/coverage.yml. Run pnpm test:coverage and pnpm test:rust locally; PRs below 80% on changed lines will not merge.

  • Coverage matrix updated — added/removed/renamed feature rows in docs/TEST-COVERAGE-MATRIX.md reflect this change (or N/A: behaviour-only change)

  • All affected feature IDs from the matrix are listed in the PR description under ## Related

  • No new external network dependencies introduced (mock backend used per Testing Strategy)

  • Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md)

  • Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Platform/runtime: desktop app + in-process Rust core (JSON-RPC + Settings UI); no mobile/web-specific changes.

  • Performance: lightweight 10s polling in UI; backend cost aggregation reads from JSONL with bounded windows.

  • Security/compatibility: no new external runtime network dependency; RPC surface expanded; config schema extended with dashboard settings and new defaults.

  • Migration: existing config remains compatible via serde defaults; dashboard fields auto-default when absent.

Related

  • Closes: #1850

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a cost dashboard displaying 7-day spending overview with daily cost tracking
    • Visualize token usage and request counts with interactive charts
    • View cost breakdown by model and provider
    • Track budget utilization with status indicators (on track, warning, exceeded)
    • Auto-refreshing dashboard with manual refresh option
  • Chores

    • Added support for 13+ languages in the cost dashboard
    • New cost tracking configuration with customizable budget limits and alert thresholds
    • Added recharts library for dashboard visualizations
  • Tests

    • Comprehensive test coverage for dashboard components and cost tracking functionality

Review Change Stack

YellowSnnowmann avatar May 27 '26 13:05 YellowSnnowmann

📝 Walkthrough

Walkthrough

Adds a 7-day cost and token dashboard: Rust telemetry/tracker, JSON-RPC endpoints, config defaults, i18n strings, a polling React hook, formatting utilities, recharts-based charts and tooltip/table/summary components, Settings route wiring, and tests.

Changes

Cost Dashboard Telemetry & Backend

Layer / File(s) Summary
Types & config
src/openhuman/cost/types.rs, src/openhuman/config/schema/identity_cost.rs
Adds DailyCostEntry, BudgetStatus, CostDashboard types and CostDashboardConfig; enables cost tracking default to true and updates defaults/tests.
Global init & provider telemetry
src/openhuman/cost/global.rs, src/core/jsonrpc.rs, src/openhuman/agent/harness/session/turn.rs
Process-global CostTracker initialization (init_global), record_provider_usage helper, and integration into agent turn execution to capture provider usage.
Persistence & reporting APIs
src/openhuman/cost/tracker.rs, src/openhuman/cost/tracker_tests.rs
Adds record_usage_unconditional, get_daily_history(days), and get_dashboard(...) to compute history, monthly pace, utilization, budget status, and per-model aggregates; includes tests.
RPC & schemas
src/openhuman/cost/rpc.rs, src/openhuman/cost/schemas.rs, src/openhuman/cost/mod.rs
Defines DTOs, RPC handlers (dashboard, daily_history, summary), fallback tracker resolution and caching, controller schema registration, and unit tests.

Frontend Data Fetching & Formatting

Layer / File(s) Summary
React hook & tests
app/src/hooks/useCostDashboard.ts, app/src/hooks/useCostDashboard.test.ts
Polling hook that calls openhuman.cost_get_dashboard, unwraps envelopes, tracks loading/fetching/error/lastUpdated, supports pause/refetch; tests for success/envelope/error.
Formatting utilities
app/src/components/dashboard/formatCurrency.ts, app/src/components/dashboard/formatCurrency.test.ts
formatCurrency, formatTokens, day label helpers, and relativeTime(t) translator-aware implementation with tests.

React Components & Visualization

Layer / File(s) Summary
Chart primitives & tooltip
app/src/components/dashboard/ChartTooltip.tsx, app/src/components/dashboard/ChartTooltip.test.tsx
Tooltip component rendering title, rows, optional colored swatches and footer with tests.
Cost bar chart & color logic
app/src/components/dashboard/CostBarChart.tsx, app/src/components/dashboard/CostBarChart.test.tsx
Recharts-based 7-day cost bar chart, colorForCost threshold logic, daily target reference line and "today" badge; tests for color thresholds.
Token usage chart
app/src/components/dashboard/TokenUsageChart.tsx, app/src/components/dashboard/TokenUsageChart.test.tsx
Stacked input/output token bars with tooltip and legend; smoke tests included.
Model breakdown table
app/src/components/dashboard/ModelCostTable.tsx, app/src/components/dashboard/ModelCostTable.test.tsx
Per-model rows with provider chips, tokens/requests/cost, percent-of-total bar, empty and unknown-provider handling; tests included.
Budget summary & metrics
app/src/components/dashboard/BudgetSummary.tsx, app/src/components/dashboard/BudgetSummary.test.tsx
Hero spend tile, status badge (normal/warning/exceeded), clamped utilization bar, monthly pace and budget limit tiles; tests for badge text, clamping, and zero-limit fallback.
Main panel & skeleton
app/src/components/dashboard/CostDashboardPanel.tsx, app/src/components/dashboard/DashboardSkeleton.tsx, app/src/components/dashboard/CostDashboardPanel.test.tsx
Composes hook and subcomponents, handles loading/error/disabled/empty states, live updated timestamp and refresh button; skeleton placeholder and tests mock RPC/recharts.

Integration & Internationalization

Layer / File(s) Summary
Settings routing
app/src/pages/Settings.tsx
Adds menu item and route cost-dashboard rendering CostDashboardPanel.
i18n
app/src/lib/i18n/chunks/{ar,bn,de,en,es,fr,hi,id,it,ko,pt,ru,zh-CN}-1.ts, app/src/lib/i18n/en.ts
Adds settings.costDashboard.* keys across language chunks and main en.ts.
Dependency
app/package.json
Adds recharts ^2.15.0 runtime dependency for chart rendering.

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant Hook as useCostDashboard
  participant RPC as openhuman.cost_get_dashboard
  participant Tracker as CostTracker
  Browser->>Hook: mount or refetch()
  Hook->>RPC: call openhuman.cost_get_dashboard
  RPC->>Tracker: get_dashboard()
  Tracker-->>RPC: CostDashboard DTO
  RPC-->>Hook: RpcOutcome{result}
  Hook->>Browser: provide data to CostDashboardPanel
  Browser->>CostBarChart: render days, thresholds
  Browser->>TokenUsageChart: render token bars
  Browser->>ModelCostTable: render rows

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

"I'm a rabbit with a chart and pen,
seven days of costs, counted then,
badges glow and bars align,
budgets track by little sign —
hop! the dashboard's live again."

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding a cost dashboard with global tracker, RPCs, and charts.
Linked Issues check ✅ Passed The PR implements all key objectives from issue #1850: 7-day cost/token charts, budget summary, model breakdown table, real-time updates, config-driven settings, and local persistence.
Out of Scope Changes check ✅ Passed All changes are directly aligned with PR objectives and issue #1850 requirements; no unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 27 '26 13:05 coderabbitai[bot]

@YellowSnnowmann unresolved review feedback — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus

Unresolved review feedback from coderabbitai[bot] — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus