Skip to content

feat(fetcher): claude_* family — claude_code_usage + claude_subscription - #251

Merged
unhappychoice merged 3 commits into
mainfrom
feat/claude-fetchers
May 23, 2026
Merged

unhappychoice merged 3 commits into
mainfrom
feat/claude-fetchers

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a new claude_* fetcher family with two members that target Splashboard's biggest persona overlap (Claude Code users):

  • claude_code_usage — token + cost rollup from local Claude Code session JSONL files. Zero-config (~/.claude/projects/*.jsonl), Safety::Safe, pricing bundled.
  • claude_subscription — Max-plan utilisation via the undocumented GET api.anthropic.com/api/oauth/usage endpoint, using the OAuth token Claude Code already stores in ~/.claude/.credentials.json. Surfaces every non-null window the response carries (5h / 7d / 7d Sonnet / 7d Opus / Claude Design / …).

claude_code_usage

Source <root>/projects/<encoded-cwd>/<session-uuid>.jsonl under every root in CLAUDE_CONFIG_DIR (default ~/.claude + ~/.config/claude)
Auth none
Safety Safe (local files)
Default shape Text ("Today: 17.0M tokens / $52.70")
Shapes (7) Text / TextBlock / MarkdownTextBlock / Entries / Bars / NumberSeries / Badge
Options since (today / 7d / 30d / all), group_by (project / model / day), limit (1..=50)
Refresh 5 min

Dedup by (message.id, requestId) — higher token total wins on collision (the ccusage gotcha for resumed sessions). Pricing for Opus / Sonnet / Haiku families plus claude-3-* legacy names is hardcoded in claude/common.rs; unknown models contribute 0 cost rather than failing the fetch.

claude_subscription

Source GET https://api.anthropic.com/api/oauth/usage with anthropic-beta: oauth-2025-04-20
Auth claudeAiOauth.accessToken from ~/.claude/.credentials.json (override path via SPLASHBOARD_CLAUDE_CREDENTIALS for tests)
Safety Safe (host fixed at api.anthropic.com)
Default shape Ratio (single window selected via window option)
Shapes (8) Ratio / Text / TextBlock / MarkdownTextBlock / Entries / Bars / Badge / Timeline
Options window (string — five_hour / seven_day / seven_day_sonnet / … plus aliases like 5h / 7d / claude_design)
Refresh 15 min

Generic walker — every key in the response that carries {utilization, resets_at} is surfaced as a window. Known codenames are mapped to claude.ai UI labels (e.g. seven_day_omelette → Claude Design); unknown keys fall through humanize_key so a future window auto-shows up with a readable label. Utilisation arrives on a 0..100 percent scale, normalised internally to 0..1 with a 1.5 ceiling for distinct over-quota rendering.

The endpoint is undocumented and may break — every failure path returns FetchError::Failed, never panics. Tone thresholds: Ok < 60% / Warn < 85% / Error ≥ 85%.

Trade-offs

  • anthropic_usage (originally part of this batch) was dropped — admin-key persona is too thin for Splashboard's audience (Org Admin-only). The catalog entry has been removed from meta: fetcher roadmap - Coding & Build #64 (see catalog edit).
  • Pricing for claude_code_usage is hardcoded rather than vendoring LiteLLM's price feed — keeps the fetcher offline-safe; future PR can wire LiteLLM if richer coverage is needed.
  • claude_code_usage walks the JSONL directory synchronously inside async fn fetch. With a 5-min TTL the cache hides the cost in normal use; if heavily used sessions push the cold-fetch latency, a follow-up can offload to spawn_blocking.

Test plan

  • cargo fmt --all -- --check ✅
  • cargo clippy --all-targets -- -D warnings ✅
  • cargo test ✅ (52 + 20 new tests, full suite 3160 + 1 green)
  • Manual smoke test against live oauth/usage endpoint — 5h gauge / grid / badge values match claude.ai/account exactly.
  • Manual smoke test against ~/.claude/projects/ on the maintainer's box — today / 7d / 30d rollups produced sensible Text / Bars / NumberSeries shapes.

Catalog

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Track local Claude code token usage and costs per project/day with deduplication, daily series, cost badges, bars, entries and summary widgets.
    • Monitor Claude subscription/quota utilization with percentage, reset-time, timeline and status badges.
    • Register Claude fetchers so Claude data appears alongside other built-in usage dashboards.

Review Change Stack

unhappychoice and others added 2 commits May 23, 2026 17:57
Walks the `<root>/projects/<encoded-cwd>/<session-uuid>.jsonl` files Claude
Code writes for every assistant turn, deduplicates by `(message.id, requestId)`
(higher token total wins on collision), then groups by project / model / day
depending on `group_by`.

Pricing is hardcoded in `claude/common.rs` (Opus / Sonnet / Haiku families plus
the legacy `claude-3-*` aliases), so the splash works offline. Refresh interval
is 5 minutes — fast enough to reflect a freshly-spent session, slow enough not
to re-walk MBs on every `cd`.

7 shapes:
- Text — `"Today: 17.0M tokens / \$52.70"` headline
- TextBlock / MarkdownTextBlock / Entries — per-group rows
- Bars — value=tokens (chart_bar ranks correctly), value_label=`\$cost`
- NumberSeries — daily token total time series
- Badge — cost tier (Ok < \$10 / Warn < \$50 / Error ≥ \$50)

Options: `since` (`today` / `7d` / `30d` / `all`), `group_by` (`project` /
`model` / `day`), `limit` (1..=50). `Safety::Safe`, no network.

Family scaffold lives in `src/fetcher/claude/` (mod + common + code_usage);
the family is plumbed into `Registry::with_builtins`.

Catalog: #64 AI / LLM — local agent activity.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…th/usage

Queries the **undocumented** `GET https://api.anthropic.com/api/oauth/usage`
endpoint with the OAuth token Claude Code stores in
`~/.claude/.credentials.json` (`.claudeAiOauth.accessToken`), plus the
`anthropic-beta: oauth-2025-04-20` header. Surfaces every non-null usage
window the response carries — `five_hour`, `seven_day`, `seven_day_sonnet`,
`seven_day_opus`, `seven_day_omelette` (= the "Claude Design" pool in the
claude.ai UI), and any internal codenames the server returns.

Generic walker: deserialize as `serde_json::Value`, iterate keys, skip
`extra_usage` (different schema). Known keys map to the claude.ai UI label
(`seven_day_omelette` → "Claude Design"); unknown keys fall through a
`humanize_key` helper so a future window auto-surfaces with a readable label.
Utilisation arrives on a 0..100 percent scale (`7.0` = 7%) — normalise to 0..1
internally and clamp at 1.5 for over-quota so a blown window still renders
distinctly.

8 shapes:
- Ratio (default) — single window selected by `window` option, label includes
  the relative reset ETA (`5h · resets 2h`)
- Text — one-line summary across every present window
- TextBlock / MarkdownTextBlock / Entries — per-window rows
- Bars — value=basis points (so chart_bar ranks correctly),
  value_label=`"7%"`
- Badge — `5h 7%` plus a tone (Ok < 60% / Warn < 85% / Error ≥ 85%)
- Timeline — one event per reset, sorted chronologically

`window` option accepts friendly aliases (`5h` → `five_hour`, `7d_sonnet`,
`claude_design` → `seven_day_omelette`, …) plus any raw response key.
Refresh interval 15 minutes. `Safety::Safe` — host fixed, token never leaves
`api.anthropic.com`.

Undocumented endpoint: every failure path short-circuits to `FetchError` so
the splash renders a placeholder rather than panicking if Anthropic moves the
endpoint or shifts the response shape.

Catalog: #64 AI / LLM — subscription seat / rate-limit headroom.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a Claude fetcher suite: shared pricing/utilities, a local JSONL code-usage aggregator (ClaudeCodeUsage), an OAuth-based subscription fetcher (ClaudeSubscription), and registry wiring to expose both fetchers.

Changes

Claude Fetcher Suite

Layer / File(s) Summary
Claude shared utilities and pricing
src/fetcher/claude/common.rs
Introduces Price struct with tiered pricing for input, output, and cache operations. Pricing table maps Claude model-id prefixes (including legacy dated names) to per-million-token costs. Implements case-insensitive prefix matching, cost aggregation across tiers, compact USD/token formatting, JSONL directory discovery with CLAUDE_CONFIG_DIR env override, and project name extraction from cwd.
Code usage fetcher (local JSONL)
src/fetcher/claude/code_usage.rs
Reads Claude session JSONL files from discovered local directories, filters to assistant events, parses and deduplicates by (message_id, request_id) keeping the max token entry, groups aggregated rows by project/model/day with cost-based sorting and limit truncation. Supports since windows (today, 7d, 30d, all) and generates per-day token series. Renders multiple shapes (text, text block, markdown, entries, bars, number series, badge) with quiet-window messaging and cost-based badge severity. Includes tests validating parsing, legacy cache split fallback, dedup collision handling, grouping logic, model normalization, and end-to-end filesystem fetch with env-root override.
Subscription fetcher (OAuth API)
src/fetcher/claude/subscription.rs
Loads OAuth access token from credentials JSON (env override or home-directory default), makes authenticated request to Anthropic utilization API with bearer auth and beta header. Parses per-window utilization/clamped-to-1.5 and optional reset timestamps, normalizes friendly window aliases (5h, 7d, claude_design). Renders multiple shapes with human-friendly labels, percentage formatting, relative reset-time strings (now/Xm/Xh/Xd), and status bucketing by utilization threshold. Includes tests for credential loading, snapshot parsing with extra_usage skipping and clamping, rendering fallbacks, formatting utilities, and fetch error cases.
Claude module wiring and registry
src/fetcher/claude/mod.rs, src/fetcher/mod.rs
Declares submodules and exports fetchers() returning both ClaudeCodeUsage and ClaudeSubscription as Arc<dyn Fetcher>. Integrates into Registry::with_builtins() alongside other fetcher families. Validates all Claude fetcher names follow the claude_ prefix convention.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • unhappychoice/splashboard#240: Adds the deal fetcher family using the same registry integration pattern, modifying Registry::with_builtins() to register additional fetcher families.

Poem

🐰 Claude the generous sent word today,
Usage and bills both displayed their way,
Through JSONL trails and OAuth streams,
Tokens tallied in tidy teams,
A fetcher hop, now bloom and play.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.71% 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 'feat(fetcher): claude_* family — claude_code_usage + claude_subscription' clearly and specifically describes the main changes: adding two new Claude fetchers to the codebase.
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.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/claude-fetchers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.71747% with 219 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.70%. Comparing base (2a2e1fd) to head (73f6808).

Files with missing lines Patch % Lines
src/fetcher/claude/subscription.rs 80.03% 121 Missing ⚠️
src/fetcher/claude/code_usage.rs 85.19% 89 Missing ⚠️
src/fetcher/claude/common.rs 92.62% 9 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #251      +/-   ##
==========================================
- Coverage   95.95%   95.70%   -0.25%     
==========================================
  Files         239      243       +4     
  Lines       64926    66271    +1345     
==========================================
+ Hits        62298    63424    +1126     
- Misses       2628     2847     +219     
Files with missing lines Coverage Δ
src/fetcher/claude/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 99.02% <100.00%> (+<0.01%) ⬆️
src/fetcher/claude/common.rs 92.62% <92.62%> (ø)
src/fetcher/claude/code_usage.rs 85.19% <85.19%> (ø)
src/fetcher/claude/subscription.rs 80.03% <80.03%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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: 3

🤖 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 `@src/fetcher/claude/code_usage.rs`:
- Around line 142-147: The Since::Days(n) inclusion uses a rolling timestamp
cutoff but should align with calendar-day buckets used by daily_series; update
the includes method in code_usage.rs so that for Since::Days(n) you compute a
cutoff_date = Utc::now().date_naive() - Duration::days(*n) and return
ts.date_naive() >= cutoff_date (compare dates, not full datetimes) to ensure
events are included by whole calendar-day buckets; make the same change in the
other occurrence of this logic (the block referenced around lines 425-443) so
both uses of Since::Days use date_naive() comparison.
- Around line 277-281: The current pipeline drops lines by checking the literal
substring "\"type\":\"assistant\"" before parsing, which is brittle; instead
feed each line into parse_event first and then filter parsed events by their
role/type (e.g., check e.role == "assistant" or e.type == "assistant") and by
timestamp via since.includes; replace the .filter(|line| line.contains(...))
step with a post-parse filter on the parsed Event result from parse_event
(referencing parse_event and the closure that checks since.includes) so JSON
formatting/whitespace changes no longer cause valid assistant records to be
skipped.
- Around line 361-374: The current dedupe uses (e.message_id.clone(),
e.request_id.clone()) as the HashMap key and treats empty strings as real IDs,
causing unrelated events to merge; update the loop in which by_key is populated
so deduplication only happens when both e.message_id and e.request_id are
non-empty (e.g., check that neither is "", then use the tuple key and the
existing entry/and_modify logic), and when either ID is empty skip using that
tuple key and instead insert the event uniquely (for example push it directly
into the output or use a fallback unique key like a sequence counter) so no
records are lost; adjust references to by_key, events, UsageEvent, token_total,
message_id, and request_id accordingly.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: c77c6967-6b32-41a8-a98b-a5055b012e6e

📥 Commits

Reviewing files that changed from the base of the PR and between 2a2e1fd and 59e3fdc.

📒 Files selected for processing (5)
  • src/fetcher/claude/code_usage.rs
  • src/fetcher/claude/common.rs
  • src/fetcher/claude/mod.rs
  • src/fetcher/claude/subscription.rs
  • src/fetcher/mod.rs

Comment thread src/fetcher/claude/code_usage.rs Resolved
Comment thread src/fetcher/claude/code_usage.rs Resolved
Comment thread src/fetcher/claude/code_usage.rs Resolved
Three nits surfaced by the bot review:

1. `Since::Days(n).includes()` was a rolling `now - n days` timestamp cutoff
   while `daily_series` bucketed by calendar day. Near the n-day boundary,
   partial-day events were counted in the totals but never appeared in the
   per-day series. Swap to a calendar-day comparison (`today .. today-(n-1)`)
   so both views agree on the window.

2. Dropped the brittle `line.contains("\"type\":\"assistant\"")` pre-filter.
   `parse_event` already gates on `raw.kind == "assistant"` — the substring
   guard was only a perf hack and would silently miss records if Claude
   Code's JSONL formatter ever emitted `"type": "assistant"` with whitespace.
   Cost is ~5% more parsing per refresh, absorbed by the 5-min cache TTL.

3. Empty-ID dedup collision: serde fills missing `message.id` / `requestId`
   with `""`, so two unrelated assistant turns lacking those fields collapsed
   into a single `("", "")` bucket and one would be discarded. Records with
   either ID missing now pass through unmodified instead.

Two new tests pin the new invariants:
- `since_days_window_uses_calendar_day_boundary_not_rolling_timestamp`
- `dedup_passes_through_events_with_empty_ids_instead_of_collapsing_them`

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/fetcher/claude/code_usage.rs (1)

918-930: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Restore CLAUDE_CONFIG_DIR with a drop guard.

If this test panics anywhere after set_var, the manual restore is skipped and later tests inherit the wrong Claude root. A tiny RAII guard makes the env cleanup happen during unwind too.

Suggested fix
         let prev = std::env::var("CLAUDE_CONFIG_DIR").ok();
+        struct EnvRestore(Option<String>);
+        impl Drop for EnvRestore {
+            fn drop(&mut self) {
+                match self.0.take() {
+                    Some(v) => unsafe { std::env::set_var("CLAUDE_CONFIG_DIR", v) },
+                    None => unsafe { std::env::remove_var("CLAUDE_CONFIG_DIR") },
+                }
+            }
+        }
+        let _restore = EnvRestore(prev);
         unsafe { std::env::set_var("CLAUDE_CONFIG_DIR", tmp.path()) };
 
         let body = ClaudeCodeUsage
             .fetch(&ctx(Some("since = \"today\""), Some(Shape::Text)))
             .await
             .unwrap()
             .body;
-
-        match prev {
-            Some(v) => unsafe { std::env::set_var("CLAUDE_CONFIG_DIR", v) },
-            None => unsafe { std::env::remove_var("CLAUDE_CONFIG_DIR") },
-        }
🤖 Prompt for 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.

In `@src/fetcher/claude/code_usage.rs` around lines 918 - 930, Wrap the temporary
env change in a small RAII guard struct (e.g., EnvRestore) that captures the
previous value of "CLAUDE_CONFIG_DIR" and the key, then set the var with
tmp.path() and let the guard live until after ClaudeCodeUsage.fetch completes;
implement Drop for EnvRestore to restore the previous value or remove the var if
None instead of the manual match block (replace the prev/match restore code with
the guard instantiation and drop-on-scope-exit behavior) so unwind during panics
also restores the environment.
🤖 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.

Outside diff comments:
In `@src/fetcher/claude/code_usage.rs`:
- Around line 918-930: Wrap the temporary env change in a small RAII guard
struct (e.g., EnvRestore) that captures the previous value of
"CLAUDE_CONFIG_DIR" and the key, then set the var with tmp.path() and let the
guard live until after ClaudeCodeUsage.fetch completes; implement Drop for
EnvRestore to restore the previous value or remove the var if None instead of
the manual match block (replace the prev/match restore code with the guard
instantiation and drop-on-scope-exit behavior) so unwind during panics also
restores the environment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fc23ef0d-01bb-4972-b6e4-b0d1b5c20c09

📥 Commits

Reviewing files that changed from the base of the PR and between 59e3fdc and 73f6808.

📒 Files selected for processing (1)
  • src/fetcher/claude/code_usage.rs

@unhappychoice
unhappychoice merged commit 833bc31 into main May 23, 2026
11 of 12 checks passed
@unhappychoice
unhappychoice deleted the feat/claude-fetchers branch May 23, 2026 09:29
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