package thintest
import (
"encoding/json"
"net/http"
"net/url"
"strings"
"testing"
"time"
"amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/wire"
)
// answer sends one answer report and waits for its ack.
func (r *toolRig) answer(id string, rep wire.AnswerReport) {
r.t.Helper()
r.step2(id, wire.FrameAnswer, rep)
}
// step2 sends a durable runner frame and waits for its ack, holding any
// command it caused for expect.
func (r *toolRig) step2(id, kind string, body any) {
r.t.Helper()
if err := r.runner.Send(r.ctx, id, kind, body); err != nil {
r.t.Fatal(err)
}
for {
f, b, err := r.runner.Next(r.ctx)
if err != nil {
r.t.Fatal(err)
}
if a, ok := b.(*wire.Ack); ok && f.Type == wire.FrameAck && a.ID == id {
return
}
if f.Type != wire.FrameAck {
r.held = append(r.held, heldFrame{f: f, body: b, raw: r.runner.Received[len(r.runner.Received)-1]})
}
}
}
// heldKinds counts the frames of kind held for expect.
func (r *toolRig) heldKinds(kind string) int {
n := 0
for _, h := range r.held {
if h.f.Type == kind {
n++
}
}
return n
}
// askableTask is a task whose Engineering step pushed cand and whose
// review approved it, both with their sessions kept.
func (r *toolRig) askableTask(key, base, cand string) (id string, eng, rev *wire.DispatchCommand) {
r.t.Helper()
id = taskID(r.t, r.call(key+"-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "The README says teh.", "separate": true}))
r.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."})
_, body := r.expect(wire.FrameDispatch)
eng = body.(*wire.DispatchCommand)
r.step(key+"-run", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
r.step(key+"-done", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a", Askable: true})
r.expect(wire.FrameWatchMerge)
c := r.dispatched(wire.SpecialistChecks, base, cand, 0)
r.checks(key+"-c", c, wire.ChecksPassed, exit(0), "", "ok\n")
rev = r.dispatched(wire.SpecialistReview, base, cand, 0)
r.step(key+"-r", wire.StepReport{TaskID: id, StepID: rev.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Family: "claude", Account: "claude-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewSameAccount, Findings: []wire.Finding{}, Summary: "Fine.", Change: facts(rev), Askable: true})
// Approved with checks passed: Equipo merges it (this fake runner
// leaves the merge running), or, below wire.ProtocolInjectionDefences, asks.
if r.runner.Welcome.Protocol < wire.ProtocolInjectionDefences {
r.wait("asking", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageReadyToMerge })
return id, eng, rev
}
r.dispatched(wire.SpecialistMerge, base, cand, 0)
r.wait("merging", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageMerging })
return id, eng, rev
}
// TestContractAskImplementer: the task's creator asks the specialist
// that did the work. The question goes to the newest Engineering step by
// default, or to Review when it addresses Review; it reaches the runner
// with the step and the exact commit; its answer streams to every
// member like a chat reply and is committed on the question. One
// question of a task is with the runner at a time; the next waits.
// Teammates read and never ask; cancel goes through the runner; a sync
// that no longer holds an acked question fails it; the task's end stops
// questions and lets the runner forget its sessions.
func TestContractAskImplementer(t *testing.T) {
r := newToolRigAt(t, wire.ProtocolInjectionDefences)
ctx := r.ctx
base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
// The teammate is an owner with a runner of their own: still not
// the task's creator.
mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner)
id, eng, rev := r.askableTask("a", base, cand)
if k, _ := r.client.Task(ctx, id); !k.Steps[0].Askable || !k.Steps[2].Askable || k.Steps[1].Askable || len(k.Questions) != 0 {
t.Fatalf("askable steps %+v", k.Steps)
}
// A teammate reads the task and cannot ask.
if _, err := mate.client.Ask(ctx, id, "What did you change?", "", "m1"); Status(err) != http.StatusForbidden {
t.Fatalf("teammate asked: %v", err)
}
// Bad input.
if _, err := r.client.Ask(ctx, id, " ", "", "k0"); Status(err) != 422 {
t.Fatalf("empty question: %v", err)
}
if _, err := r.client.Ask(ctx, id, "Why?", "checks", "k0"); Status(err) != 422 {
t.Fatalf("checks asked: %v", err)
}
// The creator asks; by default Engineering answers, on its commit.
q1, err := r.client.Ask(ctx, id, "What did you change and why?", "", "k1")
if err != nil {
t.Fatal(err)
}
if q1.StepID != eng.StepID || q1.Specialist != wire.SpecialistEngineering || q1.State != wire.QuestionQueued || q1.Asker != Owner {
t.Fatalf("question %+v", q1)
}
_, body := r.expect(wire.FrameAsk)
shape(t, "frames/ask.json", r.runner.Received[len(r.runner.Received)-1])
a1 := body.(*wire.AskCommand)
if a1.QuestionID != q1.ID || a1.StepID != eng.StepID || a1.CandidateSHA != cand || a1.BaseSHA != base || a1.Person != Owner || a1.Repo != "amadan.net/oficina/sample" || a1.Text != "What did you change and why?" || a1.Specialist != wire.SpecialistEngineering {
t.Fatalf("ask %+v", a1)
}
// The same key is the same question; another body under it is 409.
if again, err := r.client.Ask(ctx, id, "What did you change and why?", "", "k1"); err != nil || again.ID != q1.ID {
t.Fatalf("repeat %+v %v", again, err)
}
if _, err := r.client.Ask(ctx, id, "Something else", "", "k1"); Status(err) != http.StatusConflict {
t.Fatalf("conflict: %v", err)
}
// A second question, addressed to Review, waits for the first.
q2, err := r.client.Ask(ctx, id, "Review, anything you were unsure about?", "", "k2")
if err != nil || q2.StepID != rev.StepID || q2.Specialist != wire.SpecialistReview || q2.State != wire.QuestionQueued {
t.Fatalf("second question %+v %v", q2, err)
}
// Chosen explicitly, even without the word.
q3, err := r.client.Ask(ctx, id, "Anything else?", wire.SpecialistReview, "k3")
if err != nil || q3.StepID != rev.StepID {
t.Fatalf("third question %+v %v", q3, err)
}
// Another person's runner cannot answer it.
mate.answer("m-q1", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "Not mine to say."})
if q, _ := r.client.Question(ctx, q1.ID); q.State != wire.QuestionQueued || q.Answer != "" {
t.Fatalf("another runner answered: %+v", q)
}
// The answer streams to every member, the thinking line included.
r.answer("r-q1-run", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionRunning})
r.wait("running", func(c *Conversation) bool { return c.Questions[q1.ID].State == wire.QuestionRunning })
// Neither later question went to the runner while the first is there.
if n := r.heldKinds(wire.FrameAsk); n != 0 {
t.Fatalf("%d more questions went to the runner beside the first", n)
}
if err := r.runner.Send(ctx, "r-q1-act", wire.FrameActivity, wire.ActivityReport{TurnID: q1.ID, Attempt: 1, Kind: wire.ActivityTool, Tool: "read_change"}); err != nil {
t.Fatal(err)
}
if err := r.runner.Send(ctx, "r-q1-d1", wire.FrameDelta, wire.DeltaReport{TurnID: q1.ID, Attempt: 1, Offset: 0, Text: "I fixed "}); err != nil {
t.Fatal(err)
}
if err := r.runner.Send(ctx, "r-q1-d2", wire.FrameDelta, wire.DeltaReport{TurnID: q1.ID, Attempt: 1, Offset: 8, Text: "the typo."}); err != nil {
t.Fatal(err)
}
for _, who := range []*toolRig{r, mate} {
who.wait("the draft", func(c *Conversation) bool {
return c.Drafts[q1.ID] == "I fixed the typo." && c.DeltaResources[wire.ResourceQuestion] == 2 && len(c.Activity[q1.ID]) == 1
})
}
var act wire.Activity
r.conv.Locked(func(c *Conversation) { act = c.Activity[q1.ID][0] })
if act.Tool != "read_change" || act.Label == "" {
t.Fatalf("activity %+v", act)
}
if act.Label != "Looking at the change on ‘"+eng.Branch+"’…" {
t.Fatalf("creator's change subject: %+v", act)
}
mate.conv.Locked(func(c *Conversation) {
if got := c.Activity[q1.ID][0].Label; got != "Looking at the change…" {
t.Fatalf("another person's change was named: %q", got)
}
})
// Nothing streams into anyone's conversation.
r.conv.Locked(func(c *Conversation) {
if c.DeltaResources["turn"] != 0 {
t.Fatalf("question text streamed as a turn: %v", c.DeltaResources)
}
})
r.answer("r-q1-done", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I fixed the typo.", Timing: &wire.TurnTiming{FirstTextMs: 900, ResultMs: 1200}})
for _, who := range []*toolRig{r, mate} {
who.wait("answered", func(c *Conversation) bool {
q := c.Questions[q1.ID]
_, draft := c.Drafts[q1.ID]
return q.State == wire.QuestionAnswered && q.Answer == "I fixed the typo." && !draft
})
}
// A late report for the ended question changes nothing.
r.answer("r-q1-late", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionFailed, Reason: "provider_failed"})
q, _ := r.client.Question(ctx, q1.ID)
if q.State != wire.QuestionAnswered || q.Timing == nil || q.Timing.ResultMs != 1200 {
t.Fatalf("answered question %+v", q)
}
shape(t, "api/question.json", q)
// Then the second goes to the runner, to Review's step.
_, body = r.expect(wire.FrameAsk)
if a2 := body.(*wire.AskCommand); a2.QuestionID != q2.ID || a2.StepID != rev.StepID || a2.Specialist != wire.SpecialistReview || a2.CandidateSHA != cand {
t.Fatalf("second ask %+v", a2)
}
// Teammates cannot cancel it; the asker can, through the runner.
if _, err := mate.client.CancelQuestion(ctx, q2.ID); Status(err) != http.StatusForbidden {
t.Fatalf("teammate cancelled: %v", err)
}
if acc, err := r.client.CancelQuestion(ctx, q2.ID); err != nil || acc.Attempt != 1 {
t.Fatalf("cancel %+v %v", acc, err)
}
_, body = r.expect(wire.FrameCancelAsk)
shape(t, "frames/cancel_ask.json", r.runner.Received[len(r.runner.Received)-1])
if c := body.(*wire.CancelAskCommand); c.QuestionID != q2.ID || c.Attempt != 1 {
t.Fatalf("cancel_ask %+v", c)
}
if q, _ := r.client.Question(ctx, q2.ID); q.State != wire.QuestionQueued {
t.Fatalf("cancelled before the runner said so: %+v", q)
}
r.answer("r-q2-x", wire.AnswerReport{TaskID: id, QuestionID: q2.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
r.wait("cancelled", func(c *Conversation) bool { return c.Questions[q2.ID].State == wire.QuestionCancelled })
if _, err := r.client.CancelQuestion(ctx, q2.ID); Status(err) != http.StatusConflict {
t.Fatalf("cancel of an ended question: %v", err)
}
// The third goes next; a sync that no longer holds it fails it.
_, body = r.expect(wire.FrameAsk)
if a3 := body.(*wire.AskCommand); a3.QuestionID != q3.ID {
t.Fatalf("third ask %+v", a3)
}
if err := r.runner.Send(ctx, "r-sync", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}); err != nil {
t.Fatal(err)
}
r.wait("interrupted", func(c *Conversation) bool {
q := c.Questions[q3.ID]
return q.State == wire.QuestionFailed && q.Reason == "interrupted"
})
// A task with no session kept cannot be asked.
plain, _ := r.pushed("b", "Another typo", base, strings.Repeat("4", 40))
if _, err := r.client.Ask(ctx, plain, "Why?", "", "k4"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "not_askable") {
t.Fatalf("asked a step with no session: %v", err)
}
// The task is merged (Paul, 2026-11-08): its specialists can still be
// asked for 14 days. Questions carry on; the runner is told to keep
// the task's sessions until then and remove them after.
q5, err := r.client.Ask(ctx, id, "One more thing?", "", "k5")
if err != nil {
t.Fatal(err)
}
_, body = r.expect(wire.FrameAsk)
if a5 := body.(*wire.AskCommand); a5.QuestionID != q5.ID {
t.Fatalf("fifth ask %+v", a5)
}
r.step2("r-merged", wire.FrameMerged, wire.MergedReport{TaskID: id, CandidateSHA: cand})
r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
_, body = r.expect(wire.FrameForgetTask)
shape(t, "frames/forget_task.json", r.runner.Received[len(r.runner.Received)-1])
if f := body.(*wire.ForgetTaskCommand); f.TaskID != id || f.Person != Owner || f.KeepUntil == nil || time.Until(*f.KeepUntil) < wire.KeepMergedSessions-time.Minute || time.Until(*f.KeepUntil) > wire.KeepMergedSessions {
t.Fatalf("forget %+v", f)
}
if q, _ := r.client.Question(ctx, q5.ID); wire.QuestionTerminal(q.State) {
t.Fatalf("the merge stopped a question %+v", q)
}
if _, err := r.client.Ask(ctx, id, "And after the merge?", "", "k6"); err != nil {
t.Fatalf("asking about merged work: %v", err)
}
if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, `action="/tasks/`+id+`/ask"`) {
t.Fatalf("the page offers no asking about merged work: %s", page)
}
// Fourteen days after it was done, nobody can ask any more.
if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET done_at = ? WHERE id = ?", time.Now().Add(-wire.KeepMergedSessions-time.Hour).UTC(), id); err != nil {
t.Fatal(err)
}
if _, err := r.client.Ask(ctx, id, "Too late?", "", "k7"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "task_ended") {
t.Fatalf("asked 14 days after the merge: %v", err)
}
if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, `action="/tasks/`+id+`/ask"`) {
t.Fatal("the page offers asking 14 days after the merge")
}
// The task carries its thread of questions.
k, _ := mate.client.Task(ctx, id)
if len(k.Questions) != 5 || k.Questions[0].Answer != "I fixed the typo." {
t.Fatalf("task questions %+v", k.Questions)
}
}
// TestPagesTaskThread: the task page's thread is the same questions a
// device reads. The creator's composer asks (Asking Engineering, with
// change between the specialists that can answer); an answered question
// is a reply the stream can settle into; a waiting one is a thinking
// line; an ended one says why. A teammate reads the thread, and their
// composer adds a note; asking from the page is the creator's alone.
func TestPagesTaskThread(t *testing.T) {
r := newToolRigAt(t, wire.ProtocolInjectionDefences)
owner := r.inst.Cookie()
base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
id, _, _ := r.askableTask("a", base, cand)
page := r.get(owner, "/tasks/"+id, 200)
for _, want := range []string{`data-chat-stream data-task="` + id + `"`, `action="/tasks/` + id + `/ask"`, "Asking Engineering", "data-ask-change", `data-choices="engineering,review"`, "No questions or notes yet.", `id="chat-composer"`} {
if !strings.Contains(page, want) {
t.Fatalf("creator's thread lacks %q: %s", want, page)
}
}
// Asked from the page, in the background like the chat.
req, _ := http.NewRequest("POST", r.inst.URL+"/tasks/"+id+"/ask", strings.NewReader(url.Values{"body": {"What did you change?"}, "request_id": {"pg1"}, "specialist": {""}}.Encode()))
req.AddCookie(owner)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", r.inst.URL)
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
var sent struct {
Message struct {
ID string `json:"id"`
} `json:"message"`
}
json.NewDecoder(res.Body).Decode(&sent)
res.Body.Close()
if res.StatusCode != 200 || !strings.HasPrefix(sent.Message.ID, "q_") {
t.Fatalf("ask from the page: %d %+v", res.StatusCode, sent)
}
r.expect(wire.FrameAsk)
q2, _ := r.client.Ask(r.ctx, id, "And the review?", wire.SpecialistReview, "pg2")
page = r.get(owner, "/tasks/"+id, 200)
if !strings.Contains(page, `data-message="`+sent.Message.ID+`"`) || !strings.Contains(page, `equipo-thinking data-turn="`+sent.Message.ID+`"`) || !strings.Contains(page, `equipo-thinking data-turn="`+q2.ID+`"`) || !strings.Contains(page, "Waiting for its turn…") {
t.Fatalf("waiting questions: %s", page)
}
r.answer("r-pg1", wire.AnswerReport{TaskID: id, QuestionID: sent.Message.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I changed **teh** to the."})
r.expect(wire.FrameAsk)
r.answer("r-pg2", wire.AnswerReport{TaskID: id, QuestionID: q2.ID, Attempt: 1, State: wire.QuestionFailed, Reason: "session_gone"})
page = r.get(owner, "/tasks/"+id, 200)
if !strings.Contains(page, `data-turn-id="`+sent.Message.ID+`"`) || !strings.Contains(page, "teh") || !strings.Contains(page, "Review couldn't answer: its session for this work is no longer kept.") {
t.Fatalf("answered and failed questions: %s", page)
}
// A teammate reads it all; their composer adds a note, never asks.
mate := r.memberCookie()
page = r.get(mate, "/tasks/"+id, 200)
if !strings.Contains(page, "teh") || strings.Contains(page, "/ask\"") || strings.Contains(page, "equipo-ask-target") || !strings.Contains(page, `action="/tasks/`+id+`/notes"`) {
t.Fatalf("teammate's thread: %s", page)
}
if code, _ := r.post(mate, "/tasks/"+id+"/ask", url.Values{"body": {"Why?"}, "request_id": {"m1"}}); code != http.StatusForbidden {
t.Fatalf("teammate asked from the page: %d", code)
}
if code, _ := r.post(mate, "/tasks/"+id+"/notes", url.Values{"body": {"Looks good to me."}, "request_id": {"m2"}}); code != http.StatusSeeOther {
t.Fatalf("teammate's note: %d", code)
}
if page = r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, "Looks good to me.") {
t.Fatalf("the note is not in the thread: %s", page)
}
}