| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "database/sql" |
| 5 | "io" |
| 6 | "log/slog" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "amadan.net/rastrillo/rastrillo/db" |
| 14 | ) |
| 15 | |
| 16 | func tokens(n int64) *int64 { return &n } |
| 17 | |
| 18 | // TestPagesTaskSpend: the task page says quietly what the task used, |
| 19 | // from its usage rows (Claude's cached input counted beside its input, |
| 20 | // Codex's inside it), and the specialist panel has one line per step |
| 21 | // that used any. A task with no rows says nothing, and a teammate who |
| 22 | // can read the task sees the same. |
| 23 | func TestPagesTaskSpend(t *testing.T) { |
| 24 | r := newToolRig(t) |
| 25 | owner := r.inst.Cookie() |
| 26 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 27 | id := taskID(t, r.call("s1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "teh panes"})) |
| 28 | if page := r.get(owner, "/tasks/"+id, 200); strings.Contains(page, "data-spend") { |
| 29 | t.Fatalf("a task with no usage shows spend: %s", page) |
| 30 | } |
| 31 | r.call("s2", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}) |
| 32 | _, body := r.expect(wire.FrameDispatch) |
| 33 | d := body.(*wire.DispatchCommand) |
| 34 | r.step("s-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) |
| 35 | eng := []wire.Usage{{Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: tokens(2000), CachedInputTokens: tokens(60000), CacheWriteTokens: tokens(1000), OutputTokens: tokens(1000), Turns: tokens(12)}} |
| 36 | r.step("s-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a", Usage: eng}) |
| 37 | c := r.dispatched(wire.SpecialistChecks, base, cand, 0) |
| 38 | r.checks("s-c", c, wire.ChecksPassed, exit(0), "", "ok\n") |
| 39 | rv := r.dispatched(wire.SpecialistReview, base, cand, 0) |
| 40 | review := []wire.Usage{{Provider: "codex", Connection: "codex-b", Model: "gpt-6-astra", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: tokens(19000), CachedInputTokens: tokens(1000), OutputTokens: tokens(1000), Turns: tokens(3)}} |
| 41 | r.step("s-r", wire.StepReport{TaskID: id, StepID: rv.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Family: "gpt", Account: "codex-b", Verdict: wire.VerdictChanges, ReviewLabel: wire.ReviewOtherFamily, Findings: []wire.Finding{}, Summary: "One more.", Usage: review}) |
| 42 | r.wait("fix round", func(c *Conversation) bool { return c.Tasks[id].FixRounds == 1 }) |
| 43 | for _, who := range []string{"owner", "member"} { |
| 44 | cookie := owner |
| 45 | if who == "member" { |
| 46 | cookie = r.memberCookie() |
| 47 | } |
| 48 | page := r.get(cookie, "/tasks/"+id, 200) |
| 49 | for _, want := range []string{ |
| 50 | `<p equipo-quiet data-spend>Used 84k tokens (61k cached)</p>`, |
| 51 | `<li data-spend-step="` + d.StepID + `">Engineering: 64k tokens (60k cached)</li>`, |
| 52 | `<li data-spend-step="` + rv.StepID + `">Review: 20k tokens (1k cached)</li>`, |
| 53 | } { |
| 54 | if !strings.Contains(page, want) { |
| 55 | t.Fatalf("%s's task page lacks %q:\n%s", who, want, page) |
| 56 | } |
| 57 | } |
| 58 | // Checks used no model and the fix round has not reported: no line. |
| 59 | if strings.Count(page, "data-spend-step=") != 2 { |
| 60 | t.Fatalf("%s: step lines %d", who, strings.Count(page, "data-spend-step=")) |
| 61 | } |
| 62 | } |
| 63 | // What a harness did not report makes the sum a lower bound: a Claude |
| 64 | // row without its cache-write figure (counted beside input), and a row |
| 65 | // whose final usage message was not seen (a cancelled attempt). |
| 66 | fix := r.dispatched(wire.SpecialistEngineering, cand, "", 1) |
| 67 | r.step("s-f-run", wire.StepReport{TaskID: id, StepID: fix.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: cand}) |
| 68 | partial := []wire.Usage{ |
| 69 | {Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeCancelled, Complete: true, InputTokens: tokens(1000), CachedInputTokens: tokens(1000), OutputTokens: tokens(0)}, |
| 70 | {Provider: "claude", Connection: "claude-a", Model: "claude-haiku-5", Attempt: 1, Outcome: wire.OutcomeCancelled, InputTokens: tokens(500), CachedInputTokens: tokens(0), CacheWriteTokens: tokens(0), OutputTokens: tokens(500)}, |
| 71 | } |
| 72 | r.step("s-f-end", wire.StepReport{TaskID: id, StepID: fix.StepID, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", BaseSHA: cand, Termination: true, Usage: partial}) |
| 73 | page := r.get(owner, "/tasks/"+id, 200) |
| 74 | for _, want := range []string{ |
| 75 | `<p equipo-quiet data-spend>Used at least 87k tokens (62k cached)</p>`, |
| 76 | `<li data-spend-step="` + d.StepID + `">Engineering: 64k tokens (60k cached)</li>`, |
| 77 | `<li data-spend-step="` + fix.StepID + `">Engineering, fix round 1: at least 3k tokens (1k cached)</li>`, |
| 78 | } { |
| 79 | if !strings.Contains(page, want) { |
| 80 | t.Fatalf("task page lacks %q:\n%s", want, page) |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // Migration 0059 over an instance whose usage rows predate it: the rows |
| 86 | // stay, their round and turns are null (unknown, never zero), and the |
| 87 | // task page still sums them. |
| 88 | func TestContractMigrationUsageRoundTurns(t *testing.T) { |
| 89 | r := newToolRig(t) |
| 90 | owner := r.inst.Cookie() |
| 91 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 92 | id := taskID(t, r.call("u1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "teh panes"})) |
| 93 | r.call("u2", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}) |
| 94 | _, body := r.expect(wire.FrameDispatch) |
| 95 | d := body.(*wire.DispatchCommand) |
| 96 | r.step("u-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base}) |
| 97 | used := []wire.Usage{{Provider: "codex", Connection: "codex-a", Model: "gpt-6-astra", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: tokens(9000), CachedInputTokens: tokens(4000), OutputTokens: tokens(1000), Turns: tokens(2)}} |
| 98 | r.step("u-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Usage: used}) |
| 99 | r.runner.Close() |
| 100 | r.inst.Stop() |
| 101 | d0, err := db.Open(r.inst.Path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 102 | if err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | for _, q := range []string{"ALTER TABLE chat_usage DROP COLUMN round", "ALTER TABLE chat_usage DROP COLUMN turns", "ALTER TABLE chat_usage DROP COLUMN overcount", "DELETE FROM rastrillo_migrations WHERE id LIKE 'equipo/0059_%'"} { |
| 106 | if _, err := d0.Writer().Exec(q); err != nil { |
| 107 | t.Fatalf("%s: %v", q, err) |
| 108 | } |
| 109 | } |
| 110 | // A row an older runner sent for an answer on Claude: read from the |
| 111 | // session's running total, so it overcounts. |
| 112 | if _, err := d0.Writer().Exec("INSERT INTO chat_usage(person, connection, provider, model, role, task_id, step_id, turn_id, attempt, outcome, complete, input_tokens, cached_input_tokens, cache_write_tokens, output_tokens, recorded_at) VALUES(?, 'claude-a', 'claude', 'claude-opus-5-5', 'ask', ?, 'q_old', '', 1, 'replied', 1, 500, 90000, 100, 400, ?)", Owner, id, time.Now().UTC()); err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | d0.Close() |
| 116 | r.inst.Restart(t) |
| 117 | var over []bool |
| 118 | rows, err := r.inst.DB.Writer().Query("SELECT coalesce(overcount, 0) FROM chat_usage WHERE task_id = ? ORDER BY provider", id) |
| 119 | if err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | for rows.Next() { |
| 123 | var v bool |
| 124 | rows.Scan(&v) |
| 125 | over = append(over, v) |
| 126 | } |
| 127 | rows.Close() |
| 128 | if len(over) != 2 || !over[0] || over[1] { |
| 129 | t.Fatalf("overcount after the upgrade (claude, codex): %v", over) |
| 130 | } |
| 131 | var round, turns sql.NullInt64 |
| 132 | if err := r.inst.DB.Writer().QueryRow("SELECT round, turns FROM chat_usage WHERE step_id = ?", d.StepID).Scan(&round, &turns); err != nil || round.Valid || turns.Valid { |
| 133 | t.Fatalf("migrated row: round %v turns %v %v", round, turns, err) |
| 134 | } |
| 135 | if page := r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, `<p equipo-quiet data-spend>Used 10k tokens (4k cached)</p><p equipo-quiet data-spend-note>Earlier usage not shown</p>`) || strings.Contains(page, "Questions:") { |
| 136 | t.Fatalf("task page after the upgrade:\n%s", page) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // A Claude answer's row from a runner before ProtocolSpend overcounts |
| 141 | // (it read the session's running total): the task page leaves it out |
| 142 | // and says so, and so does today's usage on Connections. From a runner |
| 143 | // at ProtocolSpend it counts. |
| 144 | func TestPagesSpendLeavesOutOvercount(t *testing.T) { |
| 145 | for _, proto := range []int{wire.Protocol1, wire.Protocol2, wire.ProtocolSpend} { |
| 146 | t.Run(strconv.Itoa(proto), func(t *testing.T) { |
| 147 | r := newToolRig(t) |
| 148 | if proto > wire.Protocol1 { |
| 149 | gen := r.runner.Welcome.Generation |
| 150 | r.runner.Close() |
| 151 | h := primaryHello(gen) |
| 152 | h.Protocol = proto |
| 153 | p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, h) |
| 154 | if err != nil { |
| 155 | t.Fatal(err) |
| 156 | } |
| 157 | t.Cleanup(p.Close) |
| 158 | r.runner = p |
| 159 | } |
| 160 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 161 | id, _, _ := r.askableTask("o", base, cand) |
| 162 | q, err := r.client.Ask(r.ctx, id, "What did you change?", "", "k1") |
| 163 | if err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | r.expect(wire.FrameAsk) |
| 167 | used := []wire.Usage{{Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: tokens(500), CachedInputTokens: tokens(9000), CacheWriteTokens: tokens(100), OutputTokens: tokens(400)}} |
| 168 | r.answer("o-q", wire.AnswerReport{TaskID: id, QuestionID: q.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I fixed the typo.", Usage: used}) |
| 169 | page := r.get(r.inst.Cookie(), "/tasks/"+id, 200) |
| 170 | today, err := r.inst.Store.Chat().UsageToday(r.ctx, Owner) |
| 171 | if err != nil { |
| 172 | t.Fatal(err) |
| 173 | } |
| 174 | if proto < wire.ProtocolSpend { |
| 175 | if !strings.Contains(page, `<p equipo-quiet data-spend-note>Earlier usage not shown</p>`) || strings.Contains(page, "data-spend>") || strings.Contains(page, "data-spend-step=") || today["claude-a"] != 0 { |
| 176 | t.Fatalf("an older runner's answer counted (today %v):\n%s", today, page) |
| 177 | } |
| 178 | return |
| 179 | } |
| 180 | if !strings.Contains(page, `<p equipo-quiet data-spend>Used 10k tokens (9k cached)</p>`) || !strings.Contains(page, `<li data-spend-step="questions">Questions: 10k tokens (9k cached)</li>`) || strings.Contains(page, "data-spend-note") || today["claude-a"] != 900 { |
| 181 | t.Fatalf("a current runner's answer (today %v):\n%s", today, page) |
| 182 | } |
| 183 | }) |
| 184 | } |
| 185 | } |
| 186 | |