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 "context"
5 "net/http"
6 "net/url"
7 "strings"
8 "sync"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/equipo"
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16// What a turn was allowed, asked and given goes with it to its retry
17// (chat.Retry): the project the person chose, a question still waiting on
18// them, the words that ask for access, and what was already asked.
19
20// retried fails the tool rig's turn, tries it again, and makes the retry
21// the turn its calls belong to, at its attempt.
22func (r *toolRig) retried(reason string) *wire.MessageCommand {
23 r.t.Helper()
24 failed := r.turn
25 r.failOn(r.runner, failed, reason, "")
26 if _, err := r.client.Retry(r.ctx, failed); err != nil {
27 r.t.Fatal(err)
28 }
29 _, body := r.expect(wire.FrameMessage)
30 cmd := body.(*wire.MessageCommand)
31 r.turn, r.attempt = cmd.TurnID, cmd.Attempt
32 r.turnIs(cmd.TurnID, wire.TurnRunning)
33 return cmd
34}
35
36// A placement answer's turn that failed and is tried again keeps the
37// project the person chose: no other repository is created or recorded.
38func TestContractRetryKeepsChosenProject(t *testing.T) {
39 r := newToolRigSaying(t, wire.ProtocolCurrent, "Make a calendar")
40 if res := r.call("placement-q", wire.ToolAskPerson, map[string]any{"question": "Where?", "placement": wire.Placement{Repos: []string{"oficina/sample"}, NewRepo: "oficina/calendar"}}); res.Code != "asked" {
41 t.Fatal(res)
42 }
43 if err := r.runner.Send(r.ctx, "finish-ask", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Where should it go?"}); err != nil {
44 t.Fatal(err)
45 }
46 r.turnIs(r.turn, wire.TurnReplied)
47 snap, _ := r.client.Snapshot(r.ctx)
48 var card wire.Card
49 for _, c := range snap.Cards {
50 if c.Kind == wire.CardQuestion {
51 card = c
52 }
53 }
54 if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision); err != nil {
55 t.Fatal(err)
56 }
57 _, body := r.expect(wire.FrameMessage)
58 r.turn = body.(*wire.MessageCommand).TurnID
59 r.turnIs(r.turn, wire.TurnRunning)
60 if cmd := r.retried("provider_failed"); !strings.Contains(cmd.Text, "Make a calendar") {
61 t.Fatalf("the retried answer lost the original request %q", cmd.Text)
62 }
63 if got := r.call("wrong-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/other"}); !got.IsError {
64 t.Fatal("a retry created another repository", got)
65 }
66 if got := r.call("wrong-record", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Misfiled calendar", "brief": "Make the calendar"}); !got.IsError || got.Code != "placement_mismatch" {
67 t.Fatal("a retry recorded outside the chosen project", got)
68 }
69 if got := r.call("right-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); got.Code != "create" {
70 t.Fatal("the chosen project", got)
71 }
72 if _, err := r.client.Answer(r.ctx, card.ID, "Add to oficina/sample", card.Revision); err == nil {
73 t.Fatal("the answered card took another answer")
74 }
75}
76
77// A placement question the failed turn asked still waits on the person in
78// its retry: nothing is recorded before they choose.
79func TestContractRetryKeepsPendingChoice(t *testing.T) {
80 r := newToolRigSaying(t, wire.ProtocolCurrent, "Make a calendar")
81 if res := r.call("placement-q", wire.ToolAskPerson, map[string]any{"question": "Where?", "placement": wire.Placement{Repos: []string{"oficina/sample"}, NewRepo: "oficina/calendar"}}); res.Code != "asked" {
82 t.Fatal(res)
83 }
84 r.retried("turn_timeout")
85 if got := r.call("record-early", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Calendar", "brief": "Make the calendar"}); !got.IsError || got.Code != "placement_pending" {
86 t.Fatal("a retry recorded before the person chose", got)
87 }
88 if got := r.call("create-early", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); !got.IsError {
89 t.Fatal("a retry created before the person chose", got)
90 }
91}
92
93// The person's words that ask for access are the retry's too; an access
94// card the failed turn raised is the retry's, and not raised again.
95func TestContractRetryKeepsAccessRequest(t *testing.T) {
96 const reason = "I need access to fix the build."
97 t.Run("provenance", func(t *testing.T) {
98 r := newToolRigSaying(t, wire.ProtocolCurrent, "Please get access to the whole carlos namespace")
99 r.retried("provider_failed")
100 if got := r.call("access", wire.ToolRequestAccess, map[string]any{"target": "carlos", "reason": reason}); got.Code != "asked" {
101 t.Fatal("the retry lost the person's request", got)
102 }
103 })
104 t.Run("spent", func(t *testing.T) {
105 r := newToolRigSaying(t, wire.ProtocolCurrent, "Please get access to carlos/platform")
106 if got := r.call("access", wire.ToolRequestAccess, map[string]any{"target": "carlos/platform", "reason": reason}); got.Code != "asked" {
107 t.Fatal(got)
108 }
109 r.retried("provider_failed")
110 // The failed attempt asked: the retry, its next attempt, is answered
111 // from that (the ledger), with no second card, whatever it asks.
112 for i, why := range []string{reason, "Another reason to ask again."} {
113 if got := r.call("access-again-"+itoa(i), wire.ToolRequestAccess, map[string]any{"target": "carlos/platform", "reason": why}); got.Code != "asked" && got.Code != "already_asked" {
114 t.Fatal(got)
115 }
116 }
117 if all, mine := r.count("SELECT count(*) FROM chat_cards WHERE kind = ?", wire.CardAccess), r.count("SELECT count(*) FROM chat_cards WHERE kind = ? AND turn_id = ?", wire.CardAccess, r.turn); all != 1 || mine != 1 {
118 t.Fatalf("%d access cards, %d on the retry", all, mine)
119 }
120 })
121}
122
123// Try again from several places at once: one retry, one frame.
124func TestContractRetryConcurrent(t *testing.T) {
125 r, runner := retryRig(t, nil)
126 failed := r.say(runner, "Again, please", "k1").TurnID
127 r.failOn(runner, failed, "turn_timeout", "")
128 var wg sync.WaitGroup
129 ids := make(chan string, 8)
130 codes := make(chan int, 8)
131 for i := range 8 {
132 wg.Add(1)
133 go func() {
134 defer wg.Done()
135 if i%2 == 0 {
136 v, err := r.client.Retry(r.ctx, failed)
137 if err != nil {
138 codes <- Status(err)
139 return
140 }
141 ids <- v.ID
142 return
143 }
144 req, _ := http.NewRequest("POST", r.inst.URL+"/conversation/turns/"+failed+"/retry", strings.NewReader(url.Values{}.Encode()))
145 req.AddCookie(r.inst.Cookie())
146 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
147 req.Header.Set("Origin", r.inst.URL)
148 req.Header.Set("Sec-Fetch-Site", "same-origin")
149 res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req)
150 if err != nil {
151 codes <- 0
152 return
153 }
154 res.Body.Close()
155 if res.StatusCode != http.StatusSeeOther {
156 codes <- res.StatusCode
157 }
158 }()
159 }
160 wg.Wait()
161 close(ids)
162 close(codes)
163 for code := range codes {
164 t.Errorf("a concurrent Try again answered %d", code)
165 }
166 var first string
167 for id := range ids {
168 if first == "" {
169 first = id
170 }
171 if id != first {
172 t.Fatalf("two retries: %s and %s", first, id)
173 }
174 }
175 if n := r.count("SELECT count(*) FROM chat_turns WHERE retry_of = ?", failed); n != 1 {
176 t.Fatalf("%d retries queued", n)
177 }
178 if cmd := r.running(runner); cmd.TurnID != first {
179 t.Fatalf("the frame is for %s, not %s", cmd.TurnID, first)
180 }
181 if n := r.count("SELECT count(*) FROM runner_commands WHERE kind = ?", wire.FrameMessage); n != 2 {
182 t.Fatalf("%d message commands, want the first and one retry", n)
183 }
184}
185
186// A failed turn's note goes once a newer turn of the person's waits: for
187// a connection, or behind a turn the coordinator took on its own.
188func TestContractEndedNoteGoesWhileWaiting(t *testing.T) {
189 t.Run("no connection", func(t *testing.T) {
190 r, runner := retryRig(t, nil)
191 failed := r.say(runner, "First", "k1").TurnID
192 r.failOn(runner, failed, "turn_timeout", "")
193 waiting := r.say(runner, "Second", "k2").TurnID
194 runner.Send(r.ctx, "w-"+waiting, wire.FrameTurn, wire.TurnReport{TurnID: waiting, Attempt: 1, State: wire.TurnWaiting, Reason: wire.ReasonNoConnection})
195 r.turnIs(waiting, wire.TurnWaiting)
196 if page := r.inst.Get(t, "/conversation"); strings.Contains(page, `data-ended="`+failed) || !strings.Contains(page, `data-no-connection="`+waiting) {
197 t.Fatal("the failed turn's note came back while the next waits for a connection")
198 }
199 })
200 t.Run("queued behind", func(t *testing.T) {
201 r := newMoveInRig(t)
202 if _, err := r.client.Send(r.ctx, "First", "k1"); err != nil {
203 t.Fatal(err)
204 }
205 failed := r.dispatched(wire.TurnPerson).TurnID
206 r.failOn(r.runner, failed, "turn_timeout", "")
207 r.moveIn("r-mi-1", wire.TurnMoveIn)
208 queued, err := r.client.Send(r.ctx, "Second", "k2")
209 if err != nil || queued.Turn.State != wire.TurnQueued {
210 t.Fatalf("%+v %v", queued.Turn, err)
211 }
212 if page := r.inst.Get(t, "/conversation"); strings.Contains(page, `data-ended="`+failed) {
213 t.Fatal("the failed turn's note came back while the next is queued behind a move-in")
214 }
215 })
216}
217
218// What the failed attempt did is not done again: the task it recorded is
219// the retry's, answered from the ledger, not a second task.
220func TestContractRetryDoesNotRedo(t *testing.T) {
221 r := newToolRigAt(t, wire.ProtocolCurrent)
222 args := map[string]string{"repo": "oficina/sample", "title": "Fix the compose sheet", "brief": "The compose sheet loses its draft."}
223 first := r.call("record", wire.ToolRecordTask, args)
224 if first.Code != "recorded" {
225 t.Fatal(first)
226 }
227 r.retried("provider_failed")
228 if again := r.call("record", wire.ToolRecordTask, args); again.Code != "recorded" || again.Text != first.Text {
229 t.Fatalf("the retry recorded %+v, not the failed attempt's %+v", again, first)
230 }
231 if n := r.count("SELECT count(*) FROM chat_tasks"); n != 1 {
232 t.Fatalf("%d tasks", n)
233 }
234 if n := r.count("SELECT count(*) FROM chat_tasks WHERE turn_id = ?", r.turn); n != 1 {
235 t.Fatal("the task is not the retry's")
236 }
237}
238
239// A repository creation the failed turn used stays used: the person's
240// words for a new project, now the retry's, grant no second repository.
241func TestContractRetryKeepsSpentCreation(t *testing.T) {
242 r := newToolRigSaying(t, wire.ProtocolCurrent, "Create a new project for the calendar")
243 if got := r.call("create-a", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); got.Code != "create" {
244 t.Fatal("the person's words", got)
245 }
246 r.retried("provider_failed")
247 if got := r.call("create-b", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/other"}); !got.IsError || got.Code != "placement_required" {
248 t.Fatal("a retry created a second repository", got)
249 }
250 if n := r.count("SELECT count(*) FROM chat_turns WHERE id = ? AND create_repo = ?", r.turn, "amadan.net/oficina/calendar"); n != 1 {
251 t.Fatal("the retry lost what was spent")
252 }
253}
254
255// Every member's live stream hears of a task the retry took over, at a
256// new revision naming the retry's turn.
257func TestContractRetryTellsEveryMember(t *testing.T) {
258 r := newToolRigAt(t, wire.ProtocolCurrent)
259 if got := r.call("record", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the compose sheet", "brief": "The compose sheet loses its draft."}); got.Code != "recorded" {
260 t.Fatal(got)
261 }
262 const member = "member@example.com"
263 if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil {
264 t.Fatal(err)
265 }
266 mate := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member))
267 snap, err := mate.Snapshot(r.ctx)
268 if err != nil {
269 t.Fatal(err)
270 }
271 var before wire.Task
272 for _, k := range snap.Tasks {
273 before = k
274 }
275 if before.ID == "" {
276 t.Fatal("the member does not see the task")
277 }
278 view := NewConversation(snap)
279 s, err := mate.Open(r.ctx, snap.Cursor)
280 if err != nil {
281 t.Fatal(err)
282 }
283 t.Cleanup(s.Close)
284 go view.Follow(s)
285 cmd := r.retried("provider_failed")
286 if !view.Wait(10*time.Second, func(c *Conversation) bool {
287 k := c.Tasks[before.ID]
288 return k.Revision > before.Revision && k.TurnID == cmd.TurnID
289 }) {
290 t.Fatalf("the member's stream kept %+v", view.Tasks[before.ID].TurnID)
291 }
292 if k, err := mate.Task(r.ctx, before.ID); err != nil || k.TurnID != cmd.TurnID || k.Revision <= before.Revision || k.SourceMessageID == "" {
293 t.Fatalf("the member reads %+v %v", k, err)
294 }
295}
296
297// A reply in a card's thread that failed and is tried again stays in the
298// thread, and the card is told again at a new revision.
299func TestContractRetryKeepsThread(t *testing.T) {
300 r := newToolRigAt(t, wire.ProtocolCurrent)
301 if res := r.call("q", wire.ToolAskPerson, map[string]any{"question": "Which page?", "options": []string{"Login", "Home"}}); res.Code != "asked" {
302 t.Fatal(res)
303 }
304 r.runner.Send(r.ctx, "rep-q", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Which page?"})
305 r.turnIs(r.turn, wire.TurnReplied)
306 var card wire.Card
307 r.wait("question card", func(c *Conversation) bool {
308 for _, k := range c.Cards {
309 if k.Kind == wire.CardQuestion {
310 card = k
311 }
312 }
313 return card.ID != ""
314 })
315 answered, err := r.client.Answer(r.ctx, card.ID, "Login", card.Revision)
316 if err != nil {
317 t.Fatal(err)
318 }
319 r.expect(wire.FrameMessage)
320 r.runner.Send(r.ctx, "rep-a", wire.FrameReply, wire.Reply{TurnID: answered.Turn.ID, Attempt: 1, Text: "Looking at login."})
321 r.turnIs(answered.Turn.ID, wire.TurnReplied)
322 if status, _ := r.post(r.inst.Cookie(), "/conversation/cards/"+card.ID+"/reply", url.Values{"request_id": {"k-thread"}, "body": {"Only on Safari"}}); status != http.StatusSeeOther {
323 t.Fatal("thread reply", status)
324 }
325 _, body := r.expect(wire.FrameMessage)
326 r.turn = body.(*wire.MessageCommand).TurnID
327 r.turnIs(r.turn, wire.TurnRunning)
328 var before int64
329 r.wait("the thread's card", func(c *Conversation) bool { before = c.Cards[card.ID].Revision; return before > 0 })
330 r.retried("provider_failed")
331 if n := r.count("SELECT count(*) FROM chat_card_threads WHERE card_id = ? AND turn_id = ?", card.ID, r.turn); n != 1 {
332 t.Fatal("the thread lost the retried reply")
333 }
334 r.wait("the card told again", func(c *Conversation) bool { return c.Cards[card.ID].Revision > before })
335}
336