Skip to content

fix(rate-limits): map Codex individual usage to monthly window - #8717

Closed
rodboev wants to merge 4 commits into
stablyai:mainfrom
rodboev:pr/orca-8664-codex-business-usage
Closed

rodboev wants to merge 4 commits into
stablyai:mainfrom
rodboev:pr/orca-8664-codex-business-usage

Conversation

@rodboev

@rodboev rodboev commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Map a usable Codex spend_control.individual_limit response to the existing monthly usage window, regardless of whether the source is group-based or account-user controls.
  • Map the reported RPC individualLimit and planType fields directly, preferring precise used / limit usage and preserving the reset boundary.
  • Keep standard session and weekly windows additive, use one bounded backend request for older successful empty RPC results, and avoid retrying a WSL backend miss through the supplement path.
  • Preserve monthly-only usage in inactive Codex account previews during account switching.

Closes #8664

Screenshots

No visual change. The existing status bar and usage panels consume the monthly window already supported by Orca.

Testing

  • Focused Codex behavior tests: 31 passed across backend mapping and RPC/supplement routing.
  • Monthly-only account-switch cache test: passed.
  • Existing window classifier tests: 14 passed.
  • Node typecheck, touched-file oxlint, and oxfmt checks: passed.
  • The existing Codex fetcher file retains two unchanged baseline mock-kill failures, and the full account-target file retains five unchanged Claude-option expectation failures; the new cases pass independently.

AI Review Report

The implementation was reviewed against current main across backend and RPC payload mapping, standard-window classification, fallback eligibility, reset-credit precedence, WSL/native process routing, and inactive-account caching. The review findings were addressed with focused regression coverage for malformed shapes, direct percentage precedence, over-cap values, reset tolerance, no-retry behavior, and monthly-only previews.

Security Audit

No authentication or authorization behavior changed. The implementation reuses existing bounded request signals, credential loading, process cleanup, and reset-credit handling. Test credentials are fake literals used only in mocked fixtures.

Notes

This change is scoped to Orca's parsing, precedence, fallback, and cache behavior for the reported payload shapes. The fixtures document compatibility evidence; they do not claim to prove every Codex plan or CLI contract. Rebuilt from current main following the second spend-control payload report.

ELI5

Codex can report a monthly spending meter in two places. Orca now recognizes both places, keeps the exact reset date, and shows the saved meter when switching between accounts.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Codex rate-limit parsing now maps valid backend and RPC individual limits into monthly usage windows. Backend responses can succeed without plan_type, and plan metadata remains optional. Session enrichment reconciles monthly, weekly, session, reset-credit, and timestamp data while preventing duplicate backend requests across WSL and PTY fallbacks. Tests cover valid, malformed, and incomplete payloads. Account switching now preserves monthly-only Codex snapshots.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses issue #8664 by parsing Codex Business individual limits and exposing the usage percentage through a monthly window.
Out of Scope Changes check ✅ Passed The fixture, parsing changes, fallback handling, caching update, and focused tests directly support the linked Codex Business usage objective.
Title check ✅ Passed The title clearly identifies the main change: mapping Codex individual usage to a monthly rate-limit window.
Description check ✅ Passed The description explains the change and rationale, links issue #8664, documents testing and no visual change, and covers security and compatibility notes.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (4)
src/main/rate-limits/codex-fetcher.ts (2)

1111-1145: 🚀 Performance & Scalability | 🔵 Trivial

