Skip to content

Streaming path: preserve provider token usage - #50

Merged
ayman3000 merged 1 commit into
mainfrom
real-token-usage
Aug 21, 2026
Merged

Streaming path: preserve provider token usage#50
ayman3000 merged 1 commit into
mainfrom
real-token-usage

Conversation

@ayman3000

Copy link
Copy Markdown
Owner

What

The streaming turn (executeTurn with onText != nil) discarded the provider's token usage on the final .finish chunk (case .finish(let reason, _)) and built the response with usage: nil. That forced consumers (cost tracking, context indicators) onto a local character-based estimate instead of the model's real reported tokens.

Fix

  • Capture usage from the .finish(reason:usage:) chunk into streamedUsage.
  • Thread it onto the synthesized response (both the text and native-tool-call return paths).
  • Non-streaming path (complete) already carried usage — unchanged.

Tests

  • New ReplayRun.runStreaming helper to exercise the streaming path.
  • StreamingUsageTests.streamingResponseCarriesProviderUsage — asserts the emitted .llmCallCompleted response carries the provider's promptTokens/completionTokens. Verified RED without the fix (usage was nil), GREEN with it.
  • Full offline suite: 257 tests pass.

🤖 Generated with Claude Code

executeTurn's streaming branch discarded the usage on the final `.finish`
chunk (`case .finish(let reason, _)`) and synthesized the response with
`usage: nil`, forcing cost/context onto a local estimate. Capture the
usage and thread it onto the returned response (text and tool-call paths).

Adds ReplayRun.runStreaming to exercise the streaming path, and a
regression test asserting the emitted response carries the provider's
promptTokens/completionTokens.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@ayman3000
ayman3000 merged commit a8281e8 into main Aug 21, 2026
1 check passed
@ayman3000
ayman3000 deleted the real-token-usage branch August 21, 2026 09:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant