Repository navigation
fix(gateway): aggregate usage cost across agents - #70205
luke-skywalker-open-claw wants to merge 2 commits into
Conversation
Greptile SummaryThis PR fixes The Confidence Score: 5/5Safe to merge; all remaining findings are minor style suggestions. No P0 or P1 issues found. The only inline comment is a P2 suggestion about deriving No files require special attention. Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/gateway/server-methods/usage.ts
Line: 427
Comment:
**`days` taken from first summary only**
`params.summaries[0]?.days` works correctly when all per-agent summaries are requested for the same time range (they always are), so they all carry the same `days` value. However, if the first summary ever has a different `days` field (e.g. due to a future per-agent range override), the merged result silently drops the other summaries' values. A small guard—or deriving `days` from the requested range directly—would make the intent explicit:
```suggestion
days: Math.ceil((params.endMs - params.startMs) / DAY_MS) + 1,
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(ui): preserve usage day labels" | Re-trigger Greptile |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7c302c13c6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
Ready for human review. The PR is up to date with main, CI is green, bot review threads have been addressed/resolved, screenshots are embedded in the description, and I ran local |
37fbef2 to
aaa0910
Compare
|
Latest head |
|
Codex review: needs changes before merge. Reviewed June 14, 2026, 1:07 AM ET / 05:07 UTC. Summary PR surface: Source +205, Tests +271, Docs +1. Total +477 across 7 files. Reproducibility: yes. for the remaining UI date-label bug from source: current main still uses UTC construction for Review metrics: 1 noteworthy metric.
Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Mantis proof suggestion Risk before merge
Maintainer options:
Copy recommended automerge instructionNext step before merge
Security Review findings
Review detailsBest possible solution: Rebase the useful pieces onto current main while preserving the explicit all-agent protocol and durable/background cache path. Do we have a high-confidence way to reproduce the issue? Yes for the remaining UI date-label bug from source: current main still uses UTC construction for Is this the best way to solve the issue? No as-is. The best fix is a current-main rebase that keeps the explicit all-agent scope and background cache behavior while carrying forward the UI date-label fix and focused tests. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 66880a5d736c. Label changesLabel changes:
Label justifications:
Evidence reviewedPR surface: Source +205, Tests +271, Docs +1. Total +477 across 7 files. View PR surface stats
Acceptance criteria:
What I checked:
Likely related people:
What the crustacean ranks mean
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. How this review workflow works
|
c613510 to
54314fa
Compare
…-cost-agents-clean # Conflicts: # CHANGELOG.md
|
Addressed the ClawSweeper changelog refresh finding in current head |
|
ClawSweeper PR egg 🔥 Warming up: real-behavior proof passed; findings, security review, or rank-up moves are still in progress. Hatch commandComment Hatchability rules:
What is this egg doing here?
|
|
This pull request has been automatically marked as stale due to inactivity. |
|
Clownfish 🐠 reef update Thanks for the useful work here. Clownfish could not update this branch directly, so the replacement PR is the writable swim lane for the same fix path. Replacement PR: #93022 fish notes: model gpt-5.5, reasoning xhigh; reviewed against 9cdf774. |
|
Clownfish 🐠 landed Thanks for the report and context here. This is superseded by #93022, which has landed as the canonical Clownfish fix path for this cluster. Closing this now that the validated fix is merged. If this still splashes on current main by a different path, reply here and we can reopen or split it back out. fish notes: model gpt-5.5, reasoning medium; reviewed against 4c2fef4. |
Summary
Describe the problem and fix in 2-5 bullets:
usage.costscanned only one default transcript directory when callers did not passagentId, whilesessions.usagealready discovered sessions across configured agents.usage.costagent scope from configured gateway agents, merge daily/totals across agents, include the resolved scope in the cache key, and preserve date-only daily labels in the Control UI.usage.jsonlstorage proposal from Feature Request: Per-model usage logging for cost tracking #13219 or a separate cost-unit normalization pass; it addresses the confirmed cross-agent aggregation/scope mismatch reported in [Bug]: Usage dashboard shows total cost as millions of dollars while daily chart sums to ~$10-15 #41986.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
usage.costaggregation direction with additional cache-scope, explicit-agent, UI date-label, and partial-failure coverage.Root Cause (if applicable)
For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write
N/A. If the cause is unclear, writeUnknown.usage.costcalledloadCostUsageSummarywithout an agent scope, which resolves through the single-agent/default transcript directory instead of the configured gateway agent set.sessions.usage, but not the siblingusage.costaggregate path, non-maindefault agent ids, or browser-visible daily usage rendering for date-only buckets.Regression Test Plan (if applicable)
For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write
N/A.src/gateway/server-methods/usage.sessions-usage.test.ts,src/gateway/server-methods/usage.test.ts, andui/src/ui/views/usage-metrics.node.test.tsusage.costwithoutagentIdcalls the cost summary loader once per configured agent and merges daily/totals; explicitagentIdremains scoped; configured default agents do not need to be namedmain; date-only daily buckets render with the same calendar day in the Control UI.usage.cost.User-visible / Behavior Changes
Multi-agent deployments should see
usage.costtotals and daily entries aggregated across configured agents when noagentIdis requested. ExplicitagentIdrequests remain scoped to that agent. The Control UI daily usage chart should no longer showNo datawhen cross-agent session usage exists, and date-only daily buckets no longer shift one day backward for users west of UTC.Diagram (if applicable)
For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write
N/A.Security Impact (required)
Yes, explain risk + mitigation:usage.costnow reads the same configured agent session scopes thatsessions.usagealready reads. ExplicitagentIdrequests are validated and remain scoped, and cache keys include the resolved agent scope.Repro + Verification
Environment
v25.9.0, pnpm10.33.0agents.list = [{ id: "ops", default: true }, { id: "opus" }]Steps
usage.costwithoutagentId.Expected
No data.Actual
Daily Usage/No datawhilesessions.usageshowed activity.Evidence
Attach at least one:
Trace/log summary:
18789:usage.costfor2026-04-22returneddaily: []and zero totals, whilesessions.usagefor the same range returned a populated daily aggregate.18790:usage.costfor2026-04-22returned a populated daily bucket with about117Mtokens and by-type breakdown.Daily Token Usage,Apr 22,April 22, 2026, and token-type breakdown rows instead ofNo data.Costtoggle before/after: the official gateway still showed the daily chart asNo data, while the PR gateway renderedDaily Cost,Apr 22,$111.24, andCOST BY TYPE.Screenshots:
Before, current official build showing the scrolled
Daily Usagesection withNo data:After, PR gateway
18790showing the scrolledDaily Token Usagesection populated forApr 22:Before, current official build with
Costselected still showing the daily chart asNo data:After, PR gateway
18790withCostselected showingDaily Costpopulated forApr 22:Prior Work / Credit
This PR supersedes #42063 by @stablegenius49 and carries forward its core direction: make
usage.costaggregate across configured gateway agents. The implementation here expands that work with explicitagentIdvalidation/scoping, agent-scoped cache keys, partial per-agent failure handling, non-mainagent coverage, UI date-label handling, and visual verification.Suggested maintainer landing credit, if squashing or direct-landing this PR:
(thanks @stablegenius49)orCo-authored-by: stablegenius49 <[email protected]>.Human Verification (required)
What you personally verified (not just CI), and how:
usage.costaggregate, explicitagentIdscoping, invalid/out-of-scope explicitagentIdrejection, cache behavior with agent-scoped cache keys, configured default agent not namedmain, first configured agent fallback, no-agent fallback tomain, discovered disk agents when no list constrains the gateway, Control UI daily token rendering, and Control UI daily cost rendering against a PR-branch gateway.America/Sao_Paulotimezone.Review Conversations
If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.
Compatibility / Migration
Risks and Mitigations
List only real risks for this PR. Add/remove entries as needed. If none, write
None.usage.costrequests.sessions.usage, andusage.costremains cached with the resolved agent scope included in the cache key.AI Assistance
pnpm install --frozen-lockfile,git diff --check origin/main...HEAD, targeted gateway usage/UI Vitest shards (pnpm test src/gateway/server-methods/usage.sessions-usage.test.ts src/gateway/server-methods/usage.test.ts src/gateway/server-methods/usage.cost-usage-cache.test.ts ui/src/ui/views/usage-metrics.node.test.ts ui/src/ui/controllers/usage.node.test.ts ui/src/ui/usage-helpers.node.test.ts test/official-channel-catalog.test.ts),pnpm check:changed,pnpm build, Chrome MCP visual smoke against a PR-branch gateway includingTokensandCostmodes, andcodex review --base origin/mainat refreshed headc613510233with no actionable findings. Current mergeable heade14c554f32was refreshed with a normal merge fromorigin/mainand revalidated withgit diff --check origin/main...HEAD, the focused usage/UI tests,pnpm check:changed, andpnpm build.agentIdscoping, and fixes date-only daily label rendering.codex review --base origin/mainwas run locally and reported no actionable findings.