agent: Accumulate and persist cumulative token usage for threads (#58378)

`Thread::cumulative_token_usage` has been dead code since the agent2
rewrite: the field was added as a persistence placeholder in #36483 with
`#[allow(unused)]`, and the accumulation logic was deleted along with
agent1 in #40495. Since then, every saved thread persists
`cumulative_token_usage` as `{}` in `threads.db`, breaking offline
token-usage analysis and silently degrading eval reporting (`eval_cli`
prefers this value and was always falling back to the last request's
snapshot, undercounting multi-step turns).

This PR restores the accumulation, mirroring the original agent1
implementation:

- Providers emit multiple cumulative-per-request `UsageUpdate` snapshots
during a single request, so naive `+=` would double-count. We track the
previous snapshot for the in-flight request
(`current_request_token_usage`) and accumulate only the delta, resetting
the tracker each time a new completion request is built in
`run_turn_internal`. This counts each request exactly once, including
tool-call rounds and retries within a turn.
- Unlike agent1, the delta uses per-field `saturating_sub` instead of
the panicking `Sub` impl, so a provider reporting a smaller snapshot
can't crash Zed.
- Removed the `#[allow(unused)]`; the value now round-trips through
`to_db`/`from_db`, surviving restarts and continuing to grow when a
thread is reopened.
- Added a `cumulative_token_usage()` accessor following the
`latest_request_token_usage` convention.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
27191913e9Anant Goel committed on 6/4/2026, 3:24:02 PM· committed by GitHubparent569511a
2 files changedLine totals unavailable