package headless
import (
"context"
"database/sql"
"encoding/json"
"errors"
"log/slog"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/runner/thin"
"amadan.net/oficina/equipo/internal/thintest"
"amadan.net/oficina/equipo/internal/wire"
)
// TestHeadlessAssistant runs the Assistant's scenarios against a fresh
// local instance and runner with the fake CLI in real bubblewrap, through
// /api/v1/assistant as Base calls it.
func TestHeadlessAssistant(t *testing.T) {
t.Run("conversation", func(t *testing.T) {
env, inst, r := localEnv(t)
r.opts.NoMoveIn = true
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
a := env.Client.Assistant()
first, err := a.Send(ctx, "Hello, assistant. tool:look", key())
if err != nil {
t.Fatal(err)
}
// The Coordinator, meanwhile, in its own lane and session.
coord := open(t, env)
other := coord.send(t, "Hello, coordinator.")
reply := assistantReply(t, ctx, a, first.Turn.ID)
if !strings.Contains(reply.Text, "Turn 1, fresh session") {
t.Fatalf("first Assistant reply %q", reply.Text)
}
coord.waitTurn(t, other.Turn.ID, wire.TurnReplied)
if got := coord.reply(t, other.Turn.ID); !strings.Contains(got.Text, "Turn 1, fresh session") {
t.Fatalf("the Coordinator answered from another session: %q", got.Text)
}
second, err := a.Send(ctx, "And again.", key())
if err != nil {
t.Fatal(err)
}
if reply = assistantReply(t, ctx, a, second.Turn.ID); !strings.Contains(reply.Text, "Turn 2, resumed session") {
t.Fatalf("second Assistant reply %q", reply.Text)
}
// The Coordinator's routes saw none of it.
page, err := env.Client.Messages(ctx, "", 50)
if err != nil || len(page.Items) != 2 {
t.Fatalf("coordinator messages %+v %v", page, err)
}
// The runner launched the Assistant with the assist action: the
// session started at all only because the CLI reported exactly the
// seven tools that action pins (claude.ValidateInit), and its look call
// reached the instance in the Assistant's lane. It kept its own
// session beside the Coordinator's.
var looks int
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 {
t.Fatalf("look calls in the Assistant lane %d %v", looks, err)
}
state, err := sql.Open("sqlite", "file:"+filepath.Join(r.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
t.Fatal(err)
}
defer state.Close()
sessions := map[string]string{}
rows, err := state.Query("SELECT lane, session_id FROM sessions_lane WHERE person = ?", thintest.Owner)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var lane, id string
if err := rows.Scan(&lane, &id); err != nil {
t.Fatal(err)
}
sessions[lane] = id
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
if len(sessions) != 2 || sessions[wire.LaneAssistant] == "" || sessions[wire.LaneCoordinator] == "" || sessions[wire.LaneAssistant] == sessions[wire.LaneCoordinator] {
t.Fatalf("sessions %v", sessions)
}
})
// The Assistant looks at what Base offers and runs one operation, out
// of the tool call's transaction, through the real runner's tools.
t.Run("what_can_i_do", func(t *testing.T) {
env, inst, r := localEnv(t)
base := thintest.StartFakeBase(t)
inst.AssistantHosts = []string{base.Origin}
inst.Restart(t)
r.opts.NoMoveIn = true
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
a := env.Client.Assistant()
if _, err := a.PutHost(ctx, base.Origin, base.Token); err != nil {
t.Fatal(err)
}
sent, err := a.Send(ctx, "What can I do? tool:look tool:use:base_apps|{}", key())
if err != nil {
t.Fatal(err)
}
if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" {
t.Fatal("no reply")
}
if lists, apps := base.Calls(""), base.Calls("base_apps"); lists != 1 || apps != 1 {
t.Fatalf("Base saw %d lists and %d base_apps calls", lists, apps)
}
var done int
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 {
t.Fatalf("%d calls done %v", done, err)
}
})
// "Can we fix a bug in Tito?": the Assistant hands the person's words
// to the team; the Coordinator, in its own lane, records and starts a
// task on the test repository; when the work stops on its own the
// Assistant hears of it in a team_update turn and tells the person.
// The fake Coordinator follows tool words wherever it reads them, so
// the Assistant's context (reference, beside the person's words)
// steers it here.
t.Run("tito_bug", func(t *testing.T) {
env, inst, r := localEnv(t)
r.opts.NoMoveIn = true
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
a := env.Client.Assistant()
coord := open(t, env)
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."})
// The Assistant's fake would fill in $task itself: the JSON spells it
// so it reaches the Coordinator as written.
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())
if err != nil {
t.Fatal(err)
}
if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" {
t.Fatal("no reply")
}
var turn, words string
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" {
t.Fatalf("hand-off message %q %v", words, err)
}
// The thread's task is the job's: recorded in its lane, its task card
// in the thread, never in the person's own conversation (J4).
var id string
var leaked []wire.Card
coord.wait(t, "the thread's task", 3*time.Minute, func(c *thintest.Conversation) bool {
if leaked = cards(c, turn, wire.CardTask); len(leaked) > 0 {
return true
}
if id == "" {
_ = 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)
}
_, ok := c.Tasks[id]
return ok
})
if len(leaked) > 0 {
t.Fatalf("the thread's task card is in their conversation: %+v", leaked)
}
request, _ := handedOff(t, inst, sent.Turn.ID)
asJob(t, ctx, env, inst, r, request, turn, "Fixing the sign-in page")
var created bool
if err := inst.DB.Writer().QueryRow("SELECT created FROM chat_handoff_tasks WHERE task_id = ?", id).Scan(&created); err != nil || !created {
t.Fatalf("the hand-off does not follow its task: %v %v", created, err)
}
if done := coord.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed); done.State != wire.StepDone {
t.Fatalf("engineering %+v", done)
}
deadline := time.Now().Add(5 * time.Minute)
for {
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
replies, update := 0, ""
for _, m := range snap.Messages {
if m.Role == wire.RoleAssistant {
replies++
}
}
for _, v := range snap.Turns {
if v.Kind == wire.TurnTeamUpdate && v.State == wire.TurnReplied {
update = v.ReplyID
}
}
if replies == 2 && update != "" {
noQuestions(t, snap)
break
}
if time.Now().After(deadline) {
t.Fatalf("no reply from a team_update turn: %+v", snap.Turns)
}
time.Sleep(200 * time.Millisecond)
}
})
// "Build me a quick website" (spec ยง7, 4): the hand-off's website is
// merged on the person's go-ahead, then the Assistant lane asks to
// publish it with its preview, which answers while the card waits;
// Publish ends with the site's public address on the card. It needs
// the runner paired with a site host and a preview host, so it runs
// only where EQUIPO_SITE_HOST and EQUIPO_PREVIEW_HOST (with
// EQUIPO_CARLOS_PATH and EQUIPO_PREVIEW_CREDENTIAL_PATH when not the
// defaults) say so.
t.Run("quick_website", func(t *testing.T) {
// Since places (2026-11-26) a site publishes only to a place an
// owner confirmed on a place card first; this live run still taps
// Publish alone, so it waits for its place-card step (slice 3).
if os.Getenv("EQUIPO_LIVE_PLACES") == "" || os.Getenv("EQUIPO_PREVIEW_HOST") == "" {
t.Skip("needs a confirmed place: set EQUIPO_LIVE_PLACES and EQUIPO_PREVIEW_HOST")
}
env, inst, r := localEnv(t)
r.cfg.PreviewHost = os.Getenv("EQUIPO_PREVIEW_HOST")
r.cfg.CarlosPath, r.cfg.PreviewCredentialPath = os.Getenv("EQUIPO_CARLOS_PATH"), os.Getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH")
r.opts.NoMoveIn = true
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
a := env.Client.Assistant()
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|
Hello
; create:release/preview.json|{"output": "site"}` + "\nThat is all."})
sent, err := a.Send(ctx, "Build me a quick website tool:use:team_request|"+strings.ReplaceAll(string(input), "$task", `\u0024task`), key())
if err != nil {
t.Fatal(err)
}
if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" {
t.Fatal("no reply")
}
offers := func(c wire.AssistantCard, value string) bool {
return c.Kind == wire.CardOutcome && slices.ContainsFunc(c.Options, func(o wire.CardOption) bool { return o.Value == value })
}
// card waits for the Assistant card that matches; Merge on a
// go-ahead along the way, as the person would.
card := func(what string, match func(wire.AssistantCard) bool) wire.AssistantCard {
t.Helper()
deadline := time.Now().Add(10 * time.Minute)
for {
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
for _, c := range snap.Cards {
if match(c) {
return c
}
if c.State == wire.CardOpen && offers(c, wire.ChoiceMerge) {
if _, err := a.Answer(ctx, c.ID, wire.ChoiceMerge, c.Revision); err != nil {
t.Fatalf("merge %v", err)
}
}
}
if time.Now().After(deadline) {
t.Fatalf("no %s: %+v", what, snap.Cards)
}
time.Sleep(time.Second)
}
}
ask := card("publish card", func(c wire.AssistantCard) bool { return c.State == wire.CardOpen && offers(c, wire.ChoicePublish) })
if ask.Question != equipo.RunnerCopy("assistant.outcome.publish_question") || len(ask.Links) != 1 {
t.Fatalf("publish card %+v", ask)
}
res, err := http.Get(ask.Links[0].URL)
if err != nil {
t.Fatalf("preview %v", err)
}
res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Fatalf("preview %s answered %d", ask.Links[0].URL, res.StatusCode)
}
if _, err := a.Answer(ctx, ask.ID, wire.ChoicePublish, ask.Revision); err != nil {
t.Fatal(err)
}
live := card("published site", func(c wire.AssistantCard) bool {
return c.ID == ask.ID && slices.ContainsFunc(c.Links, func(l wire.CardLink) bool { return strings.HasPrefix(l.URL, "https://site-") })
})
// The published line, not publishing or sent but unconfirmed.
if live.State != wire.CardAnswered || live.Result != equipo.RunnerCopy("assistant.outcome.publish_published") {
t.Fatalf("published card %+v", live)
}
request, thread := handedOff(t, inst, sent.Turn.ID)
asJob(t, ctx, env, inst, r, request, thread, "Building your website")
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
noQuestions(t, snap)
})
// "Build me a website about disability benefits": the job's thread
// asks what it should be about, and the Assistant answers from the
// conversation itself (team_reply in its team_update turn), saying
// nothing; the answer reaches the thread as the person's, and the work
// goes on. The person never sees a question.
t.Run("question_from_context", func(t *testing.T) {
env, inst, r := localEnv(t)
r.opts.NoMoveIn = true
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
a := env.Client.Assistant()
const words, title, answer = "Build me a website about disability benefits", "Building your website", "Disability benefits"
// The thread asks; once answered it records and starts the work
// (onanswer:, rot13, so the first turn does not follow it).
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")
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."})
sent, err := a.Send(ctx, words+" tool:use:team_request|"+string(input), key())
if err != nil {
t.Fatal(err)
}
if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" {
t.Fatal("no reply")
}
request, thread := handedOff(t, inst, sent.Turn.ID)
lane := wire.JobLane(request)
// The team_update that told the Assistant of the question.
quietUpdate(t, inst, request, "team_reply", "answered")
var choice string
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 {
t.Fatalf("the thread's question answered %q %v", choice, err)
}
var n int
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 {
t.Fatalf("%d answers in the thread %v", n, err)
}
recorded(t, inst, lane)
jobMoves(t, ctx, a, request, title)
asJob(t, ctx, env, inst, r, request, thread, title)
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
noQuestions(t, snap)
})
// A job that stops before any work starts is pushed through: the
// first team_update nudges it once with the person's own words, which
// the thread gets again with the Assistant's context; the work starts
// and the person hears nothing of the stop.
// The Assistant's reply streams on either provider: its first text
// reaches /api/v1/assistant/events as a delta while the turn is still
// running, well before the reply message that replaces the draft.
t.Run("streamed", func(t *testing.T) {
for _, provider := range []string{"claude", "codex"} {
t.Run(provider, func(t *testing.T) {
env, _, r := localEnv(t)
r.opts.NoMoveIn = true
if provider == "codex" {
r.addAccount(t, "codex", "codex-1", thintest.Owner)
r.only(t, "codex-1")
}
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
a := env.Client.Assistant()
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
s, err := a.Open(ctx, snap.Cursor)
if err != nil {
t.Fatal(err)
}
defer s.Close()
// The fake pauses two seconds after its first words.
sent, err := a.Send(ctx, "Hello there. sleep:2000", key())
if err != nil {
t.Fatal(err)
}
var delta, reply time.Time
for reply.IsZero() {
select {
case e, ok := <-s.Events:
if !ok {
t.Fatal("the Assistant's stream ended")
}
var m wire.Message
switch {
case e.Type == wire.EventDelta && e.TurnID == sent.Turn.ID && delta.IsZero():
delta = time.Now()
case e.Type == wire.EventMessage && json.Unmarshal(e.Data, &m) == nil && m.TurnID == sent.Turn.ID && m.Role == wire.RoleAssistant:
reply = time.Now()
}
case <-ctx.Done():
t.Fatal("no reply")
}
}
if delta.IsZero() {
t.Fatalf("on %s no delta came before the reply", provider)
}
if gap := reply.Sub(delta); gap < time.Second {
t.Fatalf("on %s the first delta came only %v before the reply", provider, gap)
}
})
}
})
t.Run("nudged_through", func(t *testing.T) {
env, inst, r := localEnv(t)
r.opts.NoMoveIn = true
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
a := env.Client.Assistant()
const title = "Making the benefits page"
// The nudge's context, from the person's words (nudge:, rot13), is
// what records and starts the work; the hand-off's does nothing.
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")
input, _ := json.Marshal(map[string]string{"words": words, "title": title, "context": "That is all."})
sent, err := a.Send(ctx, words+" tool:use:team_request|"+string(input), key())
if err != nil {
t.Fatal(err)
}
if reply := assistantReply(t, ctx, a, sent.Turn.ID); reply.Text == "" {
t.Fatal("no reply")
}
request, thread := handedOff(t, inst, sent.Turn.ID)
lane := wire.JobLane(request)
quietUpdate(t, inst, request, "team_nudge", "nudged")
recorded(t, inst, lane)
var nudges, actions, again int
if err := inst.DB.Writer().QueryRow("SELECT nudges FROM chat_handoffs WHERE id = ?", request).Scan(&nudges); err != nil {
t.Fatal(err)
}
if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_handoff_actions WHERE handoff_id = ? AND kind = 'nudge'", request).Scan(&actions); err != nil {
t.Fatal(err)
}
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 {
t.Fatal(err)
}
if nudges != 1 || actions != 1 || again != 2 {
t.Fatalf("%d nudges, %d nudge actions, the words %d times in the thread", nudges, actions, again)
}
if job := jobMoves(t, ctx, a, request, title); job.State != wire.JobWorking {
t.Fatalf("the job %+v", job)
}
asJob(t, ctx, env, inst, r, request, thread, title)
})
// warm_start: after a restart under a new Assistant rule (its old
// session cannot resume), the runner starts the person's Assistant
// process and session before their first message, on either
// provider, sending the model nothing: the first turn finds it up
// (cold=false) and its first prompt is the process's first. A person
// whose Assistant was never used is not warmed, and a warm process no
// turn uses closes after WarmIdle.
t.Run("warm_start", func(t *testing.T) {
for _, provider := range []string{"claude", "codex"} {
t.Run(provider, func(t *testing.T) {
env, _, r := localEnv(t)
r.opts.NoMoveIn = true
if provider == "codex" {
r.addAccount(t, "codex", "codex-1", thintest.Owner)
r.only(t, "codex-1")
}
logs := &lockedBuffer{}
r.opts.Logger = slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
a := env.Client.Assistant()
first, err := a.Send(ctx, "Hello.", key())
if err != nil {
t.Fatal(err)
}
assistantReply(t, ctx, a, first.Turn.ID)
if line := phaseLine(t, logs, first.Turn.ID); !strings.Contains(line, "cold=true") {
t.Fatalf("the first turn ever was warm: %s", line)
}
if strings.Contains(logs.String(), `msg="assistant warm"`) {
t.Fatalf("warmed an Assistant nobody had used:\n%s", logs.String())
}
r.stop(t)
state, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db"))
if err != nil {
t.Fatal(err)
}
if _, err = state.Exec("UPDATE sessions_lane SET account = account || '-old' WHERE lane = ?", wire.LaneAssistant); err != nil {
t.Fatal(err)
}
state.Close()
r.start(t)
warmed(t, logs, 1)
second, err := a.Send(ctx, "And again.", key())
if err != nil {
t.Fatal(err)
}
reply := assistantReply(t, ctx, a, second.Turn.ID)
if line := phaseLine(t, logs, second.Turn.ID); !strings.Contains(line, "cold=false") {
t.Fatalf("the first turn after the warm-up started cold: %s", line)
}
want := map[string]string{"claude": "Turn 1, fresh session, process turn 1.", "codex": "Turn 1, fresh thread."}[provider]
if !strings.Contains(reply.Text, want) {
t.Fatalf("the warm process was not the turn's, fresh and unprompted: %q", reply.Text)
}
r.stop(t)
r.opts.Claude.WarmIdle = 2 * time.Second
r.start(t)
warmed(t, logs, 2)
time.Sleep(4 * time.Second)
third, err := a.Send(ctx, "Still there?", key())
if err != nil {
t.Fatal(err)
}
assistantReply(t, ctx, a, third.Turn.ID)
if line := phaseLine(t, logs, third.Turn.ID); !strings.Contains(line, "cold=true") {
t.Fatalf("an unused warm process outlived WarmIdle: %s", line)
}
})
}
})
// glance: a greeting has none. Once the person's glance harness is
// warm (after their first turn), the next message's glance reaches
// Base's stream before the reply's first words, on either provider:
// the small model's line, cleaned, for that turn. Nothing of it is stored, and a glance
// that comes too late (glanceslow) is not sent at all.
t.Run("glance", func(t *testing.T) {
for _, provider := range []string{"claude", "codex"} {
t.Run(provider, func(t *testing.T) {
env, inst, r := localEnv(t)
r.opts.NoMoveIn = true
if provider == "codex" {
r.addAccount(t, "codex", "codex-1", thintest.Owner)
r.only(t, "codex-1")
}
logs := &lockedBuffer{}
r.opts.Logger = slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
r.start(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
a := env.Client.Assistant()
first, err := a.Send(ctx, "Hello.", key())
if err != nil {
t.Fatal(err)
}
assistantReply(t, ctx, a, first.Turn.ID)
// A greeting has no glance: its reply is the answer.
if line := phaseLine(t, logs, first.Turn.ID); !strings.Contains(line, "glance=small_talk") {
t.Fatalf("a greeting's phase line %s", line)
}
deadline := time.Now().Add(60 * time.Second)
for !strings.Contains(logs.String(), `msg="assistant glance warm" outcome=warm`) {
if time.Now().After(deadline) {
t.Fatalf("the glance never warmed:\n%s", logs.String())
}
time.Sleep(50 * time.Millisecond)
}
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
s, err := a.Open(ctx, snap.Cursor)
if err != nil {
t.Fatal(err)
}
defer s.Close()
// The reply's first words wait a second (pause:).
sent, err := a.Send(ctx, "Could you look at my website? pause:1000", key())
if err != nil {
t.Fatal(err)
}
var order []string
var glance wire.Glance
for !slices.Contains(order, "message") {
select {
case e, ok := <-s.Events:
if !ok {
t.Fatal("the Assistant's stream ended")
}
var m wire.Message
switch {
case e.Type == wire.EventGlance && e.TurnID == sent.Turn.ID:
order = append(order, "glance")
json.Unmarshal(e.Data, &glance)
case e.Type == wire.EventDelta && e.TurnID == sent.Turn.ID && !slices.Contains(order, "delta"):
order = append(order, "delta")
case e.Type == wire.EventMessage && json.Unmarshal(e.Data, &m) == nil && m.TurnID == sent.Turn.ID && m.Role == wire.RoleAssistant:
order = append(order, "message")
}
case <-ctx.Done():
t.Fatal("no reply")
}
}
if !slices.Equal(order, []string{"glance", "delta", "message"}) || glance.TurnID != sent.Turn.ID || glance.Text != "Looking into that now" {
t.Fatalf("on %s: %v, glance %+v", provider, order, glance)
}
if line := phaseLine(t, logs, sent.Turn.ID); !strings.Contains(line, "glance=sent") {
t.Fatalf("phase line %s", line)
}
// The next glance sees the newest message alone, not the
// last one nor its line: a fresh conversation, still warm.
waitGlanceWarm(t, logs, map[string]int{"claude": 2, "codex": 1}[provider])
next, err := a.Send(ctx, "Now the invoices please. pause:1000", key())
if err != nil {
t.Fatal(err)
}
var second wire.Glance
for second.TurnID == "" {
select {
case e, ok := <-s.Events:
if !ok {
t.Fatal("the Assistant's stream ended")
}
if e.Type == wire.EventGlance && e.TurnID == next.Turn.ID {
json.Unmarshal(e.Data, &second)
}
if e.Type == wire.EventDelta && e.TurnID == next.Turn.ID && second.TurnID == "" {
t.Fatalf("on %s the second glance did not come first: %s", provider, phaseLine(t, logs, next.Turn.ID))
}
case <-ctx.Done():
t.Fatal("no second glance")
}
}
if second.Text != "Looking into that now" {
t.Fatalf("on %s the second glance saw earlier turns: %q", provider, second.Text)
}
assistantReply(t, ctx, a, next.Turn.ID)
waitGlanceWarm(t, logs, map[string]int{"claude": 3, "codex": 1}[provider])
var stored int
if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages WHERE text = ?", glance.Text).Scan(&stored); err != nil || stored != 0 {
t.Fatalf("%d stored glances %v", stored, err)
}
// Too slow (the harness is still warm from the last
// glance): the reply comes, the glance never does.
slow, err := a.Send(ctx, "And my invoices glanceslow pause:3000", key())
if err != nil {
t.Fatal(err)
}
assistantReply(t, ctx, a, slow.Turn.ID)
if line := phaseLine(t, logs, slow.Turn.ID); !strings.Contains(line, "glance=timeout") {
t.Fatalf("slow phase line %s", line)
}
for _, e := range drain(s) {
if e.Type == wire.EventGlance && e.TurnID == slow.Turn.ID {
t.Fatalf("a late glance went: %+v", e)
}
}
})
}
})
}
// waitGlanceWarm waits for the runner's n-th glance warm-up.
func waitGlanceWarm(t *testing.T, logs *lockedBuffer, n int) {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for strings.Count(logs.String(), `msg="assistant glance warm" outcome=warm`) < n {
if time.Now().After(deadline) {
t.Fatalf("no glance warm-up %d:\n%s", n, logs.String())
}
time.Sleep(50 * time.Millisecond)
}
}
// drain reads what the stream has now, without waiting.
func drain(s *thintest.Stream) []wire.Event {
var out []wire.Event
for {
select {
case e, ok := <-s.Events:
if !ok {
return out
}
out = append(out, e)
case <-time.After(300 * time.Millisecond):
return out
}
}
}
// phaseLine waits for the runner's debug phase line of an Assistant turn.
func phaseLine(t *testing.T, logs *lockedBuffer, turn string) string {
t.Helper()
deadline := time.Now().Add(30 * time.Second)
for {
for _, l := range strings.Split(logs.String(), "\n") {
if strings.Contains(l, `msg="assistant turn"`) && strings.Contains(l, "turn="+turn+" ") {
return l
}
}
if time.Now().After(deadline) {
t.Fatalf("no phase line for %s", turn)
}
time.Sleep(50 * time.Millisecond)
}
}
// warmed waits for the runner's n-th successful Assistant warm-up.
func warmed(t *testing.T, logs *lockedBuffer, n int) {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for strings.Count(logs.String(), `msg="assistant warm" outcome=warm`) < n {
if time.Now().After(deadline) {
t.Fatalf("no warm-up %d:\n%s", n, logs.String())
}
time.Sleep(50 * time.Millisecond)
}
}
// rot13 hides tool words from the fake that reads them first.
func rot13(s string) string {
return strings.Map(func(c rune) rune {
switch {
case c >= 'a' && c <= 'z':
return 'a' + (c-'a'+13)%26
case c >= 'A' && c <= 'Z':
return 'A' + (c-'A'+13)%26
}
return c
}, s)
}
// handedOff is the hand-off an Assistant turn made: its request and the
// turn of its thread's first message.
func handedOff(t *testing.T, inst *thintest.Instance, turn string) (request, thread string) {
t.Helper()
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 {
t.Fatalf("the hand-off of turn %s: %v", turn, err)
}
return request, thread
}
// asJob checks a hand-off ran as a job (J2, J3, J4): its thread's turn in
// lane job:, launched with the converse action (the
// Coordinator's opening, and its record_task done in the lane), in a
// session home of the job's own; the person's own conversation shows
// nothing of it; the Assistant has the job's card, with its title.
func asJob(t *testing.T, ctx context.Context, env *Env, inst *thintest.Instance, r *localRunner, request, thread, title string) {
t.Helper()
lane := wire.JobLane(request)
var turnLane string
var records int
if err := inst.DB.Writer().QueryRow("SELECT coalesce(lane, '') FROM chat_turns WHERE id = ?", thread).Scan(&turnLane); err != nil || turnLane != lane {
t.Fatalf("the thread's turn in lane %q, want %q: %v", turnLane, lane, err)
}
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 {
t.Fatalf("%d record_task calls in the thread %v", records, err)
}
state, err := sql.Open("sqlite", "file:"+filepath.Join(r.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
t.Fatal(err)
}
defer state.Close()
// The runner keeps the session once the thread's first turn ends.
var provider, session string
for deadline := time.Now().Add(2 * time.Minute); ; time.Sleep(200 * time.Millisecond) {
err := state.QueryRow("SELECT provider, session_id FROM sessions_lane WHERE person = ? AND lane = ?", thintest.Owner, lane).Scan(&provider, &session)
if err == nil {
break
}
if !errors.Is(err, sql.ErrNoRows) || time.Now().After(deadline) {
t.Fatalf("the job's session: %v", err)
}
}
transcripts, _ := filepath.Glob(filepath.Join(thin.SessionRoot(r.cfg), "*", "job", request, provider, "projects", "-workspace", session+".jsonl"))
if len(transcripts) != 1 {
t.Fatalf("the job's session home: %v", transcripts)
}
raw, err := os.ReadFile(transcripts[0])
if err != nil {
t.Fatal(err)
}
var first struct{ Type, Text string }
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") {
t.Fatalf("the job's first prompt %.80q", first.Text)
}
mine, err := env.Client.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
if len(mine.Messages) != 0 || len(mine.Turns) != 0 || len(mine.Cards) != 0 {
t.Fatalf("the person's conversation shows the job: %d messages, %d turns, %d cards", len(mine.Messages), len(mine.Turns), len(mine.Cards))
}
snap, err := env.Client.Assistant().Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardJob && c.Question == title }) {
t.Fatalf("no job card %q: %+v", title, snap.Cards)
}
}
// noQuestions fails if the Assistant lane holds a question card: the
// thread's questions are the Assistant's to answer or ask in its words.
func noQuestions(t *testing.T, snap wire.AssistantSnapshot) {
t.Helper()
for _, c := range snap.Cards {
if c.Kind == wire.CardQuestion {
t.Fatalf("a question card in the Assistant lane: %+v", c)
}
}
}
// quietUpdate waits for the first team_update turn about request to end
// and checks it called op once, through use, with a result of status,
// and said nothing; its id. A quiet turn has no place in the snapshot,
// so this reads the instance's rows.
func quietUpdate(t *testing.T, inst *thintest.Instance, request, op, status string) string {
t.Helper()
deadline := time.Now().Add(5 * time.Minute)
for {
var id, state, reply string
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) {
t.Fatal(err)
}
if wire.Terminal(state) {
var said, used int
var result string
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 {
t.Fatalf("the team_update turn %s %s, reply %q, %d messages %v", id, state, reply, said, err)
}
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 {
t.Fatalf("%d use calls in the team_update turn %v", used, err)
}
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+`\"`) {
t.Fatalf("%d %s calls in the team_update turn, result %s %v", used, op, result, err)
}
return id
}
if time.Now().After(deadline) {
t.Fatalf("no team_update turn about %s ended (%q %s)", request, id, state)
}
time.Sleep(200 * time.Millisecond)
}
}
// recorded waits for the job's thread to record a task; its id.
func recorded(t *testing.T, inst *thintest.Instance, lane string) string {
t.Helper()
deadline := time.Now().Add(4 * time.Minute)
for {
var id string
if _ = inst.DB.Writer().QueryRow("SELECT id FROM chat_tasks WHERE lane = ? LIMIT 1", lane).Scan(&id); id != "" {
return id
}
if time.Now().After(deadline) {
t.Fatalf("no task recorded in %s", lane)
}
time.Sleep(200 * time.Millisecond)
}
}
// jobMoves waits for the job's card to show its work under way: working,
// with a status past "Getting started".
func jobMoves(t *testing.T, ctx context.Context, a *thintest.AssistantClient, request, title string) wire.AssistantCard {
t.Helper()
deadline := time.Now().Add(4 * time.Minute)
for {
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
for _, c := range snap.Cards {
if c.Kind == wire.CardJob && c.Question == title && c.State == wire.JobWorking && c.Result != "" && c.Result != equipo.RunnerCopy("assistant.job.status.starting") {
return c
}
}
if time.Now().After(deadline) {
t.Fatalf("the job %s never got going: %+v", request, snap.Cards)
}
time.Sleep(200 * time.Millisecond)
}
}
// assistantReply waits for an Assistant turn to reply and returns its
// message, from the Assistant's snapshot.
func assistantReply(t *testing.T, ctx context.Context, a *thintest.AssistantClient, turn string) wire.Message {
t.Helper()
deadline := time.Now().Add(4 * time.Minute)
for {
snap, err := a.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
for _, v := range snap.Turns {
if v.ID != turn {
continue
}
if v.State == wire.TurnFailed || v.State == wire.TurnCancelled {
t.Fatalf("Assistant turn %s %s (%s)", turn, v.State, v.Reason)
}
for _, m := range snap.Messages {
if v.State == wire.TurnReplied && m.ID == v.ReplyID {
if m.Role != wire.RoleAssistant {
t.Fatalf("reply role %q", m.Role)
}
return m
}
}
}
if time.Now().After(deadline) {
t.Fatalf("Assistant turn %s did not reply: %+v", turn, snap.Turns)
}
time.Sleep(200 * time.Millisecond)
}
}