Skip to content

Show Grok usage-limit reset coupons - #3188

Open
Leshabeats wants to merge 1 commit into
steipete:mainfrom
Leshabeats:grok-remaining-resets-coupon
Open

Show Grok usage-limit reset coupons#3188
Leshabeats wants to merge 1 commit into
steipete:mainfrom
Leshabeats:grok-remaining-resets-coupon

Conversation

@Leshabeats

Copy link
Copy Markdown

Summary

  • keep Grok weekly credits on the CLI-proxy path
  • fetch unused SuperGrok usage-limit reset tokens from grok.com's remaining-resets RPC
  • render them as a Limit Reset Credits detail row, and leave weekly usage intact if that extra call times out or returns nothing

Tests

  • CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter GrokRemainingResetsFetcherTests
  • CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter GrokMenuCardModelTests
  • CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter GrokCreditsProxyFetcherTests
  • swiftlint lint --strict on the Grok remaining-resets files

Why this was missing

/v1/billing?format=credits reports weekly SuperGrok usage only. grok.com's Использование panel reads unused reset coupons from a separate RPC:

POST https://grok.com/prod_mc_billing.ConsumerUiSvc/GetRemainingResets

That payload includes token_id and validity_end. CodexBar never called it, so an unused coupon such as Доступен сброс / Истекает 12 сент. stayed invisible even when weekly usage was 29%.

CodexBar does not redeem or modify reset tokens.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal priority bug or improvement with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown

Codex review: needs changes before merge. Reviewed August 25, 2026, 1:33 PM ET / 17:33 UTC.

ClawSweeper review

What this changes

This PR adds a best-effort Grok request for unused usage-limit reset coupons and displays them beside weekly usage.

Merge readiness

⚠️ Needs maintainer review before merge - 6 items remain

Keep open: the supplied UI proof is sufficient, but four prior P2 cache and account-refresh defects remain in the refreshed head.

Priority: P2
Reviewed head: 458390436194ec4d04c0a63512313d3366730860

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The real UI proof is useful, but four reproducible P2 refresh-state defects block merge.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (screenshot): The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
Patch quality 🦐 gold shrimp (3/6) 4 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (screenshot): The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
Evidence reviewed 6 items Non-200 responses clear the inventory: The new fetcher returns an empty successful inventory for every non-200 response, so a temporary authentication or server failure is indistinguishable from a confirmed empty coupon list.
Deferred update leaves stale detail data: The supplemental update replaces only live reset credits; it retains the cached Limit Reset Credits detail row that the presentation deliberately uses as a fallback.
Replacement refreshes do not join lookup: When a lookup is in flight, the cache returns cached tokens with no task; generation guarding then discards the older result, leaving the newer refresh unable to apply it.
Findings 4 actionable findings [P2] Retain cached coupons on non-200 responses
[P2] Remove cached detail rows after confirmed empty results
[P2] Share the in-flight lookup with replacement refreshes
Security None None.

Live Verification

Command: CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter GrokRemainingResetsFetcherTests

Result: FAIL (failed) — execution before step 1 run: sh -lc pnpm install --ignore-scripts --frozen-lockfile failed: ! Corepack is about to download https://registry.npmjs.org/pnpm/-/pnpm-11.24.0.tgz

sh -lc pnpm install --ignore-scripts --frozen-lockfile failed: ! Corepack is about to download https://registry.npmjs.org/pnpm/-/pnpm-11.24.0.tgz

Assertions:

  • FAIL expect_output: Test run with

How this fits together

CodexBar fetches Grok usage, publishes a primary snapshot to the menu and preferences views, and caches account-specific results. This change adds an optional authenticated coupon lookup whose result is applied later to the displayed snapshot.

flowchart LR
A[Grok credential or cookie] --> B[Weekly usage fetch]
B --> C[Publish primary usage]
B --> D[Optional coupon lookup]
D --> E[Supplemental snapshot update]
E --> F[Menu and preferences display]
Loading

Before merge

  • Retain cached coupons on non-200 responses (P2) - A 401, 429, or 5xx reaches this return [], which finishRefresh treats as a confirmed empty inventory. Throw or otherwise return the failure path so the existing cache is retained; only a successful empty response should clear it.
  • Remove cached detail rows after confirmed empty results (P2) - When a deferred lookup confirms no coupons, this only clears grokResetCredits; the old detail row remains and the presentation falls back to it. Replace or remove the matching row with the supplemental result so redeemed coupons disappear immediately.
  • Share the in-flight lookup with replacement refreshes (P2) - A replacement refresh while a lookup is in flight gets no supplemental task here. The original task is rejected by its stale generation, so the current snapshot never receives the completed inventory until another refresh; return a shareable task for the in-flight lookup.
  • Schedule supplemental updates for all token accounts (P2) - The scheduling call is only reached through applySelectedOutcome, while refreshTokenAccounts fetches and stores outcomes for every visible account. Nonselected Grok cards therefore never consume their deferred lookup; schedule and apply each successful account result to its own cached snapshot.
  • Resolve merge risk (P1) - Until the P2 fixes land, temporary Grok HTTP failures can erase cached coupons, while overlapping refreshes and nonselected accounts can leave coupon state missing or stale.
  • Resolve merge risk (P1) - The new authenticated Grok request should retain same-account, failure-safe cache behavior before merge.

