Skip to content

feat(statusline): show tokens saved in the 5h window on a subscription - #511

Merged
amiddavid merged 4 commits into
mainfrom
feat/statusline-window-fit
Oct 22, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/statusline-window-fit

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #506

Summary

  • On a Claude subscription, the status line now shows the 5-hour limit use and the tokens context-guru saved in that window, split into reads and writes.
  • It shows no dollars on a subscription. The spent and ka $… segments are hidden.
  • On an API key, Bedrock or Vertex, nothing changes.
  • The counts are not weighted. Anthropic does not publish how the limit weights each token kind.

What changed

Before and after, balanced layout, same traffic (current main):

API key (before = after)
saved $0.31 of $2.10 session · saved $0.12 of $0.90 subagents
cache ● ██████ 59:00 │ next $0.30 if cold │ ctx ░░░░░░░░ 5%

Subscription, before
saved $0.31 of $2.10 session · saved $0.12 of $0.90 subagents
cache ● ██████ 59:00 │ next $0.30 if cold │ ctx ░░░░░░░░ 5%

Subscription, after
5h 34% · saved 1.2M rd / 85.0k wr
cache ● ██████ 58:59 │ ctx ░░░░░░░░ 5%

--layout=detailed adds 7d 12% and writes compaction saved …. At narrow widths the counts drop first and 5h 34% stays (30 columns: 5h 34%). An ended window (resets_at in the past) shows nothing.

What each number means:

Shown Source
5h 34% Claude Code stdin rate_limits.five_hour.used_percentage
rd (saved read) /api/stats replay_tokens = saved_gross − saved_unique. Removed tokens that later turns would have re-sent. They would have been cache reads.
wr (saved write) /api/stats saved_unique. Each distinct removal counted once. It would have been a cache write.
  • A subscription is a numeric rate_limits.five_hour.used_percentage. Window start = resets_at minus 5 hours.
  • Counts come from the existing GET /api/stats?lean=1&since=<ms>. No Go code changed. They are plain, unweighted token counts.
  • A subscription skips the spark row and the spend-explanation read, and makes no lifetime read.

Money elements on a subscription

Element (main) On a subscription
saved $x of $y session, … subagents Replaced by 5h NN% · saved … rd / … wr
↻ $z manual-ping saving Hidden (part of the saved line)
next $a warm · $b cold Hidden. A price, and a subscription is not billed per request.
Per-agent saved $x of $y (--show=agents) Dropped. The agent clocks stay.
ka 3 pings $0.04 Count stays, cost dropped: ka 3 pings
spent (detailed) Hidden
spark row (saved today) Not drawn
lost today (strip, heat) and a miss now costs (fill) Dropped
Weekly tip, ▲ update Unchanged (no dollars)

New test TestStatuslineSubscriptionShowsNoMoney feeds every money source into a subscription payload and fails on any $ in 8 layouts. The same inputs on an API key still show them.

API-key accounts: main's behaviour, unchanged.

How it was tested

Merge of origin/main into this branch (no rebase). On the eval box, CGO_ENABLED=1:

Open questions

  1. Compaction only. Cachesplit, keep-alive and declaration-filter savings are stored as dollars, with no token count. They are not in rd / wr.
  2. Token counts are the proxy's own estimates. The dollar maths scales them to the provider's count (BilledTokenFactor, about 1.4x to 1.7x). The status line shows the unscaled estimate.
  3. Whole-proxy scope. The window totals include any API-key traffic through the same proxy.
  4. Main replaced the hint with a weekly tip. It has no dollars.
  5. Dashboard and /context-guru:status are not changed. Recording the anthropic-ratelimit-unified-* headers in the proxy is left out.
  6. rate_limits can be absent before the first response. The line then shows the money view until it arrives.

Technical notes

  • statusline.py: _subscription, _saved_tokens, _window_segment. The window read uses _bg_json with a cache key per window start, TTL 30 s. It adds no new network target.
  • rd is max(replay_tokens, 0). wr is max(saved_unique, 0).

On a Claude subscription, Claude Code sends rate_limits in the status-line
input. The first line now shows the real 5-hour use and the tokens
compaction kept out of that window, split into cache reads (replay_tokens)
and cache writes (saved_unique). Counts are plain, not weighted. The spend
and ka segments are hidden. API-key accounts keep the money view.

Window totals come from the existing /api/stats?lean=1&since=<ms>.
An opt-in `fit` element shows a list-price weighted gain.

Closes #506

