Repository navigation
Add a Grok usage collector - #6485
scottjones wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Adds Grok usage, model breakdowns, subscription tier, and weekly credit limits to the model-usage panel.
Changes:
- Adds Grok transcript and billing scanners with tests.
- Integrates Grok into provider selection and synchronization.
- Adds Grok branding, configuration, and documentation.
Tip
If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.
Reviewed changes
Copilot reviewed 7 out of 9 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
test/shell.d/model-usage-grok-scanner-test.sh |
Tests Grok usage and credit scanning. |
shell/plugins/model-usage/scripts/grok_usage_scanner.py |
Scans transcripts, billing logs, and live credits. |
shell/plugins/model-usage/README.md |
Documents Grok behavior and configuration. |
shell/plugins/model-usage/providers/Grok.qml |
Implements the Grok provider. |
shell/plugins/model-usage/Panel.qml |
Adds Grok branding and icon fallback. |
shell/plugins/model-usage/manifest.json |
Enables Grok by default. |
shell/plugins/model-usage/Main.qml |
Integrates Grok into provider orchestration. |
shell/plugins/model-usage/assets/grok.svg |
Adds the dark-background Grok mark. |
shell/plugins/model-usage/assets/grok-light.svg |
Adds the light-background Grok mark. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Heads up: #6603 just landed on The Usage collection now lives in standalone collectors in The upside: adding an agent no longer touches the panel at all. Ship a collector that prints the record contract, optionally add an If you'd like to update this PR to the new structure, rebase on — Claude Fable 5, written on behalf of @dhh |
048fcb2 to
b1460f5
Compare
|
Reworked onto the new structure — thanks for the pointer to #6603. It's now one collector ( One thing worth flagging up front, because it looks like a bug otherwise: there is currently no weekly meter to draw. Grok 1.0.0 stopped reporting Verified on an Apple Silicon machine: the tab renders in a running shell on both dark and light themes, and Untested: an account with a non-zero prepaid balance or on-demand cap. Both are 0 on the identity this was built against, so that mapping is deliberately left out; the failure mode is a missing meter, not a wrong number. |
|
Verified on Omarchy 4.0.0 against a SuperGrok Heavy login. The collector printed a ready record (weekly meter + local token charts from This is the collector I’d take over #7200: current Grok sessions store billed tokens on |
|
I opened a narrow PR onto this branch: scottjones#1 It replaces only the limits transport with Grok's own ACP Why I targeted #6485 instead of opening another Basecamp PR:
So I did not open a competing Basecamp PR. This is a PR-to-PR patch for the author to take, alter, or decline. |
|
Independent confirmation of the billing endpoint, and one data point that may change the "no meter on 1.0.0" conclusion: I built an equivalent collector separately before finding this PR (not sending it — this one is ahead and has the tests), so the numbers below come from a different implementation hitting the same route.
// GET https://cli-chat-proxy.grok.com/v1/billing?format=credits
{
"creditUsagePercent": 32.0,
"period": "USAGE_PERIOD_TYPE_WEEKLY",
"products": [
{ "product": "GrokBuild", "usagePercent": 29.0 },
{ "product": "GrokChat", "usagePercent": 3.0 },
{ "product": "GrokImagine", "usagePercent": null }
],
"prepaid": 0, "onDemandCap": 0, "unified": true
}Present in 5/5 spot readings just now, and on every poll of a 15-minute timer running since ~18:00 UTC today. So it looks like a 1.0.x regression that has since been fixed, rather than xAI withdrawing the figure — worth re-checking on 1.0.5 before shipping with the meter omitted. Two other things I can confirm:
No help on your last checkbox, unfortunately: |
|
+1 on keeping this as the canonical Grok collector PR (won't open another). Confirmed on Grok 1.0.5: billed tokens are on Suggested add before merge: skip |
|
Pushed the ACP switch. Thanks @dghelm and @harrison-wallace — both findings held up here on The meter is back@harrison-wallace is right, and the caveat at the top of this PR was stale. I've corrected it. All three transports agree at 3% on the same account:
So 1.0.0 was a regression since fixed, not xAI withdrawing the figure. The collector needed no change to pick it up — only the notes were wrong. One correction to the body you posted, in case anyone builds on it. The real reply nests the config and wraps the money fields, and carries no {
"config": {
"creditUsagePercent": 3.0,
"currentPeriod": { "type": "USAGE_PERIOD_TYPE_WEEKLY", "start": "…", "end": "…" },
"prepaidBalance": { "val": 0 },
"onDemandCap": { "val": 0 },
"onDemandUsed": { "val": 0 },
"isUnifiedBillingUser": true
},
"subscription_tier": "SuperGrok"
}If your
@dghelm's patch is in, with one change
The change: I kept grok's log as the fallback rather than removing it. 19 assertions, and the fallback cases fail against the version without the fallback. @Loafer19 — on the subagent double-countI dug into this and it's more interesting than it first looks. There is no But tokens are not double-counted. Across 331 turns, no Session and prompt counts are inflated, though, and that part is worth fixing. Six spawns here, five with usage:
The session count is the real distortion. The fix isn't a field on the turn — it's collecting Happy to add that. Before I do: if you have a transcript where a |
|
Independently verified the current head (
All 19 focused collector assertions pass. Against a real signed-in Grok installation, the collector produced a valid ready record containing both local statistics and the current quota window. The quota information matched Grok’s own live billing response. I also fed the record into the stock Thanks! This works well for me. |
|
Verified the current head on Omarchy
Two checks against this machine's sessions, not the fixtures:
Today's row is 0 because nothing completed today. The last non-zero day in the 7-day window is yesterday. Token charts and the weekly meter both populated. |
cristianuibar
left a comment
There was a problem hiding this comment.
This is the Grok collector to merge. The other open Grok collector PRs are duplicates of this one.
Verified head c7e5d801 on Omarchy 4.0.0.r2153.g9c5482c-1 with Grok 1.0.34. Details are in the comment above. Short version for whoever lands it:
- Ship
bin/omarchy-agent-usage-grokas it is. The panel needs no QML change. A record in the usage directory is a tab. - Keep
updates.jsonlturn_completedas the ledger.usage.jsonis a sparse summary and would miss most sessions. Do not also sumusage.json. - Child sessions are separate
updates.jsonlfiles and do not shareprompt_ids with the parent, so they are counted once. No extra child-session pass is required. - The weekly meter is live on SuperGrok Heavy via
_x.ai/billing, with the log fallback when that call is empty. Prepaid and on-demand fields staying unmapped is correct.
No further code changes from this machine.
|
Automated duplication check: this pull request looks similar to #9498, which covers the same Grok usage collector. I keep that one open and close this one to consolidate review. If you feel this is the wrong decision, please open the PR again with a note on the difference. |
|
@bjarneo Curious why #9498 won the duplication check over #6485 — from outside it looks like the wrong survivor. They both add a Grok collector, but they aren’t the same scope:
Your close note says to open a new PR if the merge choice looks wrong. Before anyone does that: can #6485 be reopened and #9498 closed instead? Opening a third Grok collector PR would just make the duplication problem worse. |
|
Reopening after review: this PR is the stronger Grok collector (icons, ACP billing meter, review history, live verifications). It becomes the canonical PR for this group instead of #9498. |
|
The weekly meter is the right transport. One gap for people who spend the subscription through omp rather than the Grok CLI: those sessions never write omp (and pi) already record this on the same JSONL shape the Claude collector reads. Provider is This is still a collector change, not a plugin. The panel already draws any record in the usage directory. Patch against # omp and pi can spend the same xAI subscription without writing a Grok CLI
# transcript. Their JSONL sessions carry provider, model, and token usage on
# every assistant message — the same shape the Claude collector already reads.
XAI_PROVIDERS = {"xai", "xai-oauth", "grok"}
def agent_session_roots() -> list[Path]:
roots = [
Path.home() / ".omp" / "agent" / "sessions",
Path.home() / ".pi" / "agent" / "sessions",
]
extra = os.environ.get("OMP_AGENT_SESSIONS", "").strip()
if extra:
roots.append(Path(os.path.expanduser(extra)))
return roots
def omp_turn_models(message: dict[str, Any]) -> list[tuple[str, int, int, int, int]]:
usage = message.get("usage") or {}
if not isinstance(usage, dict):
return []
# totalTokens == input + output + cacheRead + cacheWrite on every omp
# record. reasoningTokens is already inside one of those buckets.
input_tokens = number(usage.get("input"))
output_tokens = number(usage.get("output"))
cache_read = number(usage.get("cacheRead"))
cache_write = number(usage.get("cacheWrite"))
if not (input_tokens or output_tokens or cache_read or cache_write):
total = number(usage.get("totalTokens"))
if total <= 0:
return []
input_tokens = total
return [(model_name(message.get("model")), input_tokens, output_tokens, cache_read, cache_write)]
def scan_agent_sessions(usage: SessionUsage) -> None:
for root in agent_session_roots():
if not root.is_dir():
continue
for path in sorted(root.rglob("*.jsonl")):
session_key = str(path)
try:
with path.open(errors="replace") as handle:
for line_number, raw in enumerate(handle, 1):
if '"usage"' not in raw or '"assistant"' not in raw:
continue
try:
entry = json.loads(raw)
except json.JSONDecodeError:
continue
message = entry.get("message") if isinstance(entry.get("message"), dict) else {}
if entry.get("type") != "message" or message.get("role") != "assistant":
continue
if str(message.get("provider") or "") not in XAI_PROVIDERS:
continue
turn_key = f"{path}:{entry.get('id') or line_number}"
if turn_key in usage.seen_turns:
continue
per_model = omp_turn_models(message)
if not per_model:
continue
usage.seen_turns.add(turn_key)
usage.add_turn(local_day(entry.get("timestamp")), session_key, per_model)
except OSError:
continue scan_sessions(usage)
scan_agent_sessions(usage)Exact provider match, same rule as the Claude collector: an Verified locally against grok 1.0.41 and omp sessions on |
omarchy-agent-usage-grok reads the session transcripts under ~/.grok/sessions into the shared record contract: one prompt per completed turn however many models answered it, and the cache figures subtracted from inputTokens so grok's folded totals do not count the same tokens twice. Grok publishes no supported way to read its weekly allowance, so the collector asks the billing endpoint the CLI itself calls, with the token grok has already cached, and falls back to the reading grok writes to its own log. A usable reading is a percentage belonging to an open period, and a closed week's number is the wrong week's, so the meter is omitted rather than guessed. Expect it to be omitted for now: grok 1.0.0 stopped reporting the figure. It answers with the current window and no percentage at all, from the endpoint and in the log alike, where 0.2.118 carried one in 100 of 102 readings on the same account. The meter returns on its own if xAI publishes the number again; until then the tab shows tokens only. The panel needs nothing: the record and the brand marks are enough for the tab. Prepaid balance and on-demand overage are untested (both 0 on the identity this was built against). The failure mode there is a missing meter, not a wrong number. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Grok answers `_x.ai/billing` over `grok agent stdio`, and that reply carries both the plan and the weekly percentage. Asking the CLI for it puts the provider back in charge of its own auth the way the Codex collector does, so this stops reading the token out of auth.json and stops calling cli-chat-proxy.grok.com directly. Verified against grok 1.0.5; the ACP call costs about 0.2s more than the HTTP one, against a 900s refresh. The log stays as the fallback rather than the source. `_x.ai/billing` is a vendor extension with no stability promise, and from here a method grok has renamed looks the same as a grok that is signed out — while the log fallback matches on a log message, which is the more brittle of the two. The plan and the meter are filled independently now, so an answer carrying one but not the other keeps what it gave. Also correct the notes: the percentage grok 1.0.0 stopped reporting came back in 1.0.5 and the meter lit up again on its own, so the section no longer says there is nothing to draw. Co-Authored-By: Daniel Helm <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The billing reply carries prepaidBalance, onDemandCap and onDemandUsed beside the percentage, so the reason the panel's balance ledger stays empty is worth writing down: every account this has been seen on reports 0, and the reply names no unit, so there is no way to tell credits from dollars from cents at zero. Guessing the scale would trade a missing balance for a wrong one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A subagent runs in a session directory of its own beside its parent's, and the scan counted each one as a session someone started, with prompts someone typed. On one machine that put totalSessions at 33 for 26 sessions actually opened. The parent names every child in a subagent_spawned record, so those sessions are now left out of the session and prompt totals. Their tokens still count: the parent never folds a child's usage into its own turns. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
c7e5d80 to
1ec3fc9
Compare
|
Thanks for the thorough work here, including tracking when |
Adds Grok to the agents panel the way #6603 asked: a collector, the brand marks, and nothing in the plugin. Tokens come from
~/.grok/sessions.The plan and the weekly allowance come from grok's own ACP
_x.ai/billingmethod, asked overgrok agent stdio. Grok owns that call, so the collector never readsauth.jsonand never talks to an xAI endpoint itself — the same boundary the Codex collector keeps. The reading grok writes to its own log stands in when the ACP call says nothing, since_x.ai/billingis a vendor extension and a renamed method looks the same from here as a signed-out CLI.A usable reading is a percentage that still belongs to an open period; otherwise the meter is omitted rather than guessed. That omission is not hypothetical — grok 1.0.0 stopped reporting
creditUsagePercententirely, where 0.2.118 had carried it in 100 of 102 readings on the same account. It came back in 1.0.5 and the meter lit up on its own, which is the behaviour to expect the next time the field moves.The meter and the token chart will not agree when both are present. Transcripts are mostly cache reads, and the allowance is billed per X identity, not per machine.
The same reply carries
prepaidBalance,onDemandCapandonDemandUsedas{"val": N}objects. None feed the panel's balance ledger: they read0on every account this has been seen on, and nothing names a unit, so credits, dollars and cents are indistinguishable at zero. Guessing the scale would trade a missing balance for a wrong one.Thanks to @dghelm for the ACP transport, @harrison-wallace for catching that the meter returned in 1.0.5, and @benwyrosdick and @Loafer19 for independent verification.
Test plan
test/shell.d/agent-usage-grok-scanner-test.sh— 20 assertions, including the ACP path, the log fallback, and both failing against a build without the fallbackbin/omarchy commands --checkand shebang-aware syntax sweepgrok 1.0.5 (5115b46bc9): ACP, the HTTP endpoint and the log all report the same metertotalSessionsortotalPrompts(children are read from the parent'ssubagent_spawnedrecords)