Findings

  • [P2] Retain cached coupons on non-200 responses — Sources/CodexBarCore/Providers/Grok/GrokRemainingResetsFetcher.swift:337-338
  • [P2] Remove cached detail rows after confirmed empty results — Sources/CodexBar/UsageStore+SupplementalUsage.swift:41-42
  • [P2] Share the in-flight lookup with replacement refreshes — Sources/CodexBarCore/Providers/Grok/GrokRemainingResetsFetcher.swift:178-180
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Patch size 26 files, +1,611 / -96 The feature spans provider transport, shared refresh state, UI presentation, documentation, and tests.
Production versus test growth production +832, tests +765, docs/changelog +14 The large new asynchronous provider path needs edge-case regression coverage in addition to the happy-path proof.

Merge-risk options

Maintainer options:

  1. Repair supplemental refresh handling (recommended)
    Preserve cached coupons on failed responses, share in-flight work, and update every account snapshot with focused regressions before merging.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Repair all four P2 supplemental coupon refresh findings and add focused regressions for empty results, HTTP failures, overlapping refreshes, and nonselected token accounts.

Technical review

Best possible solution:

Share one in-flight lookup across refresh generations, treat only a successful empty response as authoritative, and apply its result to every affected account snapshot while removing obsolete detail rows.

Do we have a high-confidence way to reproduce the issue?

Yes—source-reproducible: seed a cached coupon, then return an empty result, a non-200 response, overlap two refreshes, or refresh multiple token accounts; each path has a direct state transition to inspect.

Is this the best way to solve the issue?

No. The best-effort design is appropriate, but the current cache and publication paths do not yet preserve correct coupon state across failures, refresh races, and stacked accounts.

Full review comments:

  • [P2] Retain cached coupons on non-200 responses — Sources/CodexBarCore/Providers/Grok/GrokRemainingResetsFetcher.swift:337-338
    A 401, 429, or 5xx reaches this return [], which finishRefresh treats as a confirmed empty inventory. Throw or otherwise return the failure path so the existing cache is retained; only a successful empty response should clear it.
    Confidence: 0.99
  • [P2] Remove cached detail rows after confirmed empty results — Sources/CodexBar/UsageStore+SupplementalUsage.swift:41-42
    When a deferred lookup confirms no coupons, this only clears grokResetCredits; the old detail row remains and the presentation falls back to it. Replace or remove the matching row with the supplemental result so redeemed coupons disappear immediately.
    Confidence: 0.98
  • [P2] Share the in-flight lookup with replacement refreshes — Sources/CodexBarCore/Providers/Grok/GrokRemainingResetsFetcher.swift:178-180
    A replacement refresh while a lookup is in flight gets no supplemental task here. The original task is rejected by its stale generation, so the current snapshot never receives the completed inventory until another refresh; return a shareable task for the in-flight lookup.
    Confidence: 0.98
  • [P2] Schedule supplemental updates for all token accounts — Sources/CodexBar/UsageStore+TokenAccounts.swift:1550-1555
    The scheduling call is only reached through applySelectedOutcome, while refreshTokenAccounts fetches and stores outcomes for every visible account. Nonselected Grok cards therefore never consume their deferred lookup; schedule and apply each successful account result to its own cached snapshot.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0a1aa53598c9.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
  • add proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (screenshot): The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
  • remove status: 📣 needs proof: Current PR status label is status: ⏳ waiting on author.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove merge-risk: 🚨 availability: Current PR review merge-risk labels are merge-risk: 🚨 auth-provider.

Label justifications:

  • P2: The remaining defects affect optional Grok usage details with a bounded but user-visible blast radius.
  • merge-risk: 🚨 auth-provider: The PR adds a bearer/cookie-authenticated Grok billing request and must preserve account-scoped, failure-safe behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (screenshot): The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. The contributor supplied a redacted packaged-app screenshot showing the new Limit Reset Credits row beside Grok usage; it directly demonstrates the user-visible result.

Evidence

Acceptance criteria:

  • [P1] CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter GrokRemainingResetsFetcherTests.
  • [P1] CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter GrokRemainingResetsRoutingTests.
  • [P1] CODEXBAR_SUPPRESS_TEST_KEYCHAIN_ACCESS=1 swift test --filter UsageStoreSupplementalUsageTests.
  • [P1] make check.

What I checked:

Likely related people:

  • olddonkey: Authored the recent main-branch Grok account-context repair on the affected provider path. (role: recent Grok provider contributor; confidence: high; commits: 0194d88de2d4; files: Sources/CodexBarCore/Providers/Grok/GrokProviderDescriptor.swift)
  • Zihao Qi: Authored the current-main reset-state repair touching the shared refresh and token-account surfaces adjacent to this asynchronous update. (role: recent refresh-state contributor; confidence: medium; commits: 0a1aa53598c9; files: Sources/CodexBar/UsageStore+Refresh.swift, Sources/CodexBar/UsageStore+TokenAccounts.swift)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Repair the four supplemental lookup and account-publication paths.
  • Add focused regressions for failed HTTP responses, confirmed empty inventories, replacement refreshes, and nonselected accounts.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-25T09:48:07.005Z sha dd39a4a :: needs real behavior proof before merge. :: [P2] Do not gate weekly usage on the coupon lookup

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dd39a4ac1d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

Comment thread Sources/CodexBarCore/Providers/Grok/GrokProviderDescriptor.swift Outdated
Comment thread Sources/CodexBarCore/Providers/Grok/GrokProviderDescriptor.swift Outdated
Comment thread Sources/CodexBarCore/Providers/Grok/GrokProviderDescriptor.swift Outdated
Weekly CLI-proxy credits omit SuperGrok reset tokens, so CodexBar never
rendered an unused coupon even when grok.com listed one. Fetch remaining
resets as a best-effort overlay and keep weekly usage if that call fails.
@Leshabeats
Leshabeats force-pushed the grok-remaining-resets-coupon branch from dd39a4a to 4583904 Compare August 25, 2026 16:46

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4583904361

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

let resetCredits: GrokRateLimitResetCreditsSnapshot? = switch update {
case let .grokResetCredits(snapshot): snapshot
}
let updated = current.withGrokResetCredits(resetCredits)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Clear stale detail rows after the deferred refresh

When a previous cache entry contains a coupon but the deferred request confirms that no coupons remain, this updates only grokResetCredits to nil and leaves the cached Limit Reset Credits row in details. The Grok presentation then falls back to that row, so a redeemed coupon continues to appear until another full provider refresh rebuilds the details; remove or replace the matching detail row when applying the supplemental result.

Useful? React with 👍 / 👎.

Comment on lines +337 to +339
guard response.statusCode == 200 else {
return []
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat non-200 coupon responses as refresh failures

When the optional endpoint temporarily returns 401, 429, or 5xx, returning [] makes finishRefresh treat the response as an authoritative empty inventory and overwrite any still-valid cached coupons. Other transport and gRPC failures return nil specifically to retain the cache, so non-200 responses should follow that failure path rather than being indistinguishable from a successful response containing zero coupons.

Useful? React with 👍 / 👎.

Comment on lines +1551 to +1555
self.scheduleSupplementalUsageUpdate(
provider: provider,
result: result,
generation: generation,
accountID: account?.id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply deferred coupons to every stacked account

With stacked Grok token accounts, refreshTokenAccounts fetches and publishes snapshots for every visible account, but only the selected result reaches this scheduling call. The supplemental tasks returned for all non-selected accounts are never consumed, so their cards omit coupons after a cold refresh and remain one refresh cycle behind; schedule each successful account result against its corresponding account snapshot rather than only the selected outcome.

Useful? React with 👍 / 👎.

Comment on lines +178 to +179
guard state.shouldRefresh else {
return GrokRemainingResetsLookupResult(tokens: state.tokens, snapshotTask: nil)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Let replacement refreshes join the in-flight coupon lookup

If another Grok refresh starts after the primary snapshot publishes but before its coupon request finishes, this branch returns the still-empty cache without a supplemental task. The older task's eventual update is rejected by the refresh-generation guard, while the newer snapshot has nothing waiting to apply the now-populated cache, so coupons remain absent until a third refresh; return a shareable handle to the in-flight lookup so the current generation can consume its result.

Useful? React with 👍 / 👎.

@Leshabeats

Copy link
Copy Markdown
Author

Addressed the review feedback in 45839043:

  • rebased onto current main; the PR now merges cleanly
  • decoupled GetRemainingResets from primary weekly usage publication; the coupon arrives as a stale-safe supplemental update
  • reused the exact credential/cookie that produced the usage snapshot, avoiding cross-account enrichment
  • gated both fetch and display on optional usage
  • rendered Grok through the same localized reset-credit block used by Codex

Live proof from the packaged debug app against a real Grok account (account data and tokens redacted):

Grok limit reset credit shown in CodexBar

The weekly card remains available immediately; the reset-credit block then shows 1 доступен with its expiry.

Validation: 47 affected tests across 7 suites pass, make check passes, and ./Scripts/package_app.sh debug builds successfully.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. P2 Normal priority bug or improvement with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant