package thintest import ( "database/sql" "io" "log/slog" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "amadan.net/rastrillo/rastrillo/db" ) func tokens(n int64) *int64 { return &n } // TestPagesTaskSpend: the task page says quietly what the task used, // from its usage rows (Claude's cached input counted beside its input, // Codex's inside it), and the specialist panel has one line per step // that used any. A task with no rows says nothing, and a teammate who // can read the task sees the same. func TestPagesTaskSpend(t *testing.T) { r := newToolRig(t) owner := r.inst.Cookie() base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id := taskID(t, r.call("s1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "teh panes"})) if page := r.get(owner, "/tasks/"+id, 200); strings.Contains(page, "data-spend") { t.Fatalf("a task with no usage shows spend: %s", page) } r.call("s2", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}) _, body := r.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) r.step("s-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) 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)}} 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}) c := r.dispatched(wire.SpecialistChecks, base, cand, 0) r.checks("s-c", c, wire.ChecksPassed, exit(0), "", "ok\n") rv := r.dispatched(wire.SpecialistReview, base, cand, 0) 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)}} 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}) r.wait("fix round", func(c *Conversation) bool { return c.Tasks[id].FixRounds == 1 }) for _, who := range []string{"owner", "member"} { cookie := owner if who == "member" { cookie = r.memberCookie() } page := r.get(cookie, "/tasks/"+id, 200) for _, want := range []string{ `

Used 84k tokens (61k cached)

`, `
  • Engineering: 64k tokens (60k cached)
  • `, `
  • Review: 20k tokens (1k cached)
  • `, } { if !strings.Contains(page, want) { t.Fatalf("%s's task page lacks %q:\n%s", who, want, page) } } // Checks used no model and the fix round has not reported: no line. if strings.Count(page, "data-spend-step=") != 2 { t.Fatalf("%s: step lines %d", who, strings.Count(page, "data-spend-step=")) } } // What a harness did not report makes the sum a lower bound: a Claude // row without its cache-write figure (counted beside input), and a row // whose final usage message was not seen (a cancelled attempt). fix := r.dispatched(wire.SpecialistEngineering, cand, "", 1) r.step("s-f-run", wire.StepReport{TaskID: id, StepID: fix.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: cand}) partial := []wire.Usage{ {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)}, {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)}, } 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}) page := r.get(owner, "/tasks/"+id, 200) for _, want := range []string{ `

    Used at least 87k tokens (62k cached)

    `, `
  • Engineering: 64k tokens (60k cached)
  • `, `
  • Engineering, fix round 1: at least 3k tokens (1k cached)
  • `, } { if !strings.Contains(page, want) { t.Fatalf("task page lacks %q:\n%s", want, page) } } } // Migration 0059 over an instance whose usage rows predate it: the rows // stay, their round and turns are null (unknown, never zero), and the // task page still sums them. func TestContractMigrationUsageRoundTurns(t *testing.T) { r := newToolRig(t) owner := r.inst.Cookie() base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id := taskID(t, r.call("u1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "teh panes"})) r.call("u2", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}) _, body := r.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) r.step("u-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base}) 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)}} 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}) r.runner.Close() r.inst.Stop() d0, err := db.Open(r.inst.Path, slog.New(slog.NewTextHandler(io.Discard, nil))) if err != nil { t.Fatal(err) } 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_%'"} { if _, err := d0.Writer().Exec(q); err != nil { t.Fatalf("%s: %v", q, err) } } // A row an older runner sent for an answer on Claude: read from the // session's running total, so it overcounts. 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 { t.Fatal(err) } d0.Close() r.inst.Restart(t) var over []bool rows, err := r.inst.DB.Writer().Query("SELECT coalesce(overcount, 0) FROM chat_usage WHERE task_id = ? ORDER BY provider", id) if err != nil { t.Fatal(err) } for rows.Next() { var v bool rows.Scan(&v) over = append(over, v) } rows.Close() if len(over) != 2 || !over[0] || over[1] { t.Fatalf("overcount after the upgrade (claude, codex): %v", over) } var round, turns sql.NullInt64 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 { t.Fatalf("migrated row: round %v turns %v %v", round, turns, err) } if page := r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, `

    Used 10k tokens (4k cached)

    Earlier usage not shown

    `) || strings.Contains(page, "Questions:") { t.Fatalf("task page after the upgrade:\n%s", page) } } // A Claude answer's row from a runner before ProtocolSpend overcounts // (it read the session's running total): the task page leaves it out // and says so, and so does today's usage on Connections. From a runner // at ProtocolSpend it counts. func TestPagesSpendLeavesOutOvercount(t *testing.T) { for _, proto := range []int{wire.Protocol1, wire.Protocol2, wire.ProtocolSpend} { t.Run(strconv.Itoa(proto), func(t *testing.T) { r := newToolRig(t) if proto > wire.Protocol1 { gen := r.runner.Welcome.Generation r.runner.Close() h := primaryHello(gen) h.Protocol = proto p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, h) if err != nil { t.Fatal(err) } t.Cleanup(p.Close) r.runner = p } base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, _, _ := r.askableTask("o", base, cand) q, err := r.client.Ask(r.ctx, id, "What did you change?", "", "k1") if err != nil { t.Fatal(err) } r.expect(wire.FrameAsk) 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)}} r.answer("o-q", wire.AnswerReport{TaskID: id, QuestionID: q.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I fixed the typo.", Usage: used}) page := r.get(r.inst.Cookie(), "/tasks/"+id, 200) today, err := r.inst.Store.Chat().UsageToday(r.ctx, Owner) if err != nil { t.Fatal(err) } if proto < wire.ProtocolSpend { if !strings.Contains(page, `

    Earlier usage not shown

    `) || strings.Contains(page, "data-spend>") || strings.Contains(page, "data-spend-step=") || today["claude-a"] != 0 { t.Fatalf("an older runner's answer counted (today %v):\n%s", today, page) } return } if !strings.Contains(page, `

    Used 10k tokens (9k cached)

    `) || !strings.Contains(page, `
  • Questions: 10k tokens (9k cached)
  • `) || strings.Contains(page, "data-spend-note") || today["claude-a"] != 900 { t.Fatalf("a current runner's answer (today %v):\n%s", today, page) } }) } }