feat(usage): prefer stdin rate_limits over API polling#112
feat(usage): prefer stdin rate_limits over API polling#112nsdont wants to merge 1 commit intoHaleclipse:masterfrom
Conversation
Claude Code >= 2.1.80 passes rate_limits in the statusLine JSON input, providing real-time usage data with zero network overhead. This change makes the Usage segment read from stdin first and only falls back to the API polling path for older Claude Code versions. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Reviewer's GuideUsage segment now prefers real-time rate limit data from Claude Code stdin (with a new epoch-based reset-time formatter) while retaining the existing OAuth usage API polling as a transparent fallback for older clients. Sequence diagram for UsageSegment collect with stdin rate_limits and API fallbacksequenceDiagram
actor User
participant SegmentRenderer
participant ClaudeCode
participant UsageSegment
participant Credentials
participant OAuthAPI
User ->> SegmentRenderer: render_promptline()
SegmentRenderer ->> ClaudeCode: request_status_line_json()
ClaudeCode -->> SegmentRenderer: InputData(rate_limits, ...)
SegmentRenderer ->> UsageSegment: collect(input: &InputData)
alt rate_limits present in input
UsageSegment ->> UsageSegment: read five_hour.used_percentage
UsageSegment ->> UsageSegment: read seven_day.used_percentage
UsageSegment ->> UsageSegment: read five_hour.resets_at
UsageSegment ->> UsageSegment: format_reset_time_epoch(resets_at)
UsageSegment -->> SegmentRenderer: SegmentData from stdin rate_limits
else no rate_limits in input
UsageSegment ->> Credentials: get_oauth_token()
Credentials -->> UsageSegment: oauth_token
UsageSegment ->> OAuthAPI: fetch_usage(oauth_token)
OAuthAPI -->> UsageSegment: usage_response
UsageSegment -->> SegmentRenderer: SegmentData from API usage
end
SegmentRenderer -->> User: display usage segment
Class diagram for updated usage rate_limits data flowclassDiagram
class InputData {
+Model model
+String status
+String transcript_path
+Option~Cost~ cost
+Option~OutputStyle~ output_style
+Option~RateLimits~ rate_limits
}
class RateLimits {
+Option~RateLimitWindow~ five_hour
+Option~RateLimitWindow~ seven_day
}
class RateLimitWindow {
+Option~f64~ used_percentage
+Option~u64~ resets_at
}
class UsageSegment {
+format_reset_time_epoch(epoch: Option~u64~) String
+collect(input: &InputData) Option~SegmentData~
}
InputData --> RateLimits : rate_limits
RateLimits --> RateLimitWindow : five_hour
RateLimits --> RateLimitWindow : seven_day
UsageSegment ..> InputData : reads
UsageSegment ..> RateLimits : uses
UsageSegment ..> RateLimitWindow : uses
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- In
format_reset_time_epoch, consider using a signed integer type for the epoch andchrono::Durationarithmetic instead of castingUtc::now().timestamp()tou64, so that you avoid implicit assumptions about non-negative timestamps and make the intent around time calculations clearer. - When deriving
five_hour_percentfromfive_hour_util, it might be safer to clamp the value to an expected range (e.g. 0–100) before casting tou8to guard against unexpected or malformed input values. - The new stdin-based path returns early before loading segment configuration, while the API fallback still reads config; if there are configuration-dependent behaviors for the usage segment, consider applying them consistently in both code paths.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `format_reset_time_epoch`, consider using a signed integer type for the epoch and `chrono::Duration` arithmetic instead of casting `Utc::now().timestamp()` to `u64`, so that you avoid implicit assumptions about non-negative timestamps and make the intent around time calculations clearer.
- When deriving `five_hour_percent` from `five_hour_util`, it might be safer to clamp the value to an expected range (e.g. 0–100) before casting to `u8` to guard against unexpected or malformed input values.
- The new stdin-based path returns early before loading segment configuration, while the API fallback still reads config; if there are configuration-dependent behaviors for the usage segment, consider applying them consistently in both code paths.
## Individual Comments
### Comment 1
<location path="src/core/segments/usage.rs" line_range="209-218" />
<code_context>
+ fn collect(&self, input: &InputData) -> Option<SegmentData> {
+ // Priority 1: Use rate_limits from stdin (Claude Code >= 2.1.80, zero network)
+ if let Some(rate_limits) = &input.rate_limits {
+ let five_hour_util = rate_limits
+ .five_hour
+ .as_ref()
+ .and_then(|w| w.used_percentage)
+ .unwrap_or(0.0);
+ let seven_day_util = rate_limits
+ .seven_day
+ .as_ref()
+ .and_then(|w| w.used_percentage)
+ .unwrap_or(0.0);
+ let resets_at_epoch = rate_limits
+ .five_hour
+ .as_ref()
+ .and_then(|w| w.resets_at);
+
+ let dynamic_icon = Self::get_circle_icon(seven_day_util / 100.0);
+ let five_hour_percent = five_hour_util.round() as u8;
+ let primary = format!("{}%", five_hour_percent);
+ let secondary = format!(
</code_context>
<issue_to_address>
**issue (bug_risk):** Clamp or validate the utilization percentage before casting to `u8` and formatting.
Because `five_hour_util` is external input, if it ever falls outside `[0.0, 100.0]` the `round() as u8` cast can produce odd values like `255%`. Clamping to a sane range (e.g., `0.0..=100.0`) before rounding and casting would keep the displayed percentage within expected bounds.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| let five_hour_util = rate_limits | ||
| .five_hour | ||
| .as_ref() | ||
| .and_then(|w| w.used_percentage) | ||
| .unwrap_or(0.0); | ||
| let seven_day_util = rate_limits | ||
| .seven_day | ||
| .as_ref() | ||
| .and_then(|w| w.used_percentage) | ||
| .unwrap_or(0.0); |
There was a problem hiding this comment.
issue (bug_risk): Clamp or validate the utilization percentage before casting to u8 and formatting.
Because five_hour_util is external input, if it ever falls outside [0.0, 100.0] the round() as u8 cast can produce odd values like 255%. Clamping to a sane range (e.g., 0.0..=100.0) before rounding and casting would keep the displayed percentage within expected bounds.
Summary
rate_limitsfrom Claude Code's stdin JSON (available since CC >= 2.1.80), providing real-time data with zero network overheadformat_reset_time_epoch()to display countdown from epoch timestamps (e.g.2h,3d)Problem
The Usage segment only fetched data via the
api.anthropic.com/api/oauth/usageAPI endpoint. This could fail silently due to ureq/TLS issues, causing the segment to not display at all — even though Claude Code already passesrate_limitsin the statusLine input JSON.Test plan
cargo checkpassesrate_limitsin stdin — displays24% · 2hcorrectlyrate_limits— falls back to API path (backward compatible)?gracefully🤖 Generated with Claude Code
Summary by Sourcery
Prefer real-time usage data from Claude Code stdin rate_limits while retaining the existing API-based fallback.
New Features:
Enhancements: