package thintest import ( "context" "net/http" "net/url" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // What a turn was allowed, asked and given goes with it to its retry // (chat.Retry): the project the person chose, a question still waiting on // them, the words that ask for access, and what was already asked. // retried fails the tool rig's turn, tries it again, and makes the retry // the turn its calls belong to, at its attempt. func (r *toolRig) retried(reason string) *wire.MessageCommand { r.t.Helper() failed := r.turn r.failOn(r.runner, failed, reason, "") if _, err := r.client.Retry(r.ctx, failed); err != nil { r.t.Fatal(err) } _, body := r.expect(wire.FrameMessage) cmd := body.(*wire.MessageCommand) r.turn, r.attempt = cmd.TurnID, cmd.Attempt r.turnIs(cmd.TurnID, wire.TurnRunning) return cmd } // A placement answer's turn that failed and is tried again keeps the // project the person chose: no other repository is created or recorded. func TestContractRetryKeepsChosenProject(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, "Make a calendar") 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" { t.Fatal(res) } 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 { t.Fatal(err) } r.turnIs(r.turn, wire.TurnReplied) snap, _ := r.client.Snapshot(r.ctx) var card wire.Card for _, c := range snap.Cards { if c.Kind == wire.CardQuestion { card = c } } if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision); err != nil { t.Fatal(err) } _, body := r.expect(wire.FrameMessage) r.turn = body.(*wire.MessageCommand).TurnID r.turnIs(r.turn, wire.TurnRunning) if cmd := r.retried("provider_failed"); !strings.Contains(cmd.Text, "Make a calendar") { t.Fatalf("the retried answer lost the original request %q", cmd.Text) } if got := r.call("wrong-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/other"}); !got.IsError { t.Fatal("a retry created another repository", got) } 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" { t.Fatal("a retry recorded outside the chosen project", got) } if got := r.call("right-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); got.Code != "create" { t.Fatal("the chosen project", got) } if _, err := r.client.Answer(r.ctx, card.ID, "Add to oficina/sample", card.Revision); err == nil { t.Fatal("the answered card took another answer") } } // A placement question the failed turn asked still waits on the person in // its retry: nothing is recorded before they choose. func TestContractRetryKeepsPendingChoice(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, "Make a calendar") 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" { t.Fatal(res) } r.retried("turn_timeout") 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" { t.Fatal("a retry recorded before the person chose", got) } if got := r.call("create-early", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); !got.IsError { t.Fatal("a retry created before the person chose", got) } } // The person's words that ask for access are the retry's too; an access // card the failed turn raised is the retry's, and not raised again. func TestContractRetryKeepsAccessRequest(t *testing.T) { const reason = "I need access to fix the build." t.Run("provenance", func(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, "Please get access to the whole carlos namespace") r.retried("provider_failed") if got := r.call("access", wire.ToolRequestAccess, map[string]any{"target": "carlos", "reason": reason}); got.Code != "asked" { t.Fatal("the retry lost the person's request", got) } }) t.Run("spent", func(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, "Please get access to carlos/platform") if got := r.call("access", wire.ToolRequestAccess, map[string]any{"target": "carlos/platform", "reason": reason}); got.Code != "asked" { t.Fatal(got) } r.retried("provider_failed") // The failed attempt asked: the retry, its next attempt, is answered // from that (the ledger), with no second card, whatever it asks. for i, why := range []string{reason, "Another reason to ask again."} { 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" { t.Fatal(got) } } 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 { t.Fatalf("%d access cards, %d on the retry", all, mine) } }) } // Try again from several places at once: one retry, one frame. func TestContractRetryConcurrent(t *testing.T) { r, runner := retryRig(t, nil) failed := r.say(runner, "Again, please", "k1").TurnID r.failOn(runner, failed, "turn_timeout", "") var wg sync.WaitGroup ids := make(chan string, 8) codes := make(chan int, 8) for i := range 8 { wg.Add(1) go func() { defer wg.Done() if i%2 == 0 { v, err := r.client.Retry(r.ctx, failed) if err != nil { codes <- Status(err) return } ids <- v.ID return } req, _ := http.NewRequest("POST", r.inst.URL+"/conversation/turns/"+failed+"/retry", strings.NewReader(url.Values{}.Encode())) req.AddCookie(r.inst.Cookie()) 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") res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) if err != nil { codes <- 0 return } res.Body.Close() if res.StatusCode != http.StatusSeeOther { codes <- res.StatusCode } }() } wg.Wait() close(ids) close(codes) for code := range codes { t.Errorf("a concurrent Try again answered %d", code) } var first string for id := range ids { if first == "" { first = id } if id != first { t.Fatalf("two retries: %s and %s", first, id) } } if n := r.count("SELECT count(*) FROM chat_turns WHERE retry_of = ?", failed); n != 1 { t.Fatalf("%d retries queued", n) } if cmd := r.running(runner); cmd.TurnID != first { t.Fatalf("the frame is for %s, not %s", cmd.TurnID, first) } if n := r.count("SELECT count(*) FROM runner_commands WHERE kind = ?", wire.FrameMessage); n != 2 { t.Fatalf("%d message commands, want the first and one retry", n) } } // A failed turn's note goes once a newer turn of the person's waits: for // a connection, or behind a turn the coordinator took on its own. func TestContractEndedNoteGoesWhileWaiting(t *testing.T) { t.Run("no connection", func(t *testing.T) { r, runner := retryRig(t, nil) failed := r.say(runner, "First", "k1").TurnID r.failOn(runner, failed, "turn_timeout", "") waiting := r.say(runner, "Second", "k2").TurnID runner.Send(r.ctx, "w-"+waiting, wire.FrameTurn, wire.TurnReport{TurnID: waiting, Attempt: 1, State: wire.TurnWaiting, Reason: wire.ReasonNoConnection}) r.turnIs(waiting, wire.TurnWaiting) if page := r.inst.Get(t, "/conversation"); strings.Contains(page, `data-ended="`+failed) || !strings.Contains(page, `data-no-connection="`+waiting) { t.Fatal("the failed turn's note came back while the next waits for a connection") } }) t.Run("queued behind", func(t *testing.T) { r := newMoveInRig(t) if _, err := r.client.Send(r.ctx, "First", "k1"); err != nil { t.Fatal(err) } failed := r.dispatched(wire.TurnPerson).TurnID r.failOn(r.runner, failed, "turn_timeout", "") r.moveIn("r-mi-1", wire.TurnMoveIn) queued, err := r.client.Send(r.ctx, "Second", "k2") if err != nil || queued.Turn.State != wire.TurnQueued { t.Fatalf("%+v %v", queued.Turn, err) } if page := r.inst.Get(t, "/conversation"); strings.Contains(page, `data-ended="`+failed) { t.Fatal("the failed turn's note came back while the next is queued behind a move-in") } }) } // What the failed attempt did is not done again: the task it recorded is // the retry's, answered from the ledger, not a second task. func TestContractRetryDoesNotRedo(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) args := map[string]string{"repo": "oficina/sample", "title": "Fix the compose sheet", "brief": "The compose sheet loses its draft."} first := r.call("record", wire.ToolRecordTask, args) if first.Code != "recorded" { t.Fatal(first) } r.retried("provider_failed") if again := r.call("record", wire.ToolRecordTask, args); again.Code != "recorded" || again.Text != first.Text { t.Fatalf("the retry recorded %+v, not the failed attempt's %+v", again, first) } if n := r.count("SELECT count(*) FROM chat_tasks"); n != 1 { t.Fatalf("%d tasks", n) } if n := r.count("SELECT count(*) FROM chat_tasks WHERE turn_id = ?", r.turn); n != 1 { t.Fatal("the task is not the retry's") } } // A repository creation the failed turn used stays used: the person's // words for a new project, now the retry's, grant no second repository. func TestContractRetryKeepsSpentCreation(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, "Create a new project for the calendar") if got := r.call("create-a", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); got.Code != "create" { t.Fatal("the person's words", got) } r.retried("provider_failed") if got := r.call("create-b", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/other"}); !got.IsError || got.Code != "placement_required" { t.Fatal("a retry created a second repository", got) } if n := r.count("SELECT count(*) FROM chat_turns WHERE id = ? AND create_repo = ?", r.turn, "amadan.net/oficina/calendar"); n != 1 { t.Fatal("the retry lost what was spent") } } // Every member's live stream hears of a task the retry took over, at a // new revision naming the retry's turn. func TestContractRetryTellsEveryMember(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) 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" { t.Fatal(got) } const member = "member@example.com" if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil { t.Fatal(err) } mate := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member)) snap, err := mate.Snapshot(r.ctx) if err != nil { t.Fatal(err) } var before wire.Task for _, k := range snap.Tasks { before = k } if before.ID == "" { t.Fatal("the member does not see the task") } view := NewConversation(snap) s, err := mate.Open(r.ctx, snap.Cursor) if err != nil { t.Fatal(err) } t.Cleanup(s.Close) go view.Follow(s) cmd := r.retried("provider_failed") if !view.Wait(10*time.Second, func(c *Conversation) bool { k := c.Tasks[before.ID] return k.Revision > before.Revision && k.TurnID == cmd.TurnID }) { t.Fatalf("the member's stream kept %+v", view.Tasks[before.ID].TurnID) } if k, err := mate.Task(r.ctx, before.ID); err != nil || k.TurnID != cmd.TurnID || k.Revision <= before.Revision || k.SourceMessageID == "" { t.Fatalf("the member reads %+v %v", k, err) } } // A reply in a card's thread that failed and is tried again stays in the // thread, and the card is told again at a new revision. func TestContractRetryKeepsThread(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) if res := r.call("q", wire.ToolAskPerson, map[string]any{"question": "Which page?", "options": []string{"Login", "Home"}}); res.Code != "asked" { t.Fatal(res) } r.runner.Send(r.ctx, "rep-q", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Which page?"}) r.turnIs(r.turn, wire.TurnReplied) var card wire.Card r.wait("question card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardQuestion { card = k } } return card.ID != "" }) answered, err := r.client.Answer(r.ctx, card.ID, "Login", card.Revision) if err != nil { t.Fatal(err) } r.expect(wire.FrameMessage) r.runner.Send(r.ctx, "rep-a", wire.FrameReply, wire.Reply{TurnID: answered.Turn.ID, Attempt: 1, Text: "Looking at login."}) r.turnIs(answered.Turn.ID, wire.TurnReplied) 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 { t.Fatal("thread reply", status) } _, body := r.expect(wire.FrameMessage) r.turn = body.(*wire.MessageCommand).TurnID r.turnIs(r.turn, wire.TurnRunning) var before int64 r.wait("the thread's card", func(c *Conversation) bool { before = c.Cards[card.ID].Revision; return before > 0 }) r.retried("provider_failed") if n := r.count("SELECT count(*) FROM chat_card_threads WHERE card_id = ? AND turn_id = ?", card.ID, r.turn); n != 1 { t.Fatal("the thread lost the retried reply") } r.wait("the card told again", func(c *Conversation) bool { return c.Cards[card.ID].Revision > before }) }