Assisted-By: Claude <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid
amiddavid marked this pull request as ready for review October 13, 2026 10:58

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verdict: changes needed (posted as COMMENT because the same account owns the PR)

The Go test file does not compile. CI for ./context-guru-plugin/ cannot pass. The feature itself works once that is fixed.

Must fix

  1. statusline_golden_test.go does not build.
    • The row struct has 6 fields (name, stdin, layout, width, want, extra). Six rows give only 5 values (balanced, minimal, detailed-hides-money, narrow, no-reset-time, null-limits-is-api-key). Go rejects an unkeyed literal with too few values.
    • Evidence: go test ./context-guru-plugin/ -run Statusline on eval box 1 at a62804ed gives too few values in struct literal (6 errors) and [build failed].
    • Fix: add "" as the last value in those rows, or use keyed fields.
    • After I added "" locally (not pushed), all 7 TestStatuslineGoldenSubscription cases pass, and so do all other Statusline* tests. The goldens are not vacuous: the window stub only answers since=1800000123000, which is resets_at minus 5h in ms. A wrong window start returns the default stats and the test fails.

Should fix

  1. A past resets_at shows a dead window.

    • _subscription accepts any resets_at > 0. _window_start_ms then returns reset - 5h, even when that is hours ago.
    • Scenario: Claude Code keeps the last rate_limits after the window ended and before the next response. I rendered resets_at = now - 2h. Output: 5h 34% · saved 1.2M rd / 85.0k wr, with counts since 7 hours ago.
    • Proposal: if resets_at <= now, treat it as no reset time. Show 5h NN% only, or the money view. Add a golden for it.
    • Units are fine: seconds and milliseconds both give the right start (checked with now*1000).
  2. On a subscription the status line still fetches data it never shows.

    • _gather still starts the life job (since=0) when save is on. The save segment is replaced, so nothing reads it.
    • The code comment says this read "takes seconds on a large history". I saw since=0 and today requests on every render in the stub log.
    • Proposal: skip life (and day unless spark is on) when sub is set.
  3. Narrow widths drop the one real number.

    • At 29 columns, level 2 shows saved 1.2M rd / 85.0k wr and removes 5h 34%. The 5h share is Claude Code's own figure. The saved counts are the proxy's estimates.
    • Proposal: keep 5h NN% last in DEGRADE. Drop the saved counts first.
  4. fit is out of scope and has no tests of its value.

    • The owner asked for plain counts with no list-price weighting. This PR still adds fit, _limit_weight (an identity function), _fit_gain, _fit_segment, a DEGRADE entry, a ROW entry, WINDOW_TTL_SECONDS sharing, and docs.
    • It is dead by default and adds a weighted number the owner said not to show. It is also the only user of cost_usd from the window read.
    • Proposal: remove it. Add it later if data supports a weight.

Answers to the review questions

  • Are rd and wr honest? Mostly.
    • wr = saved_unique: removals counted once. rd = replay_tokens = saved_gross - saved_unique (dash/overview.go:680): the same removals absent on later turns.
    • Those are the proxy's token estimates. A replayed token is a cache read only when the cache hit. After a cache miss it is billed as a write. The docs say "would have been". The status line says only rd and wr.
    • Cachesplit, keep-alive and declaration-filter savings have no token count and are missing. The docs disclose this (docs/plugin/statusline.md). The line does not. Accept it, but the label saved can read as the full saving.
  • Window scoping: correct for seconds and ms. Past or missing resets_at: see item 2 and no-reset-time golden (shows 5h 34% only, good).
  • Detection: a numeric five_hour.used_percentage is a sound test. I rendered these and got the old money view each time: string "34", five_hour: null, only seven_day, rate_limits as a list, spend_limit only. No crash.
  • Dollars on a subscription: none found in balanced, detailed, minimal, watch. spend and ka are hidden.
  • Other layouts: fill and spark have no save element, so they show no window data. That is consistent with before.

Tests I ran

  • python3 -I -m py_compile statusline.py: pass.
  • Go on box 1, as-is: build failed (item 1).
  • Go on box 1 with the 6 rows patched locally: TestStatuslineGoldenSubscription 7/7 pass. All -run Statusline tests: ok.
  • Manual renders against a stub of /api/stats: 13 payloads and widths (200, 50, 40, 33, 29, 20). Results above.

The table gained an `extra` column; the other rows did not supply it,
so the package did not compile.

