package thintest import ( "context" "io" "net/http" "net/url" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // Ask the implementer, pinned exactly (Mac runners slice F, plan task // 13): a question about an Engineering step is frozen, when it is asked, // to the attempt, account, kept session, runner, base and candidate it is // about. Dispatch, cancel, the runner's replies and a reconnect's sync // all use those frozen values, never the step as it stands later. // askableOn runs w's Engineering attempt d to a commit of cand made on // account, done with its session kept (session), and the primary // publishes it. func (r *runnersRig) askableOn(w *peer, d *wire.DispatchCommand, cand, account, session string) { r.t.Helper() if !w.lease(d.StepID, d.Attempt) { r.t.Fatal("start refused") } w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, Family: "claude", Account: account, Findings: []wire.Finding{}}) w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}}) _, body := w.expect(wire.FrameSendPack) h := body.(*wire.SendPackCommand).Transfer w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, CandidateSHA: cand, Termination: true, TerminationKind: wire.TerminationProcessGroup, Family: "claude", Account: account, Askable: true, SessionID: session, Findings: []wire.Finding{}}) w.send(wire.FrameBlob, chunk(h, []byte("PACK commit"))) r.fromPrimary(wire.FrameBlob) pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand) r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true}) if s := r.engineeringStep(d.TaskID); s.State != wire.StepDone || !s.Askable || s.Attempt != d.Attempt || s.CandidateSHA != cand { r.t.Fatalf("not askable: %+v", s) } } // frozen is what a question row holds of the attempt it is about. type frozen struct { attempt int64 account, session, runner, base, candidate string } func (r *runnersRig) frozenOf(q string) frozen { r.t.Helper() var f frozen if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(eng_attempt, 0), coalesce(eng_account, ''), coalesce(eng_session, ''), coalesce(runner_id, ''), coalesce(base_sha, ''), coalesce(candidate_sha, '') FROM chat_questions WHERE id = ?", q).Scan(&f.attempt, &f.account, &f.session, &f.runner, &f.base, &f.candidate); err != nil { r.t.Fatal(err) } return f } // moveStep stands for any later path that moves a done Engineering step // on after a question was asked (no path does today: a done step's Retry // is a republish of the same attempt, and a fix round is a new step): a // new attempt on runner, with a new base, candidate, account and session. func (r *runnersRig) moveStep(step string, attempt int64, runner, base, cand string) { r.t.Helper() if _, err := r.inst.DB.Writer().Exec("UPDATE chat_steps SET attempt = ?, runner_id = ?, base_sha = ?, candidate_sha = ?, account = 'moved-account', session_id = 'moved-session' WHERE id = ?", attempt, runner, base, cand, step); err != nil { r.t.Fatal(err) } } // askIs checks an ask command against what its question froze. func askIs(t *testing.T, a *wire.AskCommand, q, step string, attempt int64, account, session, base, cand string) { t.Helper() if a.QuestionID != q || a.StepID != step || a.Specialist != wire.SpecialistEngineering || a.EngAttempt != attempt || a.EngAccount != account || a.EngSession != session || a.BaseSHA != base || a.CandidateSHA != cand { t.Fatalf("ask %+v, want %s on attempt %d (%s, %s) of %s..%s", a, q, attempt, account, session, base, cand) } } // A question created after a newer attempt made the same candidate is // bound to the attempt it was asked about (the newer one: its account and // session), never found by its commit; the step moving on later does not // change the runner, base or candidate a waiting question goes to, and a // reply from the runner the step moved to is refused. func TestContractAskBindsTheSession(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Tito Studio", wire.EngineeringReady) base, cand := sha(1), sha(0xc1) task, d1 := r.macDispatch(a, "iOS asked", base) // Attempt 1 commits cand on one account, then fails. if !a.lease(d1.StepID, 1) { t.Fatal("start refused") } a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "mac-c1", Findings: []wire.Finding{}}) a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}}) a.expect(wire.FrameSendPack) a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true, TerminationKind: wire.TerminationProcessGroup, Account: "mac-c1", SessionID: "sess-1", Findings: []wire.Finding{}}) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("retry %+v %v", acc, err) } _, body := a.expect(wire.FrameDispatch) d2 := body.(*wire.DispatchCommand) if d2.StepID != d1.StepID || d2.Attempt != 2 { t.Fatalf("retry %+v", d2) } r.engineeringTransfer(a, d2) // Attempt 2 makes the same commit, on another account, its session kept. r.askableOn(a, d2, cand, "mac-c2", "sess-2") q1, err := r.client.Ask(r.ctx, task, "What did you change?", "", "b1") if err != nil || q1.StepID != d1.StepID { t.Fatalf("ask %+v %v", q1, err) } want := frozen{2, "mac-c2", "sess-2", a.fr.Welcome.RunnerID, base, cand} if got := r.frozenOf(q1.ID); got != want { t.Fatalf("frozen %+v, want %+v", got, want) } _, body = a.expect(wire.FrameAsk) askIs(t, body.(*wire.AskCommand), q1.ID, d1.StepID, 2, "mac-c2", "sess-2", base, cand) r.primary.none(wire.FrameAsk, 0) // A second question waits for the first. q2, err := r.client.Ask(r.ctx, task, "And the tests?", "", "b2") if err != nil { t.Fatal(err) } if got := r.frozenOf(q2.ID); got != want { t.Fatalf("second frozen %+v, want %+v", got, want) } // The step moves on, to another Mac. b := r.newMacEngineer("Mac B", wire.EngineeringReady) r.moveStep(d1.StepID, 3, b.fr.Welcome.RunnerID, sha(9), sha(0xc9)) // Mac B's reply is refused; Mac A's is the answer. b.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "Not mine."}) if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionQueued || q.Answer != "" { t.Fatalf("the other Mac answered: %+v", q) } a.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "The swipe."}) if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionAnswered || q.Answer != "The swipe." { t.Fatalf("answer %+v", q) } // The waiting question goes where it was asked, as it was asked. _, body = a.expect(wire.FrameAsk) askIs(t, body.(*wire.AskCommand), q2.ID, d1.StepID, 2, "mac-c2", "sess-2", base, cand) b.none(wire.FrameAsk, 50*time.Millisecond) r.primary.none(wire.FrameAsk, 0) if got := r.frozenOf(q2.ID); got != want { t.Fatalf("the move changed the question: %+v", got) } } // Cancel, a reply and a reconnect's sync after the step moved to a new // attempt on another runner all address the runner and attempt the // question was frozen to. func TestContractQuestionLifecycleFrozen(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Tito Studio", wire.EngineeringReady) base, cand := sha(1), sha(0xc1) task, d := r.macDispatch(a, "iOS lifecycle", base) r.askableOn(a, d, cand, "mac-c1", "sess-1") q1, err := r.client.Ask(r.ctx, task, "What did you change?", "", "l1") if err != nil { t.Fatal(err) } _, body := a.expect(wire.FrameAsk) askIs(t, body.(*wire.AskCommand), q1.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand) q2, err := r.client.Ask(r.ctx, task, "Why that way?", "", "l2") if err != nil { t.Fatal(err) } b := r.newMacEngineer("Mac B", wire.EngineeringReady) r.moveStep(d.StepID, 2, b.fr.Welcome.RunnerID, sha(9), sha(0xc9)) // Cancel goes to Mac A, for the question's attempt. if _, err := r.client.CancelQuestion(r.ctx, q1.ID); err != nil { t.Fatal(err) } _, body = a.expect(wire.FrameCancelAsk) if c := body.(*wire.CancelAskCommand); c.QuestionID != q1.ID || c.Attempt != 1 { t.Fatalf("cancel_ask %+v", c) } b.none(wire.FrameCancelAsk, 50*time.Millisecond) r.primary.none(wire.FrameCancelAsk, 0) // Mac B cannot end it; Mac A does. b.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"}) if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionQueued { t.Fatalf("the other Mac ended it: %+v", q) } a.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"}) if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionCancelled { t.Fatalf("cancelled %+v", q) } // The next question goes to Mac A, frozen. _, body = a.expect(wire.FrameAsk) askIs(t, body.(*wire.AskCommand), q2.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand) b.none(wire.FrameAsk, 0) // Mac B's sync, which does not hold it, does not end it; Mac A's does. b.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}) if q, _ := r.client.Question(r.ctx, q2.ID); q.State != wire.QuestionQueued { t.Fatalf("the other Mac's sync ended it: %+v", q) } a.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}) r.wait("interrupted", func(c *Conversation) bool { q := c.Questions[q2.ID] return q.State == wire.QuestionFailed && q.Reason == "interrupted" }) } // macOffline disconnects the Mac w and waits until the instance shows it // offline, with the primary still online. func (r *runnersRig) macOffline(w *peer) { r.t.Helper() w.fr.Close() deadline := time.Now().Add(5 * time.Second) for { rs, err := r.client.Runners(context.Background()) online := map[string]bool{} for _, x := range rs.Items { online[x.ID] = x.Online } if err == nil && !online[w.fr.Welcome.RunnerID] && online[r.primary.fr.Welcome.RunnerID] { return } if time.Now().After(deadline) { r.t.Fatalf("Mac still online: %+v %v", rs, err) } time.Sleep(50 * time.Millisecond) } } // Asking about a Mac-made step while that Mac is offline is answered at // once (runner_offline), even with the primary online, and nothing // queues; once the Mac is back, the question is asked of it. func TestContractAskMacOffline(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Tito Studio", wire.EngineeringReady) base, cand := sha(1), sha(0xc1) task, d := r.macDispatch(a, "iOS offline", base) r.askableOn(a, d, cand, "mac-c1", "sess-1") r.macOffline(a) if _, err := r.client.Ask(r.ctx, task, "What did you change?", "", "o1"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "runner_offline") { t.Fatalf("ask of an offline Mac: %v", err) } // The task page's composer is told which Mac, and when to ask again, // with and without script. line := "Tito Studio is offline. Ask again when it is back." for _, accept := range []string{"text/html", "application/json"} { req, _ := http.NewRequest("POST", r.inst.URL+"/tasks/"+task+"/ask", strings.NewReader(url.Values{"body": {"What did you change?"}, "request_id": {"pg-" + accept}, "specialist": {""}}.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") req.Header.Set("Accept", accept) res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } raw, _ := io.ReadAll(res.Body) res.Body.Close() if res.StatusCode != http.StatusConflict || !strings.Contains(string(raw), line) { t.Fatalf("page ask (%s) of an offline Mac: %d %.400s", accept, res.StatusCode, raw) } } if k := r.task(task); len(k.Questions) != 0 { t.Fatalf("a question queued for an offline Mac: %+v", k.Questions) } r.primary.none(wire.FrameAsk, 0) if n := r.mailbox(a.fr.Welcome.RunnerID, wire.FrameAsk); n != 0 { t.Fatalf("%d asks wait for the offline Mac", n) } c := r.creds[a.fr] wh := macEngineerHello(c[1], wire.EngineeringReady, wire.ProtocolMacEngineering, false) wh.Generation = a.fr.Welcome.Generation fr, err := DialRunnerHello(r.ctx, r.inst.URL, c[0], wh) if err != nil { t.Fatal(err) } t.Cleanup(fr.Close) back := &peer{t: t, r: r.toolRig, fr: fr} q, err := r.client.Ask(r.ctx, task, "What did you change?", "", "o2") if err != nil { t.Fatal(err) } _, body := back.expect(wire.FrameAsk) askIs(t, body.(*wire.AskCommand), q.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand) }