Skip to content

feat(usage): prefer stdin rate_limits over API polling#112

Open
nsdont wants to merge 1 commit intoHaleclipse:masterfrom
nsdont:feat/usage-stdin-rate-limits
Open

feat(usage): prefer stdin rate_limits over API polling#112
nsdont wants to merge 1 commit intoHaleclipse:masterfrom
nsdont:feat/usage-stdin-rate-limits

Conversation

@nsdont
Copy link
Copy Markdown

@nsdont nsdont commented Apr 2, 2026

Summary

  • Usage segment now reads rate_limits from Claude Code's stdin JSON (available since CC >= 2.1.80), providing real-time data with zero network overhead
  • API polling is retained as a fallback for older Claude Code versions
  • Added format_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/usage API endpoint. This could fail silently due to ureq/TLS issues, causing the segment to not display at all — even though Claude Code already passes rate_limits in the statusLine input JSON.

Test plan

  • cargo check passes
  • Tested with rate_limits in stdin — displays 24% · 2h correctly
  • Tested without rate_limits — falls back to API path (backward compatible)
  • Tested with expired/zero epoch — shows ? 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:

  • Read and display usage rate limit information from stdin-provided rate_limits when available.
  • Show a human-friendly countdown until rate limit reset based on epoch timestamps.

Enhancements:

  • Extend input data schema to include structured rate limit window information for five-hour and seven-day limits.

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>
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Apr 2, 2026

Reviewer's Guide

Usage 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 fallback

sequenceDiagram
    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
Loading

Class diagram for updated usage rate_limits data flow

classDiagram
    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
Loading

File-Level Changes

Change Details Files
Add epoch-based rate limit reset time formatter for display in the Usage segment.
  • Introduce a helper to convert optional epoch seconds into human-readable remaining time in minutes/hours/days
  • Handle zero, past, and missing timestamps by returning an unknown placeholder to keep the UI stable
src/core/segments/usage.rs
Prefer rate limit data from stdin over network polling in the Usage segment while preserving API fallback.
  • Update the UsageSegment::collect implementation to first read rate_limits from InputData and short-circuit when present
  • Derive utilization percentages from five_hour and seven_day windows, compute a dynamic icon, and expose values as primary/secondary text plus metadata
  • Retain the existing OAuth token + config-based API path as a fallback when stdin rate_limits are unavailable
src/core/segments/usage.rs
Extend input configuration schema to accept rate limit data from Claude Code.
  • Add RateLimitWindow and RateLimits structs for deserializing stdin usage information
  • Add an optional rate_limits field to InputData so downstream segments can consume it
src/config/types.rs

Possibly linked issues

  • #feat: Support for 5hr 7day rate limit: PR reads stdin rate_limits (5h/7d) and displays utilization/reset times, implementing the described rate limit feature.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

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

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +209 to +218
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);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

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