Skip to content

Cross-provider API-value aggregate backend (SOU-265 pass 3a) - #57

Merged
tsouth89 merged 3 commits into
mainfrom
feat/sou-265-api-value-totals
Jul 18, 2026
Merged

Cross-provider API-value aggregate backend (SOU-265 pass 3a)#57
tsouth89 merged 3 commits into
mainfrom
feat/sou-265-api-value-totals

Conversation

@tsouth89

@tsouth89 tsouth89 commented Jul 18, 2026

Copy link
Copy Markdown
Owner

What

Backend foundation for SOU-265's total API-value card. A command aggregates each capable provider's local usage into Today / Yesterday / 30 Days, using the same canonical scanner aggregates as provider detail and the CLI (no new accounting path).

SOU-265 is large (donut card + period/metric switchers + transparency + responsive across tray/dashboard/pop-out), so it's split: this is pass 3a (backend + command + tests); the donut UI is pass 3b.

Changes

  • chart.rs: LocalApiValuePeriod (estimated API value USD, processed tokens, priced/total model tokens for pricing coverage, hasData) and LocalApiValueProvider across the three periods. api_value_period derives coverage from unknown_models (unpriced tokens are counted but not priced - no fabricated dollars).
  • New get_local_api_value_totals command: scans codex + claude once each (30-day report + an exact local-day "yesterday" window) and omits providers with no source data in any period.
  • Yesterday uses local calendar boundaries via local_midnight_utc (DST-safe: handles skipped/ambiguous local midnights) and local_yesterday_window_utc.
  • Registered in main.rs + permissions/commands.toml. bridge.ts types + getLocalApiValueTotals wrapper wire it to the frontend boundary.

Terminology (per SOU-265)

Dollars are token-derived estimated API value, never billed spend. Unpriced models contribute tokens but no dollars; pricedTokens / totalTokens gives the coverage the UI will surface ("N% of tokens priced").

Tests

  • api_value_period_reports_partial_pricing_coverage, _fully_priced_has_full_coverage, _empty_summary_has_no_data.
  • local_yesterday_window_spans_one_local_day (23-25h across DST).

Desktop 381 / frontend green; cargo fmt --all --check + tsc clean.

Summary by CodeRabbit

  • New Features
    • Added API value totals reporting for supported providers.
    • View estimated dollar value, token totals, pricing coverage, and data availability for today, yesterday, and the past 30 days.
    • Daily reporting accounts for daylight-saving time changes when calculating local date ranges.

Backend foundation for the total API-value card: a command that aggregates
each capable provider's local usage into Today / Yesterday / 30 Days, using
the same canonical scanner aggregates as provider detail and the CLI.

- chart.rs: `LocalApiValuePeriod` (estimated API value USD, processed tokens,
  priced/total model tokens for pricing coverage, has_data) and
  `LocalApiValueProvider` across the three periods. `api_value_period` derives
  coverage from unknown_models (unpriced tokens counted but not priced, no
  fabricated dollars). New `get_local_api_value_totals` command scans codex +
  claude once each (30-day report + an exact local-day "yesterday" window) and
  omits providers with no source data in any period.
- Yesterday uses local calendar boundaries via `local_midnight_utc`
  (DST-safe: handles skipped/ambiguous local midnights) and
  `local_yesterday_window_utc`.
- Registered in main.rs + permissions/commands.toml. bridge.ts types +
  `getLocalApiValueTotals` wrapper wire it to the frontend boundary (the
  donut card UI lands in pass 3b).

Tests: partial pricing coverage, fully priced, empty (no data), and the
yesterday window spanning one local day (23-25h across DST). Desktop 381 /
frontend green; fmt + tsc clean.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
ceiling ca3865b Commit Preview URL

Branch Preview URL
Jul 18 2026, 09:42 PM

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 16 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5b73ec9f-b4b0-4475-a59b-e34691ce0337

📥 Commits

Reviewing files that changed from the base of the PR and between 2c80009 and ca3865b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • apps/desktop-tauri/src-tauri/Cargo.toml
  • apps/desktop-tauri/src-tauri/src/commands/chart.rs
📝 Walkthrough

Walkthrough

Adds local API-value totals for codex and claude across today, yesterday, and thirty days, including token pricing coverage and DST-safe date windows. The new Tauri command is registered, permitted, and exposed through typed TypeScript bridge definitions.

Changes

Local API value totals

Layer / File(s) Summary
API-value data contracts
apps/desktop-tauri/src-tauri/src/commands/chart.rs, apps/desktop-tauri/src/types/bridge.ts
Defines Rust DTOs and TypeScript interfaces for provider period totals, token coverage, estimated USD value, and data availability.
API-value aggregation and period windows
apps/desktop-tauri/src-tauri/src/commands/chart.rs
Computes provider totals for three periods using pricing coverage and DST-safe local windows, with unit tests for coverage and date-window behavior.
Tauri command exposure
apps/desktop-tauri/src-tauri/permissions/commands.toml, apps/desktop-tauri/src-tauri/src/main.rs, apps/desktop-tauri/src/lib/tauri.ts
Permits and registers get_local_api_value_totals, then exposes it through a typed TypeScript bridge function.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Bridge as getLocalApiValueTotals
  participant Command as get_local_api_value_totals
  participant Report as get_cost_usage_report_with_windows
  Bridge->>Command: Invoke API-value totals command
  Command->>Report: Request provider period windows
  Report-->>Command: Return CostSummary data
  Command-->>Bridge: Return LocalApiValueProvider[]