Assisted-By: Claude <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
- Treat a past resets_at as an ended window: show no 5h share, no counts.
- Skip the day and lifetime reads on a subscription; nothing shows them.
- Drop the counts first at narrow widths; the 5h share stays longest.
- Remove the weighted fit element, _limit_weight and _fit_gain.
- The detailed layout writes "compaction saved" to name what the counts cover.

Assisted-By: Claude <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

All 5 findings fixed in 22db925. Replies per finding:

  1. Goldens did not compile. Fixed in 37a2994. Rows now supply every field. The extra column is gone in 22db925.
  2. Past resets_at. _subscription marks the block expired when resets_at <= now. An expired window shows no 5h share, no counts, and no money. New golden expired-window. The golden clock is pinned with CG_STATUSLINE_NOW.
  3. Unused reads. On a subscription the day and life reads are skipped. Checked against a request log: only cachestate, session stats and the window stats are asked.
  4. Narrow widths. Level 2 of the window segment is now 5h NN%. The counts go first. The 5h share is the last thing dropped. Golden narrow (30 columns) shows 5h 34%.
  5. fit removed. fit, _limit_weight, _fit_gain, _fit_segment and the related docs and DEGRADE/ROW entries are gone.

Also: --layout=detailed now writes compaction saved 1.2M rd / 85.0k wr, so the line names what the counts cover. The shorter layouts keep saved …; the docs say the counts are compaction only.

Tests on the eval box: -run Statusline 107 pass, 0 fail. Full ./context-guru-plugin/ 498 pass, 0 fail. Python test_tv.py 36 of 36.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verdict: all 5 findings fixed. No new blocking issues.

  1. Goldens do not compile: fixed. -run Statusline on box 1 at 22db925: 107 pass, 0 fail. TestStatuslineGoldenSubscription passes 7/7.
  2. Past resets_at: fixed. I rendered resets_at = now-60 and = now. Both show no 5h share, no counts and no money. The expired-window golden passes. A live window and a missing resets_at still render as before (5h 34% · saved 1.2M rd / 85.0k wr and 5h 34%).
  3. Unused reads: fixed. My request log over 9 renders shows only cachestate, stats?session= and stats?lean=1&since=<window start>. No since=0 and no day read.
  4. Narrow widths: fixed. At 29 and 20 columns the first line is 5h 34%. The counts drop first.
  5. fit removed: fixed. No fit, _limit_weight or _fit_gain remain in the diff. --show=fit is now ignored without error.

Also checked, no regression:

  • detailed now reads 5h 34% · 7d 12% · compaction saved 1.2M rd / 85.0k wr. This names what the counts cover. Good.
  • The API-key and rate_limits: null golden still shows the money view.
  • Not rerun by me: the full package (498 pass per the author) and test_tv.py (36 per the author).

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Moved to the next release by the release owner. v0.5.3 is out without it. It needs a rebase on main before review.

Keep main's status line (one timer, next-request cost, saved $x of $y,
per-agent money, weekly tip). Re-apply the subscription view on top:
5h share plus saved rd/wr tokens, no dollars on any element, and no
spark or spend-explanation reads on a subscription.

Assisted-By: Claude <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Looks good

The merge (ff0f5a3) keeps the subscription view and the API-key view intact. No findings.

  • Conflict resolution. No conflict markers remain in statusline.py, statusline.md, SKILL.md or the golden test. The diff against origin/main in statusline.py holds only the window code and the money switches. Main's money, tip and next code is untouched.
  • Dollars on a subscription: none reachable. I rendered a subscription payload with every money source in the stub (session and sub-agent saving, warm/cold/rewrite prices, manual-ping saving, keep-alive cost, Claude Code cost). I covered 8 layouts, each with no --show, with all 17 elements together, and with each element alone: 144 renders. None printed $. Kept as designed: ka 3 pings, a count with no cost.
  • API key unchanged from main. I rendered PR and origin/main side by side: 8 layouts, no --show, all elements, each element alone, for a payload with no rate_limits and one with rate_limits: null. That is 48 pairs, 0 differences after I removed the Tip: line. My copy of main did not include the tips data file, which produced the only differences.
  • The new test catches regressions. I changed one line at a time in the local worktree, ran TestStatuslineSubscriptionShowsNoMoney, then restored the file. All three mutations failed the test:
    • re-enable spend: detailed fails;
    • re-enable next: balanced and detailed fail;
    • pass the keep-alive cost through again: spark, strip, heat, fill and watch fail.
  • Tests, eval box 1, -race, new empty dir. go test -race ./context-guru-plugin -run Statusline -count=1: 162 pass, 0 fail. I did not rerun the full package. The author reports 685 pass.

