package thintest import ( "encoding/json" "fmt" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // What a job keeps track of past its first task: the change an // exploration it made becomes, a blocker only the person can clear // before work starts, a preview that goes, every open question, and its // card in a long Assistant lane. // TestContractHandoffExploreBuildFollowed: Build on a job's exploration // makes a change the job follows, as work it made, in the answer's own // transaction: the job works on while the change is built (never done), // team_status tells of it, a failed build step is the job's to push // through, and team_cancel stops it. func TestContractHandoffExploreBuildFollowed(t *testing.T) { o := newTeamRig(t) o.ask("Make me some mockups for the barber app") request, cmd := o.handoff("xb1", "mockups for the barber app", "") var id string o.in(cmd.TurnID, func() { id, _ = o.explored("xb", "Barber app mockups", candX) o.approved("xb", candX, true) }) var card wire.Card o.until("the direction card", func() bool { card = o.jobCard(request, wire.CardDirection, id) return card.State == wire.CardOpen }) if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceBuild, card.Revision); err != nil { t.Fatal(err) } d := o.nextDispatch() build := d.TaskID if d.Specialist != wire.SpecialistEngineering || build == id { t.Fatalf("the build's dispatch %+v", d) } if linked := o.linked(request); len(linked) != 2 || !linked[id] || !linked[build] { t.Fatalf("the job follows %v, not the exploration %s and its build %s", linked, id, build) } building, _ := jobStatus("building") job := o.jobOf(request, "building", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking && c.Result == building }) for _, e := range o.jobEvents(job.ID) { if e.State == wire.JobDone { t.Fatalf("the job said done while its build ran: %+v", e) } } if got := o.status("xb-st", map[string]any{"request": request}); len(got) != 1 || !strings.Contains(got[0].Summary, equipo.RunnerCopy("assistant.team.stage."+wire.StageInProgress)) { t.Fatalf("team_status %+v", got) } // Its build fails: the job's to push through. o.step("xb-fail", wire.StepReport{TaskID: build, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) o.noteFor("the failed note", failedStep(request, 2)) o.reply(o.turn) u := o.message(wire.LaneAssistant) o.in(u.TurnID, func() { nudged(t, o.teamNudge("xb-nudge", request, "mockups for the barber app"), request, 1) }) _, body := o.expect(wire.FrameDispatch) if again := body.(*wire.DispatchCommand); again.TaskID != build || again.StepID != d.StepID || again.Attempt != 2 { t.Fatalf("the retry's dispatch %+v", again) } o.reply(u.TurnID) // team_cancel stops the build. o.ask("Stop the barber app") if res := o.use("xb-cancel", "team_cancel", map[string]any{"request": request}); res.IsError || res.Text != `{"cancelled":1,"still_running":0}` { t.Fatalf("cancel %+v", res) } if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND (cancel_requested = 1 OR stage = ?)", build, wire.StageCancelled); n != 1 { t.Fatalf("the build goes on after team_cancel: %+v", o.task(build)) } } // stoppedOnResearch hands the barber shop's mockups to the team, whose // thread records a task and asks for research with a source the person // must approve, before any work starts: once the Assistant's team_update // about it ends (the job card working until then), the job is stopped. // It returns the request, the task and the stopped job card. func (o *teamRig) stoppedOnResearch() (request, id string, stopped wire.AssistantCard) { t := o.t t.Helper() o.in(o.own("Bring in research"), func() { o.researchOn() }) o.ask(personWords) request, cmd := o.handoff("rb1", "Make mockups for the barber shop.", "") o.in(cmd.TurnID, func() { id = o.shopTask("rb") if res := o.research("rb-r", id, "https://maps.example.org/place/barber-shop-on-main-street"); res.IsError { t.Fatalf("research %+v", res) } }) o.reply(cmd.TurnID) o.noteFor("the blocked note", blockedOn("they need to approve the research")) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { t.Fatalf("update frame %+v", u) } if now := o.jobOf(request, "the job card", nil); now.State != wire.JobWorking { t.Fatalf("while the Assistant's turn runs %+v", now) } o.reply(u.TurnID) stopped = o.jobOf(request, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped }) return request, id, stopped } // TestContractTeamJobStoppedBeforeWork (D5, D6, ruling P5j): a job whose // research waits for the person to approve its sources before any work // starts is stopped, as its note says, once the Assistant's team_update // about it ends, and not before; working again once they approve. func TestContractTeamJobStoppedBeforeWork(t *testing.T) { o := newTeamRig(t) request, id, stopped := o.stoppedOnResearch() if status, detail := jobWords(wire.JobStopped); stopped.Result != status || stopped.Detail != detail { t.Fatalf("stopped %+v", stopped) } card := o.jobCard(request, wire.CardResearchSources, id) if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil { t.Fatal(err) } o.jobOf(request, "working once approved", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking }) } // TestContractTeamJobPreviewExpires: a preview that expires while its // go-ahead waits is offered no more, with nothing else changed: a fresh // snapshot drops "Try it" from the job card at once, and the minute's // tick moves the job card and its go-ahead, once each, so the stream // drops it too. func TestContractTeamJobPreviewExpires(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.sitesOn(wire.ProtocolCurrent, false) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("pe1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("pe", "Quick website", base, cand, true) }) pv := o.previewDispatch(cand) o.built("pe-pv-built", pv, digestA) expires := time.Now().Add(time.Hour) link := "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone("pe-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed}) ready := o.jobOf(request, "ready to try", func(c wire.AssistantCard) bool { return c.State == wire.JobReady && len(c.Links) == 2 }) if !slices.Equal(ready.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: link}, o.equipoLink(request)}) { t.Fatalf("ready %+v", ready) } ahead := o.assistantCard("the go-ahead", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 }) jobs, aheads := len(o.jobEvents(ready.ID)), len(o.jobEvents(ahead.ID)) o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC().Add(2 * time.Hour) }) t.Cleanup(func() { o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) }) if got := o.jobOf(request, "expired", nil); got.State != wire.JobReady || !slices.Equal(got.Links, []wire.CardLink{o.equipoLink(request)}) { t.Fatalf("a fresh snapshot after the preview expired %+v", got) } for range 2 { if err := o.inst.Store.Chat().HousekeepingTick(o.ctx); err != nil { t.Fatal(err) } } job, mirror := o.jobEvents(ready.ID), o.jobEvents(ahead.ID) if len(job) != jobs+1 || job[len(job)-1].Revision <= ready.Revision || !slices.Equal(job[len(job)-1].Links, []wire.CardLink{o.equipoLink(request)}) { t.Fatalf("job card events after the preview expired %+v (ready %+v)", job[jobs:], ready) } if len(mirror) != aheads+1 || mirror[len(mirror)-1].Revision <= ahead.Revision || len(mirror[len(mirror)-1].Links) != 0 || mirror[len(mirror)-1].State != wire.CardOpen { t.Fatalf("go-ahead events after the preview expired %+v (was %+v)", mirror[aheads:], ahead) } } // TestContractTeamJobSnapshotKeepsActiveJobs (ruling R27): an unfinished // job (one stopped on a research approval too) and the go-ahead open // under one stay in the Assistant's snapshot however many newer cards // there are, oldest first as ever; a cancelled job older than the newest // cards does not. func TestContractTeamJobSnapshotKeepsActiveJobs(t *testing.T) { o := newTeamRig(t) _, _, research := o.stoppedOnResearch() o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("sk1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) o.in(cmd.TurnID, func() { o.websiteReady("sk", "Quick website", base, cand, false) }) job := o.jobOf(request, "ready", func(c wire.AssistantCard) bool { return c.State == wire.JobReady }) ahead := o.assistantCard("the go-ahead", isMergeOutcome) cancelled, _ := o.handoff("sk2", "Can we fix a bug", "") if res := o.use("sk-cancel", "team_cancel", map[string]any{"request": cancelled}); res.IsError { t.Fatalf("cancel %+v", res) } stopped := o.jobOf(cancelled, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped }) newer := time.Now().UTC().Add(time.Minute) for i := range wire.MaxProjectCards { o.exec("INSERT INTO chat_cards(id, person, kind, state, question, options, links, choice, revision, created_at, updated_at, held, lane) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", "c_newer"+itoa(i), Owner, wire.CardQuestion, wire.CardAnswered, "Which one?", "[]", "[]", "This one", 2, newer.Add(time.Duration(i)*time.Second), newer, false, wire.LaneAssistant) } snap, err := o.a.Snapshot(o.ctx) if err != nil { t.Fatal(err) } if n := len(snap.Cards); n != wire.MaxProjectCards+3 || snap.Cards[0].ID != research.ID || snap.Cards[1].ID != job.ID || snap.Cards[2].ID != ahead.ID || snap.Cards[n-1].ID != "c_newer"+itoa(wire.MaxProjectCards-1) { t.Fatalf("%d cards, the first %+v %+v %+v; the stopped job %s, the job %s and its go-ahead %s", n, snap.Cards[0], snap.Cards[1], snap.Cards[2], research.ID, job.ID, ahead.ID) } if slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.ID == stopped.ID }) { t.Fatalf("a cancelled job beyond the newest cards %+v", stopped) } } // statusPage is one team_status answer: its requests, each with its // question, and where the next page starts ("" on the last). type statusPage struct { Requests []struct { Request string `json:"request"` Question *struct { Text string `json:"text"` } `json:"question"` } `json:"requests"` Next string `json:"next"` } // TestContractTeamElevenQuestions (D8): with eleven jobs asking, the // person's next message carries the newest ten questions and says one // more is open and how to read it; team_status reads every open // request, ten at a time, each question with its request id, the next // page after the last one's cursor. func TestContractTeamElevenQuestions(t *testing.T) { o := newTeamRig(t) words := make([]string, 11) for i := range words { words[i] = fmt.Sprintf("job number %02d", i+1) } o.ask(strings.Join(words, ", ")) asked := map[string]string{} var requests []string for i, w := range words { request, cmd := o.handoff("eq"+itoa(i), w, "") requests = append(requests, request) asked[request] = "Which page for " + w + "?" o.in(cmd.TurnID, func() { if res := o.call("eq-ask"+itoa(i), wire.ToolAskPerson, map[string]any{"question": asked[request]}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) } page := func(key string, in map[string]any) statusPage { t.Helper() res := o.use(key, "team_status", in) var out statusPage if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil { t.Fatalf("team_status %+v", res) } return out } first := page("eq-st1", map[string]any{}) second := page("eq-st2", map[string]any{"after": first.Next}) if len(first.Requests) != 10 || first.Next != first.Requests[9].Request || len(second.Requests) != 1 || second.Next != "" { t.Fatalf("pages %+v then %+v", first, second) } seen := map[string]bool{} for _, r := range append(first.Requests, second.Requests...) { if r.Question == nil || r.Question.Text != asked[r.Request] || seen[r.Request] { t.Fatalf("request %s with %+v", r.Request, r.Question) } seen[r.Request] = true } if second.Requests[0].Request != requests[0] { t.Fatalf("the second page %+v, not the oldest %s", second, requests[0]) } if res := o.use("eq-st3", "team_status", map[string]any{"after": "h_nosuchrequest"}); !res.IsError || res.Code != "not_found" { t.Fatalf("after an unknown request %+v", res) } // Every team_update told, the person's next message carries the // newest ten and the count of the rest. o.reply(o.turn) for range words { u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { t.Fatalf("update frame %+v", u) } o.reply(u.TurnID) } sent, err := o.a.Send(o.ctx, "Which one first?", "eq-next") if err != nil { t.Fatal(err) } cmd := o.message(wire.LaneAssistant) if cmd.TurnID != sent.Turn.ID || strings.Count(cmd.Text, "\n- Job ") != 10 || strings.Contains(cmd.Text, requests[0]) || !strings.Contains(cmd.Text, "\n1 more job has an open question not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on).\n") { t.Fatalf("the person's next frame %q", cmd.Text) } }