package headless import ( "encoding/json" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // TestHeadlessTurnBatching: three messages sent while a slow turn runs // wait together, each in its own bubble. When the slow turn ends, one // turn picks all three up; the coordinator gets them in order, as // separate messages with their files, and answers once. The spend lines // it logs are the turns and input tokens of the batch beside the same // three messages sent one at a time. func TestHeadlessTurnBatching(t *testing.T) { env, inst, r := localEnv(t) r.start(t) s := open(t, env) busy := s.send(t, "Take your time with this one. sleep:4000") s.waitTurn(t, busy.Turn.ID, wire.TurnRunning) notes := upload(t, s, "notes.md", "text/markdown", []byte("# Notes\n\nStep three fails.\n")) sent := []wire.Sent{s.send(t, "alpha first"), sendWith(t, s, "bravo second", notes), s.send(t, "charlie third")} batch := sent[0].Turn.ID for i, m := range sent { if m.Turn.ID != batch || m.Turn.ID == busy.Turn.ID || m.Turn.State != wire.TurnQueued { t.Fatalf("message %d went to turn %s (%s), not the queued turn %s", i+1, m.Turn.ID, m.Turn.State, batch) } } 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 { t.Fatalf("queued turn holds %v", ids) } // Each message keeps its own bubble, in order, in the queued turn; the // quiet note waits under the latest. page := inst.Get(t, "/conversation") at := -1 for i, m := range sent { bubble := `data-message="` + m.Message.ID + `" data-turn-id="` + batch + `"` n := strings.Index(page, bubble) if n < 0 || n < at || strings.Count(page, `data-message="`+m.Message.ID+`"`) != 1 { t.Fatalf("bubble %d missing, repeated or out of order", i+1) } at = n } const note = "

" if strings.Count(page, note) != 1 || strings.Index(page, note) < at { t.Fatalf("queued note not once under the latest message") } s.waitTurn(t, busy.Turn.ID, wire.TurnReplied) reply := replyOf(t, s, batch) // Exactly one next turn: the batch, and no turn for any one message. var turns int if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_turns").Scan(&turns); err != nil { t.Fatal(err) } if turns != 2 { t.Fatalf("%d turns for one slow message and three queued ones", turns) } s.conv.Locked(func(c *thintest.Conversation) { if got := c.Turns[batch].MessageIDs; len(got) != 3 || len(c.Replies()) != 2 { t.Fatalf("batch picked up %v; %d replies", got, len(c.Replies())) } }) if page = inst.Get(t, "/conversation"); strings.Contains(page, note) { t.Fatal("queued note still shows after the turn picked the messages up") } // Spend goes to the turn: one usage row for the batch beside the slow // turn's own, none for any one message. if rows := logSpend(t, inst, "batched", batch); rows != 1 || logSpend(t, inst, "slow", busy.Turn.ID) != 1 { t.Fatalf("batch has %d usage rows", rows) } var usage int if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'coordinator'").Scan(&usage); err != nil || usage != 2 { t.Fatalf("%d coordinator usage rows for two turns: %v", usage, err) } // The coordinator's input: one frame naming each message apart, in // order, with its file. cmds := messageCommands(t, inst, batch) if len(cmds) != 1 { t.Fatalf("%d message commands for the batch", len(cmds)) } text, last := cmds[0].Text, -1 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"} { n := strings.Index(text, want) if n <= last { t.Fatalf("turn input lacks %q in order:\n%s", want, text) } last = n } if p := cmds[0].PersonText; len(p) != 3 || p[0] != "alpha first" || p[1] != "bravo second" || p[2] != "charlie third" { t.Fatalf("person text %q", p) } if len(cmds[0].Attachments) != 1 || cmds[0].Attachments[0].ID != notes.ID { t.Fatalf("attachments %+v", cmds[0].Attachments) } 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) { t.Fatalf("coordinator did not see three messages apart: %q", reply.Text) } // The same three words one at a time, each after the last reply: what // the person pays when nothing is running to batch behind. for i, text := range []string{"alpha first", "bravo second", "charlie third"} { one := s.send(t, text) replyOf(t, s, one.Turn.ID) logSpend(t, inst, "alone "+string(rune('1'+i)), one.Turn.ID) } } // messageCommands are the message frames the instance wrote for a turn. func messageCommands(t *testing.T, inst *thintest.Instance, turn string) []wire.MessageCommand { t.Helper() rows, err := inst.DB.Writer().Query("SELECT body FROM runner_commands WHERE kind = ? ORDER BY seq", wire.FrameMessage) if err != nil { t.Fatal(err) } defer rows.Close() var out []wire.MessageCommand for rows.Next() { var body string var m wire.MessageCommand if err := rows.Scan(&body); err != nil || json.Unmarshal([]byte(body), &m) != nil { t.Fatalf("command %v", err) } if m.TurnID == turn { out = append(out, m) } } return out } // logSpend logs a coordinator turn's recorded usage (rows, input and // cached input tokens) and returns its row count. func logSpend(t *testing.T, inst *thintest.Instance, label, turn string) int64 { t.Helper() var rows, input, cached int64 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 { t.Fatal(err) } if rows == 0 { t.Fatalf("no usage recorded for turn %s", turn) } t.Logf("spend %s: turn %s, %d usage rows, %d input tokens, %d cached", label, turn, rows, input, cached) return rows } // TestHeadlessBatchAfterRefusedReply: when the instance cannot start the // next turn, the reply that ended the slow one rolls back with it. The // real runner is not told it was revoked: it reconnects, sends the reply // again once the instance can take it, and the batch goes once. func TestHeadlessBatchAfterRefusedReply(t *testing.T) { env, inst, r := localEnv(t) r.start(t) s := open(t, env) s.keep() busy := s.send(t, "Take your time with this one. sleep:3000") s.waitTurn(t, busy.Turn.ID, wire.TurnRunning) a, b := s.send(t, "alpha first"), s.send(t, "bravo second") db := inst.DB.Writer() 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 { t.Fatal(err) } for deadline := time.Now().Add(time.Minute); strings.Count(inst.Logs(), "refused") < 2; time.Sleep(100 * time.Millisecond) { if time.Now().After(deadline) { t.Fatal("the reply was never refused twice") } } select { case err := <-r.done: t.Fatalf("the runner stopped: %v", err) default: } if st, err := env.Client.Turn(s.ctx, busy.Turn.ID); err != nil || st.State != wire.TurnRunning { t.Fatalf("slow turn %+v %v while its successor is refused", st, err) } if _, err := db.Exec(`DROP TRIGGER refuse_next`); err != nil { t.Fatal(err) } replyOf(t, s, busy.Turn.ID) reply := replyOf(t, s, a.Turn.ID) if b.Turn.ID != a.Turn.ID || !strings.Contains(reply.Text, "You sent 2 messages: 1/2 alpha first; 2/2 bravo second.") { t.Fatalf("batch %s/%s answered %q", a.Turn.ID, b.Turn.ID, reply.Text) } if cmds := messageCommands(t, inst, a.Turn.ID); len(cmds) != 1 { t.Fatalf("%d frames for the batch", len(cmds)) } }