| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "slices" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/equipo" |
| 18 | "amadan.net/oficina/equipo/internal/runner/thin" |
| 19 | "amadan.net/oficina/equipo/internal/thintest" |
| 20 | "amadan.net/oficina/equipo/internal/wire" |
| 21 | ) |
| 22 | |
| 23 | // TestHeadlessAssistant runs the Assistant's scenarios against a fresh |
| 24 | // local instance and runner with the fake CLI in real bubblewrap, through |
| 25 | // /api/v1/assistant as Base calls it. |
| 26 | func TestHeadlessAssistant(t *testing.T) { |
| 27 | t.Run("conversation", func(t *testing.T) { |
| 28 | env, inst, r := localEnv(t) |
| 29 | r.opts.NoMoveIn = true |
| 30 | r.start(t) |
| 31 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| 32 | defer cancel() |
| 33 | a := env.Client.Assistant() |
| 34 | |
| 35 | first, err := a.Send(ctx, "Hello, assistant. tool:look", key()) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | // The Coordinator, meanwhile, in its own lane and session. |
| 40 | coord := open(t, env) |
| 41 | other := coord.send(t, "Hello, coordinator.") |
| 42 | reply := assistantReply(t, ctx, a, first.Turn.ID) |
| 43 | if !strings.Contains(reply.Text, "Turn 1, fresh session") { |
| 44 | t.Fatalf("first Assistant reply %q", reply.Text) |
| 45 | } |
| 46 | coord.waitTurn(t, other.Turn.ID, wire.TurnReplied) |
| 47 | if got := coord.reply(t, other.Turn.ID); !strings.Contains(got.Text, "Turn 1, fresh session") { |
| 48 | t.Fatalf("the Coordinator answered from another session: %q", got.Text) |
| 49 | } |
| 50 | |
| 51 | second, err := a.Send(ctx, "And again.", key()) |
| 52 | if err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | if reply = assistantReply(t, ctx, a, second.Turn.ID); !strings.Contains(reply.Text, "Turn 2, resumed session") { |
| 56 | t.Fatalf("second Assistant reply %q", reply.Text) |
| 57 | } |
| 58 | // The Coordinator's routes saw none of it. |
| 59 | page, err := env.Client.Messages(ctx, "", 50) |
| 60 | if err != nil || len(page.Items) != 2 { |
| 61 | t.Fatalf("coordinator messages %+v %v", page, err) |
| 62 | } |
| 63 | |
| 64 | // The runner launched the Assistant with the assist action: the |
| 65 | // session started at all only because the CLI reported exactly the |
| 66 | // seven tools that action pins (claude.ValidateInit), and its look call |
| 67 | // reached the instance in the Assistant's lane. It kept its own |
| 68 | // session beside the Coordinator's. |
| 69 | var looks int |
| 70 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE name = ? AND lane = ? AND turn_id = ?", wire.ToolLook, wire.LaneAssistant, first.Turn.ID).Scan(&looks); err != nil || looks != 1 { |
| 71 | t.Fatalf("look calls in the Assistant lane %d %v", looks, err) |
| 72 | } |
| 73 | state, err := sql.Open("sqlite", "file:"+filepath.Join(r.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| 74 | if err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | defer state.Close() |
| 78 | sessions := map[string]string{} |
| 79 | rows, err := state.Query("SELECT lane, session_id FROM sessions_lane WHERE person = ?", thintest.Owner) |
| 80 | if err != nil { |
| 81 | t.Fatal(err) |
| 82 | } |
| 83 | defer rows.Close() |
| 84 | for rows.Next() { |
| 85 | var lane, id string |
| 86 | if err := rows.Scan(&lane, &id); err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | sessions[lane] = id |
| 90 | } |
| 91 | if err := rows.Err(); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | if len(sessions) != 2 || sessions[wire.LaneAssistant] == "" || sessions[wire.LaneCoordinator] == "" || sessions[wire.LaneAssistant] == sessions[wire.LaneCoordinator] { |
| 95 | t.Fatalf("sessions %v", sessions) |
| 96 | } |
| 97 | }) |
| 98 | |
| 99 | // The Assistant looks at what Base offers and runs one operation, out |
| 100 | // of the tool call's transaction, through the real runner's tools. |
| 101 | t.Run("what_can_i_do", func(t *testing.T) { |
| 102 | env, inst, r := localEnv(t) |
| 103 | base := thintest.StartFakeBase(t) |
| 104 | inst.AssistantHosts = []string{base.Origin} |
| 105 | inst.Restart(t) |
| 106 | r.opts.NoMoveIn = true |
| 107 | r.start(t) |
| 108 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| 109 | defer cancel() |
| 110 | a := env.Client.Assistant() |
| 111 | if _, err := a.PutHost(ctx, base.Origin, base.Token); err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | sent, err := a.Send(ctx, "What can I do? tool:look tool:use:base_apps|{}", key()) |
| 115 | if err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" { |
| 119 | t.Fatal("no reply") |
| 120 | } |
| 121 | if lists, apps := base.Calls(""), base.Calls("base_apps"); lists != 1 || apps != 1 { |
| 122 | t.Fatalf("Base saw %d lists and %d base_apps calls", lists, apps) |
| 123 | } |
| 124 | var done int |
| 125 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE turn_id = ? AND lane = ? AND state = 'done' AND name IN (?, ?)", sent.Turn.ID, wire.LaneAssistant, wire.ToolLook, wire.ToolUse).Scan(&done); err != nil || done != 2 { |
| 126 | t.Fatalf("%d calls done %v", done, err) |
| 127 | } |
| 128 | }) |
| 129 | |
| 130 | // "Can we fix a bug in Tito?": the Assistant hands the person's words |
| 131 | // to the team; the Coordinator, in its own lane, records and starts a |
| 132 | // task on the test repository; when the work stops on its own the |
| 133 | // Assistant hears of it in a team_update turn and tells the person. |
| 134 | // The fake Coordinator follows tool words wherever it reads them, so |
| 135 | // the Assistant's context (reference, beside the person's words) |
| 136 | // steers it here. |
| 137 | t.Run("tito_bug", func(t *testing.T) { |
| 138 | env, inst, r := localEnv(t) |
| 139 | r.opts.NoMoveIn = true |
| 140 | r.start(t) |
| 141 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) |
| 142 | defer cancel() |
| 143 | a := env.Client.Assistant() |
| 144 | coord := open(t, env) |
| 145 | input, _ := json.Marshal(map[string]string{"words": "Login is broken", "title": "Fixing the sign-in page", "context": "tool:record_task:oficina/sample|Fix the login|Login is broken.\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes\nThat is all."}) |
| 146 | // The Assistant's fake would fill in $task itself: the JSON spells it |
| 147 | // so it reaches the Coordinator as written. |
| 148 | sent, err := a.Send(ctx, "Can we fix a bug in Tito? Login is broken tool:use:team_request|"+strings.ReplaceAll(string(input), "$task", `\u0024task`), key()) |
| 149 | if err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" { |
| 153 | t.Fatal("no reply") |
| 154 | } |
| 155 | var turn, words string |
| 156 | if err := inst.DB.Writer().QueryRow("SELECT m.turn_id, m.text FROM chat_handoffs h JOIN chat_messages m ON m.id = h.message_id WHERE h.assistant_turn = ?", sent.Turn.ID).Scan(&turn, &words); err != nil || words != "Login is broken" { |
| 157 | t.Fatalf("hand-off message %q %v", words, err) |
| 158 | } |
| 159 | // The thread's task is the job's: recorded in its lane, its task card |
| 160 | // in the thread, never in the person's own conversation (J4). |
| 161 | var id string |
| 162 | var leaked []wire.Card |
| 163 | coord.wait(t, "the thread's task", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 164 | if leaked = cards(c, turn, wire.CardTask); len(leaked) > 0 { |
| 165 | return true |
| 166 | } |
| 167 | if id == "" { |
| 168 | _ = inst.DB.Writer().QueryRow("SELECT k.id FROM chat_tasks k JOIN chat_turns r ON r.id = k.turn_id WHERE k.turn_id = ? AND k.lane = r.lane AND k.lane LIKE 'job:%'", turn).Scan(&id) |
| 169 | } |
| 170 | _, ok := c.Tasks[id] |
| 171 | return ok |
| 172 | }) |
| 173 | if len(leaked) > 0 { |
| 174 | t.Fatalf("the thread's task card is in their conversation: %+v", leaked) |
| 175 | } |
| 176 | request, _ := handedOff(t, inst, sent.Turn.ID) |
| 177 | asJob(t, ctx, env, inst, r, request, turn, "Fixing the sign-in page") |
| 178 | var created bool |
| 179 | if err := inst.DB.Writer().QueryRow("SELECT created FROM chat_handoff_tasks WHERE task_id = ?", id).Scan(&created); err != nil || !created { |
| 180 | t.Fatalf("the hand-off does not follow its task: %v %v", created, err) |
| 181 | } |
| 182 | if done := coord.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed); done.State != wire.StepDone { |
| 183 | t.Fatalf("engineering %+v", done) |
| 184 | } |
| 185 | deadline := time.Now().Add(5 * time.Minute) |
| 186 | for { |
| 187 | snap, err := a.Snapshot(ctx) |
| 188 | if err != nil { |
| 189 | t.Fatal(err) |
| 190 | } |
| 191 | replies, update := 0, "" |
| 192 | for _, m := range snap.Messages { |
| 193 | if m.Role == wire.RoleAssistant { |
| 194 | replies++ |
| 195 | } |
| 196 | } |
| 197 | for _, v := range snap.Turns { |
| 198 | if v.Kind == wire.TurnTeamUpdate && v.State == wire.TurnReplied { |
| 199 | update = v.ReplyID |
| 200 | } |
| 201 | } |
| 202 | if replies == 2 && update != "" { |
| 203 | noQuestions(t, snap) |
| 204 | break |
| 205 | } |
| 206 | if time.Now().After(deadline) { |
| 207 | t.Fatalf("no reply from a team_update turn: %+v", snap.Turns) |
| 208 | } |
| 209 | time.Sleep(200 * time.Millisecond) |
| 210 | } |
| 211 | }) |
| 212 | |
| 213 | // "Build me a quick website" (spec §7, 4): the hand-off's website is |
| 214 | // merged on the person's go-ahead, then the Assistant lane asks to |
| 215 | // publish it with its preview, which answers while the card waits; |
| 216 | // Publish ends with the site's public address on the card. It needs |
| 217 | // the runner paired with a site host and a preview host, so it runs |
| 218 | // only where EQUIPO_SITE_HOST and EQUIPO_PREVIEW_HOST (with |
| 219 | // EQUIPO_CARLOS_PATH and EQUIPO_PREVIEW_CREDENTIAL_PATH when not the |
| 220 | // defaults) say so. |
| 221 | t.Run("quick_website", func(t *testing.T) { |
| 222 | // Since places (2026-11-26) a site publishes only to a place an |
| 223 | // owner confirmed on a place card first; this live run still taps |
| 224 | // Publish alone, so it waits for its place-card step (slice 3). |
| 225 | if os.Getenv("EQUIPO_LIVE_PLACES") == "" || os.Getenv("EQUIPO_PREVIEW_HOST") == "" { |
| 226 | t.Skip("needs a confirmed place: set EQUIPO_LIVE_PLACES and EQUIPO_PREVIEW_HOST") |
| 227 | } |
| 228 | env, inst, r := localEnv(t) |
| 229 | r.cfg.PreviewHost = os.Getenv("EQUIPO_PREVIEW_HOST") |
| 230 | r.cfg.CarlosPath, r.cfg.PreviewCredentialPath = os.Getenv("EQUIPO_CARLOS_PATH"), os.Getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH") |
| 231 | r.opts.NoMoveIn = true |
| 232 | r.start(t) |
| 233 | ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute) |
| 234 | defer cancel() |
| 235 | a := env.Client.Assistant() |
| 236 | input, _ := json.Marshal(map[string]string{"words": "Build me a quick website", "title": "Building your website", "context": `tool:record_task:oficina/sample|Quick website|A one page site.` + "\n" + `tool:start_task:$task|Build it. create:site/index.html|<h1>Hello</h1>; create:release/preview.json|{"output": "site"}` + "\nThat is all."}) |
| 237 | sent, err := a.Send(ctx, "Build me a quick website tool:use:team_request|"+strings.ReplaceAll(string(input), "$task", `\u0024task`), key()) |
| 238 | if err != nil { |
| 239 | t.Fatal(err) |
| 240 | } |
| 241 | if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" { |
| 242 | t.Fatal("no reply") |
| 243 | } |
| 244 | offers := func(c wire.AssistantCard, value string) bool { |
| 245 | return c.Kind == wire.CardOutcome && slices.ContainsFunc(c.Options, func(o wire.CardOption) bool { return o.Value == value }) |
| 246 | } |
| 247 | // card waits for the Assistant card that matches; Merge on a |
| 248 | // go-ahead along the way, as the person would. |
| 249 | card := func(what string, match func(wire.AssistantCard) bool) wire.AssistantCard { |
| 250 | t.Helper() |
| 251 | deadline := time.Now().Add(10 * time.Minute) |
| 252 | for { |
| 253 | snap, err := a.Snapshot(ctx) |
| 254 | if err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | for _, c := range snap.Cards { |
| 258 | if match(c) { |
| 259 | return c |
| 260 | } |
| 261 | if c.State == wire.CardOpen && offers(c, wire.ChoiceMerge) { |
| 262 | if _, err := a.Answer(ctx, c.ID, wire.ChoiceMerge, c.Revision); err != nil { |
| 263 | t.Fatalf("merge %v", err) |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | if time.Now().After(deadline) { |
| 268 | t.Fatalf("no %s: %+v", what, snap.Cards) |
| 269 | } |
| 270 | time.Sleep(time.Second) |
| 271 | } |
| 272 | } |
| 273 | ask := card("publish card", func(c wire.AssistantCard) bool { return c.State == wire.CardOpen && offers(c, wire.ChoicePublish) }) |
| 274 | if ask.Question != equipo.RunnerCopy("assistant.outcome.publish_question") || len(ask.Links) != 1 { |
| 275 | t.Fatalf("publish card %+v", ask) |
| 276 | } |
| 277 | res, err := http.Get(ask.Links[0].URL) |
| 278 | if err != nil { |
| 279 | t.Fatalf("preview %v", err) |
| 280 | } |
| 281 | res.Body.Close() |
| 282 | if res.StatusCode != http.StatusOK { |
| 283 | t.Fatalf("preview %s answered %d", ask.Links[0].URL, res.StatusCode) |
| 284 | } |
| 285 | if _, err := a.Answer(ctx, ask.ID, wire.ChoicePublish, ask.Revision); err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | live := card("published site", func(c wire.AssistantCard) bool { |
| 289 | return c.ID == ask.ID && slices.ContainsFunc(c.Links, func(l wire.CardLink) bool { return strings.HasPrefix(l.URL, "https://site-") }) |
| 290 | }) |
| 291 | // The published line, not publishing or sent but unconfirmed. |
| 292 | if live.State != wire.CardAnswered || live.Result != equipo.RunnerCopy("assistant.outcome.publish_published") { |
| 293 | t.Fatalf("published card %+v", live) |
| 294 | } |
| 295 | request, thread := handedOff(t, inst, sent.Turn.ID) |
| 296 | asJob(t, ctx, env, inst, r, request, thread, "Building your website") |
| 297 | snap, err := a.Snapshot(ctx) |
| 298 | if err != nil { |
| 299 | t.Fatal(err) |
| 300 | } |
| 301 | noQuestions(t, snap) |
| 302 | }) |
| 303 | |
| 304 | // "Build me a website about disability benefits": the job's thread |
| 305 | // asks what it should be about, and the Assistant answers from the |
| 306 | // conversation itself (team_reply in its team_update turn), saying |
| 307 | // nothing; the answer reaches the thread as the person's, and the work |
| 308 | // goes on. The person never sees a question. |
| 309 | t.Run("question_from_context", func(t *testing.T) { |
| 310 | env, inst, r := localEnv(t) |
| 311 | r.opts.NoMoveIn = true |
| 312 | r.start(t) |
| 313 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) |
| 314 | defer cancel() |
| 315 | a := env.Client.Assistant() |
| 316 | const words, title, answer = "Build me a website about disability benefits", "Building your website", "Disability benefits" |
| 317 | // The thread asks; once answered it records and starts the work |
| 318 | // (onanswer:, rot13, so the first turn does not follow it). |
| 319 | later := rot13("tool:record_task:oficina/sample|Disability benefits site|A site about disability benefits. tool:start_task:$task|Build it. stepsleep:60000 edit:README.md|teh panes|the panes") |
| 320 | input, _ := json.Marshal(map[string]string{"words": words, "title": title, "context": "tool:ask_person:What should the website be about?|" + answer + "|Something else\nonanswer:" + later + "\nThat is all."}) |
| 321 | sent, err := a.Send(ctx, words+" tool:use:team_request|"+string(input), key()) |
| 322 | if err != nil { |
| 323 | t.Fatal(err) |
| 324 | } |
| 325 | if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" { |
| 326 | t.Fatal("no reply") |
| 327 | } |
| 328 | request, thread := handedOff(t, inst, sent.Turn.ID) |
| 329 | lane := wire.JobLane(request) |
| 330 | // The team_update that told the Assistant of the question. |
| 331 | quietUpdate(t, inst, request, "team_reply", "answered") |
| 332 | var choice string |
| 333 | if err := inst.DB.Writer().QueryRow("SELECT coalesce(choice, '') FROM chat_cards WHERE kind = ? AND lane = ?", wire.CardQuestion, lane).Scan(&choice); err != nil || choice != answer { |
| 334 | t.Fatalf("the thread's question answered %q %v", choice, err) |
| 335 | } |
| 336 | var n int |
| 337 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages WHERE lane = ? AND role = ? AND text = ?", lane, wire.RolePerson, answer).Scan(&n); err != nil || n != 1 { |
| 338 | t.Fatalf("%d answers in the thread %v", n, err) |
| 339 | } |
| 340 | recorded(t, inst, lane) |
| 341 | jobMoves(t, ctx, a, request, title) |
| 342 | asJob(t, ctx, env, inst, r, request, thread, title) |
| 343 | snap, err := a.Snapshot(ctx) |
| 344 | if err != nil { |
| 345 | t.Fatal(err) |
| 346 | } |
| 347 | noQuestions(t, snap) |
| 348 | }) |
| 349 | |
| 350 | // A job that stops before any work starts is pushed through: the |
| 351 | // first team_update nudges it once with the person's own words, which |
| 352 | // the thread gets again with the Assistant's context; the work starts |
| 353 | // and the person hears nothing of the stop. |
| 354 | // The Assistant's reply streams on either provider: its first text |
| 355 | // reaches /api/v1/assistant/events as a delta while the turn is still |
| 356 | // running, well before the reply message that replaces the draft. |
| 357 | t.Run("streamed", func(t *testing.T) { |
| 358 | for _, provider := range []string{"claude", "codex"} { |
| 359 | t.Run(provider, func(t *testing.T) { |
| 360 | env, _, r := localEnv(t) |
| 361 | r.opts.NoMoveIn = true |
| 362 | if provider == "codex" { |
| 363 | r.addAccount(t, "codex", "codex-1", thintest.Owner) |
| 364 | r.only(t, "codex-1") |
| 365 | } |
| 366 | r.start(t) |
| 367 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| 368 | defer cancel() |
| 369 | a := env.Client.Assistant() |
| 370 | snap, err := a.Snapshot(ctx) |
| 371 | if err != nil { |
| 372 | t.Fatal(err) |
| 373 | } |
| 374 | s, err := a.Open(ctx, snap.Cursor) |
| 375 | if err != nil { |
| 376 | t.Fatal(err) |
| 377 | } |
| 378 | defer s.Close() |
| 379 | // The fake pauses two seconds after its first words. |
| 380 | sent, err := a.Send(ctx, "Hello there. sleep:2000", key()) |
| 381 | if err != nil { |
| 382 | t.Fatal(err) |
| 383 | } |
| 384 | var delta, reply time.Time |
| 385 | for reply.IsZero() { |
| 386 | select { |
| 387 | case e, ok := <-s.Events: |
| 388 | if !ok { |
| 389 | t.Fatal("the Assistant's stream ended") |
| 390 | } |
| 391 | var m wire.Message |
| 392 | switch { |
| 393 | case e.Type == wire.EventDelta && e.TurnID == sent.Turn.ID && delta.IsZero(): |
| 394 | delta = time.Now() |
| 395 | case e.Type == wire.EventMessage && json.Unmarshal(e.Data, &m) == nil && m.TurnID == sent.Turn.ID && m.Role == wire.RoleAssistant: |
| 396 | reply = time.Now() |
| 397 | } |
| 398 | case <-ctx.Done(): |
| 399 | t.Fatal("no reply") |
| 400 | } |
| 401 | } |
| 402 | if delta.IsZero() { |
| 403 | t.Fatalf("on %s no delta came before the reply", provider) |
| 404 | } |
| 405 | if gap := reply.Sub(delta); gap < time.Second { |
| 406 | t.Fatalf("on %s the first delta came only %v before the reply", provider, gap) |
| 407 | } |
| 408 | }) |
| 409 | } |
| 410 | }) |
| 411 | |
| 412 | t.Run("nudged_through", func(t *testing.T) { |
| 413 | env, inst, r := localEnv(t) |
| 414 | r.opts.NoMoveIn = true |
| 415 | r.start(t) |
| 416 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) |
| 417 | defer cancel() |
| 418 | a := env.Client.Assistant() |
| 419 | const title = "Making the benefits page" |
| 420 | // The nudge's context, from the person's words (nudge:, rot13), is |
| 421 | // what records and starts the work; the hand-off's does nothing. |
| 422 | words := "Please make the benefits page nudge:" + rot13("tool:record_task:oficina/sample|Benefits page|A page about benefits. tool:start_task:$task|Build it. stepsleep:60000 edit:README.md|teh panes|the panes") |
| 423 | input, _ := json.Marshal(map[string]string{"words": words, "title": title, "context": "That is all."}) |
| 424 | sent, err := a.Send(ctx, words+" tool:use:team_request|"+string(input), key()) |
| 425 | if err != nil { |
| 426 | t.Fatal(err) |
| 427 | } |
| 428 | if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" { |
| 429 | t.Fatal("no reply") |
| 430 | } |
| 431 | request, thread := handedOff(t, inst, sent.Turn.ID) |
| 432 | lane := wire.JobLane(request) |
| 433 | quietUpdate(t, inst, request, "team_nudge", "nudged") |
| 434 | recorded(t, inst, lane) |
| 435 | var nudges, actions, again int |
| 436 | if err := inst.DB.Writer().QueryRow("SELECT nudges FROM chat_handoffs WHERE id = ?", request).Scan(&nudges); err != nil { |
| 437 | t.Fatal(err) |
| 438 | } |
| 439 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_handoff_actions WHERE handoff_id = ? AND kind = 'nudge'", request).Scan(&actions); err != nil { |
| 440 | t.Fatal(err) |
| 441 | } |
| 442 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages WHERE lane = ? AND role = ? AND text = ?", lane, wire.RolePerson, words).Scan(&again); err != nil { |
| 443 | t.Fatal(err) |
| 444 | } |
| 445 | if nudges != 1 || actions != 1 || again != 2 { |
| 446 | t.Fatalf("%d nudges, %d nudge actions, the words %d times in the thread", nudges, actions, again) |
| 447 | } |
| 448 | if job := jobMoves(t, ctx, a, request, title); job.State != wire.JobWorking { |
| 449 | t.Fatalf("the job %+v", job) |
| 450 | } |
| 451 | asJob(t, ctx, env, inst, r, request, thread, title) |
| 452 | }) |
| 453 | |
| 454 | // warm_start: after a restart under a new Assistant rule (its old |
| 455 | // session cannot resume), the runner starts the person's Assistant |
| 456 | // process and session before their first message, on either |
| 457 | // provider, sending the model nothing: the first turn finds it up |
| 458 | // (cold=false) and its first prompt is the process's first. A person |
| 459 | // whose Assistant was never used is not warmed, and a warm process no |
| 460 | // turn uses closes after WarmIdle. |
| 461 | t.Run("warm_start", func(t *testing.T) { |
| 462 | for _, provider := range []string{"claude", "codex"} { |
| 463 | t.Run(provider, func(t *testing.T) { |
| 464 | env, _, r := localEnv(t) |
| 465 | r.opts.NoMoveIn = true |
| 466 | if provider == "codex" { |
| 467 | r.addAccount(t, "codex", "codex-1", thintest.Owner) |
| 468 | r.only(t, "codex-1") |
| 469 | } |
| 470 | logs := &lockedBuffer{} |
| 471 | r.opts.Logger = slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})) |
| 472 | r.start(t) |
| 473 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| 474 | defer cancel() |
| 475 | a := env.Client.Assistant() |
| 476 | first, err := a.Send(ctx, "Hello.", key()) |
| 477 | if err != nil { |
| 478 | t.Fatal(err) |
| 479 | } |
| 480 | assistantReply(t, ctx, a, first.Turn.ID) |
| 481 | if line := phaseLine(t, logs, first.Turn.ID); !strings.Contains(line, "cold=true") { |
| 482 | t.Fatalf("the first turn ever was warm: %s", line) |
| 483 | } |
| 484 | if strings.Contains(logs.String(), `msg="assistant warm"`) { |
| 485 | t.Fatalf("warmed an Assistant nobody had used:\n%s", logs.String()) |
| 486 | } |
| 487 | r.stop(t) |
| 488 | state, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db")) |
| 489 | if err != nil { |
| 490 | t.Fatal(err) |
| 491 | } |
| 492 | if _, err = state.Exec("UPDATE sessions_lane SET account = account || '-old' WHERE lane = ?", wire.LaneAssistant); err != nil { |
| 493 | t.Fatal(err) |
| 494 | } |
| 495 | state.Close() |
| 496 | r.start(t) |
| 497 | warmed(t, logs, 1) |
| 498 | second, err := a.Send(ctx, "And again.", key()) |
| 499 | if err != nil { |
| 500 | t.Fatal(err) |
| 501 | } |
| 502 | reply := assistantReply(t, ctx, a, second.Turn.ID) |
| 503 | if line := phaseLine(t, logs, second.Turn.ID); !strings.Contains(line, "cold=false") { |
| 504 | t.Fatalf("the first turn after the warm-up started cold: %s", line) |
| 505 | } |
| 506 | want := map[string]string{"claude": "Turn 1, fresh session, process turn 1.", "codex": "Turn 1, fresh thread."}[provider] |
| 507 | if !strings.Contains(reply.Text, want) { |
| 508 | t.Fatalf("the warm process was not the turn's, fresh and unprompted: %q", reply.Text) |
| 509 | } |
| 510 | |
| 511 | r.stop(t) |
| 512 | r.opts.Claude.WarmIdle = 2 * time.Second |
| 513 | r.start(t) |
| 514 | warmed(t, logs, 2) |
| 515 | time.Sleep(4 * time.Second) |
| 516 | third, err := a.Send(ctx, "Still there?", key()) |
| 517 | if err != nil { |
| 518 | t.Fatal(err) |
| 519 | } |
| 520 | assistantReply(t, ctx, a, third.Turn.ID) |
| 521 | if line := phaseLine(t, logs, third.Turn.ID); !strings.Contains(line, "cold=true") { |
| 522 | t.Fatalf("an unused warm process outlived WarmIdle: %s", line) |
| 523 | } |
| 524 | }) |
| 525 | } |
| 526 | }) |
| 527 | |
| 528 | // glance: a greeting has none. Once the person's glance harness is |
| 529 | // warm (after their first turn), the next message's glance reaches |
| 530 | // Base's stream before the reply's first words, on either provider: |
| 531 | // the small model's line, cleaned, for that turn. Nothing of it is stored, and a glance |
| 532 | // that comes too late (glanceslow) is not sent at all. |
| 533 | t.Run("glance", func(t *testing.T) { |
| 534 | for _, provider := range []string{"claude", "codex"} { |
| 535 | t.Run(provider, func(t *testing.T) { |
| 536 | env, inst, r := localEnv(t) |
| 537 | r.opts.NoMoveIn = true |
| 538 | if provider == "codex" { |
| 539 | r.addAccount(t, "codex", "codex-1", thintest.Owner) |
| 540 | r.only(t, "codex-1") |
| 541 | } |
| 542 | logs := &lockedBuffer{} |
| 543 | r.opts.Logger = slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})) |
| 544 | r.start(t) |
| 545 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| 546 | defer cancel() |
| 547 | a := env.Client.Assistant() |
| 548 | first, err := a.Send(ctx, "Hello.", key()) |
| 549 | if err != nil { |
| 550 | t.Fatal(err) |
| 551 | } |
| 552 | assistantReply(t, ctx, a, first.Turn.ID) |
| 553 | // A greeting has no glance: its reply is the answer. |
| 554 | if line := phaseLine(t, logs, first.Turn.ID); !strings.Contains(line, "glance=small_talk") { |
| 555 | t.Fatalf("a greeting's phase line %s", line) |
| 556 | } |
| 557 | deadline := time.Now().Add(60 * time.Second) |
| 558 | for !strings.Contains(logs.String(), `msg="assistant glance warm" outcome=warm`) { |
| 559 | if time.Now().After(deadline) { |
| 560 | t.Fatalf("the glance never warmed:\n%s", logs.String()) |
| 561 | } |
| 562 | time.Sleep(50 * time.Millisecond) |
| 563 | } |
| 564 | snap, err := a.Snapshot(ctx) |
| 565 | if err != nil { |
| 566 | t.Fatal(err) |
| 567 | } |
| 568 | s, err := a.Open(ctx, snap.Cursor) |
| 569 | if err != nil { |
| 570 | t.Fatal(err) |
| 571 | } |
| 572 | defer s.Close() |
| 573 | // The reply's first words wait a second (pause:). |
| 574 | sent, err := a.Send(ctx, "Could you look at my website? pause:1000", key()) |
| 575 | if err != nil { |
| 576 | t.Fatal(err) |
| 577 | } |
| 578 | var order []string |
| 579 | var glance wire.Glance |
| 580 | for !slices.Contains(order, "message") { |
| 581 | select { |
| 582 | case e, ok := <-s.Events: |
| 583 | if !ok { |
| 584 | t.Fatal("the Assistant's stream ended") |
| 585 | } |
| 586 | var m wire.Message |
| 587 | switch { |
| 588 | case e.Type == wire.EventGlance && e.TurnID == sent.Turn.ID: |
| 589 | order = append(order, "glance") |
| 590 | json.Unmarshal(e.Data, &glance) |
| 591 | case e.Type == wire.EventDelta && e.TurnID == sent.Turn.ID && !slices.Contains(order, "delta"): |
| 592 | order = append(order, "delta") |
| 593 | case e.Type == wire.EventMessage && json.Unmarshal(e.Data, &m) == nil && m.TurnID == sent.Turn.ID && m.Role == wire.RoleAssistant: |
| 594 | order = append(order, "message") |
| 595 | } |
| 596 | case <-ctx.Done(): |
| 597 | t.Fatal("no reply") |
| 598 | } |
| 599 | } |
| 600 | if !slices.Equal(order, []string{"glance", "delta", "message"}) || glance.TurnID != sent.Turn.ID || glance.Text != "Looking into that now" { |
| 601 | t.Fatalf("on %s: %v, glance %+v", provider, order, glance) |
| 602 | } |
| 603 | if line := phaseLine(t, logs, sent.Turn.ID); !strings.Contains(line, "glance=sent") { |
| 604 | t.Fatalf("phase line %s", line) |
| 605 | } |
| 606 | // The next glance sees the newest message alone, not the |
| 607 | // last one nor its line: a fresh conversation, still warm. |
| 608 | waitGlanceWarm(t, logs, map[string]int{"claude": 2, "codex": 1}[provider]) |
| 609 | next, err := a.Send(ctx, "Now the invoices please. pause:1000", key()) |
| 610 | if err != nil { |
| 611 | t.Fatal(err) |
| 612 | } |
| 613 | var second wire.Glance |
| 614 | for second.TurnID == "" { |
| 615 | select { |
| 616 | case e, ok := <-s.Events: |
| 617 | if !ok { |
| 618 | t.Fatal("the Assistant's stream ended") |
| 619 | } |
| 620 | if e.Type == wire.EventGlance && e.TurnID == next.Turn.ID { |
| 621 | json.Unmarshal(e.Data, &second) |
| 622 | } |
| 623 | if e.Type == wire.EventDelta && e.TurnID == next.Turn.ID && second.TurnID == "" { |
| 624 | t.Fatalf("on %s the second glance did not come first: %s", provider, phaseLine(t, logs, next.Turn.ID)) |
| 625 | } |
| 626 | case <-ctx.Done(): |
| 627 | t.Fatal("no second glance") |
| 628 | } |
| 629 | } |
| 630 | if second.Text != "Looking into that now" { |
| 631 | t.Fatalf("on %s the second glance saw earlier turns: %q", provider, second.Text) |
| 632 | } |
| 633 | assistantReply(t, ctx, a, next.Turn.ID) |
| 634 | waitGlanceWarm(t, logs, map[string]int{"claude": 3, "codex": 1}[provider]) |
| 635 | var stored int |
| 636 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages WHERE text = ?", glance.Text).Scan(&stored); err != nil || stored != 0 { |
| 637 | t.Fatalf("%d stored glances %v", stored, err) |
| 638 | } |
| 639 | // Too slow (the harness is still warm from the last |
| 640 | // glance): the reply comes, the glance never does. |
| 641 | slow, err := a.Send(ctx, "And my invoices glanceslow pause:3000", key()) |
| 642 | if err != nil { |
| 643 | t.Fatal(err) |
| 644 | } |
| 645 | assistantReply(t, ctx, a, slow.Turn.ID) |
| 646 | if line := phaseLine(t, logs, slow.Turn.ID); !strings.Contains(line, "glance=timeout") { |
| 647 | t.Fatalf("slow phase line %s", line) |
| 648 | } |
| 649 | for _, e := range drain(s) { |
| 650 | if e.Type == wire.EventGlance && e.TurnID == slow.Turn.ID { |
| 651 | t.Fatalf("a late glance went: %+v", e) |
| 652 | } |
| 653 | } |
| 654 | }) |
| 655 | } |
| 656 | }) |
| 657 | } |
| 658 | |
| 659 | // waitGlanceWarm waits for the runner's n-th glance warm-up. |
| 660 | func waitGlanceWarm(t *testing.T, logs *lockedBuffer, n int) { |
| 661 | t.Helper() |
| 662 | deadline := time.Now().Add(60 * time.Second) |
| 663 | for strings.Count(logs.String(), `msg="assistant glance warm" outcome=warm`) < n { |
| 664 | if time.Now().After(deadline) { |
| 665 | t.Fatalf("no glance warm-up %d:\n%s", n, logs.String()) |
| 666 | } |
| 667 | time.Sleep(50 * time.Millisecond) |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | // drain reads what the stream has now, without waiting. |
| 672 | func drain(s *thintest.Stream) []wire.Event { |
| 673 | var out []wire.Event |
| 674 | for { |
| 675 | select { |
| 676 | case e, ok := <-s.Events: |
| 677 | if !ok { |
| 678 | return out |
| 679 | } |
| 680 | out = append(out, e) |
| 681 | case <-time.After(300 * time.Millisecond): |
| 682 | return out |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | // phaseLine waits for the runner's debug phase line of an Assistant turn. |
| 688 | func phaseLine(t *testing.T, logs *lockedBuffer, turn string) string { |
| 689 | t.Helper() |
| 690 | deadline := time.Now().Add(30 * time.Second) |
| 691 | for { |
| 692 | for _, l := range strings.Split(logs.String(), "\n") { |
| 693 | if strings.Contains(l, `msg="assistant turn"`) && strings.Contains(l, "turn="+turn+" ") { |
| 694 | return l |
| 695 | } |
| 696 | } |
| 697 | if time.Now().After(deadline) { |
| 698 | t.Fatalf("no phase line for %s", turn) |
| 699 | } |
| 700 | time.Sleep(50 * time.Millisecond) |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | // warmed waits for the runner's n-th successful Assistant warm-up. |
| 705 | func warmed(t *testing.T, logs *lockedBuffer, n int) { |
| 706 | t.Helper() |
| 707 | deadline := time.Now().Add(60 * time.Second) |
| 708 | for strings.Count(logs.String(), `msg="assistant warm" outcome=warm`) < n { |
| 709 | if time.Now().After(deadline) { |
| 710 | t.Fatalf("no warm-up %d:\n%s", n, logs.String()) |
| 711 | } |
| 712 | time.Sleep(50 * time.Millisecond) |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | // rot13 hides tool words from the fake that reads them first. |
| 717 | func rot13(s string) string { |
| 718 | return strings.Map(func(c rune) rune { |
| 719 | switch { |
| 720 | case c >= 'a' && c <= 'z': |
| 721 | return 'a' + (c-'a'+13)%26 |
| 722 | case c >= 'A' && c <= 'Z': |
| 723 | return 'A' + (c-'A'+13)%26 |
| 724 | } |
| 725 | return c |
| 726 | }, s) |
| 727 | } |
| 728 | |
| 729 | // handedOff is the hand-off an Assistant turn made: its request and the |
| 730 | // turn of its thread's first message. |
| 731 | func handedOff(t *testing.T, inst *thintest.Instance, turn string) (request, thread string) { |
| 732 | t.Helper() |
| 733 | if err := inst.DB.Writer().QueryRow("SELECT h.id, m.turn_id FROM chat_handoffs h JOIN chat_messages m ON m.id = h.message_id WHERE h.assistant_turn = ?", turn).Scan(&request, &thread); err != nil { |
| 734 | t.Fatalf("the hand-off of turn %s: %v", turn, err) |
| 735 | } |
| 736 | return request, thread |
| 737 | } |
| 738 | |
| 739 | // asJob checks a hand-off ran as a job (J2, J3, J4): its thread's turn in |
| 740 | // lane job:<request>, launched with the converse action (the |
| 741 | // Coordinator's opening, and its record_task done in the lane), in a |
| 742 | // session home of the job's own; the person's own conversation shows |
| 743 | // nothing of it; the Assistant has the job's card, with its title. |
| 744 | func asJob(t *testing.T, ctx context.Context, env *Env, inst *thintest.Instance, r *localRunner, request, thread, title string) { |
| 745 | t.Helper() |
| 746 | lane := wire.JobLane(request) |
| 747 | var turnLane string |
| 748 | var records int |
| 749 | if err := inst.DB.Writer().QueryRow("SELECT coalesce(lane, '') FROM chat_turns WHERE id = ?", thread).Scan(&turnLane); err != nil || turnLane != lane { |
| 750 | t.Fatalf("the thread's turn in lane %q, want %q: %v", turnLane, lane, err) |
| 751 | } |
| 752 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE lane = ? AND name = 'record_task'", lane).Scan(&records); err != nil || records == 0 { |
| 753 | t.Fatalf("%d record_task calls in the thread %v", records, err) |
| 754 | } |
| 755 | state, err := sql.Open("sqlite", "file:"+filepath.Join(r.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| 756 | if err != nil { |
| 757 | t.Fatal(err) |
| 758 | } |
| 759 | defer state.Close() |
| 760 | // The runner keeps the session once the thread's first turn ends. |
| 761 | var provider, session string |
| 762 | for deadline := time.Now().Add(2 * time.Minute); ; time.Sleep(200 * time.Millisecond) { |
| 763 | err := state.QueryRow("SELECT provider, session_id FROM sessions_lane WHERE person = ? AND lane = ?", thintest.Owner, lane).Scan(&provider, &session) |
| 764 | if err == nil { |
| 765 | break |
| 766 | } |
| 767 | if !errors.Is(err, sql.ErrNoRows) || time.Now().After(deadline) { |
| 768 | t.Fatalf("the job's session: %v", err) |
| 769 | } |
| 770 | } |
| 771 | transcripts, _ := filepath.Glob(filepath.Join(thin.SessionRoot(r.cfg), "*", "job", request, provider, "projects", "-workspace", session+".jsonl")) |
| 772 | if len(transcripts) != 1 { |
| 773 | t.Fatalf("the job's session home: %v", transcripts) |
| 774 | } |
| 775 | raw, err := os.ReadFile(transcripts[0]) |
| 776 | if err != nil { |
| 777 | t.Fatal(err) |
| 778 | } |
| 779 | var first struct{ Type, Text string } |
| 780 | if line, _, _ := strings.Cut(string(raw), "\n"); json.Unmarshal([]byte(line), &first) != nil || first.Type != "user" || !strings.HasPrefix(first.Text, "You are the Equipo coordinator") { |
| 781 | t.Fatalf("the job's first prompt %.80q", first.Text) |
| 782 | } |
| 783 | mine, err := env.Client.Snapshot(ctx) |
| 784 | if err != nil { |
| 785 | t.Fatal(err) |
| 786 | } |
| 787 | if len(mine.Messages) != 0 || len(mine.Turns) != 0 || len(mine.Cards) != 0 { |
| 788 | t.Fatalf("the person's conversation shows the job: %d messages, %d turns, %d cards", len(mine.Messages), len(mine.Turns), len(mine.Cards)) |
| 789 | } |
| 790 | snap, err := env.Client.Assistant().Snapshot(ctx) |
| 791 | if err != nil { |
| 792 | t.Fatal(err) |
| 793 | } |
| 794 | if !slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardJob && c.Question == title }) { |
| 795 | t.Fatalf("no job card %q: %+v", title, snap.Cards) |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | // noQuestions fails if the Assistant lane holds a question card: the |
| 800 | // thread's questions are the Assistant's to answer or ask in its words. |
| 801 | func noQuestions(t *testing.T, snap wire.AssistantSnapshot) { |
| 802 | t.Helper() |
| 803 | for _, c := range snap.Cards { |
| 804 | if c.Kind == wire.CardQuestion { |
| 805 | t.Fatalf("a question card in the Assistant lane: %+v", c) |
| 806 | } |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | // quietUpdate waits for the first team_update turn about request to end |
| 811 | // and checks it called op once, through use, with a result of status, |
| 812 | // and said nothing; its id. A quiet turn has no place in the snapshot, |
| 813 | // so this reads the instance's rows. |
| 814 | func quietUpdate(t *testing.T, inst *thintest.Instance, request, op, status string) string { |
| 815 | t.Helper() |
| 816 | deadline := time.Now().Add(5 * time.Minute) |
| 817 | for { |
| 818 | var id, state, reply string |
| 819 | if err := inst.DB.Writer().QueryRow("SELECT r.id, r.state, coalesce(r.reply_id, '') FROM chat_turns r JOIN chat_handoff_turns l ON l.turn_id = r.id WHERE l.handoff_id = ? AND r.kind = ? ORDER BY r.created_at, r.rowid LIMIT 1", request, wire.TurnTeamUpdate).Scan(&id, &state, &reply); err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 820 | t.Fatal(err) |
| 821 | } |
| 822 | if wire.Terminal(state) { |
| 823 | var said, used int |
| 824 | var result string |
| 825 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages WHERE turn_id = ?", id).Scan(&said); err != nil || state != wire.TurnReplied || reply != "" || said != 0 { |
| 826 | t.Fatalf("the team_update turn %s %s, reply %q, %d messages %v", id, state, reply, said, err) |
| 827 | } |
| 828 | if err := inst.DB.Writer().QueryRow("SELECT count(*), coalesce(max(result), '') FROM chat_tool_calls WHERE turn_id = ? AND name = ? AND state = 'done'", id, wire.ToolUse).Scan(&used, &result); err != nil || used != 1 { |
| 829 | t.Fatalf("%d use calls in the team_update turn %v", used, err) |
| 830 | } |
| 831 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE turn_id = ? AND operation = ?", id, op).Scan(&used); err != nil || used != 1 || !strings.Contains(result, `\"status\":\"`+status+`\"`) { |
| 832 | t.Fatalf("%d %s calls in the team_update turn, result %s %v", used, op, result, err) |
| 833 | } |
| 834 | return id |
| 835 | } |
| 836 | if time.Now().After(deadline) { |
| 837 | t.Fatalf("no team_update turn about %s ended (%q %s)", request, id, state) |
| 838 | } |
| 839 | time.Sleep(200 * time.Millisecond) |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | // recorded waits for the job's thread to record a task; its id. |
| 844 | func recorded(t *testing.T, inst *thintest.Instance, lane string) string { |
| 845 | t.Helper() |
| 846 | deadline := time.Now().Add(4 * time.Minute) |
| 847 | for { |
| 848 | var id string |
| 849 | if _ = inst.DB.Writer().QueryRow("SELECT id FROM chat_tasks WHERE lane = ? LIMIT 1", lane).Scan(&id); id != "" { |
| 850 | return id |
| 851 | } |
| 852 | if time.Now().After(deadline) { |
| 853 | t.Fatalf("no task recorded in %s", lane) |
| 854 | } |
| 855 | time.Sleep(200 * time.Millisecond) |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | // jobMoves waits for the job's card to show its work under way: working, |
| 860 | // with a status past "Getting started". |
| 861 | func jobMoves(t *testing.T, ctx context.Context, a *thintest.AssistantClient, request, title string) wire.AssistantCard { |
| 862 | t.Helper() |
| 863 | deadline := time.Now().Add(4 * time.Minute) |
| 864 | for { |
| 865 | snap, err := a.Snapshot(ctx) |
| 866 | if err != nil { |
| 867 | t.Fatal(err) |
| 868 | } |
| 869 | for _, c := range snap.Cards { |
| 870 | if c.Kind == wire.CardJob && c.Question == title && c.State == wire.JobWorking && c.Result != "" && c.Result != equipo.RunnerCopy("assistant.job.status.starting") { |
| 871 | return c |
| 872 | } |
| 873 | } |
| 874 | if time.Now().After(deadline) { |
| 875 | t.Fatalf("the job %s never got going: %+v", request, snap.Cards) |
| 876 | } |
| 877 | time.Sleep(200 * time.Millisecond) |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | // assistantReply waits for an Assistant turn to reply and returns its |
| 882 | // message, from the Assistant's snapshot. |
| 883 | func assistantReply(t *testing.T, ctx context.Context, a *thintest.AssistantClient, turn string) wire.Message { |
| 884 | t.Helper() |
| 885 | deadline := time.Now().Add(4 * time.Minute) |
| 886 | for { |
| 887 | snap, err := a.Snapshot(ctx) |
| 888 | if err != nil { |
| 889 | t.Fatal(err) |
| 890 | } |
| 891 | for _, v := range snap.Turns { |
| 892 | if v.ID != turn { |
| 893 | continue |
| 894 | } |
| 895 | if v.State == wire.TurnFailed || v.State == wire.TurnCancelled { |
| 896 | t.Fatalf("Assistant turn %s %s (%s)", turn, v.State, v.Reason) |
| 897 | } |
| 898 | for _, m := range snap.Messages { |
| 899 | if v.State == wire.TurnReplied && m.ID == v.ReplyID { |
| 900 | if m.Role != wire.RoleAssistant { |
| 901 | t.Fatalf("reply role %q", m.Role) |
| 902 | } |
| 903 | return m |
| 904 | } |
| 905 | } |
| 906 | } |
| 907 | if time.Now().After(deadline) { |
| 908 | t.Fatalf("Assistant turn %s did not reply: %+v", turn, snap.Turns) |
| 909 | } |
| 910 | time.Sleep(200 * time.Millisecond) |
| 911 | } |
| 912 | } |
| 913 | |