Skip to content

feat(quota): show the Fable weekly limit from the usage endpoint - #145

Open
jo9900 wants to merge 4 commits into
Haleclipse:masterfrom
jo9900:feat/fable-weekly-limit
Open

jo9900 wants to merge 4 commits into
Haleclipse:masterfrom
jo9900:feat/fable-weekly-limit

Conversation

@jo9900

@jo9900 jo9900 commented Nov 16, 2026 •

Copy link
Copy Markdown

Closes #144

Adds quota.fable, the weekly Fable limit, which Claude Code doesn't pass to status lines.

󰔠 ▱▱▱▱▱▱▱▱▱▱ 2% · 15:00 | 󰔠 ▰▰▰▰▰▰▰▱▱▱ 73% · 23:00 | 󰔠 ▰▰▱▱▱▱▱▱▱▱ Fable 27% · 23:00

How it works

  • Data: the limits[] row of /api/oauth/usage with kind: "weekly_scoped" and a model label starting with the word "Fable" (the test Claude Code applies, so "Fable 5.2" also matches). The reset time is rounded to the minute, since the endpoint can send 22:59:59.
  • Same pattern as the update check: renders only read state/oauth_usage.json. When it is older than 5 minutes (15 after a failed check), a render starts a detached ccline usage-check (hidden subcommand) behind the existing swr lock, which calls the endpoint through curl and records the answer. No HTTP stack is added.
  • Opt-in: nothing is read or fetched unless a line shows quota.fable (Config::shows).
  • Token: the macOS keychain item Claude Code-credentials, else .credentials.json in the Claude config directory. With CLAUDE_CONFIG_DIR set it uses the file only, rather than guess the suffixed keychain name. The token goes to curl on stdin (-H @-), never on its command line. An expired token is skipped; ccline never refreshes it, so it can't disturb Claude Code's own sign-in.
  • Missing data: no Fable row, a failed request, an unreadable state file or a window that already reset all hide the item. A failed check keeps the last good value until its reset time.
  • The metric is a Pace window like quota.5h / quota.7d, with default templates prefixed Fable so it can be told apart from the other quota items, which share its icon. The preview scenarios normal and near-full include sample values.

Tests

  • Unit tests: parsing the row (ISO and epoch resets, other scopes, missing fields, label matching, minute rounding), token handling (expired / empty / malformed), the metric (missing, present, already reset) and Config::shows.
  • cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test (207 passed).
  • Manually on macOS against a real subscription: ccline usage-check recorded {"used_percentage":27.0,"resets_at":…} and the status line showed the item; a config without quota.fable creates no state file and makes no request.

Not tested on Linux or Windows; there it relies on .credentials.json and curl being present.

🤖 Generated with Claude Code

Summary by Sourcery

Expose the weekly Fable limit as an opt-in quota metric backed by cached OAuth usage data.

New Features:

  • Add the opt-in quota.fable metric to display the weekly Fable usage limit from Claude Code’s OAuth usage data.

Enhancements:

  • Cache usage data per Claude configuration and refresh it asynchronously without blocking status-line rendering.
  • Support Claude Code credentials from the macOS keychain or configuration file while avoiding expired-token refreshes and exposing only valid, current quota windows.

Documentation:

  • Document the new Fable quota metric, its data source, refresh behavior, and credential handling in the English and Chinese READMEs.

Tests:

  • Add coverage for usage response parsing, reset handling, credential validation, failed checks, metric rendering, configuration detection, and preview scenarios.

jo9900 and others added 2 commits November 16, 2026 13:43
Claude Code's status line input carries only the 5-hour and 7-day
windows, so the weekly Fable limit is missing. The new quota.fable item
reads it from the usage endpoint's limits[] row (kind weekly_scoped,
scoped to a model labeled Fable). Renders only read the recorded
answer; a detached `ccline usage-check` refreshes it at most every five
minutes, and only when a line shows quota.fable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Add the persisted OAuth usage state and per-profile storage for the Fable weekly window, including its refresh status and failure reason.

  • src/state/mod.rs L12, L173-174, L238
  • src/state/oauth_usage.rs L29-79

API

Expose a hidden usage-check command and the configuration query used to determine whether Fable usage is opted in.

  • src/cli.rs L40-43
  • src/config/mod.rs L246-254

Uses of the API

Connect opted-in status and task-line renders to the cached Fable window, and dispatch the background usage check through the CLI.

  • src/main.rs L28-31, L118-125, L132-141 (+1 small edits)

Implementation

Implement asynchronous refresh, credential selection, endpoint parsing, and protection against stale or failed checks overwriting a usable Fable limit.

  • src/state/oauth_usage.rs L1-28, L80-252

UI

Register quota.fable as a pace widget with Fable-specific default templates and calculate its reading from the stored weekly window.

  • src/metrics/projection.rs L294-295, L304
  • src/metrics/usage.rs L94-110, L298-306

Documentation

Document the new quota metric, its endpoint and credentials, and its opt-in refresh behavior in both READMEs.

  • README.md L146, L156-157, L162-163
  • README.zh.md L146, L156-157, L162-163

Tests

Add regression coverage for metric discovery, Fable window rendering, credential and endpoint handling, and preview scenario values.

  • src/config/mod.rs L314-325
  • src/metrics/usage.rs L442-465
  • src/scenarios.rs L573-576 (+10 small edits)
  • src/state/oauth_usage.rs L253-396
  • src/tui/pages/layout/inspector.rs L572

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

@sourcery-ai

sourcery-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 487946a

#144 Show the weekly Fable limit (not in the status line input) · 6 of 6 met

# Requirement Status Notes
1 Show the weekly Fable limit as a status-line metric. ✅ Met The quota.fable metric is registered as a pace window and reads the Fable value from state.
2 Read the Fable limit from the weekly_scoped usage row for a model labeled with the word “Fable.” ✅ Met The parser matches limits[] rows by kind and Fable model label, then reads the percentage and reset time.
3 Use Claude Code’s OAuth credentials to query the usage endpoint. ✅ Met The implementation uses the keychain or credentials file and sends the OAuth token and beta header to the endpoint.
4 Only fetch when a line shows quota.fable. ✅ Met Config::shows checks both status lines and the background task line before usage state is read or refreshed.
5 Refresh in the background at most every five minutes. ✅ Met Renders use the recorded value and start a detached check when due; successful checks are refreshed at five-minute intervals.
6 Hide the item whenever usable Fable limit data is unavailable. ✅ Met Missing or invalid data and reset windows produce no metric; a failed check retains the last good value only until its reset.

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

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/state/mod.rs" line_range="174" />
<code_context>
     /// What the companion mod reports for this session.
     pub bridge: Option<std::rc::Rc<bridge::Bridge>>,
+    /// The Fable weekly limit, from the usage endpoint.
+    pub fable_weekly: Option<crate::input::Window>,
 }

</code_context>
<issue_to_address>
**Downstream struct literals stop compiling**

When an external consumer constructs `StateView` without struct-update syntax, downstream crates that construct the public `StateView` with a complete struct literal now fail to compile because the new required `fable_weekly` field is missing.

Provide a compatible construction API and avoid exposing `StateView` as an externally constructible field-by-field struct.
</issue_to_address>

### Comment 2
<location path="src/state/oauth_usage.rs" line_range="55" />
<code_context>
+
+fn paths() -> (PathBuf, PathBuf) {
+    (
+        dir().join("oauth_usage.json"),
+        dir().join("oauth_usage.lock"),
+    )
</code_context>
<issue_to_address>
**Previous account quota appears**

When the same ccline state directory is used with different Claude profiles or accounts, `paths()` stores the cached window and refresh lock in the shared state directory, while token lookup follows the active Claude config. `fable_weekly()` can therefore return the previous profile’s quota, and the shared lock can suppress the correct profile’s refresh; failed checks leave the old value visible until reset.

Scope the cached window and refresh lock to the active Claude profile or account, or invalidate them when that profile changes.

Also at `src/main.rs:85-86`, `src/state/oauth_usage.rs:70-73`, `src/state/oauth_usage.rs:79`.
</issue_to_address>

### Comment 3
<location path="src/state/oauth_usage.rs" line_range="76-93" />
<code_context>
+}
+
+/// Check now, record the result and release the background lock.
+pub fn check(now: i64) {
+    let (path, lock) = paths();
+    let answer = access_token().and_then(|token| fetch(&token));
+    let previous: UsageState = read_json(&path).unwrap_or_default();
+    let state = match answer {
+        Some(body) => UsageState {
+            checked_at: now,
+            ok: true,
+            fable_weekly: fable_window(&body),
+        },
+        None => UsageState {
+            checked_at: now,
+            ok: false,
+            ..previous
+        },
+    };
+    let _ = write_json(&path, &state);
+    swr::release(&lock);
+}
+
</code_context>
<issue_to_address>
**Concurrent checks overwrite newer quota**

