| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/thintest" |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | ) |
| 12 | |
| 13 | // TestHeadlessTurnBatching: three messages sent while a slow turn runs |
| 14 | // wait together, each in its own bubble. When the slow turn ends, one |
| 15 | // turn picks all three up; the coordinator gets them in order, as |
| 16 | // separate messages with their files, and answers once. The spend lines |
| 17 | // it logs are the turns and input tokens of the batch beside the same |
| 18 | // three messages sent one at a time. |
| 19 | func TestHeadlessTurnBatching(t *testing.T) { |
| 20 | env, inst, r := localEnv(t) |
| 21 | r.start(t) |
| 22 | s := open(t, env) |
| 23 | busy := s.send(t, "Take your time with this one. sleep:4000") |
| 24 | s.waitTurn(t, busy.Turn.ID, wire.TurnRunning) |
| 25 | notes := upload(t, s, "notes.md", "text/markdown", []byte("# Notes\n\nStep three fails.\n")) |
| 26 | sent := []wire.Sent{s.send(t, "alpha first"), sendWith(t, s, "bravo second", notes), s.send(t, "charlie third")} |
| 27 | batch := sent[0].Turn.ID |
| 28 | for i, m := range sent { |
| 29 | if m.Turn.ID != batch || m.Turn.ID == busy.Turn.ID || m.Turn.State != wire.TurnQueued { |
| 30 | t.Fatalf("message %d went to turn %s (%s), not the queued turn %s", i+1, m.Turn.ID, m.Turn.State, batch) |
| 31 | } |
| 32 | } |
| 33 | if ids := sent[2].Turn.MessageIDs; len(ids) != 3 || ids[0] != sent[0].Message.ID || ids[1] != sent[1].Message.ID || ids[2] != sent[2].Message.ID { |
| 34 | t.Fatalf("queued turn holds %v", ids) |
| 35 | } |
| 36 | // Each message keeps its own bubble, in order, in the queued turn; the |
| 37 | // quiet note waits under the latest. |
| 38 | page := inst.Get(t, "/conversation") |
| 39 | at := -1 |
| 40 | for i, m := range sent { |
| 41 | bubble := `data-message="` + m.Message.ID + `" data-turn-id="` + batch + `"` |
| 42 | n := strings.Index(page, bubble) |
| 43 | if n < 0 || n < at || strings.Count(page, `data-message="`+m.Message.ID+`"`) != 1 { |
| 44 | t.Fatalf("bubble %d missing, repeated or out of order", i+1) |
| 45 | } |
| 46 | at = n |
| 47 | } |
| 48 | const note = "<p equipo-card-note data-queued>" |
| 49 | if strings.Count(page, note) != 1 || strings.Index(page, note) < at { |
| 50 | t.Fatalf("queued note not once under the latest message") |
| 51 | } |
| 52 | s.waitTurn(t, busy.Turn.ID, wire.TurnReplied) |
| 53 | reply := replyOf(t, s, batch) |
| 54 | // Exactly one next turn: the batch, and no turn for any one message. |
| 55 | var turns int |
| 56 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_turns").Scan(&turns); err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | if turns != 2 { |
| 60 | t.Fatalf("%d turns for one slow message and three queued ones", turns) |
| 61 | } |
| 62 | s.conv.Locked(func(c *thintest.Conversation) { |
| 63 | if got := c.Turns[batch].MessageIDs; len(got) != 3 || len(c.Replies()) != 2 { |
| 64 | t.Fatalf("batch picked up %v; %d replies", got, len(c.Replies())) |
| 65 | } |
| 66 | }) |
| 67 | if page = inst.Get(t, "/conversation"); strings.Contains(page, note) { |
| 68 | t.Fatal("queued note still shows after the turn picked the messages up") |
| 69 | } |
| 70 | // Spend goes to the turn: one usage row for the batch beside the slow |
| 71 | // turn's own, none for any one message. |
| 72 | if rows := logSpend(t, inst, "batched", batch); rows != 1 || logSpend(t, inst, "slow", busy.Turn.ID) != 1 { |
| 73 | t.Fatalf("batch has %d usage rows", rows) |
| 74 | } |
| 75 | var usage int |
| 76 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'coordinator'").Scan(&usage); err != nil || usage != 2 { |
| 77 | t.Fatalf("%d coordinator usage rows for two turns: %v", usage, err) |
| 78 | } |
| 79 | // The coordinator's input: one frame naming each message apart, in |
| 80 | // order, with its file. |
| 81 | cmds := messageCommands(t, inst, batch) |
| 82 | if len(cmds) != 1 { |
| 83 | t.Fatalf("%d message commands for the batch", len(cmds)) |
| 84 | } |
| 85 | text, last := cmds[0].Text, -1 |
| 86 | for _, want := range []string{"Message 1 of 3:\nalpha first", "Message 2 of 3 (attached: notes.md):\nbravo second", "Message 3 of 3:\ncharlie third"} { |
| 87 | n := strings.Index(text, want) |
| 88 | if n <= last { |
| 89 | t.Fatalf("turn input lacks %q in order:\n%s", want, text) |
| 90 | } |
| 91 | last = n |
| 92 | } |
| 93 | if p := cmds[0].PersonText; len(p) != 3 || p[0] != "alpha first" || p[1] != "bravo second" || p[2] != "charlie third" { |
| 94 | t.Fatalf("person text %q", p) |
| 95 | } |
| 96 | if len(cmds[0].Attachments) != 1 || cmds[0].Attachments[0].ID != notes.ID { |
| 97 | t.Fatalf("attachments %+v", cmds[0].Attachments) |
| 98 | } |
| 99 | if want := "You sent 3 messages: 1/3 alpha first; 2/3 bravo second [notes.md]; 3/3 charlie third."; !strings.Contains(reply.Text, want) { |
| 100 | t.Fatalf("coordinator did not see three messages apart: %q", reply.Text) |
| 101 | } |
| 102 | // The same three words one at a time, each after the last reply: what |
| 103 | // the person pays when nothing is running to batch behind. |
| 104 | for i, text := range []string{"alpha first", "bravo second", "charlie third"} { |
| 105 | one := s.send(t, text) |
| 106 | replyOf(t, s, one.Turn.ID) |
| 107 | logSpend(t, inst, "alone "+string(rune('1'+i)), one.Turn.ID) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // messageCommands are the message frames the instance wrote for a turn. |
| 112 | func messageCommands(t *testing.T, inst *thintest.Instance, turn string) []wire.MessageCommand { |
| 113 | t.Helper() |
| 114 | rows, err := inst.DB.Writer().Query("SELECT body FROM runner_commands WHERE kind = ? ORDER BY seq", wire.FrameMessage) |
| 115 | if err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | defer rows.Close() |
| 119 | var out []wire.MessageCommand |
| 120 | for rows.Next() { |
| 121 | var body string |
| 122 | var m wire.MessageCommand |
| 123 | if err := rows.Scan(&body); err != nil || json.Unmarshal([]byte(body), &m) != nil { |
| 124 | t.Fatalf("command %v", err) |
| 125 | } |
| 126 | if m.TurnID == turn { |
| 127 | out = append(out, m) |
| 128 | } |
| 129 | } |
| 130 | return out |
| 131 | } |
| 132 | |
| 133 | // logSpend logs a coordinator turn's recorded usage (rows, input and |
| 134 | // cached input tokens) and returns its row count. |
| 135 | func logSpend(t *testing.T, inst *thintest.Instance, label, turn string) int64 { |
| 136 | t.Helper() |
| 137 | var rows, input, cached int64 |
| 138 | if err := inst.DB.Writer().QueryRow("SELECT count(*), coalesce(sum(input_tokens), 0), coalesce(sum(cached_input_tokens), 0) FROM chat_usage WHERE turn_id = ? AND role = 'coordinator'", turn).Scan(&rows, &input, &cached); err != nil { |
| 139 | t.Fatal(err) |
| 140 | } |
| 141 | if rows == 0 { |
| 142 | t.Fatalf("no usage recorded for turn %s", turn) |
| 143 | } |
| 144 | t.Logf("spend %s: turn %s, %d usage rows, %d input tokens, %d cached", label, turn, rows, input, cached) |
| 145 | return rows |
| 146 | } |
| 147 | |
| 148 | // TestHeadlessBatchAfterRefusedReply: when the instance cannot start the |
| 149 | // next turn, the reply that ended the slow one rolls back with it. The |
| 150 | // real runner is not told it was revoked: it reconnects, sends the reply |
| 151 | // again once the instance can take it, and the batch goes once. |
| 152 | func TestHeadlessBatchAfterRefusedReply(t *testing.T) { |
| 153 | env, inst, r := localEnv(t) |
| 154 | r.start(t) |
| 155 | s := open(t, env) |
| 156 | s.keep() |
| 157 | busy := s.send(t, "Take your time with this one. sleep:3000") |
| 158 | s.waitTurn(t, busy.Turn.ID, wire.TurnRunning) |
| 159 | a, b := s.send(t, "alpha first"), s.send(t, "bravo second") |
| 160 | db := inst.DB.Writer() |
| 161 | if _, err := db.Exec(`CREATE TRIGGER refuse_next BEFORE INSERT ON runner_commands WHEN NEW.kind = 'message' BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | for deadline := time.Now().Add(time.Minute); strings.Count(inst.Logs(), "refused") < 2; time.Sleep(100 * time.Millisecond) { |
| 165 | if time.Now().After(deadline) { |
| 166 | t.Fatal("the reply was never refused twice") |
| 167 | } |
| 168 | } |
| 169 | select { |
| 170 | case err := <-r.done: |
| 171 | t.Fatalf("the runner stopped: %v", err) |
| 172 | default: |
| 173 | } |
| 174 | if st, err := env.Client.Turn(s.ctx, busy.Turn.ID); err != nil || st.State != wire.TurnRunning { |
| 175 | t.Fatalf("slow turn %+v %v while its successor is refused", st, err) |
| 176 | } |
| 177 | if _, err := db.Exec(`DROP TRIGGER refuse_next`); err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | replyOf(t, s, busy.Turn.ID) |
| 181 | reply := replyOf(t, s, a.Turn.ID) |
| 182 | if b.Turn.ID != a.Turn.ID || !strings.Contains(reply.Text, "You sent 2 messages: 1/2 alpha first; 2/2 bravo second.") { |
| 183 | t.Fatalf("batch %s/%s answered %q", a.Turn.ID, b.Turn.ID, reply.Text) |
| 184 | } |
| 185 | if cmds := messageCommands(t, inst, a.Turn.ID); len(cmds) != 1 { |
| 186 | t.Fatalf("%d frames for the batch", len(cmds)) |
| 187 | } |
| 188 | } |
| 189 | |