From 6be422ac5261cc0dbfc5c270914afc490a021448 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 23:31:31 +0300 Subject: [PATCH] feat(quota): show Codex limit resets in the Plan tab, hover card and CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Plan tab row #724 added showed a count and an expiry. It now also shows how many of those credits can be applied right now and when the most recent one landed, which is what a user deciding whether to push through or throttle back actually needs. The same sentence appears in the agent-tab quota hover card and in `codeburn quota`. One formatter produces it, mirrored line for line in Swift and TypeScript, down to the compact-age rules — deliberately not RelativeDateTimeFormatter or Intl.RelativeTimeFormat, because the two surfaces have to print the same characters, and a locale-aware formatter would not. `codeburn quota` grows a `notes` channel for provider facts that are not a window; only Codex sets it, so every other provider's output is byte-identical to before. The CLI reads the credits off the `rate_limit_reset_credits` block of the usage response it already fetches and never calls the companion endpoint, so it prints the count without the grant and expiry captions that only the per-credit list carries. Refs #725. No new polling loop and no new data source: this reads fields from a response already fetched on the existing cadence. --- CHANGELOG.md | 3 + docs/providers/codex.md | 26 ++- .../Views/HeatmapSection.swift | 18 +- src/quota/codex.ts | 119 ++++++++++++- src/quota/index.ts | 7 + src/quota/types.ts | 4 + tests/quota-codex-banked-resets.test.ts | 156 ++++++++++++++++++ 7 files changed, 317 insertions(+), 16 deletions(-) create mode 100644 tests/quota-codex-banked-resets.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ce38f67..d987c4eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +### Added +- **CodeBurn tells you when OpenAI banks a limit reset on your Codex account.** These grants — the "banked" or "goodwill" resets that restore a rate-limit window early — are sometimes announced and sometimes not, and until now the only way to notice one was to go looking. The reset-credit inventory CodeBurn already reads on every Codex quota refresh is now compared against the previous reading: a credit seen for the first time posts one notification naming what was granted, when it landed and how many you have available to use. The first reading after connecting is a baseline, not news; a credit that disappears because you spent it says nothing; a failed fetch or a malformed payload is treated as no opinion rather than as an empty account, so reconnecting does not re-announce what you were already told; and the fired event is persisted next to the existing quota snapshots, so a relaunch does not repeat it. Settings → Notifications gains a switch for it, on by default. The count and the most recent grant also appear in the Codex Plan tab, in the agent-tab quota hover card, and as a `Limit resets · …` line in `codeburn quota` (text and `--format json`), worded identically on both sides. No new endpoint, no new polling loop and no new data source: this reads fields off a response already fetched on the existing cadence, per the rule #702/#724 established. CodeBurn never spends a credit — this is a notice only. (#725) + ### Added (macOS) - **The Capacity Dock shows today's cache-read tokens and tells you whether each quota window will last to its reset.** The Today section gains a provider-scoped cache-read figure beside input, output and calls; a known zero prints as `0` while missing or incomplete historical accounting stays unknown rather than becoming a fabricated zero, and because cache reads were already priced into the burned figure this adds visibility without changing any total. Each quota window then gets one line under it: `Lasts until reset`, `Runs out in 2d 8h`, or — on windows of six hours or less, where one burst would make a linear ETA cry wolf — the pace stage the Plan tab uses (`On pace`, `40% in deficit`, `30% in reserve`). The same line appears under each bar in the agent-tab quota hover card. The projection runs against the window length the provider adapter reports, never a length guessed from the display label, so a monthly cycle whose label happens to read `Weekly` is still paced against its month; it stays silent early in a window, on an exhausted window, without a reset time or a validated duration, and on stale, disconnected or older-than-ten-minute data. Four quota windows move to a two-column grid so scope labels, reset times and captions stay readable, and the dock reserves the caption's height whether or not a column has one so the bubble cannot resize under the pointer. Status snapshot revision 7 invalidates older cached payloads without purging daily history, and no extra polling is introduced. (#1267) - **The macOS menubar item can show a second line.** Settings → General → Display gains a "Second row" switch, off by default, and a picker for what that line shows: quota remaining with its reset countdown for whichever connected provider is nearest its limit, today's all-provider cost, today's total tokens, or the number of running sessions. Both lines render as one attributed title at 9pt with their line height clamped to 10pt, so the pair fits the standard 22pt menu bar, and the second line hides itself whenever its metric has no data yet, leaving the existing single-row figure exactly as it was. This is a deliberately small first slice of the multi-row layout request: no layout editor, no presets, no live preview, no per-item provider or period scoping. The setting persists as `CodeBurnMenubarSecondRowEnabled` and `CodeBurnMenubarSecondRowMetric` in the app's own defaults domain alongside the existing menubar period, scope and metric keys. (#1252) diff --git a/docs/providers/codex.md b/docs/providers/codex.md index 5bc7e953..7b65c2fd 100644 --- a/docs/providers/codex.md +++ b/docs/providers/codex.md @@ -151,10 +151,28 @@ Composite tiers (`enterprise_cbp_usage_based`, `self_serve_business_usage_based` ### Reset credits `rate_limit_reset_credits` is carried inline on the usage payload -(`available_count`). The dedicated `GET /wham/rate-limit-reset-credits` -endpoint is only called when the inline block is absent. It is the sole source -of per-credit `expires_at` values, so the "next expires" caption is omitted on -the inline path. +(`available_count`, and sometimes `applicable_available_count` — how many can be +applied right now). The dedicated `GET /wham/rate-limit-reset-credits` endpoint +is only called when the inline block is absent or non-zero. It is the sole +source of the per-credit list — `id`, `reset_type`, `status`, `granted_at`, +`expires_at` — so the "next expires" caption and the "latest grant" caption are +both omitted on the inline path. + +**Banked resets.** OpenAI sometimes grants an account an extra reset out of +band. A credit whose identity (`id`, else its raw `granted_at`) has not been +seen before is a new grant, and the menubar notifies once per credit. The seen +set lives in `codex-banked-resets.json` in the CodeBurn cache directory, written +the same way `subscription-snapshots.json` is. Rules that matter: the first +observation is a baseline, a disappearing credit was spent and is not an event, +and an absent or malformed credits payload is *no opinion* — never an empty +account — so a failed fetch cannot cause a re-announcement on reconnect. The CLI +reads the same inventory from the inline block only; it never calls the +companion endpoint. + +Nothing in the payload distinguishes a granted-but-not-yet-usable credit from a +usable one: there is no `available_at`, no pending status, and `granted_at` has +only ever been observed in the past. The earliest warning CodeBurn can give from +this source is therefore "it just landed", not "it lands at 5pm". ## When fixing a bug here diff --git a/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift b/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift index 53f77406..a9977301 100644 --- a/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift +++ b/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift @@ -2184,15 +2184,17 @@ private struct CodexPlanInsight: View { .foregroundStyle(.secondary) } } - // Limit-reset credits the account is holding. Hidden at zero so - // plans that never receive these grants see no extra row. - if let resets = usage.resetCredits, resets.availableCount > 0 { + // Limit-reset credits the account is holding, including the banked + // ones OpenAI grants out of band. Hidden at zero so plans that never + // receive these grants see no extra row. + if let resets = usage.resetCredits, + let detail = CodexBankedResetPresentation.detail(resets, now: Date()) { HStack(alignment: .firstTextBaseline) { - Text("Limit resets") + Text(CodexBankedResetPresentation.rowLabel) .font(.system(size: 11, weight: .medium)) .foregroundStyle(.secondary) Spacer() - Text(resetCreditsLabel(resets)) + Text(detail) .font(.system(size: 10.5)) .foregroundStyle(.secondary) } @@ -2241,12 +2243,6 @@ private struct CodexPlanInsight: View { ) } - private func resetCreditsLabel(_ resets: CodexUsage.ResetCredits) -> String { - let count = "\(resets.availableCount) available" - guard let next = resets.nextExpiresAt else { return count } - return "\(count) · next expires \(relativeReset(next))" - } - private func relativeReset(_ date: Date) -> String { let f = RelativeDateTimeFormatter() f.unitsStyle = .short diff --git a/src/quota/codex.ts b/src/quota/codex.ts index a0dddcdc..bebd5f76 100644 --- a/src/quota/codex.ts +++ b/src/quota/codex.ts @@ -204,7 +204,119 @@ function spendControlWindow(data: Record): QuotaWindow | null { return { label: reached ? `${label} · limit reached` : label, percent, resetsAt } } -export function decodeCodexUsage(body: unknown): QuotaProvider { +// Banked limit-reset credits. The Swift menubar owns the same three functions +// (mac/Sources/CodeBurnMenubar/Data/CodexBankedResets.swift); they are mirrored +// line for line so both surfaces print the same sentence. The CLI reads them off +// the `rate_limit_reset_credits` block of the usage response it already fetches +// and never calls the companion endpoint, so no new request and no new cadence. + +type ResetGrant = { id: string; resetType: string | null; grantedAt: number | null } + +type ResetCredits = { + availableCount: number + /** How many can be applied right now. Null is unknown, not zero. */ + applicableAvailableCount: number | null + grants: ResetGrant[] + nextExpiresAt: number | null +} + +function isoMillis(value: unknown): number | null { + if (typeof value !== 'string' || !value.trim()) return null + const at = Date.parse(value) + return Number.isFinite(at) ? at : null +} + +/** Null on any unexpected shape: the row hides, the quota read still succeeds. */ +export function decodeResetCredits(value: unknown, now: number): ResetCredits | null { + if (!value || typeof value !== 'object') return null + const block = value as Record + const count = num(block.available_count) + if (count === null || count < 0 || !Number.isInteger(count)) return null + const rows = Array.isArray(block.credits) ? block.credits : [] + const available = rows.filter((row): row is Record => + Boolean(row) && typeof row === 'object' + && String((row as Record).status ?? '').toLowerCase() === 'available') + const expiries = available + .map(row => isoMillis(row.expires_at)) + .filter((at): at is number => at !== null && at > now) + // Identity first, and only then a grant: a credit we cannot name is a credit + // we could re-announce on every refresh. + const grants: ResetGrant[] = [] + for (const row of available) { + const identity = [row.id, row.granted_at] + .map(candidate => typeof candidate === 'string' ? candidate.trim() : '') + .find(candidate => candidate !== '') + if (!identity) continue + grants.push({ + id: identity, + resetType: typeof row.reset_type === 'string' && row.reset_type ? row.reset_type : null, + grantedAt: isoMillis(row.granted_at), + }) + } + const applicable = num(block.applicable_available_count) + return { + availableCount: count, + applicableAvailableCount: applicable !== null && applicable >= 0 && Number.isInteger(applicable) ? applicable : null, + grants, + nextExpiresAt: expiries.length > 0 ? Math.min(...expiries) : null, + } +} + +/** Deliberately not `Intl.RelativeTimeFormat`: this string has to come out + * character-identical in TypeScript and in Swift, so the rules are spelled out + * instead of delegated to a locale-aware formatter. */ +export function compactAge(at: number, now: number): string { + const elapsed = (now - at) / 1000 + if (elapsed >= 0) { + if (elapsed < 60) return 'just now' + if (elapsed < 3600) return `${Math.floor(elapsed / 60)}m ago` + if (elapsed < 86_400) return `${Math.floor(elapsed / 3600)}h ago` + return `${Math.floor(elapsed / 86_400)}d ago` + } + const ahead = -elapsed + if (ahead < 60) return 'in under a minute' + if (ahead < 3600) return `in ${Math.floor(ahead / 60)}m` + if (ahead < 86_400) return `in ${Math.floor(ahead / 3600)}h` + return `in ${Math.floor(ahead / 86_400)}d` +} + +/** "weekly" -> "weekly reset". An absent `reset_type` degrades to the bare noun + * rather than inventing a scope the payload did not state. */ +function resetTypeLabel(resetType: string | null): string { + const raw = (resetType ?? '').trim().replace(/[_-]/g, ' ').toLowerCase() + return raw ? `${raw} reset` : 'limit reset' +} + +function latestGrant(credits: ResetCredits): ResetGrant | null { + let latest: ResetGrant | null = null + for (const grant of credits.grants) { + if (grant.grantedAt === null) continue + if (latest === null || grant.grantedAt > (latest.grantedAt ?? -Infinity)) latest = grant + } + return latest +} + +/** `Limit resets · 2 available · 1 usable now · latest weekly reset granted 2h ago`. + * Null when the account holds nothing — the line hides rather than printing a zero. */ +export function resetCreditsLine(credits: ResetCredits | null, now: number): string | null { + if (!credits || credits.availableCount <= 0) return null + const parts = [`${credits.availableCount} available`] + // Only worth saying when it disagrees with the headline count. + if (credits.applicableAvailableCount !== null && credits.applicableAvailableCount !== credits.availableCount) { + parts.push(`${credits.applicableAvailableCount} usable now`) + } + const grant = latestGrant(credits) + if (grant?.grantedAt != null) { + const type = resetTypeLabel(grant.resetType) + parts.push(grant.grantedAt > now + ? `next ${type} lands ${compactAge(grant.grantedAt, now)}` + : `latest ${type} granted ${compactAge(grant.grantedAt, now)}`) + } + if (credits.nextExpiresAt !== null) parts.push(`next expires ${compactAge(credits.nextExpiresAt, now)}`) + return `Limit resets · ${parts.join(' · ')}` +} + +export function decodeCodexUsage(body: unknown, now: number = Date.now()): QuotaProvider { const data = body && typeof body === 'object' ? body as Record : {} const primaryRaw = windowOf(data.rate_limit?.primary_window) const secondaryRaw = windowOf(data.rate_limit?.secondary_window) @@ -234,10 +346,15 @@ export function decodeCodexUsage(body: unknown): QuotaProvider { } // Uncapped on purpose, so a bar-less card does not read as a failed fetch. if (!credits && data.credits?.unlimited === true) footerLines.push('Credits · Unlimited') + // Limit-reset credits, banked ones included. `notes` is what `codeburn quota` + // prints; the footer keeps the desktop surfaces in step. + const resets = resetCreditsLine(decodeResetCredits(data.rate_limit_reset_credits, now), now) + if (resets) footerLines.push(resets) return { provider: 'codex', connection: 'connected', primary: primary ?? credits, details, planLabel: planLabel(data.plan_type), footerLines, + ...(resets ? { notes: [resets] } : {}), } } diff --git a/src/quota/index.ts b/src/quota/index.ts index 892c3d59..c879054c 100644 --- a/src/quota/index.ts +++ b/src/quota/index.ts @@ -27,6 +27,9 @@ export type QuotaCommandProvider = { plan?: string windows: QuotaCommandWindow[] error?: string + /** Provider facts that are not a window, such as Codex's limit-reset credits. + * Printed under the provider's rows and carried in `--format json`. */ + notes?: string[] } export type QuotaReport = { providers: QuotaCommandProvider[] } @@ -81,6 +84,7 @@ export function toCommandProvider(id: ProviderName, name: string, quota: QuotaPr ...(quota.planLabel ? { plan: quota.planLabel } : {}), windows: toWindows(quota), ...(error ? { error } : {}), + ...(quota.notes?.length ? { notes: quota.notes } : {}), } } @@ -119,11 +123,14 @@ export function renderQuotaTable(report: QuotaReport, opts: { color?: boolean } const title = provider.plan ? `${provider.name} (${provider.plan})` : provider.name if (provider.windows.length === 0) { rows.push([title, provider.error ?? 'Not connected', '', '']) + // A provider with no readable window can still hold a fact worth saying. + for (const note of provider.notes ?? []) rows.push(['', note, '', '']) continue } provider.windows.forEach((window, index) => { rows.push([index === 0 ? title : '', window.label, `${window.usedPct}%`, resetLabel(window.resetsAt)]) }) + for (const note of provider.notes ?? []) rows.push(['', note, '', '']) } const columns = [{ header: 'Provider' }, { header: 'Window' }, { header: 'Used', right: true }, { header: 'Resets' }] return renderTable(columns, rows, { color: opts.color }) diff --git a/src/quota/types.ts b/src/quota/types.ts index 2afd7a56..f4cae2a9 100644 --- a/src/quota/types.ts +++ b/src/quota/types.ts @@ -15,6 +15,10 @@ export type QuotaProvider = { * upstream quota endpoint), so the UI can say so honestly instead of the * generic "waiting" copy. */ rateLimited?: boolean + /** Facts that belong in `codeburn quota` output, not only in a hover card: + * a `footerLines` entry is a detail panel row, a note is printed under the + * provider's windows in the table and carried in `--format json`. */ + notes?: string[] } export type ProviderName = QuotaProvider['provider'] diff --git a/tests/quota-codex-banked-resets.test.ts b/tests/quota-codex-banked-resets.test.ts new file mode 100644 index 00000000..ae201648 --- /dev/null +++ b/tests/quota-codex-banked-resets.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from 'vitest' + +import { compactAge, decodeCodexUsage, decodeResetCredits, resetCreditsLine } from '../src/quota/codex.js' +import { renderQuotaTable, toCommandProvider } from '../src/quota/index.js' + +// 2027-01-15T08:00:00Z, the same instant the Swift suite pins, so the two sets +// of expected strings can be compared by eye. +const NOW = 1_800_000_000_000 + +function usageBody(block: unknown) { + return { + plan_type: 'plus', + rate_limit: { + primary_window: { used_percent: 12, limit_window_seconds: 18_000 }, + }, + rate_limit_reset_credits: block, + } +} + +describe('Codex limit-reset credits', () => { + it('names the count and the most recent grant, in the menubar wording', () => { + const quota = decodeCodexUsage(usageBody({ + available_count: 2, + credits: [ + { id: 'c1', reset_type: 'weekly', status: 'available', granted_at: '2027-01-15T06:00:00Z' }, + { id: 'c2', reset_type: 'weekly', status: 'available', granted_at: '2027-01-15T07:50:00Z' }, + ], + }), NOW) + expect(quota.notes).toEqual(['Limit resets · 2 available · latest weekly reset granted 10m ago']) + expect(quota.footerLines).toContain('Limit resets · 2 available · latest weekly reset granted 10m ago') + }) + + it('states the usable count only when it disagrees with the headline', () => { + const same = decodeCodexUsage(usageBody({ available_count: 1, applicable_available_count: 1 }), NOW) + expect(same.notes).toEqual(['Limit resets · 1 available']) + + const differs = decodeCodexUsage(usageBody({ available_count: 2, applicable_available_count: 1 }), NOW) + expect(differs.notes).toEqual(['Limit resets · 2 available · 1 usable now']) + }) + + it('keeps the expiry clause when the payload carries per-credit expiries', () => { + const line = resetCreditsLine(decodeResetCredits({ + available_count: 1, + credits: [{ + id: 'c1', reset_type: 'weekly', status: 'available', + granted_at: '2027-01-14T08:00:00Z', expires_at: '2027-01-16T00:00:00Z', + }], + }, NOW), NOW) + expect(line).toBe('Limit resets · 1 available · latest weekly reset granted 1d ago · next expires in 16h') + }) + + it('the expiry reported is the soonest one, not the last', () => { + const credits = decodeResetCredits({ + available_count: 2, + credits: [ + { id: 'c1', status: 'available', expires_at: '2027-01-20T08:00:00Z' }, + { id: 'c2', status: 'available', expires_at: '2027-01-16T00:00:00Z' }, + ], + }, NOW) + expect(credits?.nextExpiresAt).toBe(Date.parse('2027-01-16T00:00:00Z')) + expect(resetCreditsLine(credits, NOW)).toBe('Limit resets · 2 available · next expires in 16h') + }) + + it('only available credits count toward the grant and the expiry', () => { + const credits = decodeResetCredits({ + available_count: 1, + credits: [ + { id: 'c1', reset_type: 'weekly', status: 'available', granted_at: '2027-01-14T08:00:00Z' }, + { + id: 'c2', reset_type: 'weekly', status: 'redeemed', + granted_at: '2027-01-15T07:00:00Z', expires_at: '2027-01-15T09:00:00Z', + }, + ], + }, NOW) + expect(credits?.grants.map(grant => grant.id)).toEqual(['c1']) + expect(credits?.nextExpiresAt).toBeNull() + }) + + it('an absent applicable count is unknown, never zero', () => { + expect(decodeResetCredits({ available_count: 0 }, NOW)?.applicableAvailableCount).toBeNull() + expect(decodeResetCredits({ available_count: 0, applicable_available_count: 0 }, NOW) + ?.applicableAvailableCount).toBe(0) + }) + + it('falls back to granted_at as the identity, and drops a credit with neither', () => { + const credits = decodeResetCredits({ + available_count: 2, + credits: [ + { status: 'available', granted_at: '2027-01-14T08:00:00Z' }, + { status: 'available' }, + ], + }, NOW) + expect(credits?.grants.map(grant => grant.id)).toEqual(['2027-01-14T08:00:00Z']) + // Still counted — the server said two are available — but only one can ever + // be told apart from the next grant. + expect(credits?.availableCount).toBe(2) + }) + + it('holds nothing, says nothing', () => { + const quota = decodeCodexUsage(usageBody({ available_count: 0, applicable_available_count: 0 }), NOW) + expect(quota.notes).toBeUndefined() + expect(quota.footerLines).toEqual([]) + }) + + it('a malformed or missing block hides the line without failing the read', () => { + for (const block of [undefined, null, 'nonsense', {}, { available_count: -1 }, { available_count: 'two' }]) { + const quota = decodeCodexUsage(usageBody(block), NOW) + expect(quota.connection).toBe('connected') + expect(quota.primary?.percent).toBe(0.12) + expect(quota.notes).toBeUndefined() + } + }) + + it('a grant timestamped in the future reads as landing, not as granted', () => { + const line = resetCreditsLine(decodeResetCredits({ + available_count: 1, + credits: [{ id: 'c1', reset_type: 'weekly', status: 'available', granted_at: '2027-01-15T10:00:00Z' }], + }, NOW), NOW) + expect(line).toBe('Limit resets · 1 available · next weekly reset lands in 2h') + }) + + it('an absent reset_type degrades to the bare noun', () => { + const line = resetCreditsLine(decodeResetCredits({ + available_count: 1, + credits: [{ id: 'c1', status: 'available', granted_at: '2027-01-15T07:00:00Z' }], + }, NOW), NOW) + expect(line).toBe('Limit resets · 1 available · latest limit reset granted 1h ago') + }) + + it('compact ages read the same as the Swift port', () => { + expect(compactAge(NOW, NOW)).toBe('just now') + expect(compactAge(NOW - 59_000, NOW)).toBe('just now') + expect(compactAge(NOW - 60_000, NOW)).toBe('1m ago') + expect(compactAge(NOW - 7_200_000, NOW)).toBe('2h ago') + // Elapsed time is floored, never rounded up: 2h50m is still "2h ago". + expect(compactAge(NOW - 10_200_000, NOW)).toBe('2h ago') + expect(compactAge(NOW - 3 * 86_400_000, NOW)).toBe('3d ago') + expect(compactAge(NOW - 3.9 * 86_400_000, NOW)).toBe('3d ago') + expect(compactAge(NOW + 30_000, NOW)).toBe('in under a minute') + expect(compactAge(NOW + 7_200_000, NOW)).toBe('in 2h') + expect(compactAge(NOW + 2 * 86_400_000, NOW)).toBe('in 2d') + }) + + it('`codeburn quota` prints the line under the provider windows', () => { + const quota = decodeCodexUsage(usageBody({ available_count: 2, applicable_available_count: 1 }), NOW) + const provider = toCommandProvider('codex', 'Codex', quota) + expect(provider.notes).toEqual(['Limit resets · 2 available · 1 usable now']) + const table = renderQuotaTable({ providers: [provider] }) + expect(table).toContain('Limit resets · 2 available · 1 usable now') + }) + + it('a provider that reports no notes is rendered exactly as before', () => { + const quota = decodeCodexUsage(usageBody(undefined), NOW) + expect(toCommandProvider('codex', 'Codex', quota).notes).toBeUndefined() + }) +})