When a manual `ccline usage-check` runs while a render-started check is in flight, `check()` writes its response without verifying that it owns the refresh lock, then releases the shared lock. A later render can start another check, and whichever response finishes last can replace fresher quota data and reset the refresh timestamp.

Make checks acquire and release only their own lock, and prevent an overlapping check from writing over a newer result.

Also at `src/main.rs:29`.
</issue_to_address>

### Comment 4
<location path="src/config/mod.rs" line_range="248-252" />
<code_context>
 impl Config {
+    /// Whether any status line shows `metric`.
+    pub fn shows(&self, metric: &str) -> bool {
+        self.lines
+            .iter()
+            .flat_map(|l| l.left.iter().chain(&l.right))
+            .any(|item| item.config().metric == metric)
+    }
+
     pub fn to_toml(&self) -> String {
</code_context>
<issue_to_address>
**Subagent quota has no reading**

When a user configures `quota.fable` in the subagent line, `Config::shows` checks only the main lines, and the normal render path sets `view.fable_weekly` after the subagent path has returned. The subagent frame therefore has no Fable reading and does not start a background refresh.

Recognize `quota.fable` in the subagent line and populate its frame with the Fable reading before rendering it.

Also at `src/main.rs:84-87`.
</issue_to_address>

### Comment 5
<location path="src/state/oauth_usage.rs" line_range="115-118" />
<code_context>
+/// else its `.credentials.json`. An expired token is left alone; Claude
+/// Code refreshes it on its next request.
+fn access_token() -> Option<String> {
+    let raw = keychain_credentials().or_else(|| {
+        std::fs::read_to_string(crate::paths::claude_dir().join(".credentials.json")).ok()
+    })?;
+    token_from_credentials(&raw, chrono::Utc::now().timestamp_millis())
+}
+
</code_context>
<issue_to_address>
**Valid file token is skipped**

When the macOS keychain command succeeds with invalid or expired credentials while `.credentials.json` contains a valid token, `or_else` selects the keychain credentials, then `token_from_credentials()` returns `None` without trying the file credentials, so the Fable limit stays unavailable.

Try the `.credentials.json` credentials when the keychain credentials do not produce a valid token.
</issue_to_address>

### Comment 6
<location path="src/metrics/usage.rs" line_range="97" />
<code_context>
+        Metric {
+            meta: MetricMeta {
+                widget: WidgetKind::Pace,
+                templates: ["Fable {pct}%[ · {reset}]", "Fable {pct}%", "{pct}%"],
+                fields: WINDOW_FIELDS,
+                levels: LEVELS,
</code_context>
<issue_to_address>
**Fable percentage loses its label**

When a layout selects the compact or minimal template for `quota.fable`, the selected template renders only `{pct}%`, so the Fable limit is indistinguishable from other quota items that share its icon.

Keep a Fable label in every template variant.
</issue_to_address>

### Comment 7
<location path="src/state/oauth_usage.rs" line_range="164-169" />
<code_context>
+/// the same test Claude Code applies.
+fn fable_window(body: &Value) -> Option<StoredWindow> {
+    let row = body.get("limits")?.as_array()?.iter().find(|row| {
+        row.get("kind").and_then(Value::as_str) == Some("weekly_scoped")
+            && row
+                .pointer("/scope/model/display_name")
+                .and_then(Value::as_str)
+                .is_some_and(is_fable)
+    })?;
+    Some(StoredWindow {
+        used_percentage: row.get("percent")?.as_f64()?,
</code_context>
<issue_to_address>
**Quota depends on API row order**

When the usage response contains more than one `weekly_scoped` row with a Fable-prefixed model label, `fable_window` takes the first matching row, so when `limits[]` contains multiple weekly-scoped Fable model rows, the stored percentage depends on API array order and can represent a different model’s limit.

Define how multiple matching model limits should resolve and apply that selection or aggregation explicitly.
</issue_to_address>

### Comment 8
<location path="src/state/oauth_usage.rs" line_range="80-92" />
<code_context>
+    let (path, lock) = paths();
+    let answer = access_token().and_then(|token| fetch(&token));
+    let previous: UsageState = read_json(&path).unwrap_or_default();
+    let state = match answer {
+        Some(body) => UsageState {
+            checked_at: now,
+            ok: true,
+            fable_weekly: fable_window(&body),
+        },
+        None => UsageState {
+            checked_at: now,
+            ok: false,
+            ..previous
+        },
+    };
+    let _ = write_json(&path, &state);
+    swr::release(&lock);
+}
</code_context>
<issue_to_address>
**Quota fetch failures are invisible**

When credentials are unavailable, the endpoint request or response parsing fails, or the state file cannot be written, `check()` turns missing credentials, curl errors, and invalid response JSON into `None`, records `ok: false`, and ignores write errors. The render then either keeps showing a cached value or hides the metric, with no diagnostic to distinguish a broken integration from an account without a Fable limit.

Record or emit a rate-limited diagnostic that distinguishes credential, request, parse, and persistence failures while keeping renders non-blocking.
</issue_to_address>

Sourcery assessment

Approval pending. 8 findings to address first.

Blocking findings: src/state/mod.rs:174, src/state/oauth_usage.rs:55, src/state/oauth_usage.rs:93, src/config/mod.rs:252, src/state/oauth_usage.rs:118, and 3 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/state/mod.rs Resolved
Comment thread src/state/oauth_usage.rs Resolved
Comment thread src/state/oauth_usage.rs Resolved
Comment thread src/config/mod.rs Resolved
Comment thread src/state/oauth_usage.rs Resolved
Comment thread src/metrics/usage.rs Resolved
Comment thread src/state/oauth_usage.rs Resolved
Comment thread src/state/oauth_usage.rs Resolved
jo9900 and others added 2 commits November 16, 2026 14:17
Config::shows looked at the status lines only, and the subagent render
never asked for the window, so quota.fable on the subagent line stayed
empty and started no refresh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ck failed

- Record the answer per Claude config directory, so two profiles sharing
  one ccline home don't show each other's limit or hold each other's
  refresh lock.
- Use the first credentials that hold a usable token: an expired keychain
  item no longer hides a valid .credentials.json.
- Record why a check got no answer (no_token, request, response), to
  tell a broken setup from an account without the limit.
- A check that started earlier no longer overwrites the answer of one
  that started later.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@jo9900

jo9900 commented Nov 16, 2026

Copy link
Copy Markdown
Author

Went through the Sourcery findings. Five are addressed in 165e5d8 and 487946a; three I left as they are, with reasons below.

Changed

  • Previous account's quota appears — the answer and its refresh lock are now recorded per Claude config directory (state/oauth_usage/<key>.json, using the existing file_key), so two profiles sharing one ccline home no longer read each other's limit.
  • Valid file token is skipped — the keychain item and .credentials.json are tried in order and the first usable token wins, so an expired keychain item no longer hides a valid file.
  • Fetch failures are invisible — the state file now records why a check got no answer ("error": "no_token" | "request" | "response"), which tells a broken setup from an account without the limit. Renders are unchanged. A failed write of the state file itself is still silent, as it is for the other state files.
  • Subagent quota has no reading — Config::shows also looks at the [subagent] line, and the subagent render reads the window.
  • Concurrent checks overwrite newer quota — a check that started earlier no longer overwrites the answer of one that started later. I kept the lock handling as it is: it follows update-check, where the hidden subcommand also releases the shared lock when run by hand.

Not changed

  • Downstream struct literals stop compiling — StateView is only built inside this crate (ccline ships as a binary through npm, not as a library on crates.io), and it gained fields the same way before (bridge in e1f86b8).
  • Fable percentage loses its label — only the shortest template drops it, the same way quota.5h and quota.7d carry no label there; it is what a line falls back to when it runs out of room.
  • Quota depends on API row order — the endpoint sends one Fable row today. Taking the first match follows the server's order; I'd rather not guess an aggregation for a case that doesn't exist yet.

Tests: cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test (210 passed). Also checked by hand with two empty Claude config directories: each gets its own state file, a profile without credentials records no_token and makes no request, and a [subagent] line with quota.fable shows the value.

One correction to the description above: the state file is now state/oauth_usage/<key>.json rather than state/oauth_usage.json.

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.

Show the weekly Fable limit (not in the status line input)

1 participant