Skip to content

menubar: detect early quota resets and say so - #1320

Closed
ozymandiashh wants to merge 4 commits into
getagentseal:mainfrom
ozymandiashh:feat/early-quota-reset
Closed

ozymandiashh wants to merge 4 commits into
getagentseal:mainfrom
ozymandiashh:feat/early-quota-reset

Conversation

@ozymandiashh

Copy link
Copy Markdown
Collaborator

Summary

Vendors sometimes reset a usage window ahead of schedule as a goodwill gesture. CodeBurn showed the new
percentage but never said it had happened, so the window of free capacity went unused.

Two signals now catch it on the refresh lifecycle that already runs, with no new polling (#725's hard
non-goal): a reset time that jumps to a genuinely new cycle while the stored one still had time to run, and
usage emptying — a fall of at least 40 points landing at or under 10% — while the advertised reset time
stands still. Both carry the same identity for the cycle they cut short, so the second cannot re-announce
what the first already said.

Three surfaces: a system notification through the existing notifier naming the provider, the window and the
lead ("Claude's weekly limit reset 18h early. You're back to 100%."); a Capacity Dock band saying the same
for twelve hours, drawn and reserved exactly like the staleness notice; and, in the quota hover card, this
Mac's own pattern derived from the 30 days of snapshots already on disk ("Last 3 weekly resets came ~18h
early") — from the stored reset times alone, no network and no external feed. A new Quota Alerts switch in
Settings turns the notification off, default on; the dock band still appears with it off.

It stays silent on a normal scheduled reset, a plan change, clock or timestamp skew, a window appearing or
disappearing between fetches, a window's first observation, a reconnect after a terminal failure or a fresh
bootstrap, and a window whose duration the adapter does not validate. A missing or malformed stored reading
is no opinion rather than an event.

One design note for review: the baseline is the previous fetch's readings, kept alongside the announcement
record, not SubscriptionSnapshotStore. The store keeps each cycle's highest reading, which is right for
"what did the cycle end at" and wrong for "what did the last fetch say" — used as a baseline it would
re-announce a usage-drop reset on every later fetch of that cycle, and make the fetch after a reconnect look
like a fresh drop. The store keeps its stated job and now also backs the history summary; it is otherwise
untouched.