Reset-credit reconciliation and business-plan gating look correct, verified against the paired test files (restoring RPC's rateLimitResetCredits when the backend explicitly returns null, and skipping the retry entirely for WSL-managed homes).

One operational note: this branch triggers a full fetchViaBackend network round-trip on every poll whenever native RPC returns empty session/weekly, even for non-Business accounts (the plan check only gates whether the result is used, not whether the fetch happens). For accounts that persistently return empty native windows for reasons unrelated to Business plans, this adds a repeated extra request per poll cycle. Worth keeping an eye on if polling frequency is high.


125-139: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Remove the unused backend window fields
mapBackendUsageWindow only reads used_percent and reset_at, so remaining_percent and reset_after_seconds are dead type surface here unless they’re wired in as fallbacks.

src/main/rate-limits/codex-fetcher-business-usage.test.ts (2)

288-317: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

"Malformed" sub-case doesn't actually test a malformed backend payload.

The second scenario (malformedResultPromise) doesn't queue a new fetch mock — it relies on the already-exhausted mock queue falling back to vi.fn()'s default undefined return, which incidentally passes only because callers wrap fetchViaBackend/fetchBackendRateLimitResetCredits in try/catch. This doesn't actually exercise the typeof payload.plan_type !== 'string' rejection path in fetchViaBackend that "malformed" implies.

♻️ Suggested explicit malformed-payload mock
     vi.mocked(fetch)
       .mockRejectedValueOnce(new Error('backend unavailable'))
-      .mockResolvedValueOnce({ ok: true, json: async () => ({}) } as Response)
+      .mockResolvedValueOnce({ ok: true, json: async () => ({}) } as Response)
+      .mockResolvedValueOnce({ ok: true, json: async () => ({ not_a_valid_payload: true }) } as Response)
+      .mockResolvedValueOnce({ ok: true, json: async () => ({}) } as Response)

105-117: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test helper/fixture duplication across three Codex rate-limit test files. makeRpcChild() and the RPC reset-credit fixtures (rpcResetCreditPayload/expectedRpcResetCredits) are copy-pasted verbatim into the two new test files instead of being imported from a shared module, risking drift if the RPC mock shape or reset-credit normalization changes.

  • src/main/rate-limits/codex-fetcher-business-usage.test.ts#L105-L117: import a shared makeRpcChild() instead of redefining it.
  • src/main/rate-limits/codex-fetcher-backend.test.ts#L21-L34: import the same shared makeRpcChild() instead of redefining it.
  • src/main/rate-limits/codex-fetcher-business-usage.test.ts#L35-L55: import shared rpcResetCreditPayload/expectedRpcResetCredits fixtures instead of redefining them.
  • src/main/rate-limits/codex-fetcher.test.ts#L41-L63: move these fixtures into a shared test-utils module so both this file and codex-fetcher-business-usage.test.ts import from one source.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0f7e3507-07e4-4877-b43c-1390274115f4

📥 Commits

Reviewing files that changed from the base of the PR and between 31f643c and 279de54f484ce6fef9d123ddd62dfb67bc2face8.

📒 Files selected for processing (5)
  • src/main/rate-limits/codex-business-wham-usage-8664.fixture.json
  • src/main/rate-limits/codex-fetcher-backend.test.ts
  • src/main/rate-limits/codex-fetcher-business-usage.test.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts

@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@brennanb2025
brennanb2025 force-pushed the pr/orca-8664-codex-business-usage branch from 279de54 to e5bb6df Compare July 20, 2026 20:42
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the clear report and fix! I rebased this onto current main and pushed a small maintainer follow-up: Business individual_limit usage is now exposed as the monthly spend window (so it is not mislabeled as a 5-hour session), while standard session/weekly windows remain intact. I also tightened the malformed-payload coverage and removed the unused backend type fields; the focused Codex tests, status-bar monthly-window tests, formatting, lint on touched files, and node typecheck all pass.

@zeikar

zeikar commented Aug 18, 2026

Copy link
Copy Markdown

Still broken on main at 1b5cc00. rg 'spend_control|individualLimit' src/main/rate-limits/ finds nothing, and this branch is CONFLICTING now.

Hit it on a second account, different spend-control source than the one in #8664 (amounts redacted):

{ "plan_type": "business", "rate_limit": null,
  "spend_control": { "individual_limit": {
    "source": "account_user_spend_controls",
    "used_percent": 65, "remaining_percent": 35,
    "reset_at": <unix seconds, exactly 00:00 UTC on the 1st> } } }

#8664's was group_based_spend_controls, this one account_user_spend_controls, same field layout either way. reset_at lands on a month boundary, which backs the monthly bucket.

Three things from reading the diff.

Both gates key off the literal plan_type === 'business'. I couldn't check what Enterprise or Edu report, so I can't claim they're missed, but keying off the presence of spend_control.individual_limit sidesteps that question: any plan carrying the object gets mapped, any plan without it is left alone. monthly is additive, so a plan with both rate_limit windows and a spend control still degrades cleanly (StatusBar.tsx only renders monthly inline when session and weekly are both absent).

The RPC path may already have this. On codex-cli 0.147.0, account/rateLimits/read returns individualLimit { limit, used, remainingPercent, resetsAt } and planType next to the null primary/secondary, so the extra wham/usage fetch could be skipped on non-WSL hosts. The backend supplement is still the right fallback for older CLIs that don't emit it. Two smaller things: remainingPercent is integer-rounded, so used/limit*100 is more precise when both are present, and planType is dropped from the RPC result today, which is why the plan label doesn't render on macOS either.

Last one is mechanical. mapBackendUsageWindow is gone from main; it's backendWindowToSnapshot + classifyCodexRateLimitWindows + snapshotWindowMinutes in codex-rate-limit-window-classification.ts now, with window kind inferred from limit_window_seconds rather than passed in. So this needs rebuilding, not a rebase.

Calling the spend control a monthly window rather than a session was right and should stay. I can do the rework as a follow-up crediting you both, or leave it if either of you wants to pick it back up.

@rodboev @brennanb2025

@rodboev
rodboev force-pushed the pr/orca-8664-codex-business-usage branch from e5bb6df to 57bff8e Compare August 19, 2026 01:38
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@rodboev rodboev changed the title fix(rate-limits): show Codex Business usage percentage in the status bar fix(rate-limits): map Codex individual usage to monthly window Aug 19, 2026
@rodboev

rodboev commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed current-main trace and the second payload. I rebuilt this from current main instead of rebasing the conflicting branch.

The spend control is mapped as a monthly window whenever a usable individual_limit object is present, independent of the source label or plan label. The backend and RPC paths map planType and individualLimit directly, prefer used / limit when available, and preserve the reported month-boundary reset.

Standard windows remain additive. Direct RPC monthly data avoids the extra backend usage request; an older successful empty RPC result gets the bounded backend fallback, while WSL backend-first misses aren't retried through the supplement path. Monthly-only snapshots also remain available in inactive-account previews when switching Codex accounts.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 47309000-89ec-4257-bbec-39ea6fc26ba2

📥 Commits

Reviewing files that changed from the base of the PR and between fae9282 and 57bff8e.

📒 Files selected for processing (6)
  • src/main/rate-limits/codex-business-wham-usage-8664.fixture.json
  • src/main/rate-limits/codex-fetcher-backend.test.ts
  • src/main/rate-limits/codex-fetcher-session-supplement.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/rate-limits/codex-business-wham-usage-8664.fixture.json

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment thread src/main/rate-limits/codex-fetcher.ts Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Codex Business usage percentage is not displayed correctly in Status Bar

4 participants