Repository navigation
fix(usage): Claude Code subscription usage missing for agents running on claude-cli - #157753
8bitsforge wants to merge 1 commit into
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: needs real behavior proof before merge. What this changesThis PR captures Claude Code subscription windows from local agent output and displays them separately from Anthropic credential usage. Example: A native Claude Code turn reports five-hour utilization of 0.56 and weekly utilization of 0.67.
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 6 items remain This PR addresses missing native Claude Code quota reporting that current main still lacks, but the rebased Models card loses its observation-age label and two new cache tests violate the repository’s no-polling rule. Priority: P2 Decision needed
Before merge
Findings
Tests
Agent review detailsHow this fits togetherClaude stream-json records enter the agent runner, which admits host-login observations into process-local memory and supplies quota snapshots to Gateway usage responses, chat status, and UI cards. flowchart LR
A[Claude Code output] --> B[Stream parser]
B --> C[Host login check]
C --> D[Observed quota store]
D --> E[Gateway usage cache]
E --> F[Usage and Models pages]
D --> G[Chat status]
Technical reviewBest possible solution: Keep native and Anthropic usage separate, show observation age in both UI renderers, and adopt an explicit observation contract. Do we have a high-confidence way to reproduce the issue? Current-main source discards quota events, and the contributor’s isolated Gateway trace demonstrates the missing-to-present usage row after a native Claude Code turn; no target code was executed during this review. Is this the best way to solve the issue? Observing the existing CLI stream preserves native credential ownership and supplies otherwise unavailable quota facts, but the Models renderer must consume the same freshness metadata as the Usage page. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 481813822c01. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +629, Tests +1207, Docs +30. Total +1866 across 33 files. Added test files: 4. View PR surface stats
Review metrics
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 (8 earlier review cycles)
Reviewed October 11, 2026, 12:03 PM ET / 16:03 UTC (Revision 9). |
127147d to
53f2ce2
Compare
fa18045 to
2036029
Compare
|
This pull request has been automatically marked as stale due to inactivity. |
2036029 to
afc713c
Compare
|
Refreshed onto current
|
|
Closing as superseded by #207543, which restores live on-demand Claude CLI quota usage (including native-only Claude CLI setups) while keeping token refresh ownership with Claude Code. |
Related: #143419, #156296
What Problem This Solves
Fixes: agents that run through Claude Code (
claude-cli) never show the subscription usage they actually consume.usage.statuseither has no Claude row or shows an error for a different Anthropic credential.User Impact
Usage now follows the route an agent runs on. When agents run through Claude Code under the Gateway host's own login,
usage.statusreports a separate Claude Code row with that subscription's 5-hour and weekly windows and reset times. The row reaches the Control UI Usage page, chat/status, and Gateway clients. The Anthropic row is unchanged: an API key still shows spend and cost, a setup-token still shows its own result or error, and nothing is substituted between the two.The row appears after the first Claude Code turn following a Gateway start. It carries when it was reported (
observedAt), shown asas of 12m agoin/statusandObserved 12m agoon the Control UI usage cards, so a reader can tell when it may be out of date.Why This Change Was Made
Anthropic has two billing surfaces, and OpenClaw can use both at once:
claude auth login): the 5-hour and weekly windows.OpenClaw currently reports both as one "Claude" row and only asks the Anthropic credential for usage. For the Claude Code route that cannot work:
scope requirement user:profile([Bug]: Claude setup-token profile is not able to get usage info #143419).b9b2f455, Claude Code runs never borrow a generic saved Anthropic credential. So whatever the Anthropic row reports can belong to a different account, or a different billing surface, than the one the agent is using.Claude Code already reports its own windows on every turn. Its stream-json output carries a
rate_limit_eventwhoserate_limit_info.unifiedWindowshasfive_hourandseven_dayutilization and reset times, and OpenClaw currently discards it. This change:Recording is limited to the Gateway host's own Claude login. It is skipped for:
ANTHROPIC_*variable counts except model selectors, OpenClaw's Admin API usage and API-key rotation keys, and Vertex project settings (inert withoutCLAUDE_CODE_USE_VERTEX, which counts). Claude Code tokens and switches such as Bedrock, Vertex, Foundry, Mantle, or a gateway count too; names are matched case-insensitively;--settingsor--managed-settingsbackend argument;CLAUDE_CONFIG_DIR.Each of those can be another account. A record that carries only some windows updates just those. The store clears with the model-auth status usage cache, which runs on any model-auth change.
Where the row shows.
/statusshows the Claude Code row only for a Claude Code session on the host login, and reads it from the in-memory store without a network request. Two checks must pass. First, the runner notes on every Claude Code turn whether the recording rule admitted it, using the turn's real environment, arguments, skills, and account; the session's latest turn must have been admitted. Second, the run's own account resolver (resolveCliExecutionAuthProfileId) is asked with the session's pin, the agent's configured@profile, and the session's Claude Code binding, so a profile chosen since that turn also excludes it. Every other session keeps the usage line it had before, and the Claude Code row never stands in for its provider.claude-cliprofile that later Claude Code runs pick up.Cache expiry. A cached usage summary no longer serves a window after that window's reset time. The usage cache refreshes at the earliest reset in the summary instead of waiting for the 60 s TTL, and stale serves drop windows that have reset. A summary cached before Claude Code first reported its windows is also refreshed on the next read, so the row does not wait out the TTL after a Gateway start. This applies to every provider's windows, since a window past its reset is stale regardless of source.
Placement. #129485 parsed the same record in core for turn-log diagnostics. It was closed because its target error was not an OpenClaw bug. This change uses the record for the documented usage surface. If maintainers prefer the Anthropic plugin to own the parser and row once #156296 moves Claude usage fetching there, both can move with it.
Known limits:
claude /loginswitch, is picked up on the next turn or when model auth changes. The row'sobservedAt(the oldest time among its windows) makes that visible instead of presenting the windows as current.models.authStatus). Matching a session to the Claude Code row there is a UI follow-up; this PR reports the row throughusage.status.openclaw status --usageprocess does not see Gateway memory.No config, schema, or storage changes. One additive, optional field:
ProviderUsageSnapshot.observedAt(epoch ms), set only on usage observed from runtime output rather than fetched.Evidence
Live proof on a head-built dist and an isolated Gateway (
OPENCLAW_STATE_DIRand port isolated). Config:anthropic/claude-haiku-4-5withagentRuntime: claude-cli, Claude Code 2.1.280 with its native subscription login, no Anthropic credential in OpenClaw.usage.statusreturned"providers": [].openclaw agentturn ran (cli turn: provider=claude-cli model=claude-haiku-4-5 …).usage.statusreturned:{ "provider": "claude-cli", "displayName": "Claude Code", "windows": [ { "label": "5h", "usedPercent": 56, "resetAt": 1790340000000 }, { "label": "Week", "usedPercent": 67, "resetAt": 1790784000000 } ] }56.00000000000001from0.56 * 100. The head rounds to two decimals, and a test covers it.Control UI proof (September 26). Same isolated setup for both: a fresh state directory, the Usage page opened first, one real
openclaw agentturn through Claude Code, then the Usage page again. Headless Chromium 1187, dark theme, 1280×900 at 2×. Nothing private is shown; the session is the throwawayccusage-proof.516b1f8c4a6, captured more than 60 s after the turn so the usage cache had expired: the page ends at Sessions. No provider section and no Claude Code row.127147da3e7, captured on the first page load after the turn: the Claude Code card with its 5-hour and weekly windows, reset times, andObserved just now. The page had been opened before the turn, so this load also exercises the first-observation cache refresh below.516b1f8c4a6)127147da3e7)Models page proof (same isolated setup, one real Claude Code turn, Settings → Models). Before, the Anthropic card said "Not configured" yet showed Claude Code's windows as its own. After, Claude Code has its own usage-only card, and the Anthropic card reports its own (empty) usage with its usual actions.
127147da3e7)fa180453a67)Live
/statuson the same Gateway and session after the turn (sent throughchat.send):Wire shape (Claude Code 2.1.280, identifiers removed), used as the parser fixture:
{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1790305200,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"out_of_credits","isUsingOverage":false,"unifiedWindows":{"five_hour":{"utilization":0.03,"resetsAt":1790305200},"seven_day":{"utilization":0.48,"resetsAt":1790784000}}}}Tests:
Infinityor leave the Date range are dropped, malformed sibling windows, events withoutunifiedWindows.executePreparedCliRunwith a Claude stream on stdout): records under the host login, not under an OpenClaw-selected profile or a configured backend credential override. The recording rule also rejects other backends, paired nodes, account and endpoint variables (including lowercase spellings), settings arguments, and a different or skill-providedCLAUDE_CONFIG_DIR. It keeps recording for model selectors, OpenClaw's own Admin and key-rotation variables, and feature switches./status(buildStatusText): a host-login Claude Code session showsUsage: 5h 80% leftfrom the store with no usage request; a session whose latest turn the runner kept off the host login (for example, a backend credential) does not show the row; a session whose run uses a stored Claude token profile shows the Anthropic row instead; a session whose agent model pins an API-key@profiledoes not show the Claude Code row. The runner test also checks the per-session verdict it notes. The selection helper passes the session pin, the configured@profile, and the Claude Code binding to the run's resolver. The/statustests fail without their fixes.observedAt, no recording of windows without a reset time or with one beyond the longest quota period (8 days), clear./statussummary and the usage report label observed rowsas of ….Observed 12m agowith the exact time on hover; a fetched row shows no age line.Test cost (
pnpm test <file> --maxWorkers=1, vitest-reported, cold transform included):provider-usage.observed.test.tscli-runner/observed-usage.test.tscli-output-records.test.tscli-output-stream.test.tsprovider-usage.load.test.tsusage.status-cache.test.tscommands-status-claude-code-usage.test.ts/status; the four cases take ≈6 s. A new sibling file becausecommands-status.test.tsis at its line capstatus-usage-entry.test.tsNo sleeps or process boots.
Rebase (September 26): rebased onto main
5be36d37cb7as53f2ce20d0b. The only conflict was the upstream rewrite of the provider filter inprovider-usage.load.ts(#158210); the Claude Code row block is unchanged and now precedes the new filter.git range-diffshows no other content change, so the proof above (captured on127147da3e7) applies to this head. The focused suites were re-run on the rebased head: 161 tests passed.September 26,
2036029ad1d: rebased onto maine518bd7310c(263 commits, no conflicts;git range-diffshows the earlier commits unchanged). The last three commits address ClawSweeper Revisions 6 and 7 and two rounds of our own adversarial review (responses below). All 20 test files the PR touches, plus the session-override suites the refactor reaches, pass: 382 tests.pnpm buildpassed. The live proofs above were captured onfa180453a67; the only change since is the/statussession check below, which a host-login turn satisfies.Checks:
node scripts/check-changed.mjspassed (format, lint, core and core-test typecheck, UI typecheck, boundaries, line-cap ratchet, dead-export scan).pnpm ui:i18n:baselinereports no raw-copy drift. The Control UI usage and model-provider page suites pass (544 jsdom tests).Review responses (ClawSweeper, September 25)
Review responses (ClawSweeper, second review)
resetsAtafter the millisecond conversion. Fixed. The parser keeps a reset time only whenresetsAt * 1000is finite and within the Date range. The store also refuses a reset time more than 8 days after the observation (the longest subscription window is 7 days), so a finite but far-future value cannot pin a window either. Tests cover both.observedAt, the time its windows were reported, and/statusshows it asas of …. Aclaude auth loginswitch still shows the previous login's windows until Claude Code's next turn, but the row no longer presents them as current. Docs say so.Review responses (ClawSweeper, third review)
ui/src/components/provider-usage.ts), used by the Usage page and both Models settings surfaces, now rendersObserved <relative time>under the windows whenever a snapshot carriesobservedAt, with the exact timestamp as a tooltip. Fetched snapshots are unchanged. A new English stringusage.providerUsage.observedgoes through the standard locale workflow. Covered by a card test for both states.Review responses (ClawSweeper, fourth review)
127147da3e7. The observed store keeps a window-set version that changes only when a provider gains a window it did not have. Each cached usage summary records the version it was loaded against, read before the load starts, and a mismatch makes it stale. The next read refreshes as with an expired entry, and the Claude Code row appears as soon as that refresh finishes instead of after the 60 s TTL. Newer readings of windows already shown keep the normal cadence, so a busy agent does not re-query every usage provider after each turn. Covered by ausage.statuscache test for the sequence "empty summary → first observation → row", which fails without the fix, and by a store test for when the version changes.Review responses (ClawSweeper Revision 6, plus our own review)
3a469d30f3b. Recording now fails closed: anyANTHROPIC_*variable in the child environment disables it except model selectors, OpenClaw's Admin API usage and API-key rotation keys, and Vertex project settings. Claude Code's own tokens, auth endpoints, and provider switches (checked against the Claude Code 2.1.280 binary) disable it too, matched case-insensitively. A runner-level test covers a configured backendenvthat re-addsANTHROPIC_OAUTH_TOKEN./statusonly loaded usage for OAuth/token auth labels, so a host-login session (native (claude-cli)) never showed the row. It judged the account by the session pin alone. It now uses the run's own resolver, including the agent's configured@profile.CLAUDE_CONFIG_DIRpassed the config-directory comparison. Recording now fails closed on it.Review responses (ClawSweeper Revision 7)
/statuscannot see a session's backend environment, settings arguments, config directory, or skill environment, so it no longer guesses. The runner already evaluates the recording rule on every Claude Code turn from the turn's real environment and arguments. It now also notes that verdict per session, and/statusshows the host login's windows only when the session's latest Claude Code turn was admitted and the run's account resolver still selects no profile. A session with a backend credential override is therefore never shown the host's quota. The notes are process-local, bounded, and cleared with the observed windows./status, helper, store, and runner tests cover it; the/statusand helper tests fail without the fix.raw.githubusercontent.comURLs on this fork'spr-157753-proofbranch and return200 image/png; the review's media manifest could not fetch them.