AggregateRunSummary reads all steps for the given run, computes token totals, and merges them with the run's existing summary (preserving any seeded first_message label). The baseSummary parameter should be the current run summary (may be nil).
( ctx context.Context, runID uuid.UUID, baseSummary map[string]any, )
| 68 | // seeded first_message label). The baseSummary parameter should be the |
| 69 | // current run summary (may be nil). |
| 70 | func (s *Service) AggregateRunSummary( |
| 71 | ctx context.Context, |
| 72 | runID uuid.UUID, |
| 73 | baseSummary map[string]any, |
| 74 | ) (map[string]any, error) { |
| 75 | if runID == uuid.Nil { |
| 76 | return baseSummary, nil |
| 77 | } |
| 78 | |
| 79 | steps, err := s.db.GetChatDebugStepsByRunID(chatdContext(ctx), runID) |
| 80 | if err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | |
| 84 | // Start from a shallow copy of baseSummary to avoid mutating the |
| 85 | // caller's map. |
| 86 | // Capacity hint: baseSummary entries plus 8 derived keys |
| 87 | // (step_count, total_input_tokens, total_output_tokens, |
| 88 | // total_reasoning_tokens, total_cache_creation_tokens, |
| 89 | // total_cache_read_tokens, has_error, endpoint_label). |
| 90 | result := make(map[string]any, len(baseSummary)+8) |
| 91 | for k, v := range baseSummary { |
| 92 | result[k] = v |
| 93 | } |
| 94 | |
| 95 | // Clear derived fields before recomputing them so stale values from a |
| 96 | // previous aggregation do not survive when the new totals are zero or |
| 97 | // the endpoint label is unavailable. |
| 98 | for _, key := range []string{ |
| 99 | "step_count", |
| 100 | "total_input_tokens", |
| 101 | "total_output_tokens", |
| 102 | "total_reasoning_tokens", |
| 103 | "total_cache_creation_tokens", |
| 104 | "total_cache_read_tokens", |
| 105 | "endpoint_label", |
| 106 | "has_error", |
| 107 | } { |
| 108 | delete(result, key) |
| 109 | } |
| 110 | var ( |
| 111 | totalInput int64 |
| 112 | totalOutput int64 |
| 113 | totalReasoning int64 |
| 114 | totalCacheCreation int64 |
| 115 | totalCacheRead int64 |
| 116 | hasError bool |
| 117 | ) |
| 118 | |
| 119 | for _, step := range steps { |
| 120 | // Flag runs that hit a real error. Interrupted steps represent |
| 121 | // user-initiated cancellation (e.g. clicking Stop) and should |
| 122 | // not trigger the error indicator in the debug panel. |
| 123 | // A JSONB null (used by jsonClear to erase a prior error) is |
| 124 | // Valid but carries no meaningful content, so exclude it. |
| 125 | errorIsReal := step.Error.Valid && |
| 126 | len(step.Error.RawMessage) > 0 && |
| 127 | !bytes.Equal(step.Error.RawMessage, []byte("null")) |