Skip to content

fix(grok): preserve billing semantics in nonempty requests - #3336

Open
CharlieLZ wants to merge 6 commits into
steipete:mainfrom
CharlieLZ:fix/grok-billing-rpc
Open

fix(grok): preserve billing semantics in nonempty requests#3336
CharlieLZ wants to merge 6 commits into
steipete:mainfrom
CharlieLZ:fix/grok-billing-rpc

Conversation

@CharlieLZ

@CharlieLZ CharlieLZ commented Sep 1, 2026

Copy link
Copy Markdown

Summary

Addresses the reported grpc-status 13 / Missing request message. rejection by sending a nonempty GetGrokCreditsConfigRequest, while preserving the default billing semantics.

The current official Grok descriptor defines request field 1 as bool exclude_legacy_monthly_usage, not a weekly-period enum. The web client requests {}. This patch explicitly encodes false (00 00 00 00 02 08 00) so the message is nonempty without excluding legacy monthly usage. Decoding with protoc confirms empty and 0800 both mean false, whereas the original 0802 means true.

The maintainer repair also restores the 15-second timeout and the displaced @Test. Response parsing is unchanged from main. The captured frame's nonzero timestamp nanoseconds are not usage limits, so its inferred zero must not replace an unknown proxy percentage. The fixture now covers that boundary through the real parser, proxy enrichment, and usage snapshot; explicit wire zero/nonzero percentages still work.

The later unified-billing 0/0 inference has also been removed. Its fixtures remain as regression coverage: absent subscription usage stays unknown, and real fallback usage can enrich it without changing the authoritative reset date. Zero on-demand spending does not establish zero subscription usage.

Thanks @CharlieLZ for the report, original request change, and captured regression fixture.

Protocol evidence

Public assets checked September 1, 2026 UTC; downloaded JavaScript was inspected, not executed.

Verification and merge gate

  • The corrected regression tests fail on the submitted implementation: false-zero adoption, request bytes, and lost timeouts are detected.
  • Focused billing/proxy tests pass on 10cefdc9c4cbf470ce882d27ef3cc2432b450b69: 81 tests across two suites, with stubbed HTTP and synthetic credentials. The same compiler was used through SwiftPM's native backend after Xcode's SDK stat-cache tool stalled before compilation.
  • Independent Codex autoreview is clean at its configured P0 threshold; maintainer review also checked the request schema, fallback ownership, and lower-severity regressions.
  • make check passes with zero lint violations across 2,079 Swift files.
  • Current-head CI passes all eight jobs on 10cefdc9c4cbf470ce882d27ef3cc2432b450b69, including both macOS test shards and all three Linux builds.
  • The earlier full local repository run stopped on a 600-second StatusMenuTests timeout, after two timing-sensitive failures recovered on retry. It is not a green full-suite result. The independently diagnosed Sakana cancellation-test race is addressed separately in #3344.

Leave unmerged until the corrected 0800 request is confirmed against the affected account. No authenticated provider probe, real cookie import, Keychain access, or installed-app relaunch was performed for this repair. The original reported 0% result was produced by the discarded parser heuristic and is not proof of published usage or of this corrected request's live recovery. Unknown percentages intentionally remain unknown.

…usage

grok.com's billing API now rejects the empty GetGrokCreditsConfig request
(grpc-status 13, "Missing request message."), so the Grok usage fetch always
failed and the card never showed a percentage. Send the request with
usage_period_type: WEEKLY explicitly.

SuperGrok Heavy weekly-limit frames carry a per-period limit but no used
amount, so the previous parse rule classified them as unknown usage and the
adoption guard rejected the value as fabricated 0%. A limit-declared period is
a fully determined zero-usage response on the wire, so publish it as 0% and
let the web billing candidate fill the usage bar.
@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-01T01:27:23.927391Z fb12ee7 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added 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. 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. labels Sep 1, 2026

@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: fb12ee75e4

ℹ️ 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 on lines +322 to +324
let hasDefinedPeriodLimit = scan.varintFields.contains { field in
(field.path == [1, 4, 2] || field.path == [1, 5, 2])
&& field.value > 0 && field.value < 1_000_000_000_000

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Stop treating timestamp nanoseconds as a usage limit

For any period-only response whose start or end has a nonzero fractional second, this condition mistakes the Timestamp.nanos value for a billing limit: the same parser already treats [1,5,1] as the reset's epoch seconds, and the new fixture's [1,5,2] is 56,343,000, the corresponding nanoseconds field. Such a response is therefore marked as having a wire-published 0%, allowing resolvingUnknownUsage to replace genuinely unknown proxy usage with a fabricated zero; use an actual limit/usage field rather than the second member of these timestamp messages.

Useful? React with 👍 / 👎.

request.httpMethod = "POST"
request.timeoutInterval = Self.requestTimeoutSeconds
request.httpBody = Data([0x00, 0x00, 0x00, 0x00, 0x00])
request.httpBody = Self.weeklyCreditsConfigRequest

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 Restore the explicit billing request timeout

When the grok.com request stalls in a direct cookie/bearer gRPC path or after the proxy fails, replacing these assignments also removes request.timeoutInterval = Self.requestTimeoutSeconds; the request now inherits the transport default instead of the intended 15 seconds. This also makes the existing request.timeoutInterval == 15 assertion fail and leaves requestTimeoutSeconds unused, so retain the timeout assignment alongside the new body.

Useful? React with 👍 / 👎.

}

@Test
func `parses live weekly limit billing response as zero percent`() throws {

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 Re-add the annotation to the displaced parser test

Inserting this method immediately after the existing @Test causes that annotation to attach to the new fixture test, leaving the following parses omitted zero percent with current billing period method unannotated. Swift Testing therefore no longer discovers or executes that existing regression test; add a separate @Test before the displaced method.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed September 1, 2026, 1:29 AM ET / 05:29 UTC.

ClawSweeper review

What this changes

This PR sends Grok’s billing fallback a nonempty protobuf request that explicitly preserves legacy monthly-usage semantics, with regression tests for request bytes and unknown usage enrichment.

Merge readiness

Blocked until real behavior proof from a real setup is added - 3 items remain

The implementation is focused and resolves all previously raised code defects, but the intended Grok endpoint recovery remains unproven on an affected account. Keep this PR open for real post-change behavior proof before merge.

Priority: P2
Reviewed head: 10cefdc9c4cbf470ce882d27ef3cc2432b450b69

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is narrow and well-covered by fixtures, but the claimed external endpoint recovery still needs real behavior proof.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The changed production owner is the Grok billing request builder; URLProtocol fixtures exercise the new bytes and synthetic parser/enrichment outcomes, but no affected-account request demonstrates post-fix recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The changed production owner is the Grok billing request builder; URLProtocol fixtures exercise the new bytes and synthetic parser/enrichment outcomes, but no affected-account request demonstrates post-fix recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Introduced request change: The fallback request retains the established 15-second timeout and replaces only the empty frame with a seven-byte gRPC-web frame carrying protobuf field 1 set to false.
Unknown-usage safety remains intact: A fallback snapshot is adopted only when it contains a wire-published percentage; otherwise the valid proxy result is retained.
Regression coverage: The added fixtures verify that fractional timestamp fields do not become published usage and that explicit wire percentages may enrich an unknown proxy value.
Findings None None.
Security None None.

How this fits together

CodexBar’s Grok provider combines a CLI proxy result with a best-effort grok.com billing fallback to produce usage, reset, and plan data for the menu bar. This change alters the fallback request bytes before its parsed result can enrich an otherwise unknown proxy usage value.

flowchart LR
    A[Grok credentials] --> B[Usage fetch strategy]
    B --> C[CLI proxy billing]
    B --> D[grok.com billing fallback]
    D --> E[Protobuf response parser]
    C --> F[Usage enrichment]
    E --> F
    F --> G[Menu bar usage display]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The changed production owner is the Grok billing request builder; URLProtocol fixtures exercise the new bytes and synthetic parser/enrichment outcomes, but no affected-account request demonstrates post-fix recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P2) - Until an affected account confirms the external Grok endpoint accepts the explicit-false frame, merging could leave the best-effort billing fallback unavailable for the reported setup.
  • Complete next step (P2) - The outstanding requirement is contributor-side affected-account proof rather than a mechanical repair suitable for an automated fix lane.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Code and test delta production +5/-1, tests +139/-1, docs +17/-3 The production behavior change is narrow; most of the patch is targeted regression coverage and protocol documentation.

Merge-risk options

Maintainer options:

  1. Add affected-account recovery proof (recommended)
    Capture a redacted request/response trace showing that the corrected billing call succeeds for the reported account before merging.

Technical review

Best possible solution:

Merge after a redacted affected-account trace shows the corrected request receives a successful billing response while unknown proxy usage remains unknown when no wire percentage is returned.

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

No: source and stubs establish the changed request and fallback behavior, but the supplied evidence lacks a real affected-account request and observed post-change response.

Is this the best way to solve the issue?

Yes, conditionally: explicit proto3 false is the narrowest semantics-preserving way to make the request nonempty, provided an affected-account trace confirms the endpoint accepts it.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The affected best-effort Grok billing path can leave usage unavailable, but the core app and proxy fallback remain usable.
  • merge-risk: 🚨 availability: The new external protocol frame is not yet confirmed to restore the reported billing response on a real affected account.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The changed production owner is the Grok billing request builder; URLProtocol fixtures exercise the new bytes and synthetic parser/enrichment outcomes, but no affected-account request demonstrates post-fix recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • olddonkey: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Add a redacted terminal trace or runtime log from the affected account showing the nonempty request receives a successful billing response, then update the PR body for re-review.

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 (6 earlier review cycles)
  • reviewed 2026-09-01T01:31:52.624Z sha fb12ee7 :: found issues before merge. :: [P1] Do not treat timestamp nanoseconds as a usage limit | [P2] Restore the explicit billing request timeout | [P2] Re-add the test annotation to the displaced parser test
  • reviewed 2026-09-01T02:27:42.506Z sha 39fe529 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-01T02:43:24.677Z sha 93e50b9 :: needs real behavior proof before merge. :: [P1] Keep zero-cap proxy values unknown
  • reviewed 2026-09-01T04:23:42.231Z sha ced9e52 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-01T04:43:25.735Z sha 10cefdc :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-01T04:57:07.050Z sha 10cefdc :: needs real behavior proof before merge. :: none

Use the verified exclude_legacy_monthly_usage boolean default instead of treating it as a weekly selector. Keep inferred usage out of proxy enrichment, retain the timeout, and restore parser regression coverage. Live endpoint recovery remains to be confirmed.

Co-authored-by: charlielz <1540060247@qq.com>
@steipete steipete changed the title fix(grok): restore Grok billing usage after weekly-period API change fix(grok): preserve billing semantics in nonempty requests Sep 1, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient Contributor real behavior proof is sufficient. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 1, 2026
CharlieLZ and others added 4 commits September 1, 2026 10:38
…hed 0%

A unified-billing account with onDemandCap 0 / onDemandUsed 0 has no credit usage
at all; the grok.com Usage page shows 0% used for the weekly period. The proxy
omits creditUsagePercent entirely for this shape, so the fetch pipeline reported
unknown usage and the Grok menu card showed the unavailable-usage diagnostic.
Treat the 0/0 unified-billing payload as a wire-published zero, keeping the
legacy period-only unknown-usage semantics for everything else.
Zero on-demand credits do not establish included subscription usage. Preserve the existing unknown-usage enrichment path and retain the new proxy fixtures as negative regression coverage.

Co-authored-by: charlielz <1540060247@qq.com>
Match the expected reset with the fractional timestamp in the captured proxy payload.
Assert the observable fallback contract instead of the provenance flag, which is not meaningful for a missing percentage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants