Repository navigation
feat(fetcher): claude_* family — claude_code_usage + claude_subscription - #251
Conversation
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]>
📝 WalkthroughWalkthroughAdds 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. ChangesClaude Fetcher Suite
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
src/fetcher/claude/code_usage.rssrc/fetcher/claude/common.rssrc/fetcher/claude/mod.rssrc/fetcher/claude/subscription.rssrc/fetcher/mod.rs
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]>
There was a problem hiding this comment.
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 winRestore
CLAUDE_CONFIG_DIRwith 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
📒 Files selected for processing (1)
src/fetcher/claude/code_usage.rs
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 undocumentedGET api.anthropic.com/api/oauth/usageendpoint, 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<root>/projects/<encoded-cwd>/<session-uuid>.jsonlunder every root inCLAUDE_CONFIG_DIR(default~/.claude+~/.config/claude)Safe(local files)Text("Today: 17.0M tokens / $52.70")Text/TextBlock/MarkdownTextBlock/Entries/Bars/NumberSeries/Badgesince(today/7d/30d/all),group_by(project/model/day),limit(1..=50)Dedup by
(message.id, requestId)— higher token total wins on collision (the ccusage gotcha for resumed sessions). Pricing for Opus / Sonnet / Haiku families plusclaude-3-*legacy names is hardcoded inclaude/common.rs; unknown models contribute 0 cost rather than failing the fetch.claude_subscriptionGET https://api.anthropic.com/api/oauth/usagewithanthropic-beta: oauth-2025-04-20claudeAiOauth.accessTokenfrom~/.claude/.credentials.json(override path viaSPLASHBOARD_CLAUDE_CREDENTIALSfor tests)Safe(host fixed atapi.anthropic.com)Ratio(single window selected viawindowoption)Ratio/Text/TextBlock/MarkdownTextBlock/Entries/Bars/Badge/Timelinewindow(string —five_hour/seven_day/seven_day_sonnet/ … plus aliases like5h/7d/claude_design)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 throughhumanize_keyso 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).claude_code_usageis 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_usagewalks the JSONL directory synchronously insideasync 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 tospawn_blocking.Test plan
cargo fmt --all -- --check✅cargo clippy --all-targets -- -D warnings✅cargo test✅ (52 + 20 new tests, full suite 3160 + 1 green)oauth/usageendpoint — 5h gauge / grid / badge values match claude.ai/account exactly.~/.claude/projects/on the maintainer's box — today / 7d / 30d rollups produced sensible Text / Bars / NumberSeries shapes.Catalog
claude_code_usagein meta: fetcher roadmap - Coding & Build #64 (AI / LLM — local agent activity) — to flip after merge.claude_subscriptionin meta: fetcher roadmap - Coding & Build #64 (AI / LLM — subscription seat / rate-limit headroom) — to flip after merge.anthropic_usagefrom meta: fetcher roadmap - Coding & Build #64 (already applied to the issue body — out of scope going forward).🤖 Generated with Claude Code
Summary by CodeRabbit