Loading

Possibly related PRs

Suggested reviewers: finesssee, darknight105

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: a cross-provider API-value aggregate backend for SOU-265.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/sou-265-api-value-totals

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/desktop-tauri/src-tauri/src/commands/chart.rs`:
- Around line 493-500: Update get_local_api_value_totals to return a friendly
Result error when spawn_blocking fails instead of substituting Vec::new().
Preserve the existing structured tracing::warn! call, and use the project’s
established anyhow/thiserror error pattern so worker panic or cancellation is
surfaced clearly to the frontend.
- Around line 472-482: The local_midnight_utc function must not fall back to
interpreting the naive timestamp as UTC when LocalResult::None occurs. Search
forward from the skipped midnight until the first valid local instant, or
propagate an error, and preserve the earliest choice for Ambiguous results. Add
deterministic tests covering both None and Ambiguous outcomes instead of relying
on Local::now().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 38717975-5707-44ad-9e43-d717e17967d5

📥 Commits

Reviewing files that changed from the base of the PR and between 0688cb0 and 2c80009.

📒 Files selected for processing (5)
  • apps/desktop-tauri/src-tauri/permissions/commands.toml
  • apps/desktop-tauri/src-tauri/src/commands/chart.rs
  • apps/desktop-tauri/src-tauri/src/main.rs
  • apps/desktop-tauri/src/lib/tauri.ts
  • apps/desktop-tauri/src/types/bridge.ts

Comment thread apps/desktop-tauri/src-tauri/src/commands/chart.rs
Comment thread apps/desktop-tauri/src-tauri/src/commands/chart.rs
tsouth89 added 2 commits July 18, 2026 17:32
Build the test CostSummary via a struct literal with ..Default::default()
instead of assigning scalar fields after default(), which tripped
clippy::field_reassign_with_default under -D warnings in CI.
Two fixes on the API-value aggregate:

- local_midnight_utc: on a skipped (spring-forward) local midnight, advance
  minute by minute to the first instant that actually exists instead of the
  old "+1h then treat naive as UTC" fallback, which gave a wrong boundary if
  more than one hour was skipped. Extracted a generic `local_midnight_in_tz`
  so the DST edges are deterministically testable, and added a chrono-tz
  dev-dependency + a test that finds real skipped/ambiguous midnights across
  several midnight-transition zones (replacing the Local::now() test that
  could never hit either edge).
- get_local_api_value_totals now returns Result<_, String>: a panicked or
  cancelled worker surfaces as an error, not an empty Vec, so the card can
  tell "unavailable" apart from genuine "No data".

clippy (-D warnings), desktop 382, fmt, and tsc all clean.
@tsouth89
tsouth89 merged commit 13e64e2 into main Jul 18, 2026
10 of 11 checks passed
@tsouth89
tsouth89 deleted the feat/sou-265-api-value-totals branch July 18, 2026 21:47
tsouth89 added a commit that referenced this pull request Jul 18, 2026
## What

The aggregate "estimated API value" card from SOU-265, consuming the
pass-3a backend (#57). Completes the SOU-262 dollar-analytics epic's UI.

## Changes

- **lib/apiValueCard.ts** - pure, unit-tested model + ring geometry.
`buildApiValueCard` omits providers with no data (never counts zero),
computes per-provider shares and pricing coverage; `ringSegments` turns
shares into stroke-dasharray donut segments.
- **components/TotalApiValueCard.tsx** - period switcher (Today /
Yesterday / 30 days) + metric switcher (API value / Tokens), an SVG
donut coloured by provider brand colors, a ranked legend (share +
value), and transparency copy: an estimate marker plus "N% of tokens
priced (unpriced models in ...)" whenever coverage is below 100%. Empty
periods show **No data**; a failed command shows an unavailable state.
`role="img"` on the ring carries an a11y summary of metric, period,
total, and providers.
- Mounted at the top of **ChartsPanel**; styling is responsive and
theme-aware, reusing existing design tokens.

## Terminology (per SOU-265)

Dollars are labelled **Estimated API value**, never a bill or
subscription spend. Providers with no source data are omitted; coverage
is surfaced whenever any tokens are unpriced.

## Tests

- 8 pure-logic cases: single / multiple / tiny-share / missing-data /
partial-pricing / all-unpriced, plus ring geometry.
- 3 render cases: aggregate total + ranked legend + coverage note, "No
data" on switching to an empty period, unavailable state on command
failure.

Frontend 258 / `tsc` clean.

**Note:** the donut was verified via the geometry unit tests and the
standard stroke-dasharray technique - the in-app browser preview was
unavailable for a live screenshot this session, so a visual pass on the
rendered ring is worth a glance before release.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added an API value card to the charts panel, always shown at the top.
* Lets you switch between periods (today, yesterday, past 30 days) and
metrics (API value vs tokens).
* Visualizes provider contributions with a ring breakdown and legend,
including token-pricing coverage where available.
  * Shows clear “no data” and “unavailable right now” states.
* **Tests**
* Added UI and calculation test coverage, including pricing coverage,
empty-period behavior, and error handling.
* **Style**
* Added responsive styling for the API value card (including
small-screen layout).
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: tsouth89 <tsouth89@users.noreply.github.com>
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