Repository navigation
Add local provider usage trend charts - #8406
jellychoco wants to merge 5 commits into
Conversation
… popover Add a chart panel to the right side of the status-bar Claude usage popover, porting the "Time Trends" hour-of-day overlay and daily trend charts from UsageScope. The popover previously showed only rate-limit bars (Session/Weekly/Fable); it now also charts locally scanned token usage history so users can see when and how much they use Claude. User-visible behavior: - Time Trends: hour-of-day overlay line chart (X = 00-23h). One line per day, today emphasized at 2px full opacity, historical days at 1px with per-window opacity (1D 0.9 / 7D 0.38 / 30D 0.2 / 6M 0.08) so overlap density reads as "hours I use most". Hover shows a per-hour tooltip: Today / Avg (active days) / Peak. - Day Trends: total-token bars per day (7D/30D) or per month (6M), hover tooltip with Total/Input/Output/Cache read/Cache write. A leading partial month is trimmed from the 6M view so month totals compare honestly. - Mode (Time/Day) and range (1D/7D/30D/6M) persist via localStorage. - Charts fill the panel height via ResizeObserver-driven SVG sizing; gridline density increases (2 -> 4 lines) on plots >= 200px tall. - Usage tracking stays opt-in: the panel shows an enable CTA until claude-usage scanning is turned on; data never leaves the device. - The panel is hidden while a remote runtime environment is active: the popover then shows the remote account (stablyai#7973) and pairing it with local-disk charts would misattribute the data. Data pipeline (main process): - claude-usage scanner now aggregates hour-of-day buckets (day x hour, project/model-free key to keep the cache small) alongside daily aggregates, merged across files with the same dedupe/ownership semantics (stablyai#8006 fork reclaim unaffected). - SCHEMA_VERSION 5 -> 6: old caches lack per-file hourly projections, so they are dropped and fully reparsed on next refresh; scanState.enabled is preserved across the bump (existing behavior). - New query getHourly(days): serves hourly points clamped to HOURLY_RETENTION_DAYS = 185 (6M window + slack) via new IPC channel claudeUsage:getHourly, exposed on window.api.claudeUsage. Per-file changes: | File | Change | | --- | --- | | src/main/claude-usage/types.ts | ClaudeUsageHourlyAggregate; hourlyAggregates on persisted state/file; hour on attributed turn | | src/main/claude-usage/scanner.ts | local day+hour bucketing, hourly aggregation/merge/sort, hourly in per-file reuse check and scan result | | src/main/claude-usage/store.ts | SCHEMA_VERSION 5->6, HOURLY_RETENTION_DAYS=185, getHourly/buildHourly, getDayCutoff extracted from getRangeCutoff | | src/main/ipc/claude-usage.ts | claudeUsage:getHourly handler | | src/preload/index.ts, api-types.ts | claudeUsage.getHourly bridge + ClaudeUsageHourlyResult typing | | src/shared/claude-usage-types.ts | ClaudeUsageHourlyPoint, ClaudeUsageHourlyResult DTOs | | src/renderer/.../ClaudeUsageTrendsPanel.tsx | new: panel shell, mode/range segmented controls, fetch + enable/error/empty/loading states | | src/renderer/.../claude-usage-trends-model.ts | new: pure model — hour-of-day matrix, day/month buckets, monotone-cubic path builder, tooltip stats | | src/renderer/.../claude-usage-trend-charts.tsx | new: TimeTrendsChart + DayTrendsChart SVG rendering and hover hit-testing | | src/renderer/.../claude-usage-trend-chart-frame.tsx | new: shared chart scaffolding — dims hook (ResizeObserver), Y axis, tooltip surface | | src/renderer/.../StatusBar.tsx | ProviderDetailsMenu sideContent prop (260px -> 588px two-column layout when present); Claude menu passes the panel, gated off remote runtimes | | src/main/claude-usage/*.test.ts, .../claude-usage-trends-model.test.ts | 13 new tests: hourly aggregation, window/185d clamp, day/month bucketing, partial-month trim, monotone path, tooltip stats | | src/renderer/src/i18n/locales/*.json | 28 new auto.* keys via pnpm run sync:localization-catalog | Design decisions: - Hourly aggregates are account-wide (no scope/model/project dimension) because the popover complements account-level rate limits; persisted size stays <= 24 rows per active day per file. - Retention is enforced at query time (matching the store's existing "no pruning, filter at query" convention); 185 days is the ceiling the API will serve regardless of requested window. - Charts are hand-rolled SVG with --chart-3 tokens (no chart library, matching the existing stats-pane convention of hand-rolled charts). Known limitation: controls inside the Radix DropdownMenu popover are not keyboard-reachable (Radix menus block Tab and rove only across menu items). This matches the pre-existing AccountRuntimeToggle in the same popover; usage tracking can also be enabled from Settings > Stats & Usage, which remains keyboard-accessible. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds hourly usage aggregation and persistence for Claude, Codex, and OpenCode, plus local Gemini and Kimi history scanning. Exposes hourly queries through main-process IPC and preload APIs. Adds provider trend models, responsive charts, configurable trend panels, localized labels, and status-bar integration. Tests cover hourly aggregation, persistence filtering, local-history parsing, reuse, trend modeling, and chart calculations. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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 |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
src/renderer/src/components/status-bar/ClaudeUsageTrendsPanel.tsx (2)
89-115: 🩺 Stability & Availability | 🔵 TrivialNo timeout on the
getHourlyIPC round trip.If the main-process scan (or the underlying
refresh()it triggers) stalls, the "Scanning local transcripts…" state can persist indefinitely with no fallback for the user. Consider wrapping this call with a bounded timeout so a stuck scan surfaces theloadFailedstate instead of hanging silently.
41-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace the custom segmented control with the existing
ToggleGroupprimitive.src/renderer/src/components/ui/toggle-group.tsxalready exists, so reusing it keeps keyboard/focus behavior and styling aligned with the rest of the UI.Source: Path instructions
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 0f4944b0-ddc4-4109-b39b-1e7010bea54b
📒 Files selected for processing (20)
src/main/claude-usage/scanner.test.tssrc/main/claude-usage/scanner.tssrc/main/claude-usage/store.test.tssrc/main/claude-usage/store.tssrc/main/claude-usage/types.tssrc/main/ipc/claude-usage.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/status-bar/ClaudeUsageTrendsPanel.tsxsrc/renderer/src/components/status-bar/StatusBar.tsxsrc/renderer/src/components/status-bar/claude-usage-trend-chart-frame.tsxsrc/renderer/src/components/status-bar/claude-usage-trend-charts.tsxsrc/renderer/src/components/status-bar/claude-usage-trends-model.test.tssrc/renderer/src/components/status-bar/claude-usage-trends-model.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/claude-usage-types.ts
Review: stablyai#8406 (CodeRabbit, 3 actionable + 2 nitpicks) Per-file changes: | File | Change | | --- | --- | | claude-usage-trend-charts.tsx | date axis/tooltip labels now use the active UI locale (i18n.language) instead of the OS locale (toLocaleDateString undefined -> i18n.language) | | ClaudeUsageTrendsPanel.tsx | SegmentedControl reimplemented on the ui/toggle-group shadcn primitive (guarding Radix's empty-value emit on re-click); Enable button disabled while loading to prevent overlapping setEnabled/getHourly calls; mode toggle gets its own aria-label 'Chart mode' (new key 53ce9bcf71) instead of duplicating the region label | | i18n/locales/*.json | 'Chart mode' key synced across 5 catalogs | Declined (with rationale in PR thread): client-side timeout on the getHourly IPC — first scans of large transcript histories legitimately run long and the IPC resolves when the scan completes; a fixed timeout would misreport in-progress scans as failures, and scan errors already surface via scanState.lastScanError. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Addressed the CodeRabbit review in bd711c6:
Declining one nitpick with rationale — client-side timeout on the Re-ran |
There was a problem hiding this comment.
🧹 Nitpick comments (6)
src/renderer/src/components/status-bar/provider-usage-trend-chart-frame.tsx (1)
127-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHardcoded shadow bypasses design tokens.
shadow-[0_10px_24px_rgba(0,0,0,0.18)]is a raw, hand-picked value rather than a token frommain.css. Consider using an existing shadow scale (e.g.shadow-lg) or adding a named token if this exact elevation is intentional.As per coding guidelines,
src/renderer/src/**/*.{tsx,ts,css}: "All UI work must followdocs/STYLEGUIDE.md, use tokens fromsrc/renderer/src/assets/main.css, and use shadcn primitives fromsrc/renderer/src/components/ui/."Source: Coding guidelines
src/renderer/src/components/status-bar/ProviderUsageTrendsPanel.tsx (1)
376-382: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winNo lower bound on the custom range start date.
The Start date input only caps the upper end (
max={customEndDay}); nothing stops a user from picking a start date years/decades in the past. That unbounded range flows intolistLocalDaysInRangewith no cap, which then drivesTimeTrendsChartto render one SVG line per day (unbounded) and can pushDayTrendsChart's month-bucket count high enough thatbarWidth = Math.min(getDayBarWidth(...), band - 2)goes negative for very long ranges.Consider adding a reasonable
min(e.g. a fixed lookback cap) to bound both the day-count and the downstream rendering cost.src/main/codex-usage/store.ts (1)
284-304: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract
getDayCutoff/isValidDayKeyinto a shared helper. Both provider stores introduce byte-for-byte identical date-validation helpers (and structurally identicalbuildHourlyfiltering logic) in this PR; the same pattern also exists insrc/main/opencode-usage/store.ts. Neither helper touches provider-specific state, so they're safe to consolidate into a single shared module to avoid the three copies drifting apart on future fixes (e.g. leap-year/timezone edge cases).
src/main/codex-usage/store.ts#L284-L304: replace the localgetDayCutoff/isValidDayKeydefinitions with an import from a new shared date-utils module.src/main/claude-usage/store.ts#L295-L305: replace the localisValidDayKeydefinition with the same shared import (and itsgetDayCutoffcounterpart).src/preload/index.ts (1)
3792-3793: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse shared
*HourlyQuery/*HourlyResulttypes instead of inlining and widening tounknown.All three new
getHourlyforwarders inline the query union type rather than importingClaudeUsageHourlyQuery/CodexUsageHourlyQuery/OpenCodeUsageHourlyQuery(already used inapi-types.ts), and returnPromise<unknown>rather than the corresponding*HourlyResulttype declared in the*Apiinterfaces. This duplicates the type definition and loses type safety for consumers ofwindow.api.*Usage.getHourly(...).♻️ Proposed fix
- getHourly: (args: { days: number } | { startDay: string; endDay: string }): Promise<unknown> => + getHourly: (args: ClaudeUsageHourlyQuery): Promise<ClaudeUsageHourlyResult> => ipcRenderer.invoke('claudeUsage:getHourly', args),(repeat analogously for the codex and openCode blocks, importing the respective
*HourlyQuery/*HourlyResulttypes)Also applies to: 3812-3813, 3832-3833
src/main/opencode-usage/store.test.ts (1)
317-339: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test for the
{ days }branch ofgetHourly.Only the
{ startDay, endDay }custom-range branch ofbuildHourlyis tested here; the{ days }branch (the default path used for 1D/7D/30D/6M windows) has no direct test coverage in this file.✅ Suggested additional test
it('serves hourly points within a days-based cutoff', async () => { const point = (day: string, hour: number, inputTokens: number) => ({ day, hour, eventCount: 1, inputTokens, cachedInputTokens: 10, outputTokens: 25, reasoningOutputTokens: 10, totalTokens: inputTokens + 25 }) const store = createStoreWithState({ hourlyAggregates: [point('2020-01-01', 9, 500), point(getTodayDayKey(), 10, 100)] }) const result = await store.getHourly({ days: 1 }) expect(result.points).toEqual([point(getTodayDayKey(), 10, 100)]) })src/main/opencode-usage/store.ts (1)
77-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHour-bucketing/date-validation utilities are triplicated across provider modules. This PR introduces
getDayCutoff,isValidDayKey,localDayAndHourFromTimestamp,mergeHourlyAggregates, andsortHourlyAggregatesindependently in the OpenCode modules, while graph evidence shows near-identical copies already exist in the Codex and Claude usage modules (codex-usage/store.ts,codex-usage/scanner.ts,claude-usage/store.ts). Since all three providers are gaining this feature in the same effort, extracting these into a shared date/aggregation utility module now avoids three copies drifting independently later.
src/main/opencode-usage/store.ts#L77-L104: extractgetDayCutoffandisValidDayKeyinto a shared module imported by all three provider stores.src/main/opencode-usage/scanner.ts#L412-L421: extractlocalDayAndHourFromTimestampinto the shared module, replacing the equivalent function incodex-usage/scanner.ts.src/main/opencode-usage/scanner.ts#L874-L901: extractmergeHourlyAggregates/sortHourlyAggregatesinto the shared module, replacing the equivalent functions incodex-usage/scanner.ts.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3e699f70-1d92-406a-8093-e4ef24efbdc8
📒 Files selected for processing (34)
src/main/claude-usage/store.test.tssrc/main/claude-usage/store.tssrc/main/codex-usage/scanner.test.tssrc/main/codex-usage/scanner.tssrc/main/codex-usage/store.test.tssrc/main/codex-usage/store.tssrc/main/codex-usage/types.tssrc/main/ipc/claude-usage.tssrc/main/ipc/codex-usage.tssrc/main/ipc/opencode-usage.tssrc/main/opencode-usage/scanner.test.tssrc/main/opencode-usage/scanner.tssrc/main/opencode-usage/store.test.tssrc/main/opencode-usage/store.tssrc/main/opencode-usage/types.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/status-bar/ProviderUsageTrendsPanel.tsxsrc/renderer/src/components/status-bar/StatusBar.tsxsrc/renderer/src/components/status-bar/provider-usage-trend-chart-frame.tsxsrc/renderer/src/components/status-bar/provider-usage-trend-charts.tsxsrc/renderer/src/components/status-bar/provider-usage-trends-configuration.tssrc/renderer/src/components/status-bar/provider-usage-trends-date-range.tssrc/renderer/src/components/status-bar/provider-usage-trends-model.test.tssrc/renderer/src/components/status-bar/provider-usage-trends-model.tssrc/renderer/src/components/status-bar/provider-usage-trends-segmented-control.tsxsrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/claude-usage-types.tssrc/shared/codex-usage-types.tssrc/shared/opencode-usage-types.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/shared/claude-usage-types.ts
- src/renderer/src/i18n/locales/es.json
- src/renderer/src/i18n/locales/ja.json
- src/renderer/src/i18n/locales/zh.json
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/index.ts (1)
923-951: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winMissing null-guard for
geminiUsage/kimiUsagebefore use, unlike every other lifecycle dependency.Every other service passed into
registerCoreHandlers(claudeUsage,codexUsage,openCodeUsage,rateLimits,automations,codexAccounts,codexRuntimeHome,claudeAccounts,claudeRuntimeAuth,keybindings) is explicitly checked withif (!x) throw new Error(...)earlier inopenMainWindow()before being used.geminiUsage!/kimiUsage!skip that guard and rely purely on a non-null assertion at Line 945. BecauseregisterCoreHandlersonly runs its body once (registeredflag), if these happen to benullon the first call, the Gemini/Kimi local-usage-history IPC handlers would never register for the app's lifetime, rather than failing with the descriptive error used elsewhere.🛡️ Proposed fix: mirror the existing guard pattern
if (!keybindings) { throw new Error('Keybinding service must be initialized before opening the main window') } + if (!geminiUsage) { + throw new Error('Gemini usage history store must be initialized before opening the main window') + } + if (!kimiUsage) { + throw new Error('Kimi usage history store must be initialized before opening the main window') + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 5ecb6e63-6a03-435d-9910-de93c0f1a49a
📒 Files selected for processing (18)
src/main/index.tssrc/main/ipc/local-usage-history.tssrc/main/ipc/register-core-handlers.tssrc/main/local-usage-history/scanner.test.tssrc/main/local-usage-history/scanner.tssrc/main/local-usage-history/store.test.tssrc/main/local-usage-history/store.tssrc/main/local-usage-history/types.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/status-bar/ProviderUsageTrendsPanel.tsxsrc/renderer/src/components/status-bar/StatusBar.tsxsrc/renderer/src/components/status-bar/provider-usage-trend-charts.tsxsrc/renderer/src/components/status-bar/provider-usage-trends-configuration.tssrc/renderer/src/components/status-bar/provider-usage-trends-detail-rows.tssrc/renderer/src/components/status-bar/provider-usage-trends-model.test.tssrc/renderer/src/components/status-bar/provider-usage-trends-model.tssrc/shared/local-usage-history-types.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/renderer/src/components/status-bar/provider-usage-trend-charts.tsx
- src/renderer/src/components/status-bar/ProviderUsageTrendsPanel.tsx
- src/renderer/src/components/status-bar/provider-usage-trends-model.ts
- src/renderer/src/components/status-bar/provider-usage-trends-model.test.ts
|
very cool feature. @brennanb2025 can help get it in |
What
Adds opt-in, local token-usage trend charts to the status-bar usage popovers for:
Each provider shows the same two chart modes:
Screenshots
Custom period
The presets remain 1D / 7D / 30D / 6M, and every supported provider also has a Custom range with Start and End date inputs. The previous Claude-only 185-day response ceiling is removed: a custom range queries only the corresponding interval from already-persisted local hourly projections.
For long custom ranges, daily totals are grouped by month and hourly overlays reduce line opacity as the number of days grows, keeping the popover responsive without discarding local history.
Local sources and privacy
~/.gemini/tmpJSON/JSONL session records and projects the recordedinput,cached,output,thoughts,tool, andtotaltoken fields.wire.jsonlusage.recordevents below<KIMI_CODE_HOME>/sessions. It records input, output, cache read, and cache creation fields, while ignoring cumulative session records so a turn is never counted twice.day × hourprojections. On later scans, unchanged transcript files are reused by mtime and size rather than reparsed.Deferred providers
Validation
pnpm testpnpm lintpnpm run typecheckpnpm run build:desktopFocused coverage includes Claude/Codex/OpenCode hourly aggregation, Gemini JSON/JSONL token parsing, Kimi wire usage parsing, custom date-range retrieval, persisted-file reuse, cache schema invalidation, monthly grouping, adaptive line opacity, and chart tooltip math.
ELI5
Status-bar usage popovers can show opt-in local token trend charts for major agents (Claude Code, Codex, OpenCode, Gemini CLI, Kimi Code). You can see hour-of-day and day/month usage patterns without leaving the app.