Claude is the provider wired up today, because it is the one whose quota readings are persisted. The CLI has
no equivalent persisted quota store — src/quota/* fetches live and persists nothing between invocations —
so it is untouched rather than given an invented one.

Refs #725 rather than Closes: that issue is a five-part epic and this is one slice of its surfaces.

Testing

  • cd mac && swift build — Build complete, exit 0 (pre-existing Keychain deprecation warnings only).
  • 30 new tests in mac/Tests/CodeBurnMenubarTests/EarlyQuotaResetTests.swift (swift-testing, matching the
    neighbouring notification suite), covering both signals, every listed false-positive case as its own test,
    notification coalescing and no-repeat-after-relaunch, the preference, the bounded dock band, the history
    summariser, and the reserved panel height.
  • swift test cannot run on this machine — error: no such module 'Testing', which reproduces on files this
    branch does not touch and on pristine main. The suite was syntax-checked with swiftc -parse, and the
    logic was executed instead through a standalone swiftc harness built from the real source files, which
    mirrors every assertion in the suite (including the monitor's, over an isolated UserDefaults suite with a
    recording notifier): all pass.
  • Mutation-checked: 20 mutations of the new logic — every false-positive guard, both thresholds, the history
    rules, the notice expiry, the preference, the dedupe and the coalescing — each rebuilt and re-run against
    the harness. All 20 are caught. The first pass left three survivors, which produced two additional tests
    and corrected one wrong expectation; it also surfaced a real bug, an exact-timestamp dedupe key that would
    have re-announced the same reset when a vendor replica's timestamp differed by minutes, fixed before commit.
  • Not verified: no notification was actually delivered and the dock band and hover caption were not seen in a
    running app; the band's reserved height is asserted arithmetically, as the neighbouring dock tests do.

Vendors sometimes reset a usage window ahead of schedule as a goodwill
gesture. Nothing in the app noticed, so the capacity that was handed back
went unused.

The decision is two pure pieces so it can be tested without a view or a
network: a detector that takes the previous and current reading of one
window and returns an optional event, and a summariser that reads a
window's early-reset pattern out of the snapshots already on disk.

Detection needs both signals to be defensible on their own. A reset time
that jumps to a genuinely new cycle while the stored one still had time
to run is one; usage emptying while the advertised reset time stands
still is the other, for vendors that grant the reset without moving the
time. Both carry the same identity for the cycle they cut short, so the
second cannot re-announce what the first already said.

The thresholds are deliberately conservative, because a false "you have
your capacity back" is worse than silence. Inside a cycle reported usage
only rises, moving down by a point or two of rounding, so the drop signal
asks for a fall of at least 40 points that lands at or under 10% — far
outside rounding, with room for a refresh interval of real use after the
reset. A new cycle cannot start before our last look at the old one, so
its reset time must sit about a window past that look; a reset time that
merely creeps forward is a rolling window, not a reset.

Silence is the answer for a scheduled reset, a plan change, clock or
timestamp skew (the discipline QuotaPace already applies), a window
appearing or disappearing, a window's first observation, a reconnect
after a failure, and a reading that is missing or malformed.

The monitor around it keeps the previous fetch's readings, the plan label
and the reset times it has already announced, and delivers through the
existing UpdateNotifier rather than a second notification stack. The
snapshot store keeps each cycle's highest reading, which is right for
"what did the cycle end at" and wrong for "what did the last fetch say",
so the baseline is kept alongside the announcement record instead.

History is derived from the stored reset times alone: a fixed window
starting at t ends at t + length, so a cycle ending sooner than a full
window after the previous cycle's scheduled end began early by the
difference. No network, no external feed.
Detection rides the refresh lifecycle that already runs: it happens where
each successful Claude fetch is captured into the snapshot store, before
the store is written, so it costs no request. Issue getagentseal#725 names "no new
network polling loops" a hard non-goal, and this adds none.

Three surfaces, because the user can be looking at any of them. A system
notification names the provider, the window and the lead. The Capacity
Dock carries a band saying the same for twelve hours after the reset was
seen, drawn and reserved exactly like the staleness notice, because the
panel's frame is computed rather than fitted. The quota hover card gains
this Mac's own pattern next to the pace captions.

The state before the fetch decides whether the stored baseline can be
compared against it: a provider coming back from a terminal failure, a
fresh bootstrap or no credentials has a baseline from the far side of a
gap, where stale state looks like a jump. A window the API did not report
this time is passed as absent rather than omitted, so a window that comes
and goes is never read as a reset. Disconnect drops the baseline along
with the snapshots, so a reconnect under another account starts clean.

The Settings switch is on by default, and turning it off withholds only
the notification — the dock band still appears, since it is a caption on
data the user is already looking at rather than an interruption.
The Capacity Dock design doc gains the band, the switch and the two new
code boundaries; the Claude provider doc explains what the detection
reads, how the local history is derived from stored reset times, and why
it stays quiet, so the next person changing the snapshot store knows what
depends on it.

Refs getagentseal#725, rather than Closes: that issue is a five-part epic and this is
one slice of its surfaces, so it should not close on this PR. No issue
tracks early-reset detection on its own.
swift-testing's `#expect` captures each operand separately, so the literal
`18 * 3600` on the right of a `TimeInterval` comparison was typed as Int
and the equality never resolved as Double == Double. CI reported
`(event?.earlyBySeconds → 64800.0) == (18 * 3600 → 64800)` as a failure
while the two numbers plainly agree. A bare literal in the same position
(`percentBefore == 80`) is inferred as Double and passed, which is why
only the two compound expressions failed.

The lead is now one explicitly typed `TimeInterval` constant, the event is
unwrapped with `#require` so a nil event fails with a clear message rather
than a silently false comparison, and the percent expectations are spelled
as Double literals. The rest of the file was swept for the same shape: the
remaining equalities are Int counts, CGFloat, enums, strings, or already
explicitly typed TimeIntervals.

The standalone swiftc harness could not have caught this — plain Swift
infers the same literal as Double, and the harness does not reproduce the
macro's per-operand capture. It now forces the comparison through a
TimeInterval parameter, which at least pins the type.
@iamtoruk

Copy link
Copy Markdown
Member

Landed as #1329 (5110eb8) with your four commits and authorship intact, rebased onto current main, plus follow-ups from a real-data review: the usage-drop signal has its own wording (the fetch that fires it shows the reset time did not move, so 'reset early' misstated it; it now says the usage was cleared before its reset), the lead rounds to the unit it prints instead of truncating, two constants the tests read back are now pinned with literals so their mutations fail, the three notification sections in Settings are one Notifications section, and a test asserts the alert identifier never carries the update-notice prefix (tapping it must not install an update). Replay of this Mac's 2,351 snapshots over 30 days: one notification, at the one real event on Sep 1, nothing else. Full Swift suite the author could not run: 606 pass. Thank you, the detector is careful work.

@iamtoruk iamtoruk closed this Sep 12, 2026
ozymandiashh added a commit to ozymandiashh/codeburn that referenced this pull request Sep 12, 2026
…ecord

The forecast has two inputs with very different freshness needs, and
only one of them was being met.

The distribution of waits comes from the bundled record and is stale by
a release cycle - Action, pull request, merge, release, update. That is
fine: 44 waits do not change shape in a week and a 3.6-day median does
not move because the file is four days old.

The last-reset clock is the other input, and it was frozen at the last
release. A forecast that still believes the last reset was six days ago
when one landed this morning is not slightly wrong; it is wrong in the
direction that matters, and it is the direction that tells someone to
spend down quota that is not coming back. The public trackers learn of a
reset in about two minutes. This machine can learn of it in one refresh
cycle, and now does.

`CodexResetForecastLocalEvents` reads what the two sibling features
already persist and maps them onto the `LocalResetEvent` seam the model
has had since it was written. It reads rather than imports: neither
branch is on main, so a code dependency would make this one unmergeable
until they land. The persisted records are decoded through private
mirror types carrying only the two fields the forecast needs, and a
missing file, a missing key, a wrong shape or an unreadable date is no
opinion rather than an error - with neither feature installed the loader
returns nothing and the forecast conditions on the global record exactly
as before.

Worth recording, because both differ from what you would guess:

- getagentseal#1320 persists to UserDefaults, one JSON record per provider under
  `codeburn.quota.earlyReset.state.<providerID>`, seconds-since-1970,
  not a file in the cache directory. Only `latestEvent` is retained,
  which is the one this needs. Its `detectedAt` is used, never
  `scheduledResetAt` - the latter is when the cut-short cycle would have
  reset, which is in the future and is not when anything happened.
- getagentseal#1322's store keeps `firstSeenAt`, not `grantedAt`; `grantedAt` only
  exists on that branch's transient event and never reaches disk. So the
  timestamp errs late by up to one refresh cycle, never early.
- getagentseal#1320 currently only records Claude. Until it also records Codex, the
  early-reset half of this is correct and dormant; the banked half works
  today. The Codex filter is enforced twice regardless, by storage key
  and by the id inside the record, because an Anthropic early reset
  moving the Codex clock would wreck the forecast silently.

The sentence now names the clock it is reading: "12h since the reset
observed on this machine at 14:30" rather than "since the last global
reset", mirrored in the TypeScript module so the two stay identical.

The CLI is untouched: `src/quota/*` persists nothing between
invocations, so there is no local store for it to read and `codeburn
quota` stays conditioned on the bundled record.
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.

2 participants