Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): rank Copilot usage sources, fix model attribution, surface the token gap (MUL-5712) (#6373)
Bohan Jiang398b7fd06c28
diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.goindex 74dff6e6ac..17bf6de1a3 100644--- a/server/pkg/agent/copilot.go+++ b/server/pkg/agent/copilot.go@@ -41,7 +41,93 @@ type copilotEventState struct {activeModel stringfinalStatus stringfinalError string- usage map[string]TokenUsage++ // Token usage arrives on up to three different events, so each source is+ // accumulated separately and resolved once at the end by resolveUsage.+ //+ // session.shutdown per-model session totals, full breakdown+ // assistant.usage per model call, full breakdown+ // assistant.message outputTokens only — legacy, older CLIs+ //+ // They must never be summed together: all three describe the same tokens.+ callUsage map[string]TokenUsage+ msgUsage map[string]TokenUsage+ shutdownUsage map[string]TokenUsage+ // resumed marks a run that continued an existing Copilot session, which is+ // what disqualifies the session.shutdown totals — see resolveUsage.+ resumed bool+}++// resolveUsage picks the single best usage source this run produced, most+// complete first.+//+// On a fresh session, session.shutdown is the CLI's own final accounting for+// the whole session — which here IS this run — so it is the most complete+// source available and cannot be short-changed by an individual model call+// that failed to report. It is unusable on a resumed run: the CLI restores its+// accumulators from a checkpoint, so it also carries every earlier turn's+// tokens, and reporting that on a follow-up would bill the same tokens once per+// turn. Under-reporting beats double-billing, so a resumed run falls through.+//+// assistant.usage is per model call, so it measures exactly this run either+// way. assistant.message is last: it only ever carries output tokens, so+// letting it win over a source with the full breakdown would silently drop the+// input and cache tiers.+func (st *copilotEventState) resolveUsage() map[string]TokenUsage {+ if !st.resumed && hasTokens(st.shutdownUsage) {+ return st.shutdownUsage+ }+ if hasTokens(st.callUsage) {+ return st.callUsage+ }+ if hasTokens(st.msgUsage) {+ return st.msgUsage+ }+ return map[string]TokenUsage{}+}++// hasTokens reports whether a source carries any real numbers. Presence alone+// is not enough: every token field on assistant.usage is optional upstream, so+// a usage event that names only a model would otherwise mark that source+// "populated" and shadow one that actually has tokens.+func hasTokens(usage map[string]TokenUsage) bool {+ for _, u := range usage {+ if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {+ return true+ }+ }+ return false+}++// addUsage folds one usage record into dst under model, ignoring records that+// carry no tokens at all so an empty one never creates an entry.+//+// Copilot reports cached tokens INSIDE inputTokens (its own event-log reducer+// derives uncached input as inputTokens - cacheRead - cacheWrite), whereas+// TokenUsage.InputTokens is the uncached remainder that prices at the input+// rate. Subtract here so the cache tiers are not billed twice. reasoningTokens+// are deliberately ignored: they are already part of outputTokens.+func addUsage(dst map[string]TokenUsage, model string, input, output, cacheRead, cacheWrite int64) {+ cacheRead = nonNegativeTokens(cacheRead)+ cacheWrite = nonNegativeTokens(cacheWrite)+ output = nonNegativeTokens(output)+ uncachedInput := nonNegativeTokens(input - cacheRead - cacheWrite)+ if uncachedInput == 0 && output == 0 && cacheRead == 0 && cacheWrite == 0 {+ return+ }+ u := dst[model]+ u.InputTokens += uncachedInput+ u.OutputTokens += output+ u.CacheReadTokens += cacheRead+ u.CacheWriteTokens += cacheWrite+ dst[model] = u+}++func nonNegativeTokens(n int64) int64 {+ if n < 0 {+ return 0+ }+ return n}// finalOutput is the deliverable for Result.Output: the last complete assistant@@ -53,11 +139,14 @@ func (st *copilotEventState) finalOutput() string {return st.output.String()}-func newCopilotEventState(seedModel string) *copilotEventState {+func newCopilotEventState(seedModel string, resumed bool) *copilotEventState {return &copilotEventState{- activeModel: seedModel,- finalStatus: "completed",- usage: make(map[string]TokenUsage),+ activeModel: seedModel,+ finalStatus: "completed",+ callUsage: make(map[string]TokenUsage),+ msgUsage: make(map[string]TokenUsage),+ shutdownUsage: make(map[string]TokenUsage),+ resumed: resumed,}}@@ -111,13 +200,18 @@ func handleCopilotEvent(evt copilotEvent, st *copilotEventState) []Message {// leaving its deltas buffered would let them be stitched onto the NEXT// turn's partial text if the process then died mid-stream.st.pendingDelta.Reset()+ // The message names the model that produced it. Without this the first+ // turn's tokens land under the seed model — the literal string+ // "copilot" when no model was configured — which no price table maps,+ // so a run that DID report tokens still estimated $0.00.+ if msg.Model != "" {+ st.activeModel = msg.Model+ }if msg.ReasoningText != "" {msgs = append(msgs, Message{Type: MessageThinking, Content: msg.ReasoningText})}if msg.OutputTokens > 0 {- u := st.usage[st.activeModel]- u.OutputTokens += msg.OutputTokens- st.usage[st.activeModel] = u+ addUsage(st.msgUsage, st.activeModel, 0, msg.OutputTokens, 0, 0)}for _, tr := range msg.ToolRequests {var input map[string]any@@ -132,6 +226,36 @@ func handleCopilotEvent(evt copilotEvent, st *copilotEventState) []Message {})}+ case "assistant.usage":+ // One record per model API call, with the full token breakdown. This is+ // the only event that reports input and cache tokens at all.+ var u copilotUsageData+ if err := json.Unmarshal(evt.Data, &u); err != nil {+ return nil+ }+ model := u.Model+ // The CLI writes "unknown" when it cannot name the model; keep whatever+ // the session already resolved rather than opening a bogus usage row.+ if model == "" || model == "unknown" {+ model = st.activeModel+ } else {+ st.activeModel = model+ }+ addUsage(st.callUsage, model, u.InputTokens, u.OutputTokens, u.CacheReadTokens, u.CacheWriteTokens)++ case "session.shutdown":+ // Session-wide per-model totals, emitted once as the session tears down.+ var sd copilotShutdownData+ if err := json.Unmarshal(evt.Data, &sd); err != nil {+ return nil+ }+ for model, m := range sd.ModelMetrics {+ if model == "" {+ model = st.activeModel+ }+ addUsage(st.shutdownUsage, model, m.Usage.InputTokens, m.Usage.OutputTokens, m.Usage.CacheReadTokens, m.Usage.CacheWriteTokens)+ }+case "assistant.reasoning", "assistant.reasoning_delta":// Streaming thinking content — may arrive as full or delta.var r copilotReasoning@@ -264,7 +388,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpif seedModel == "" {seedModel = "copilot"}- st := newCopilotEventState(seedModel)+ st := newCopilotEventState(seedModel, opts.ResumeSessionID != "")go func() {<-runCtx.Done()@@ -313,13 +437,26 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpb.cfg.Logger.Info("copilot finished", "pid", cmd.Process.Pid, "status", st.finalStatus, "duration", duration.Round(time.Millisecond).String())+ usage := st.resolveUsage()+ // A run that produced output but no tokens is a silent billing hole:+ // the daemon skips reporting empty usage, so nothing surfaces anywhere+ // downstream. This is the current state on Copilot CLI 1.0.77 (see+ // copilotUsageData), and it went unnoticed until a user reported it —+ // log it so the next regression is visible from the daemon log alone.+ if len(usage) == 0 && st.finalStatus == "completed" {+ b.cfg.Logger.Warn("copilot reported no token usage",+ "session", st.sessionID,+ "model", st.activeModel,+ "hint", "Copilot CLI filters assistant.usage and session.shutdown out of --output-format json; only assistant.message.outputTokens remains, and newer CLIs no longer populate it")+ }+resCh <- Result{Status: st.finalStatus,Output: st.finalOutput(),Error: st.finalError,DurationMs: duration.Milliseconds(),SessionID: st.sessionID,- Usage: st.usage,+ Usage: usage,}}()@@ -360,8 +497,13 @@ type copilotSessionStart struct {}// copilotAssistantMessage is data payload for "assistant.message".+//+// OutputTokens is optional in the CLI's own event schema and is the ONLY token+// field that survives onto the `--output-format json` stream — see the+// suppression note on copilotUsageData.type copilotAssistantMessage struct {MessageID string `json:"messageId"`+ Model string `json:"model"`Content string `json:"content"`ToolRequests []copilotToolRequest `json:"toolRequests"`OutputTokens int64 `json:"outputTokens"`@@ -369,6 +511,38 @@ type copilotAssistantMessage struct {ReasoningText string `json:"reasoningText,omitempty"`}+// copilotUsageData is data payload for "assistant.usage": one record per model+// API call, carrying the only complete token breakdown the CLI produces.+//+// InputTokens INCLUDES the cached tiers; addUsage subtracts them back out. The+// payload also carries reasoningTokens, deliberately not parsed here: those are+// a subset of outputTokens, so counting them would double-bill reasoning.+//+// NOTE (Copilot CLI 1.0.77): the CLI's JSONL writer drops a fixed set of event+// types before writing stdout, and both "assistant.usage" and+// "session.shutdown" are on that list — so on a current CLI neither reaches us+// and Copilot runs report no tokens at all. Everything here is still parsed+// because older CLIs, and any future build that stops filtering them, deliver+// real numbers through exactly these events. The `result` event we already+// parse carries premiumRequests and durations but no token counts.+type copilotUsageData struct {+ Model string `json:"model"`+ InputTokens int64 `json:"inputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ CacheReadTokens int64 `json:"cacheReadTokens"`+ CacheWriteTokens int64 `json:"cacheWriteTokens"`+}++// copilotShutdownData is data payload for "session.shutdown": session-wide+// totals keyed by model.+type copilotShutdownData struct {+ ModelMetrics map[string]copilotShutdownModelMetric `json:"modelMetrics"`+}++type copilotShutdownModelMetric struct {+ Usage copilotUsageData `json:"usage"`+}+// copilotToolRequest is one tool invocation inside assistant.message.type copilotToolRequest struct {ToolCallID string `json:"toolCallId"`diff --git a/server/pkg/agent/copilot_test.go b/server/pkg/agent/copilot_test.goindex 64e0beadb7..57a03f1c35 100644--- a/server/pkg/agent/copilot_test.go+++ b/server/pkg/agent/copilot_test.go@@ -241,9 +241,15 @@ func simulateCopilotEventLoop(t *testing.T, lines []string) ([]Message, string,}func simulateCopilotEventLoopWithModel(t *testing.T, lines []string, seedModel string) ([]Message, string, string, map[string]TokenUsage) {+ t.Helper()+ msgs, st := runCopilotEventLoop(t, lines, seedModel, false)+ return msgs, st.sessionID, st.finalStatus, st.resolveUsage()+}++func runCopilotEventLoop(t *testing.T, lines []string, seedModel string, resumed bool) ([]Message, *copilotEventState) {t.Helper()var msgs []Message- st := newCopilotEventState(seedModel)+ st := newCopilotEventState(seedModel, resumed)for _, line := range lines {var evt copilotEvent@@ -252,7 +258,7 @@ func simulateCopilotEventLoopWithModel(t *testing.T, lines []string, seedModel s}msgs = append(msgs, handleCopilotEvent(evt, st)...)}- return msgs, st.sessionID, st.finalStatus, st.usage+ return msgs, st}func TestCopilotEventLoopSimpleMessage(t *testing.T) {@@ -440,7 +446,7 @@ func TestCopilotEventLoopNonZeroExit(t *testing.T) {func TestCopilotEventLoopSessionErrorSurvivesNonZeroResult(t *testing.T) {t.Parallel()- st := newCopilotEventState("copilot")+ st := newCopilotEventState("copilot", false)for _, line := range []string{fixtureSessionError, fixtureResultNonZero} {var evt copilotEvent@@ -520,6 +526,209 @@ func TestCopilotEventLoopMultiTurnUsage(t *testing.T) {}}+// ── Token accounting (MUL-5712) ──++const fixtureAssistantUsage = `{"type":"assistant.usage","data":{"model":"claude-sonnet-4.5","inputTokens":12000,"outputTokens":250,"cacheReadTokens":9000,"cacheWriteTokens":1500,"reasoningTokens":80,"duration":1400},"id":"u-1","timestamp":"2026-08-04T08:00:01.000Z","parentId":"p-1","ephemeral":true}`++const fixtureShutdown = `{"type":"session.shutdown","data":{"shutdownType":"routine","totalPremiumRequests":3,"modelMetrics":{"claude-sonnet-4.5":{"requests":{"count":3,"cost":3},"usage":{"inputTokens":30000,"outputTokens":900,"cacheReadTokens":24000,"cacheWriteTokens":2000,"reasoningTokens":100}}}},"id":"sd-1","timestamp":"2026-08-04T08:00:09.000Z","parentId":"p-1"}`++func TestCopilotAssistantUsageIsAuthoritative(t *testing.T) {+ t.Parallel()+ // assistant.usage carries the full breakdown; assistant.message.outputTokens+ // describes the SAME tokens, so the two must never be summed.+ lines := []string{+ fixtureSessionStart,+ fixtureTurnStart,+ fixtureAssistantUsage,+ fixtureAssistantMessage, // 5 outputTokens — superseded+ fixtureResult,+ }++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ if len(usage) != 1 {+ t.Fatalf("expected exactly one model entry, got %#v", usage)+ }+ u, ok := usage["claude-sonnet-4.5"]+ if !ok {+ t.Fatalf("expected usage under 'claude-sonnet-4.5', got %#v", usage)+ }+ // inputTokens includes the cached tiers, so uncached input is 12000-9000-1500.+ if u.InputTokens != 1500 {+ t.Fatalf("expected 1500 uncached input tokens, got %d", u.InputTokens)+ }+ if u.OutputTokens != 250 {+ t.Fatalf("expected 250 output tokens (not 255 — message tokens must not be added), got %d", u.OutputTokens)+ }+ if u.CacheReadTokens != 9000 || u.CacheWriteTokens != 1500 {+ t.Fatalf("expected cache 9000/1500, got %d/%d", u.CacheReadTokens, u.CacheWriteTokens)+ }+}++func TestCopilotAssistantUsageNeverGoesNegative(t *testing.T) {+ t.Parallel()+ // Defensive: a CLI that reports inputTokens EXCLUDING cache would otherwise+ // drive uncached input negative.+ lines := []string{+ `{"type":"assistant.usage","data":{"model":"m","inputTokens":100,"outputTokens":10,"cacheReadTokens":9000,"cacheWriteTokens":0},"id":"u","timestamp":"2026-08-04T08:00:01.000Z"}`,+ }++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ if u := usage["m"]; u.InputTokens != 0 {+ t.Fatalf("expected input tokens clamped to 0, got %d", u.InputTokens)+ }+}++func TestCopilotShutdownUsageFallback(t *testing.T) {+ t.Parallel()+ // No assistant.usage and no outputTokens: the session totals are all we have.+ lines := []string{fixtureSessionStart, fixtureTurnStart, fixtureShutdown, fixtureResult}++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ u, ok := usage["claude-sonnet-4.5"]+ if !ok {+ t.Fatalf("expected session.shutdown totals to be used, got %#v", usage)+ }+ if u.InputTokens != 4000 || u.OutputTokens != 900 {+ t.Fatalf("expected 4000/900 input/output, got %d/%d", u.InputTokens, u.OutputTokens)+ }+}++func TestCopilotShutdownBeatsMessageOnFreshRun(t *testing.T) {+ t.Parallel()+ // A CLI that still populates assistant.message.outputTokens AND emits the+ // session totals: the totals win, because outputTokens describes only part+ // of the same tokens and taking it would drop input and cache entirely.+ lines := []string{+ fixtureSessionStart,+ fixtureTurnStart,+ fixtureAssistantMessage, // 5 outputTokens, no input/cache+ fixtureShutdown,+ fixtureResult,+ }++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ u, ok := usage["claude-sonnet-4.5"]+ if !ok {+ t.Fatalf("expected the session totals to win over message outputTokens, got %#v", usage)+ }+ if u.InputTokens != 4000 || u.OutputTokens != 900 {+ t.Fatalf("expected 4000/900 input/output from session.shutdown, got %d/%d", u.InputTokens, u.OutputTokens)+ }+ if u.CacheReadTokens != 24000 || u.CacheWriteTokens != 2000 {+ t.Fatalf("expected cache 24000/2000, got %d/%d", u.CacheReadTokens, u.CacheWriteTokens)+ }+}++func TestCopilotTokenlessUsageEventDoesNotShadow(t *testing.T) {+ t.Parallel()+ // Every token field on assistant.usage is optional upstream. A usage event+ // that names only a model must not mark that source populated and shadow+ // the sources that do carry numbers.+ tokenless := `{"type":"assistant.usage","data":{"model":"claude-sonnet-4.5","duration":900},"id":"u-0","timestamp":"2026-08-04T08:00:01.000Z","ephemeral":true}`++ t.Run("falls through to session totals", func(t *testing.T) {+ t.Parallel()+ lines := []string{fixtureSessionStart, fixtureTurnStart, tokenless, fixtureShutdown, fixtureResult}++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ if u := usage["claude-sonnet-4.5"]; u.OutputTokens != 900 {+ t.Fatalf("expected session totals to survive a tokenless usage event, got %#v", usage)+ }+ })++ t.Run("falls through to message tokens on resume", func(t *testing.T) {+ t.Parallel()+ // Resumed, so the session totals are off the table and the legacy+ // message tokens are the only thing left.+ lines := []string{fixtureSessionStart, fixtureTurnStart, tokenless, fixtureAssistantMessage, fixtureShutdown, fixtureResult}++ _, st := runCopilotEventLoop(t, lines, "copilot", true)++ usage := st.resolveUsage()+ if u := usage["claude-sonnet-4.5"]; u.OutputTokens != 5 {+ t.Fatalf("expected the 5 message outputTokens to survive, got %#v", usage)+ }+ })+}++func TestCopilotShutdownUsageSkippedOnResume(t *testing.T) {+ t.Parallel()+ // session.shutdown totals span the WHOLE session, and the CLI restores its+ // accumulators on resume — reporting them on a follow-up turn would bill+ // every earlier turn again. Reporting nothing is the lesser error.+ lines := []string{fixtureSessionStart, fixtureTurnStart, fixtureShutdown, fixtureResult}++ _, st := runCopilotEventLoop(t, lines, "copilot", true)++ if usage := st.resolveUsage(); len(usage) != 0 {+ t.Fatalf("expected no usage on a resumed run, got %#v", usage)+ }+}++func TestCopilotResumeStillReportsPerCallUsage(t *testing.T) {+ t.Parallel()+ // assistant.usage is per model call, so a resumed run reports it normally.+ lines := []string{fixtureSessionStart, fixtureTurnStart, fixtureAssistantUsage, fixtureShutdown, fixtureResult}++ _, st := runCopilotEventLoop(t, lines, "copilot", true)++ usage := st.resolveUsage()+ if len(usage) != 1 {+ t.Fatalf("expected per-call usage on a resumed run, got %#v", usage)+ }+ if u := usage["claude-sonnet-4.5"]; u.OutputTokens != 250 {+ t.Fatalf("expected the per-call figure (250), not the session total (900), got %d", u.OutputTokens)+ }+}++func TestCopilotAssistantMessageModelAttribution(t *testing.T) {+ t.Parallel()+ // assistant.message names its own model. Before this the first turn's tokens+ // landed under the seed model — the unpriceable literal "copilot".+ lines := []string{+ fixtureTurnStart,+ `{"type":"assistant.message","data":{"messageId":"m1","model":"claude-opus-4.6","content":"hi","toolRequests":[],"outputTokens":42},"id":"e1","timestamp":"2026-08-04T08:00:02.000Z"}`,+ fixtureResult,+ }++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ if _, ok := usage["copilot"]; ok {+ t.Fatalf("tokens must not be filed under the seed model when the message names one: %#v", usage)+ }+ if u := usage["claude-opus-4.6"]; u.OutputTokens != 42 {+ t.Fatalf("expected 42 output tokens under 'claude-opus-4.6', got %#v", usage)+ }+}++func TestCopilotModernStreamReportsNoUsage(t *testing.T) {+ t.Parallel()+ // Copilot CLI 1.0.77 shape: assistant.message without outputTokens or model,+ // tool.execution_complete without model, and no assistant.usage /+ // session.shutdown (the CLI filters both off stdout). Nothing to report —+ // this documents the upstream gap so a future CLI change shows up as a+ // failing test rather than a silent one.+ lines := []string{+ `{"type":"session.start","data":{"sessionId":"s1","version":1,"producer":"copilot-agent"},"id":"e1","timestamp":"2026-08-04T08:00:00.000Z"}`,+ `{"type":"assistant.turn_start","data":{"turnId":"t1"},"id":"e2","timestamp":"2026-08-04T08:00:01.000Z"}`,+ `{"type":"assistant.message","data":{"messageId":"m1","content":"","toolRequests":[{"toolCallId":"c1","name":"bash","arguments":{"command":"ls"}}]},"id":"e3","timestamp":"2026-08-04T08:00:02.000Z"}`,+ `{"type":"tool.execution_complete","data":{"toolCallId":"c1","success":true,"turnId":"t1","result":{"content":"a.go\n"}},"id":"e4","timestamp":"2026-08-04T08:00:03.000Z"}`,+ `{"type":"assistant.message","data":{"messageId":"m2","content":"Done."},"id":"e5","timestamp":"2026-08-04T08:00:04.000Z"}`,+ fixtureResult,+ }++ _, _, _, usage := simulateCopilotEventLoop(t, lines)++ if len(usage) != 0 {+ t.Fatalf("expected no usage from a 1.0.77-shaped stream, got %#v", usage)+ }+}+func TestCopilotEventLoopSessionStartSetsModel(t *testing.T) {t.Parallel()lines := []string{@@ -640,7 +849,7 @@ func TestCopilotEventLoopDeltaFallbackOutput(t *testing.T) {`{"type":"assistant.message_delta","data":{"messageId":"m1","deltaContent":"world"},"id":"d2","timestamp":"2026-04-16T08:43:38.100Z","parentId":"p1","ephemeral":true}`,}- st := newCopilotEventState("copilot")+ st := newCopilotEventState("copilot", false)for _, line := range lines {var evt copilotEventif err := json.Unmarshal([]byte(line), &evt); err != nil {@@ -669,7 +878,7 @@ func TestCopilotEventLoopDeliversFinalTurnOnly(t *testing.T) {`{"type":"assistant.message","data":{"messageId":"m2","content":"The retry loop is the cause."},"id":"a2","timestamp":"2026-04-16T08:43:40.100Z","parentId":"p1"}`,}- st := newCopilotEventState("copilot")+ st := newCopilotEventState("copilot", false)var streamed []stringfor _, line := range lines {var evt copilotEvent@@ -708,7 +917,7 @@ func TestCopilotEventLoopToolOnlyTurnClearsPendingDelta(t *testing.T) {`{"type":"assistant.message_delta","data":{"messageId":"m2","deltaContent":"The retry loop"},"id":"d2","timestamp":"2026-04-16T08:43:40.000Z","parentId":"p1","ephemeral":true}`,}- st := newCopilotEventState("copilot")+ st := newCopilotEventState("copilot", false)for _, line := range lines {var evt copilotEventif err := json.Unmarshal([]byte(line), &evt); err != nil {