Repository navigation
fix(grok): restore weekly Credits window on a zero-usage week - #4679
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis PR restores missing Grok weekly usage through the existing bounded bearer enrichment while retaining prepaid balances. Example: ACP reports an active weekly period and $1.23 prepaid balance without a usage percentage, while grok.com validates zero usage.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness✅ Ready for maintainer review Keep open for landing: this PR repairs a current Grok regression, preserves wallet-only billing, and has relevant shipped-CLI proof with passing checks; no blocking defects were found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Grok status probe reads ACP billing and local credentials, optionally enriches unknown usage through grok.com, and converts the result into usage windows and prepaid balance for app and CLI consumers. flowchart TD
A[Grok ACP billing] --> B[Grok status probe]
C[Captured Grok credentials] --> B
B --> D[Bounded unknown usage resolver]
D --> E[Grok bearer billing endpoint]
E --> D
D --> F[Usage snapshot]
F --> G[App and CLI output]
Technical reviewBest possible solution: Land the focused ACP enrichment repair with the existing validation, timeout, cancellation, and wallet-preservation contracts intact. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the wallet-only short circuit, and the contributor's shipped-CLI proof demonstrates the missing window when the enrichment wiring is removed; this review executed no target code. Is this the best way to solve the issue? Reusing the existing resolver addresses the missing ACP integration without inferring zero from absent JSON fields or discarding useful prepaid billing. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 489aad74fbd5. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 21, 2026, 2:26 AM ET / 06:26 UTC (Revision 2). |
The ACP `_x.ai/billing` credits payload can describe an active weekly period and a prepaid balance while omitting `creditUsagePercent` right after a period rollover. `GrokRPCClient.fetchBilling()` accepted that wallet-only snapshot, so `GrokStatusProbe.fetch()` treated billing as successful and the auto pipeline never reached the steipete#3261 web fallback; `toUsageSnapshot()` then had no primary window for the rest of the week. Reuse the existing bounded, same-account usage enrichment for ACP credits whose percentage is unknown: ask the grok.com bearer surface with the same auth-file token under the six-second budget and adopt only a wire-published percentage or a parser-validated implicit zero for an active period. The ACP period, plan, and prepaid balance stay authoritative, a failed or slow enrichment keeps the already-valid wallet-only billing, and missing or expired tokens never reach the network. Adds synthetic ACP regression coverage for the zero-usage week, enrichment unknown/failure/cancellation/timeout paths, credential guards, published-percent no-retry behavior, and unknown-usage preservation. Updates docs/grok.md and the 0.79.1 changelog. Refs steipete#4674
`CredentialsMode` is a parameter of an internal `@Test(arguments:)` entry point, so declaring the nested enum private fails the macOS test-target compile: "method must be declared private because its parameter uses a private type". Nesting it in the internal suite already keeps it test-target-local. Refs steipete#4674
270f614 to
a7b3d12
Compare
Fork-only proof harness: mirrors the macOS `GrokACPUnknownUsageTests` into the Linux test target (the same synthetic ACP fixture and probe paths are platform-independent) and adds a GitHub-hosted Ubuntu workflow that 1. runs the focused regression on the fixed tree (expected green), then 2. applies a patch removing only the `GrokStatusProbe.fetch()` ACP enrichment wiring and reruns the same focused regression (expected red). The workflow logs label each phase explicitly. This branch/workflow is proof material for steipete#4679 and must not be merged upstream. Refs steipete#4674
|
@clawsweeper re-review — PR body now has a Behavior proof section: (1) fork-run bash Linux Proof B: shipped entry point |
|
🦞👀 Re-review progress:
|
Use the existing quota enrichment path for wallet-only ACP replies, preserving validated zero usage and the ACP billing period without adding another fetch hook. Keep the end-to-end synthetic ACP regression and remove duplicate result assembly. Fixes steipete#4674 Co-authored-by: Zhongyue Lin <101193087+LeoLin990405@users.noreply.github.com>
# Conflicts: # CHANGELOG.md
|
Merged in ad0c567, thanks @LeoLin990405! A zero-usage week keeps Grok's weekly Credits window again. We routed ACP credits through the existing bounded enrichment resolver instead of a new path, so production code didn't grow, and kept a trimmed version of your tests. It will ship in the next release. |
Summary
On a zero-usage week, the ACP
_x.ai/billingcredits payload describes an active weekly period + prepaid balance but omitscreditUsagePercent(proto3 zero scalars). Since 0.78.0's ACP billing support (#4595),GrokRPCClient.fetchBilling()accepts that snapshot because the prepaid balance is non-nil,GrokStatusProbe.fetch()marks billing as successful, and the Auto pipeline never reaches the web fallback that #3261/#3325 added for this exact shape.usage.primaryis then missing for the whole first part of every weekly period (source: grok-cli, onlyproviderCostremains) — reported in #4674 against 0.79.0, working on 0.77.0.This PR applies the existing bounded, same-account usage enrichment to ACP credits whose percentage is unknown, while keeping the prepaid balance and leaving usage unknown when the retry cannot validate a percent.
Fixes #4674.
Root cause
GrokRPCClient.fetchBilling()accepts credits whencredits.usedPercent != nil || credits.prepaidBalanceUSD != nil; a zero-usage-week payload passes on the prepaid balance alone.GrokStatusProbe.fetch()setshasBilling = truefor that snapshot, soGrokCLIFetchStrategyreturnssource: grok-cliand the Auto pipeline ends beforeGrokWebFetchStrategy.GrokUsageSnapshot.toUsageSnapshot()only createsprimaryfrombilling.monthlyUsedPercentorwebBilling.usedPercent, so the wallet-only answer produces no rate window at all.GrokOAuthFetchStrategy.resolvingUnknownUsage(six-secondBoundedTaskJoinbudget, grok.com bearer retry, strict wire-published/implicit-zero validation). ACP was simply not wired into it.Fix
GrokStatusProbegains an injectableenrichUnknownCreditsseam plus a staticenrichingUnknownCredits(_:credentials:budget:grpcBilling:)helper that reusesGrokOAuthFetchStrategy.resolvingUnknownUsagewith the existing six-second budget and validation rules.fetch()enriches ACP credits only whenusedPercent == nil, before computinghasBilling. Enrichment is best-effort:CancellationError/URLError.cancelledpropagate exactly like the existing enrichment path, while any other failure keeps the already-valid wallet-only billing.usedPercent == niland a non-expired~/.grok/auth.jsoncredential exists, so missing/expired tokens never reach the network.completing(with:): the merged snapshot keeps the ACP reset, window duration, and prepaid USD; only the percent comes from grok.com, and only if the strict validation accepts it. Thegrok-clisource label and the identity-only team path are unchanged.Tests
New
Tests/CodexBarTests/GrokACPUnknownUsageTests.swift, using a syntheticgrokJSON-RPC fixture and dates relative toDate()(weekly period: startnow-3d, endnow+4d, so the bar cannot rot):usage.primary.usedPercent == 0,windowMinutes == 10080,resetsAtat the ACP period end,providerCost.balance == 1.23,sourcepipeline unchanged.grpcBilling(no network), wallet retained.Commands run
Local environment has Command Line Tools Swift 5.10 only (no Swift 6.2 toolchain, no Xcode), so the SwiftPM test target cannot be built here; PR CI is the test gate.
git diff --check✅.build/lint-tools/bin/swiftformat Sources/CodexBarCore/Providers/Grok/GrokStatusProbe.swift Tests/CodexBarTests/GrokACPUnknownUsageTests.swift --lint✅ (pinned 0.63.0)swiftc -parse Sources/CodexBarCore/Providers/Grok/GrokStatusProbe.swift✅; test file parsed via a sanitized copy (the 5.10 frontend predates Swift 6.2 backticked test names, which existing Grok suites already use) ✅node Scripts/check-app-locales.mjs✅node Scripts/check-documentation-links.mjs✅swift test --filter 'GrokACPUnknownUsageTests|GrokFailedBillingWorkTests|GrokZeroUsageTests|GrokCreditsProxyFetcherTests'Known residual behavior
grok-clisource label; the CLI-proxy path is unchanged.Behavior proof (failing-before-fix → passing-after, through the shipped CLI)
Fork-owned GitHub Actions run on Ubuntu (forks cannot use this repo's
xcode-27runner, so the CLI-level proof runs on Linux; the macOS shipped suite is the PR CI lane below). Production tree is identical to this PR's heada7b3d1298; only a Linux mirror of the regression suite + proof workflow were added on the fork branch.CodexBarCLI, serves a syntheticgrok agent stdiofixture answering_x.ai/billingwith the zero-usage-week ACP payload (active weekly period,prepaidBalance.val=123, nocreditUsagePercent), and a local TLS stub for the grok.com gRPC-web billing endpoint returning the validated active-period implicit-zero frame. No real network, accounts, or credentials are involved.After fix — shipped CLI restores the weekly window and keeps the wallet:
CodexBarCLI usage --provider grok --source cli --format json→"source":"grok-cli","rateWindowLabels":{"primary":"Weekly"},usage.primary = {"usedPercent":0,"windowMinutes":10080,"resetsAt":"<active period end>"},providerCost.balance = 1.23.After fix — wallet retained, usage unknown when enrichment is unavailable:
With the stub stopped:
usage.primary = null,providerCost.balance = 1.23,source = grok-cli— the wallet-only ACP answer is still a successful result.Before fix — same CLI, same stub, fix wiring reverted (only the 6-line enrichment call removed):
usage.primary = null,providerCost.balance = 1.23,source = grok-cli; focused regression also fails on that tree:✘ Expectation failed: (snapshot.webBilling?.usedPercent → nil) == (0 → 0.0)✘ Test run with 11 tests in 1 suite failed after 0.075 seconds with 4 issues.So the regression test fails without the wiring and passes with it, and the user-visible symptom (
usage.primarymissing on a zero-usage week) is reproduced and fixed through the shippedCodexBarCLI usageentry point, with prepaid balance preserved in both states.