oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "encoding/json"
5 "net/http"
6 "net/url"
7 "strings"
8 "testing"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/equipo"
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15// answer sends one answer report and waits for its ack.
16func (r *toolRig) answer(id string, rep wire.AnswerReport) {
17 r.t.Helper()
18 r.step2(id, wire.FrameAnswer, rep)
19}
20
21// step2 sends a durable runner frame and waits for its ack, holding any
22// command it caused for expect.
23func (r *toolRig) step2(id, kind string, body any) {
24 r.t.Helper()
25 if err := r.runner.Send(r.ctx, id, kind, body); err != nil {
26 r.t.Fatal(err)
27 }
28 for {
29 f, b, err := r.runner.Next(r.ctx)
30 if err != nil {
31 r.t.Fatal(err)
32 }
33 if a, ok := b.(*wire.Ack); ok && f.Type == wire.FrameAck && a.ID == id {
34 return
35 }
36 if f.Type != wire.FrameAck {
37 r.held = append(r.held, heldFrame{f: f, body: b, raw: r.runner.Received[len(r.runner.Received)-1]})
38 }
39 }
40}
41
42// heldKinds counts the frames of kind held for expect.
43func (r *toolRig) heldKinds(kind string) int {
44 n := 0
45 for _, h := range r.held {
46 if h.f.Type == kind {
47 n++
48 }
49 }
50 return n
51}
52
53// askableTask is a task whose Engineering step pushed cand and whose
54// review approved it, both with their sessions kept.
55func (r *toolRig) askableTask(key, base, cand string) (id string, eng, rev *wire.DispatchCommand) {
56 r.t.Helper()
57 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}))
58 r.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."})
59 _, body := r.expect(wire.FrameDispatch)
60 eng = body.(*wire.DispatchCommand)
61 r.step(key+"-run", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
62 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})
63 r.expect(wire.FrameWatchMerge)
64 c := r.dispatched(wire.SpecialistChecks, base, cand, 0)
65 r.checks(key+"-c", c, wire.ChecksPassed, exit(0), "", "ok\n")
66 rev = r.dispatched(wire.SpecialistReview, base, cand, 0)
67 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})
68 // Approved with checks passed: Equipo merges it (this fake runner
69 // leaves the merge running), or, below wire.ProtocolInjectionDefences, asks.
70 if r.runner.Welcome.Protocol < wire.ProtocolInjectionDefences {
71 r.wait("asking", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageReadyToMerge })
72 return id, eng, rev
73 }
74 r.dispatched(wire.SpecialistMerge, base, cand, 0)
75 r.wait("merging", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageMerging })
76 return id, eng, rev
77}
78
79// TestContractAskImplementer: the task's creator asks the specialist
80// that did the work. The question goes to the newest Engineering step by
81// default, or to Review when it addresses Review; it reaches the runner
82// with the step and the exact commit; its answer streams to every
83// member like a chat reply and is committed on the question. One
84// question of a task is with the runner at a time; the next waits.
85// Teammates read and never ask; cancel goes through the runner; a sync
86// that no longer holds an acked question fails it; the task's end stops
87// questions and lets the runner forget its sessions.
88func TestContractAskImplementer(t *testing.T) {
89 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
90 ctx := r.ctx
91 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
92 // The teammate is an owner with a runner of their own: still not
93 // the task's creator.
94 mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner)
95 id, eng, rev := r.askableTask("a", base, cand)
96 if k, _ := r.client.Task(ctx, id); !k.Steps[0].Askable || !k.Steps[2].Askable || k.Steps[1].Askable || len(k.Questions) != 0 {
97 t.Fatalf("askable steps %+v", k.Steps)
98 }
99
100 // A teammate reads the task and cannot ask.
101 if _, err := mate.client.Ask(ctx, id, "What did you change?", "", "m1"); Status(err) != http.StatusForbidden {
102 t.Fatalf("teammate asked: %v", err)
103 }
104 // Bad input.
105 if _, err := r.client.Ask(ctx, id, " ", "", "k0"); Status(err) != 422 {
106 t.Fatalf("empty question: %v", err)
107 }
108 if _, err := r.client.Ask(ctx, id, "Why?", "checks", "k0"); Status(err) != 422 {
109 t.Fatalf("checks asked: %v", err)
110 }
111
112 // The creator asks; by default Engineering answers, on its commit.
113 q1, err := r.client.Ask(ctx, id, "What did you change and why?", "", "k1")
114 if err != nil {
115 t.Fatal(err)
116 }
117 if q1.StepID != eng.StepID || q1.Specialist != wire.SpecialistEngineering || q1.State != wire.QuestionQueued || q1.Asker != Owner {
118 t.Fatalf("question %+v", q1)
119 }
120 _, body := r.expect(wire.FrameAsk)
121 shape(t, "frames/ask.json", r.runner.Received[len(r.runner.Received)-1])
122 a1 := body.(*wire.AskCommand)
123 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 {
124 t.Fatalf("ask %+v", a1)
125 }
126 // The same key is the same question; another body under it is 409.
127 if again, err := r.client.Ask(ctx, id, "What did you change and why?", "", "k1"); err != nil || again.ID != q1.ID {
128 t.Fatalf("repeat %+v %v", again, err)
129 }
130 if _, err := r.client.Ask(ctx, id, "Something else", "", "k1"); Status(err) != http.StatusConflict {
131 t.Fatalf("conflict: %v", err)
132 }
133
134 // A second question, addressed to Review, waits for the first.
135 q2, err := r.client.Ask(ctx, id, "Review, anything you were unsure about?", "", "k2")
136 if err != nil || q2.StepID != rev.StepID || q2.Specialist != wire.SpecialistReview || q2.State != wire.QuestionQueued {
137 t.Fatalf("second question %+v %v", q2, err)
138 }
139 // Chosen explicitly, even without the word.
140 q3, err := r.client.Ask(ctx, id, "Anything else?", wire.SpecialistReview, "k3")
141 if err != nil || q3.StepID != rev.StepID {
142 t.Fatalf("third question %+v %v", q3, err)
143 }
144
145 // Another person's runner cannot answer it.
146 mate.answer("m-q1", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "Not mine to say."})
147 if q, _ := r.client.Question(ctx, q1.ID); q.State != wire.QuestionQueued || q.Answer != "" {
148 t.Fatalf("another runner answered: %+v", q)
149 }
150
151 // The answer streams to every member, the thinking line included.
152 r.answer("r-q1-run", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionRunning})
153 r.wait("running", func(c *Conversation) bool { return c.Questions[q1.ID].State == wire.QuestionRunning })
154 // Neither later question went to the runner while the first is there.
155 if n := r.heldKinds(wire.FrameAsk); n != 0 {
156 t.Fatalf("%d more questions went to the runner beside the first", n)
157 }
158 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 {
159 t.Fatal(err)
160 }
161 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 {
162 t.Fatal(err)
163 }
164 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 {
165 t.Fatal(err)
166 }
167 for _, who := range []*toolRig{r, mate} {
168 who.wait("the draft", func(c *Conversation) bool {
169 return c.Drafts[q1.ID] == "I fixed the typo." && c.DeltaResources[wire.ResourceQuestion] == 2 && len(c.Activity[q1.ID]) == 1
170 })
171 }
172 var act wire.Activity
173 r.conv.Locked(func(c *Conversation) { act = c.Activity[q1.ID][0] })
174 if act.Tool != "read_change" || act.Label == "" {
175 t.Fatalf("activity %+v", act)
176 }
177 if act.Label != "Looking at the change on ‘"+eng.Branch+"’…" {
178 t.Fatalf("creator's change subject: %+v", act)
179 }
180 mate.conv.Locked(func(c *Conversation) {
181 if got := c.Activity[q1.ID][0].Label; got != "Looking at the change…" {
182 t.Fatalf("another person's change was named: %q", got)
183 }
184 })
185 // Nothing streams into anyone's conversation.
186 r.conv.Locked(func(c *Conversation) {
187 if c.DeltaResources["turn"] != 0 {
188 t.Fatalf("question text streamed as a turn: %v", c.DeltaResources)
189 }
190 })
191 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}})
192 for _, who := range []*toolRig{r, mate} {
193 who.wait("answered", func(c *Conversation) bool {
194 q := c.Questions[q1.ID]
195 _, draft := c.Drafts[q1.ID]
196 return q.State == wire.QuestionAnswered && q.Answer == "I fixed the typo." && !draft
197 })
198 }
199 // A late report for the ended question changes nothing.
200 r.answer("r-q1-late", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionFailed, Reason: "provider_failed"})
201 q, _ := r.client.Question(ctx, q1.ID)
202 if q.State != wire.QuestionAnswered || q.Timing == nil || q.Timing.ResultMs != 1200 {
203 t.Fatalf("answered question %+v", q)
204 }
205 shape(t, "api/question.json", q)
206
207 // Then the second goes to the runner, to Review's step.
208 _, body = r.expect(wire.FrameAsk)
209 if a2 := body.(*wire.AskCommand); a2.QuestionID != q2.ID || a2.StepID != rev.StepID || a2.Specialist != wire.SpecialistReview || a2.CandidateSHA != cand {
210 t.Fatalf("second ask %+v", a2)
211 }
212 // Teammates cannot cancel it; the asker can, through the runner.
213 if _, err := mate.client.CancelQuestion(ctx, q2.ID); Status(err) != http.StatusForbidden {
214 t.Fatalf("teammate cancelled: %v", err)
215 }
216 if acc, err := r.client.CancelQuestion(ctx, q2.ID); err != nil || acc.Attempt != 1 {
217 t.Fatalf("cancel %+v %v", acc, err)
218 }
219 _, body = r.expect(wire.FrameCancelAsk)
220 shape(t, "frames/cancel_ask.json", r.runner.Received[len(r.runner.Received)-1])
221 if c := body.(*wire.CancelAskCommand); c.QuestionID != q2.ID || c.Attempt != 1 {
222 t.Fatalf("cancel_ask %+v", c)
223 }
224 if q, _ := r.client.Question(ctx, q2.ID); q.State != wire.QuestionQueued {
225 t.Fatalf("cancelled before the runner said so: %+v", q)
226 }
227 r.answer("r-q2-x", wire.AnswerReport{TaskID: id, QuestionID: q2.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
228 r.wait("cancelled", func(c *Conversation) bool { return c.Questions[q2.ID].State == wire.QuestionCancelled })
229 if _, err := r.client.CancelQuestion(ctx, q2.ID); Status(err) != http.StatusConflict {
230 t.Fatalf("cancel of an ended question: %v", err)
231 }
232
233 // The third goes next; a sync that no longer holds it fails it.
234 _, body = r.expect(wire.FrameAsk)
235 if a3 := body.(*wire.AskCommand); a3.QuestionID != q3.ID {
236 t.Fatalf("third ask %+v", a3)
237 }
238 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 {
239 t.Fatal(err)
240 }
241 r.wait("interrupted", func(c *Conversation) bool {
242 q := c.Questions[q3.ID]
243 return q.State == wire.QuestionFailed && q.Reason == "interrupted"
244 })
245
246 // A task with no session kept cannot be asked.
247 plain, _ := r.pushed("b", "Another typo", base, strings.Repeat("4", 40))
248 if _, err := r.client.Ask(ctx, plain, "Why?", "", "k4"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "not_askable") {
249 t.Fatalf("asked a step with no session: %v", err)
250 }
251
252 // The task is merged (Paul, 2026-11-08): its specialists can still be
253 // asked for 14 days. Questions carry on; the runner is told to keep
254 // the task's sessions until then and remove them after.
255 q5, err := r.client.Ask(ctx, id, "One more thing?", "", "k5")
256 if err != nil {
257 t.Fatal(err)
258 }
259 _, body = r.expect(wire.FrameAsk)
260 if a5 := body.(*wire.AskCommand); a5.QuestionID != q5.ID {
261 t.Fatalf("fifth ask %+v", a5)
262 }
263 r.step2("r-merged", wire.FrameMerged, wire.MergedReport{TaskID: id, CandidateSHA: cand})
264 r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
265 _, body = r.expect(wire.FrameForgetTask)
266 shape(t, "frames/forget_task.json", r.runner.Received[len(r.runner.Received)-1])
267 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 {
268 t.Fatalf("forget %+v", f)
269 }
270 if q, _ := r.client.Question(ctx, q5.ID); wire.QuestionTerminal(q.State) {
271 t.Fatalf("the merge stopped a question %+v", q)
272 }
273 if _, err := r.client.Ask(ctx, id, "And after the merge?", "", "k6"); err != nil {
274 t.Fatalf("asking about merged work: %v", err)
275 }
276 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, `action="/tasks/`+id+`/ask"`) {
277 t.Fatalf("the page offers no asking about merged work: %s", page)
278 }
279 // Fourteen days after it was done, nobody can ask any more.
280 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 {
281 t.Fatal(err)
282 }
283 if _, err := r.client.Ask(ctx, id, "Too late?", "", "k7"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "task_ended") {
284 t.Fatalf("asked 14 days after the merge: %v", err)
285 }
286 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, `action="/tasks/`+id+`/ask"`) {
287 t.Fatal("the page offers asking 14 days after the merge")
288 }
289 // The task carries its thread of questions.
290 k, _ := mate.client.Task(ctx, id)
291 if len(k.Questions) != 5 || k.Questions[0].Answer != "I fixed the typo." {
292 t.Fatalf("task questions %+v", k.Questions)
293 }
294}
295
296// TestPagesTaskThread: the task page's thread is the same questions a
297// device reads. The creator's composer asks (Asking Engineering, with
298// change between the specialists that can answer); an answered question
299// is a reply the stream can settle into; a waiting one is a thinking
300// line; an ended one says why. A teammate reads the thread, and their
301// composer adds a note; asking from the page is the creator's alone.
302func TestPagesTaskThread(t *testing.T) {
303 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
304 owner := r.inst.Cookie()
305 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
306 id, _, _ := r.askableTask("a", base, cand)
307 page := r.get(owner, "/tasks/"+id, 200)
308 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"`} {
309 if !strings.Contains(page, want) {
310 t.Fatalf("creator's thread lacks %q: %s", want, page)
311 }
312 }
313 // Asked from the page, in the background like the chat.
314 req, _ := http.NewRequest("POST", r.inst.URL+"/tasks/"+id+"/ask", strings.NewReader(url.Values{"body": {"What did you change?"}, "request_id": {"pg1"}, "specialist": {""}}.Encode()))
315 req.AddCookie(owner)
316 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
317 req.Header.Set("Origin", r.inst.URL)
318 req.Header.Set("Sec-Fetch-Site", "same-origin")
319 req.Header.Set("Accept", "application/json")
320 res, err := http.DefaultClient.Do(req)
321 if err != nil {
322 t.Fatal(err)
323 }
324 var sent struct {
325 Message struct {
326 ID string `json:"id"`
327 } `json:"message"`
328 }
329 json.NewDecoder(res.Body).Decode(&sent)
330 res.Body.Close()
331 if res.StatusCode != 200 || !strings.HasPrefix(sent.Message.ID, "q_") {
332 t.Fatalf("ask from the page: %d %+v", res.StatusCode, sent)
333 }
334 r.expect(wire.FrameAsk)
335 q2, _ := r.client.Ask(r.ctx, id, "And the review?", wire.SpecialistReview, "pg2")
336 page = r.get(owner, "/tasks/"+id, 200)
337 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…") {
338 t.Fatalf("waiting questions: %s", page)
339 }
340 r.answer("r-pg1", wire.AnswerReport{TaskID: id, QuestionID: sent.Message.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I changed **teh** to the."})
341 r.expect(wire.FrameAsk)
342 r.answer("r-pg2", wire.AnswerReport{TaskID: id, QuestionID: q2.ID, Attempt: 1, State: wire.QuestionFailed, Reason: "session_gone"})
343 page = r.get(owner, "/tasks/"+id, 200)
344 if !strings.Contains(page, `data-turn-id="`+sent.Message.ID+`"`) || !strings.Contains(page, "<strong>teh</strong>") || !strings.Contains(page, "Review couldn&#39;t answer: its session for this work is no longer kept.") {
345 t.Fatalf("answered and failed questions: %s", page)
346 }
347 // A teammate reads it all; their composer adds a note, never asks.
348 mate := r.memberCookie()
349 page = r.get(mate, "/tasks/"+id, 200)
350 if !strings.Contains(page, "<strong>teh</strong>") || strings.Contains(page, "/ask\"") || strings.Contains(page, "equipo-ask-target") || !strings.Contains(page, `action="/tasks/`+id+`/notes"`) {
351 t.Fatalf("teammate's thread: %s", page)
352 }
353 if code, _ := r.post(mate, "/tasks/"+id+"/ask", url.Values{"body": {"Why?"}, "request_id": {"m1"}}); code != http.StatusForbidden {
354 t.Fatalf("teammate asked from the page: %d", code)
355 }
356 if code, _ := r.post(mate, "/tasks/"+id+"/notes", url.Values{"body": {"Looks good to me."}, "request_id": {"m2"}}); code != http.StatusSeeOther {
357 t.Fatalf("teammate's note: %d", code)
358 }
359 if page = r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, "Looks good to me.") {
360 t.Fatalf("the note is not in the thread: %s", page)
361 }
362}
363