Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions internal/runtime/claude_progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,14 @@ type contentItem struct {
Input json.RawMessage `json:"input"`
}

// resultEvent represents the final NDJSON event from Claude Code's stream-json
// output, containing execution metrics.
// resultEvent represents a result NDJSON event from Claude Code's stream-json
// output, containing execution metrics. A session writes one per segment: one
// for the prompt, and one more each time a background task's completion
// resumes it after its final answer. NumTurns covers that segment only;
// TotalCostUSD and ModelUsage are running totals for the session. Usage is per
// segment, and for the top-level loop only, in Claude Code 2.1.306, the image
// pin (seen in the agents nightly streams); 2.1.334 derives it from
// modelUsage, a running total. Either way it is kept last-wins, never summed.
type resultEvent struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
Expand All @@ -177,9 +183,10 @@ type resultEvent struct {
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
CacheReadInputTokens int `json:"cache_read_input_tokens"`
} `json:"usage"`
// ModelUsage is keyed by model id and, unlike Usage (top-level loop
// only), includes sub-agent activity. Like TotalCostUSD it is a running
// total for the session, not a per-result delta.
// ModelUsage is keyed by model id and, unlike Usage on 2.1.306
// (top-level loop only), includes sub-agent activity. Like
// TotalCostUSD it is a running total for the session, not a
// per-result delta.
ModelUsage map[string]claudeModelUsage `json:"modelUsage"`
}

Expand Down Expand Up @@ -267,6 +274,7 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error {
cumulativeCacheWrite int
seenResult bool
totalReasoning int // accumulated thinking tokens across all messages (for ResultEvent)
totalTurns int // num_turns summed across result events (for ResultEvent)
Comment thread
AshwinUgale marked this conversation as resolved.
Resolved
Comment thread
AshwinUgale marked this conversation as resolved.
Resolved
)

// Emit a final cumulative TokensEvent when the stream ends without
Expand Down Expand Up @@ -506,6 +514,11 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error {
continue
}
seenResult = true
// num_turns counts one segment's turns (see resultEvent), so
// each ResultEvent carries the stream's turns so far, like the
// running totals beside it.
totalTurns += re.NumTurns
re.NumTurns = totalTurns
onEvent(newClaudeResultEvent(re, totalReasoning))

case "assistant":
Expand Down Expand Up @@ -688,10 +701,13 @@ func recordClaudeMetrics(metrics *RunMetrics, evt AgentEvent) {
metrics.CacheCreationInputTokens = e.CacheWrite
case ResultEvent:
// Authoritative totals from the result event overwrite the
// incremental snapshot. They are session running totals, so a
// later result (steered or retried run) replaces an earlier one —
// PerModelUsage included, which is assigned rather than merged so
// nothing is counted twice.
// incremental snapshot. They are session running totals (NumTurns
// is made one by parseClaudeStream; the token counts are when the
// result carries modelUsage, and the last segment's without it on
// Claude Code 2.1.306; see resultEvent), so a later result (a session
// resumed by a background task, or a steered or retried run)
// replaces an earlier one — PerModelUsage included, which is
// assigned rather than merged so nothing is counted twice.
metrics.NumTurns = e.NumTurns
metrics.TotalCostUSD = e.TotalCostUSD
metrics.InputTokens = e.InputTokens
Expand Down
76 changes: 76 additions & 0 deletions internal/runtime/claude_progress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"slices"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -2066,6 +2068,77 @@ func TestNewClaudeResultEventReasoningTokens(t *testing.T) {
}
}