Not a finding: the doc example in docs/plugin/statusline.md still shows agents 2 · soonest. Main now writes agent caches (N). It is only an illustration.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 ff0f5a3a409a approve

Verdict: approve

Findings

None. The implementation is correct.

Non-blocking

  • The subscription detection logic is robust. It handles missing fields, expired windows, and malformed data gracefully.
  • The token counting correctly maps replay_tokens to "rd" and saved_unique to "wr" as documented.
  • The fail-open behavior is preserved: subscription detection returns None when rate_limits is absent or malformed, keeping the money view.
  • The test coverage is comprehensive, including edge cases like expired windows, missing reset times, and null rate_limits.
  • The money-hiding logic correctly removes all dollar signs on subscriptions while keeping counts (e.g., keep-alive pings).

What I checked

  • Read the full diff (statusline.py, statusline_golden_test.go, SKILL.md, statusline.md)
  • Verified the subscription detection logic in _subscription() handles all edge cases
  • Traced the token counting through _saved_tokens() → _saved_tokens_text() → _window_segment()
  • Confirmed the return value order matches the docstring: (read, write) = (replay_tokens, saved_unique)
  • Verified the test stub data matches the expected output format
  • Checked that all money elements are correctly hidden when sub is not None
  • Confirmed the window start calculation uses the correct formula: reset - WINDOW_SECONDS
  • Verified the expired window logic prevents showing stale data
  • Checked that the API key path (no rate_limits) preserves the original money view
  • Confirmed the documentation accurately describes the feature behavior

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 ff0f5a3a409a approve

Verdict: approve

Findings

None. The subscription view implementation is correct.

Non-blocking

  • statusline.py:1412 — The window start calculation int((reset - WINDOW_SECONDS) * 1000) could produce a negative timestamp if reset < 18000 (5 hours after epoch, January 1970). This is a theoretical edge case: Claude Code sends current timestamps (year 2026+), not epoch-relative ones. The expired-window guard at line 1406 (reset <= _now_s()) would catch any timestamp before now, making the window show nothing. Still, an explicit guard reset >= WINDOW_SECONDS would make the constraint clear.

  • statusline.py:1669 — The cache key f"win-{win_start // 1000}" divides milliseconds by 1000 to get seconds. This is correct, but the division could be documented: f"win-{win_start // 1000}" # milliseconds → seconds for stable key.

What I checked

  • Read CLAUDE.md and docs/design.md for repo rules
  • Read the full diff (statusline.py, statusline_golden_test.go, docs/plugin/statusline.md, SKILL.md)
  • Verified the subscription detection logic (_subscription()) correctly parses rate_limits.five_hour and handles missing/null/expired cases
  • Verified the window start calculation (_window_start_ms()) correctly computes the 5-hour window boundary
  • Verified the token counting logic (_saved_tokens(), _saved_tokens_text()) correctly extracts saved_unique (writes) and replay_tokens (reads) from /api/stats
  • Verified the window segment display (_window_segment()) correctly formats the output and respects the detailed layout
  • Verified all money-related segments are correctly hidden on subscriptions: save, next, agents (level override), spend, ka (cost only), spark (removed from on), strip/heat/fill (money parameter)
  • Verified the spend fetch is correctly skipped on subscriptions (line 1657) and the money parameter guards prevent unsafe calls
  • Verified test coverage: TestStatuslineGoldenSubscription covers balanced/minimal/detailed/narrow layouts, expired windows, missing reset times, and null rate_limits (API key fallback)
  • Verified test coverage: TestStatuslineSubscriptionShowsNoMoney confirms no dollar signs appear in any layout on a subscription, and keep-alive count stays
  • Verified the stub at line 29-30 in statusline_golden_test.go correctly returns window stats for since=1800000123000
  • Verified the documentation in docs/plugin/statusline.md correctly describes the subscription view, token counts, and money hiding
  • Verified the SKILL.md update correctly documents the subscription behavior

The implementation is correct. The subscription view replaces money with token counts, hides all dollar figures, and handles edge cases (expired windows, missing reset times, API key fallback). The test coverage is comprehensive. The documentation is clear and accurate.

@amiddavid
amiddavid merged commit 7cc97da into main Oct 22, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Status line: show savings against the usage limit, not dollars, on Claude subscriptions

1 participant