GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — feat(quota): per-account Claude rate limits, canonical 5-hour window by wonsh42 · Pull Request #493 · lidge-jun/opencodex Conversation
|
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughAnthropic per-account quota probing now uses account-scoped tokens, caches results, and exposes quota overlays through the OAuth accounts API. Provider workspace account rows display returned quota bars, with updated types, styles, cache invalidation, tests, and package version metadata. ChangesOAuth account quota flow
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ProviderWorkspace
participant useProviderAccountPools
participant OAuthAccountsAPI
participant fetchProviderAccountQuotas
participant AnthropicUsageAPI
ProviderWorkspace->>useProviderAccountPools: load provider account sets
useProviderAccountPools->>OAuthAccountsAPI: request accounts with quota=1
OAuthAccountsAPI->>fetchProviderAccountQuotas: fetch per-account quota rows
fetchProviderAccountQuotas->>AnthropicUsageAPI: probe usage with each account token
AnthropicUsageAPI-->>fetchProviderAccountQuotas: return account usage data
fetchProviderAccountQuotas-->>OAuthAccountsAPI: return quota rows
OAuthAccountsAPI-->>ProviderWorkspace: return accounts with quota fields
ProviderWorkspace-->>ProviderWorkspace: render account quota bars
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
✅ Target branch corrected This pull request now targets The |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
e4b0b9e to
5e466a7
Compare
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@gui/src/components/provider-workspace/ProviderAuthPanel.tsx`:
- Around line 247-251: Update the quota rendering in ProviderAuthPanel to read
account.quotaUnavailable: preserve and render stale quota bars when quota data
exists, while adding a translated pws.quotaUnavailable hint alongside them; when
quota is null but unavailable is true, render the same unavailable hint instead
of omitting the section. Add the pws.quotaUnavailable translation entry to the
locale files using the existing i18n conventions.
In `@src/providers/quota.ts`:
- Around line 283-326: Update fetchAccountQuota and fetchProviderAccountQuotas
to preserve quota data together with an explicit unavailable status, so failed
refreshes remain marked unavailable even when prior quota exists. Record failed
probes in the account cache with a refreshed timestamp and failure state to
enforce ACCOUNT_QUOTA_TTL_MS backoff, while retaining the last successful quota
for display; ensure successful probes clear the failure state and continue
returning normal rows.
In `@tests/provider-account-quota.test.ts`:
- Around line 86-100: Add a regression test alongside the existing provider
quota tests that first returns a successful probe to populate the account cache,
then force-refreshes with a failing response. Assert the refreshed result
preserves the cached quota while setting unavailable to true, using
fetchProviderAccountQuotas and the existing seed/setup helpers.
Fix all unresolved CodeRabbit comments on this PR:
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 2ba29eed-9518-4927-9a6e-361fa3ce192a
docs/assets/anthropic-account-quota-after.png is excluded by !**/*.pngdocs/assets/anthropic-account-quota-before.png is excluded by !**/*.pngdocs/assets/anthropic-five-hour-limit-overview.png is excluded by !**/*.pngdocs/assets/anthropic-usage-tab-active-account.png is excluded by !**/*.pnggui/src/components/provider-workspace/ProviderAuthPanel.tsxgui/src/components/provider-workspace/ProviderWorkspaceShell.tsxgui/src/components/provider-workspace/types.tsgui/src/hooks/useProviderAccountPools.tsgui/src/styles/provider-workspace-settings.csspackage.jsonsrc/providers/quota.tssrc/server/management/oauth-account-routes.tstests/provider-account-quota.test.tstests/provider-quota.test.ts
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| {account.quota && ( | ||
| <div className="pwi-auth-acct-quota"> | ||
| <QuotaBars quota={account.quota} plan={null} threshold={80} t={t} layout="stacked" /> | ||
| </div> | ||
| )} |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
account.quotaUnavailable is never surfaced to the user.
The row/hook types carry quotaUnavailable specifically to flag a failed probe while preserving stale data (per the PR's own stated behavior), but this component only checks account.quota and never reads account.quotaUnavailable. Two consequences:
quota: null, unavailable: true), nothing renders at all — no bars, no "unavailable" message.</div> - {account.quota && ( + {(account.quota || account.quotaUnavailable) && ( <div className="pwi-auth-acct-quota"> - <QuotaBars quota={account.quota} plan={null} threshold={80} t={t} layout="stacked" /> + {account.quotaUnavailable && ( + <span className="pwi-auth-quota-stale">{t("pws.quotaUnavailable")}</span> + )} + {account.quota && ( + <QuotaBars quota={account.quota} plan={null} threshold={80} t={t} layout="stacked" /> + )} </div> )}
New copy would need a pws.quotaUnavailable entry added to the locale files, per the i18n path guideline.
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| {account.quota && ( | |
| <div className="pwi-auth-acct-quota"> | |
| <QuotaBars quota={account.quota} plan={null} threshold={80} t={t} layout="stacked" /> | |
| </div> | |
| )} | |
| {(account.quota || account.quotaUnavailable) && ( | |
| <div className="pwi-auth-acct-quota"> | |
| {account.quotaUnavailable && ( | |
| <span className="pwi-auth-quota-stale">{t("pws.quotaUnavailable")}</span> | |
| )} | |
| {account.quota && ( | |
| <QuotaBars quota={account.quota} plan={null} threshold={80} t={t} layout="stacked" /> | |
| )} | |
| </div> | |
| )} |
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@gui/src/components/provider-workspace/ProviderAuthPanel.tsx` around lines 247
- 251, Update the quota rendering in ProviderAuthPanel to read
account.quotaUnavailable: preserve and render stale quota bars when quota data
exists, while adding a translated pws.quotaUnavailable hint alongside them; when
quota is null but unavailable is true, render the same unavailable hint instead
of omitting the section. Add the pws.quotaUnavailable translation entry to the
locale files using the existing i18n conventions.
Source: Path instructions
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| async function fetchAccountQuota(provider: string, accountId: string, forceRefresh: boolean): Promise<ProviderQuota | null> { | ||
| const key = accountCacheKey(provider, accountId); | ||
| const cached = accountQuotaCache.get(key); | ||
| if (!forceRefresh && cached && Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) return cached.quota; | ||
| const joinable = accountQuotaInflight.get(key); | ||
| if (joinable) return joinable; | ||
|
|
||
| const probe = (async (): Promise<ProviderQuota | null> => { | ||
| try { | ||
| // Account-scoped token: refreshes (and persists) only THIS account, never the active one. | ||
| const token = await getValidAccessTokenForAccount(provider, accountId); | ||
| const quota = await fetchAnthropicUsageQuota(token); | ||
| // A failed probe keeps the previous good row rather than flashing an empty bar. | ||
| if (!quota) return cached?.quota ?? null; | ||
| accountQuotaCache.set(key, { ts: Date.now(), quota }); | ||
| return quota; | ||
| } catch { | ||
| return cached?.quota ?? null; | ||
| } | ||
| })().finally(() => { | ||
| if (accountQuotaInflight.get(key) === probe) accountQuotaInflight.delete(key); | ||
| }); | ||
| accountQuotaInflight.set(key, probe); | ||
| return probe; | ||
| } | ||
|
|
||
| /** | ||
| * Per-account quota rows for a provider's logged-in accounts. Probes run in parallel; a | ||
| * single failing account never blocks the others. | ||
| */ | ||
| export async function fetchProviderAccountQuotas( | ||
| provider: string, | ||
| forceRefresh = false, | ||
| ): Promise<ProviderAccountQuota[]> { | ||
| if (!supportsPerAccountQuota(provider)) return []; | ||
| const set = getAccountSet(provider); | ||
| if (!set) return []; | ||
| return await Promise.all(set.accounts.map(async account => { | ||
| const quota = await fetchAccountQuota(provider, account.id, forceRefresh); | ||
| return quota | ||
| ? { accountId: account.id, quota } | ||
| : { accountId: account.id, quota: null, unavailable: true as const }; | ||
| })); | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Failed probes silently lose the unavailable signal once a prior good value exists — and there's no backoff, risking a 429 retry storm.
Two issues in fetchAccountQuota / fetchProviderAccountQuotas:
unavailable flag on preserved data. When a probe fails but cached?.quota exists, fetchAccountQuota returns that truthy quota value (Line 296/300: return cached?.quota ?? null;). Back in fetchProviderAccountQuotas (Line 322-324), a truthy return is treated as success: quota ? { accountId, quota } : { accountId, quota: null, unavailable: true }. So once an account has ever succeeded, every subsequent failure (expired login, 429, network) is indistinguishable from a fresh success — the PR's own stated behavior ("Failed probes are marked unavailable while preserving the last successful data") is only honored the very first time a probe fails (before any cache entry exists). This is confirmed by tests/provider-account-quota.test.ts Lines 86-100, which only exercises the "never succeeded" path.cached.ts (Lines 296, 300), the TTL guard (Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) stays permanently expired for that account after any failure, so every subsequent accounts-list fetch (e.g. GUI polling) re-probes upstream immediately with no backoff — exactly the "observed 429 under repeated probing" scenario the file's own comment (Lines 248-249) warns about.-async function fetchAccountQuota(provider: string, accountId: string, forceRefresh: boolean): Promise<ProviderQuota | null> { +async function fetchAccountQuota(provider: string, accountId: string, forceRefresh: boolean): Promise<{ quota: ProviderQuota | null; unavailable: boolean }> { const key = accountCacheKey(provider, accountId); const cached = accountQuotaCache.get(key); - if (!forceRefresh && cached && Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) return cached.quota; + if (!forceRefresh && cached && Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) return { quota: cached.quota, unavailable: false }; const joinable = accountQuotaInflight.get(key); if (joinable) return joinable; - const probe = (async (): Promise<ProviderQuota | null> => { + const probe = (async (): Promise<{ quota: ProviderQuota | null; unavailable: boolean }> => { try { // Account-scoped token: refreshes (and persists) only THIS account, never the active one. const token = await getValidAccessTokenForAccount(provider, accountId); const quota = await fetchAnthropicUsageQuota(token); - // A failed probe keeps the previous good row rather than flashing an empty bar. - if (!quota) return cached?.quota ?? null; - accountQuotaCache.set(key, { ts: Date.now(), quota }); - return quota; + // A failed probe keeps the previous good row rather than flashing an empty bar, but + // still bumps `ts` so we don't hammer upstream on every subsequent list refresh. + if (!quota) { + accountQuotaCache.set(key, { ts: Date.now(), quota: cached?.quota ?? null }); + return { quota: cached?.quota ?? null, unavailable: true }; + } + accountQuotaCache.set(key, { ts: Date.now(), quota }); + return { quota, unavailable: false }; } catch { - return cached?.quota ?? null; + accountQuotaCache.set(key, { ts: Date.now(), quota: cached?.quota ?? null }); + return { quota: cached?.quota ?? null, unavailable: true }; } })().finally(() => { if (accountQuotaInflight.get(key) === probe) accountQuotaInflight.delete(key); }); accountQuotaInflight.set(key, probe); return probe; } export async function fetchProviderAccountQuotas( provider: string, forceRefresh = false, ): Promise<ProviderAccountQuota[]> { if (!supportsPerAccountQuota(provider)) return []; const set = getAccountSet(provider); if (!set) return []; return await Promise.all(set.accounts.map(async account => { - const quota = await fetchAccountQuota(provider, account.id, forceRefresh); - return quota - ? { accountId: account.id, quota } - : { accountId: account.id, quota: null, unavailable: true as const }; + const { quota, unavailable } = await fetchAccountQuota(provider, account.id, forceRefresh); + return unavailable + ? { accountId: account.id, quota, unavailable: true as const } + : { accountId: account.id, quota }; })); }
Note: this bug propagates downstream to GET /api/oauth/accounts?quota=1 in src/server/management/oauth-account-routes.ts (Lines 190-196), which forwards row.unavailable as-is, and ultimately to the GUI's quotaUnavailable field — no code change is needed there once this root cause is fixed.
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/providers/quota.ts` around lines 283 - 326, Update fetchAccountQuota and
fetchProviderAccountQuotas to preserve quota data together with an explicit
unavailable status, so failed refreshes remain marked unavailable even when
prior quota exists. Record failed probes in the account cache with a refreshed
timestamp and failure state to enforce ACCOUNT_QUOTA_TTL_MS backoff, while
retaining the last successful quota for display; ensure successful probes clear
the failure state and continue returning normal rows.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| test("a failing probe is flagged unavailable without dropping the other account", async () => { | ||
| await seedTwoAccounts(); | ||
| globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { | ||
| const auth = new Headers(init?.headers).get("authorization") ?? ""; | ||
| // Anthropic rate-limits this endpoint; one 429 must not blank the sibling account. | ||
| if (auth.endsWith("token-first")) return new Response("rate limited", { status: 429 }); | ||
| return new Response(usageBody(3, 21), { status: 200 }); | ||
| }) as typeof fetch; | ||
|
|
||
| const rows = await fetchProviderAccountQuotas("anthropic"); | ||
| const failed = rows.find(row => row.quota === null); | ||
| const ok = rows.find(row => row.quota !== null); | ||
| expect(failed?.unavailable).toBe(true); | ||
| expect(ok?.quota?.fiveHourPercent).toBe(3); | ||
| }); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Missing regression test: probe fails after a prior success.
This test only covers accounts that never had a successful probe (fresh beforeEach cache). It doesn't cover the scenario where an account has a cached good value and a subsequent probe then fails — which is exactly the case where unavailable currently gets dropped in src/providers/quota.ts (see the comment there on Lines 283-326). Add a case that: (1) succeeds once to populate the cache, (2) force-refreshes with a failing response, and (3) asserts both that quota is preserved AND unavailable === true.
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/provider-account-quota.test.ts` around lines 86 - 100, Add a regression
test alongside the existing provider quota tests that first returns a successful
probe to populate the account cache, then force-refreshes with a failing
response. Assert the refreshed result preserves the cached quota while setting
unavailable to true, using fetchProviderAccountQuotas and the existing
seed/setup helpers.
Source: Path instructions
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Here are some automated review suggestions for this pull request.
Reviewed commit: 5e466a7946
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const token = await getValidAccessTokenForAccount(provider, accountId); | ||
| const quota = await fetchAnthropicUsageQuota(token); | ||
| // A failed probe keeps the previous good row rather than flashing an empty bar. | ||
| if (!quota) return cached?.quota ?? null; |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Preserve failure status when returning cached quota
When a cached account is force-refreshed and Anthropic returns a non-OK response such as 429, this fallback returns the cached quota as though the probe succeeded. fetchProviderAccountQuotas consequently omits unavailable, so ?refresh=1 silently returns stale data and clients cannot report that the requested refresh failed. Preserve the cached quota and the probe-failure status separately.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| <IconTrash style={{ width: 13, height: 13 }} aria-hidden="true" /> | ||
| </button> | ||
| </div> | ||
| {account.quota && ( |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Surface unavailable account quotas
When an account's initial probe fails because of an expired login, network error, or 429, the API returns quota: null with quotaUnavailable: true, but this component renders only truthy account.quota and never consumes the failure flag. The account therefore looks as if quota reporting does not exist, with no error or retry indication. Render a localized unavailable state when the flag is set.
AGENTS.md reference: gui/AGENTS.md:L5-L9
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const wantQuota = url.searchParams.get("quota") === "1" && supportsPerAccountQuota(provider); | ||
| if (!wantQuota) return jsonResponse({ activeAccountId: status.activeAccountId ?? null, accounts }); | ||
| const forceRefresh = url.searchParams.get("refresh") === "1"; | ||
| const rows = await fetchProviderAccountQuotas(provider, forceRefresh); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Rebuild health after quota-triggered token refresh
For an expired Anthropic credential whose refresh fails terminally, this call marks the stored account needsReauth, but status, set, and the projected accounts array were all captured before the call. The response still reports that account as healthy, and the GUI has no periodic account-list refresh, so the reauthentication action remains absent until another action or page reload. Probe before projecting account health, or rebuild the status and health fields afterward.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| </div> | ||
| {account.quota && ( | ||
| <div className="pwi-auth-acct-quota"> | ||
| <QuotaBars quota={account.quota} plan={null} threshold={80} t={t} layout="stacked" /> |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Document Anthropic account quota behavior
This adds a user-visible per-account Anthropic quota surface and changes the displayed 5-hour window, but the commit does not update docs-site/; the four new docs/assets screenshots are also unreferenced anywhere in the repository. Update the public dashboard/provider documentation, keeping localized pages consistent with the English source.
AGENTS.md reference: AGENTS.md:L78-L79
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| } catch { | ||
| return null; | ||
| } | ||
| const quota = await fetchAnthropicUsageQuota(accessToken); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Share Anthropic quota probes across report paths
On every Providers-page load with Anthropic OAuth, the workspace requests both /api/provider-quotas and /api/oauth/accounts?..."a=1. This provider-report path probes the active credential here, while the account path independently probes the same credential through a separate cache and inflight map, so the active account receives two near-simultaneous calls to Anthropic's rate-limited usage endpoint. Reuse the active per-account probe for the provider report, or share a single cache and inflight operation between both paths.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| { | ||
| "name": "@bitkyc08/opencodex", | ||
| "version": "2.7.35", | ||
| "version": "2.7.40", |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Leave the package version to the release workflow
This feature commit advances the package version from 2.7.35 to 2.7.40, even though version bumps are owned by the repository's release authority and normally live in dedicated release: v... commits. Applied before that release commit, this advertises an unreleased version and takes the bump outside the guarded release flow; applied afterward, it is unrelated version churn. Revert this line from the feature change and let scripts/release.ts perform the bump.
AGENTS.md reference: AGENTS.md:L21-L22
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const probe = (async (): Promise<ProviderQuota | null> => { | ||
| try { | ||
| // Account-scoped token: refreshes (and persists) only THIS account, never the active one. | ||
| const token = await getValidAccessTokenForAccount(provider, accountId); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Avoid adopting the global CLI token into background slots
When a stored Anthropic account originated from the local Claude CLI, is now a background account, and its token enters the refresh window, this new all-account probe calls getValidAccessTokenForAccount for it automatically. Anthropic's refresh path then checks the single global Claude CLI credential and persists any newer generation into the requested slot without verifying that its accountId or email matches; if the external CLI has since logged into another identity, merely opening Providers silently replaces the background slot's credential and later routes that slot's requests through the wrong account. Skip global-CLI adoption for background probes or require an identity match before persisting it.
AGENTS.md reference: AGENTS.md:L65-L71
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Request changes ÔÇö do not merge until this branch is rebased onto current dev (resolve the package.json conflict without downgrading the version), and the per-account probe failure / credential-integrity defects below are fixed in this PR. Optional follow-ups are not accepted; every quality item below must ship here.
Base is correctly dev. Direction is right: Anthropic usage is per credential, so per-account probing with account-scoped tokens, a longer TTL, canonical fiveHourPercent / fiveHourResetAt, opt-in ?quota=1, and focused tests match the stated gaps. Tip 5e466a79 is still the current head. GitHub reports mergeable: CONFLICTING, mergeStateStatus: DIRTY, and the branch is 124 commits behind dev.
Merge conflict against current dev (mergeable=CONFLICTING, mergeStateStatus=DIRTY).
git merge-tree of 5e466a79 into dev @ 58f0fab3.package.json only (src/server/management/oauth-account-routes.ts auto-merges).dev: "version": "2.7.41""version": "2.7.40"dev into this branch and resolve in this PR. Keep 2.7.41 (current dev)  do not downgrade. Prefer dropping the release: v2.7.40 / version bump from this feature PR entirely; version bumps belong to maintainer release promotion (scripts/release.ts), not a contributor quota UI fix.Failed probes drop unavailable once a prior good row exists, and do not advance the TTL  retry storm  src/providers/quota.ts ~L283324
fetchAccountQuota returns cached?.quota ?? null without writing a new cache entry (L296, L300). fetchProviderAccountQuotas then treats any truthy quota as success (L322324) and omits unavailable. After a first success, every later 429 / network / expired-login failure looks like a fresh success. Because a failed probe does not refresh ts, once the old TTL expires the next ?quota=1 load immediately re-probes again  the author already observed Anthropic 429s; this path amplifies them. ?refresh=1 has the same silent-stale outcome.{ ts, quota, unavailable? }). On failure: keep last-good quota for display, set unavailable: true, and advance ts so ACCOUNT_QUOTA_TTL_MS backs off. On success: clear unavailable. Propagate { quota, unavailable } from fetchAccountQuota instead of collapsing to ProviderQuota | null. Add the fail-after-success regression test CodeRabbit called for in tests/provider-account-quota.test.ts.Background Claude local-cli slots can adopt the global CLI token with no identity check  triggered from src/providers/quota.ts ~L293 via getValidAccessTokenForAccount  refreshAnthropicAccountWithLock / newerClaudeCredential in src/oauth/index.ts ~L304338
quota=1). For any background slot with source: "local-cli" whose stored generation differs from detectClaudeCodeToken(), newerClaudeCredential returns the disk credential and mergeAccountCredential persists it into that slot with no accountId / email match and no active-only guard (unlike Kiros active-only CLI import at ~L425426 and Groks identity-gated authoritative). If the user later logged the Claude CLI into another identity, merely opening Providers can silently overwrite a background account and later route that slot through the wrong credential.local-cli account does not persist a mismatched disk credential.Drop / neutralize the version bump. Three-dot diff still changes package.json 2.7.35  2.7.40 via f47726a0 (release: v2.7.40). Out of scope; it is what conflicts with devs 2.7.41. Resolve by taking devs version (no version change in this PR).
Surface quotaUnavailable in the GUI ÔÇö gui/src/components/provider-workspace/ProviderAuthPanel.tsx ~L247ÔÇô249
quotaUnavailable, but the row only renders {account.quota && <QuotaBars .../>}. Failed first probe  blank (looks like no limits); failed later probe  bars look fresh. Render a localized stale/unavailable hint (and still show last-good bars when present).Rebuild account health after quota-triggered token work  src/server/management/oauth-account-routes.ts ~L164195
status before fetchProviderAccountQuotas. A probe that terminally fails refresh / marks needsReauth still returns pre-probe healthy rows; the GUI has no periodic account-list refresh, so reauth UI can stay missing until reload. Probe first, or rebuild status/health after probing.Share Anthropic usage probes across provider-report and per-account paths ÔÇö src/providers/quota.ts (fetchAnthropicQuota vs fetchProviderAccountQuotas)
/api/provider-quotas and /api/oauth/accounts?..."a=1, so the active credential is probed twice through separate caches/inflight maps. Reuse the active per-account probe (or one shared cache/inflight) for the provider report.clearAccountQuotaCache must also clear accountQuotaInflight ÔÇö src/providers/quota.ts ~L272ÔÇô280 / L253
Key Usage/overview quota refetch on active account identity, not only activeAccountNeedsReauth ÔÇö gui/src/components/provider-workspace/ProviderWorkspaceShell.tsx ~L180ÔÇô207
switchAccount already calls fetchProviderQuotas(true) for the Providers hook, but the shell keeps a separate /api/provider-quotas effect. Depending on object-identity of a boolean map is brittle (two healthy accounts  empty maps that only refetch because useMemo allocates a new object). Key on anthropic/active account id (or a dedicated refresh token bumped by switchAccount) so the stated no reload after switch fix is explicit.Docs sync for user-visible behavior  missing docs-site/ updates; docs/assets/anthropic-*.png are unreferenced.
Re-run full CI on the rebased tip. Tip CI: ubuntu/macOS Cross-platform green; windows-latest was cancelled (not a clean green matrix). After rebase/conflict resolution, require Cross-platform CI (incl. Windows), typecheck, tests, privacy:scan, and GUI lint/build green on the mergeable SHA.
None. Follow-up PRs are rejected for this review; every item above is required in this PR before merge.
tests/provider-account-quota.test.ts, updated tests/provider-quota.test.ts). Gaps: release-owned package.json bump, docs-site sync, incomplete failure-state / cache-clear invariants, fragile GUI refresh coupling.unavailable while keeping last-goodÔÇØ (API flag dropped after first success; GUI never consumes the flag) and amplifies credential side effects not called out in the design notes.local-cli adoption) is the security gate for this PR. Screenshots claim emails were redacted before capture ÔÇö good; keep real addresses out of committed assets.| Gate | Status |
|---|---|
| Base branch | dev (correct) |
mergeable / mergeStateStatus |
CONFLICTING / DIRTY ÔÇö block |
| Divergence | ahead 2 / behind 124 vs dev |
| Conflicted files | package.json (2.7.41 vs 2.7.40) |
Cross-platform CI @ 5e466a79 |
ubuntu/macOS pass; windows-latest cancelled |
| react-doctor / enforce-target / privacy (author-reported) | pass / pass / author claims pass |
| Review event | CHANGES REQUESTED |
Reviewed tip: 5e466a79461ad1934ff88a1eb960dcc2824f2f26.
Once all blocking + required quality changes above are addressed (and conflicts/rebase done), mark this PR Ready for review (leave draft only until then). Then ping for re-review / CI.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Anthropic reports OAuth usage per CREDENTIAL, so every logged-in account can be probed with its own bearer token. Three related gaps: 1. Only the ACTIVE account's rate limits were ever fetched, so a multiauth Claude setup could not see a background account's headroom before switching to it. Adds fetchProviderAccountQuotas() (mirroring the Codex pool's per-account probe, including a per-account TTL) and exposes it on GET /api/oauth/accounts?quota=1, rendered as bars on each account row. 2. The 5-hour window was reported as a generic `customWindows` entry labelled "5h", so it rendered differently from the Codex login rows. It now uses the canonical fiveHourPercent/fiveHourResetAt fields and picks up the standard "5-hour limit" label and ordering. Opus/Sonnet stay custom windows. 3. The workspace shell fetched provider quotas once on mount, so switching the active account left the previous account's numbers on the Usage tab until a full page reload. The fetch is now keyed on account state. The per-account TTL is longer than the provider-level one: this path multiplies by account count and the usage endpoint rate-limits under repeated probing (observed 429). A failing probe is flagged unavailable and keeps the last good row instead of blanking a sibling account.
Preserve last-good bars with unavailable + TTL backoff, skip CLI token adoption on background slots, rebuild health after probes, share the active-account usage probe, and surface stale quota in the GUI/docs.
Maintainer takeoverRebased onto latest Applied CodeRabbit + Codex review fixes on top of @wonsh42's feature commit:
Credit: original feature by @wonsh42. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
5e466a7 to
f186fc8
Compare
…account id Address remaining Wibias review items: logout/remove must drop accountQuotaInflight, and Providers overview/Usage must refetch on active-account identity rather than the reauth boolean map.
|
Follow-up: two Wibias-review items that were missed in the first takeover pass are now on the tip:
Also strengthened the background Marked ready for re-review. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Here are some automated review suggestions for this pull request.
Reviewed commit: 000f67937f
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const activeId = getAccountSet("anthropic")?.activeAccountId; | ||
| if (activeId) { | ||
| accountQuotaCache.set(accountCacheKey("anthropic", activeId), { ts: Date.now(), quota }); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Bind seeded quota to the probed account
If /api/provider-quotas begins probing account A and the user switches to account B before Anthropic responds, this post-request lookup reads B as active and caches A's quota under B's ID. The subsequent quota-enabled account list can then skip probing B and display A's limits as B's for the 10-minute cache TTL without marking them unavailable. Capture the account ID alongside the token before awaiting the request, or otherwise verify that the token still belongs to the ID being seeded, and add an account-switch race regression test.
AGENTS.md reference: AGENTS.md:L93-L95
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| // `quota=1` asks the proxy for each account's own rate limits (Anthropic reports usage | ||
| // per credential), so every logged-in account can show its 5h/weekly bars — not just | ||
| // the active one. | ||
| const res = await fetch(`${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}"a=1`); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Do not block account rows on quota probes
When Anthropic's usage endpoint is slow or unreachable, the initial account-list request now waits for every quota probe, each of which can run until the 8-second timeout. Since the first load has no cached account rows, the dashboard hides account switching, reauthentication, and removal controls for that entire interval even though the account metadata is available locally. Load the cheap account list first and enrich it with quotas asynchronously, or return cached/local rows while probing in the background.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const activeId = getAccountSet(provider)?.activeAccountId; | ||
| if (activeId !== accountId) { | ||
| throw new Error("background account token expired; skip CLI-adopting refresh for quota probe"); | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Refresh ordinary OAuth background accounts
Once a non-active Anthropic account enters the token refresh window, this rejects it regardless of how the credential was obtained. Browser-login credentials have source: "oauth", and refreshAnthropicAccountWithLock consults the global Claude credential only when the stored source is local-cli, so those ordinary background slots can be refreshed without the cross-account adoption risk. As written, their quota remains unavailable after access expiry until the user makes each account active, defeating the ability to inspect headroom before switching; restrict this guard to local-cli slots and add a focused OAuth-background regression case.
AGENTS.md reference: AGENTS.md:L93-L95
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const key = accountCacheKey(provider, accountId); | ||
| const cached = accountQuotaCache.get(key); | ||
| if (!forceRefresh && cached && Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) return cached; |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Invalidate cached quota when credentials are replaced
If a quota probe caches unavailable and the user then successfully reauthenticates that account, the new credential is written back into the same stable account ID, but this cache entry is keyed only by that ID and no successful-login path clears it. The post-login GUI fetch is non-forced, so it continues showing the failure and any old bars for up to 10 minutes despite the repaired login. Include the credential generation in the cache validity check or clear this provider's account-quota cache when login/reauth persists credentials, with a focused reauth regression test.
AGENTS.md reference: AGENTS.md:L93-L95
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| const customWindows: ProviderQuotaWindow[] = []; | ||
| if (opus?.percent !== undefined) customWindows.push({ label: "Opus", percent: opus.percent, ...(opus.resetAt !== undefined ? { resetAt: opus.resetAt } : {}) }); | ||
| if (sonnet?.percent !== undefined) customWindows.push({ label: "Sonnet", percent: sonnet.percent, ...(sonnet.resetAt !== undefined ? { resetAt: sonnet.resetAt } : {}) }); | ||
| return { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Reject Anthropic responses with no quota rows
If Anthropic returns HTTP 200 with an empty, error-envelope, or changed-schema JSON object, this helper still returns a non-null quota containing only updatedAt. The provider report happens to filter that object through report(), but the new per-account path treats any non-null result as success, so the account renders neither bars nor the unavailable state and negative-caches that result for 10 minutes. Return null unless the constructed object passes hasQuotaRows, and cover an empty successful payload in the focused quota tests.
AGENTS.md reference: AGENTS.md:L93-L95
Useful? React with 👍 / 👎.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Reject empty usage payloads, refresh ordinary OAuth background slots, bind provider-report seeds to the probed account, clear account-quota cache on login/reauth, and load account rows before waiting on quota enrichment.
|
Addressed tip Codex comments on
Waiting on CodeRabbit for the new tip before squash-merge. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Approve — tip 75b80d5a is mergeable; Cross-platform CI green (ubuntu/macOS/windows + npm-global); CodeRabbit completed with no new actionable tip comments; prior Codex tip findings addressed on this SHA.
Maintainer takeover of @wonsh42's per-account Anthropic quota work, rebased onto dev, with CodeRabbit/Codex/Wibias review blockers fixed (unavailable+TTL, local-cli fail-closed, health rebuild, probe sharing, GUI surface, docs, inflight clear, active-account refresh key, empty-payload reject, OAuth background refresh, login cache clear, async account-list enrichment, seed-binding race).
Original feature: @wonsh42. Maintainer harden/rebase: Wibias.
Squash-merging with author credit to wonsh42.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
…idge-jun#493) Anthropic OAuth usage is per credential: probe each logged-in account for 5h/weekly bars, use canonical fiveHour fields, and refresh overview quotas after active-account switches. Maintainer takeover on latest dev with CodeRabbit/Codex/Wibias review harden (unavailable+TTL, local-cli fail-closed, health rebuild, probe sharing, GUI/docs, cache/inflight/login invalidation, async account-list load). Credit: @wonsh42 (original feature). Co-authored-by: wonsh42 <[email protected]>
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.