// TestProgressParserMultiResultSumsTurns: num_turns covers one segment, so a
// session that background tasks resumed five times records the sum, while the
// cost and modelUsage, running totals, keep the last value. The turns, cost
// and output tokens are those of a live review run (Claude Code 2.1.306).
func TestProgressParserMultiResultSumsTurns(t *testing.T) {
turns := []int{18, 2, 1, 1, 1, 4}
var lines []string
for _, n := range turns {
lines = append(lines, fmt.Sprintf(
`{"type":"result","subtype":"success","num_turns":%d,"total_cost_usd":0.9311,"modelUsage":{"claude-sonnet-5-5":{"outputTokens":22504,"costUSD":0.9311}}}`, n))
}
stream := strings.Join(lines, "\n")

var soFar []int
if err := parseClaudeStream(strings.NewReader(stream), func(evt AgentEvent) {
if e, ok := evt.(ResultEvent); ok {
soFar = append(soFar, e.NumTurns)
}
}); err != nil {
t.Fatalf("parseClaudeStream returned error: %v", err)
}
if want := []int{18, 20, 21, 22, 23, 27}; !slices.Equal(soFar, want) {
t.Errorf("ResultEvent turns = %v, want %v (turns so far)", soFar, want)
}

var buf bytes.Buffer
metrics := &RunMetrics{}
if err := progressParser(strings.NewReader(stream), ui.New(&buf), metrics); err != nil {
t.Fatalf("progressParser returned error: %v", err)
}
if metrics.NumTurns != 27 {
t.Errorf("num_turns = %d, want 27", metrics.NumTurns)
}
if metrics.TotalCostUSD != 0.9311 || metrics.OutputTokens != 22504 {
t.Errorf("cost=%v out=%d, want 0.9311 and 22504 (running totals, not summed)",
metrics.TotalCostUSD, metrics.OutputTokens)
}
}

// TestProgressParserMultiResultWithoutModelUsageKeepsLastUsage: a result with
// no modelUsage falls back to usage, which Claude Code 2.1.306 reports per
// segment and 2.1.334 as a running total. Either way the last result's usage
// is kept and never summed, so neither version is double-counted. The turns
// and output tokens are those of a live 2.1.306 run with three segments.
func TestProgressParserMultiResultWithoutModelUsageKeepsLastUsage(t *testing.T) {
Comment thread
AshwinUgale marked this conversation as resolved.
Resolved
stream := strings.Join([]string{
`{"type":"result","subtype":"success","num_turns":19,"total_cost_usd":0.61,"usage":{"input_tokens":40,"output_tokens":16717}}`,
`{"type":"result","subtype":"success","num_turns":1,"total_cost_usd":0.62,"usage":{"input_tokens":3,"output_tokens":62}}`,
`{"type":"result","subtype":"success","num_turns":5,"total_cost_usd":0.70,"usage":{"input_tokens":9,"output_tokens":4661}}`,
}, "\n")

var buf bytes.Buffer
metrics := &RunMetrics{}
if err := progressParser(strings.NewReader(stream), ui.New(&buf), metrics); err != nil {
t.Fatalf("progressParser returned error: %v", err)
}
if metrics.NumTurns != 25 {
t.Errorf("num_turns = %d, want 25 (19+1+5, per segment)", metrics.NumTurns)
}
if metrics.InputTokens != 9 || metrics.OutputTokens != 4661 {
t.Errorf("in=%d out=%d, want 9 and 4661 (the last result's usage, not summed)",
metrics.InputTokens, metrics.OutputTokens)
}
if metrics.TotalCostUSD != 0.70 {
t.Errorf("cost = %v, want 0.70 (a running total)", metrics.TotalCostUSD)
}
if metrics.PerModelUsage != nil {
t.Errorf("PerModelUsage = %v, want nil without modelUsage", metrics.PerModelUsage)
}
}

// TestProgressParserMultiResultModelUsageNotDoubleCounted: modelUsage is a
// session running total, so a steered or retried session with two results
// records the last one, not their sum.
Expand All @@ -2087,6 +2160,9 @@ func TestProgressParserMultiResultModelUsageNotDoubleCounted(t *testing.T) {
if metrics.TotalCostUSD != 0.3 {
t.Errorf("expected cost 0.3, got %v", metrics.TotalCostUSD)
}
if metrics.NumTurns != 6 {
t.Errorf("expected num_turns 6 (2+4, per segment), got %d", metrics.NumTurns)
}
want := map[string]ModelUsage{
"claude-opus-4-6": {InputTokens: 150, OutputTokens: 250, CacheReadInputTokens: 350, CacheCreationInputTokens: 450, CostUSD: 0.3},
}
Expand Down
6 changes: 5 additions & 1 deletion internal/runtime/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,11 @@ type TokensEvent struct {

func (TokensEvent) agentEvent() {}

// ResultEvent is emitted once at stream end with final metrics.
// ResultEvent carries a run's metrics. It is emitted once at stream end,
Comment thread
AshwinUgale marked this conversation as resolved.
Resolved
// except on claude, which emits one per result in the stream: each holds the
// totals so far, so the last one is final (its token counts are totals when
// the result carries modelUsage; without it, on Claude Code 2.1.306, they are
// the last segment's).
type ResultEvent struct {
NumTurns int
TotalCostUSD float64
Expand Down
Loading