package webtest import ( "bufio" "context" "database/sql" "encoding/json" "html" "net/http" "net/url" "os" "regexp" "strconv" "strings" "testing" "time" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/equipo/equipotest" "amadan.net/oficina/base/internal/store" "amadan.net/oficina/base/internal/web" ) func strconv64(n int64) string { return strconv.FormatInt(n, 10) } // newAskApp is Base with "Ask Base anything" on, answered by a fake Equipo, // and the owner signed in. func newAskApp(t *testing.T) (*testApp, *equipotest.Fake) { t.Helper() f := equipotest.New(t) a := newAppConfigured(t, func(*sql.DB, config.Config) web.Installer { return noInstaller{} }, time.UTC, func(c *config.Config) { c.EquipoOrigin = f.URL }) a.signedInOwner() return a, f } var codeRE = regexp.MustCompile(`

]*>([A-Z0-9]{8})

`) // ownerID is the bootstrapped owner's member id. func (a *testApp) ownerID() string { a.t.Helper() m, ok, err := store.MemberByEmail(context.Background(), a.DB, ownerAddress) if err != nil || !ok { a.t.Fatalf("owner: %v %v", ok, err) } return m.ID } // pollable makes Base's last look at Equipo old enough to look again. func (a *testApp) pollable() { a.t.Helper() if _, err := a.DB.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-10*time.Second).UTC()); err != nil { a.t.Fatal(err) } } // connectEquipo connects the owner from Settings the way a person does: // Connect Equipo, approve the code in Equipo, come back. It returns the // bearer Equipo issued. func (a *testApp) connectEquipo(f *equipotest.Fake) string { a.t.Helper() a.approveEquipo(f) tokens := f.Tokens() if len(tokens) != 1 { a.t.Fatalf("tokens: %v", tokens) } return tokens[0] } // approveEquipo is connectEquipo without asking which bearer Equipo // issued: it connects again just as well. func (a *testApp) approveEquipo(f *equipotest.Fake) { a.t.Helper() r := a.post("/ask/connect", url.Values{"next": {"settings"}}) if r.Code != 303 || r.Location() != "/ask/connect?next=settings" { a.t.Fatalf("connect: %d %q\n%s", r.Code, r.Location(), r.Body) } page := a.get(r.Location()) m := codeRE.FindStringSubmatch(page.Body) if page.Code != 200 || m == nil { a.t.Fatalf("pending page: %d\n%s", page.Code, page.Body) } if err := f.Approve(m[1]); err != nil { a.t.Fatal(err) } a.pollable() if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" { a.t.Fatalf("after approval: %d %q\n%s", r.Code, r.Location(), r.Body) } } // check presses "Check again" on the connect page. func (a *testApp) check(next string) Resp { a.t.Helper() return a.post("/ask/connect/check", url.Values{"next": {next}}) } // noLeak fails if any response so far carried token: body, header or cookie. func (a *testApp) noLeak(token string) { a.t.Helper() for _, r := range a.seen { if strings.Contains(r.Body, token) { a.t.Fatalf("a response body carried the bearer:\n%s", r.Body) } for k, vs := range r.Header { for _, v := range vs { if strings.Contains(v, token) { a.t.Fatalf("header %s carried the bearer", k) } } } } } func TestAskOffWithoutEquipo(t *testing.T) { a := newApp(t) a.signedInOwner() // Home has no chat column, no Base button and no field. home := a.get("/").Body if strings.Contains(home, `class="ask`) || strings.Contains(home, "base-btn") || strings.Contains(home, `/ask`) || strings.Contains(home, "Ask Base anything`, `"} { if !strings.Contains(settings, want) { t.Errorf("Settings lacks %q:\n%s", want, settings) } } } func TestConnectEquipo(t *testing.T) { a, f := newAskApp(t) r := a.post("/ask/connect", url.Values{"next": {"settings"}}) if r.Code != 303 { t.Fatalf("connect: %d\n%s", r.Code, r.Body) } begin := f.Calls("/api/v1/auth/devices") if len(begin) != 1 || !strings.Contains(begin[0].Body, `"label":"Base (Acme)"`) { t.Fatalf("begin: %+v", begin) } page := a.get(r.Location()) m := codeRE.FindStringSubmatch(page.Body) if m == nil || f.Label(m[1]) != "Base (Acme)" { t.Fatalf("no user code:\n%s", page.Body) } for _, want := range []string{f.URL + "/auth/devices/", `
Check again"} { if !strings.Contains(html.UnescapeString(page.Body), want) { t.Errorf("pending page lacks %q:\n%s", want, page.Body) } } // Checking asks once; checking again inside Equipo's five seconds does not. if r := a.check("settings"); r.Code != 303 || r.Location() != "/ask/connect?next=settings" { t.Fatalf("check while pending: %d %q", r.Code, r.Location()) } a.check("settings") if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { t.Fatalf("exchanges: %d, want 1", n) } if err := f.Approve(m[1]); err != nil { t.Fatal(err) } a.pollable() if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" { t.Fatalf("after approval: %d %q", r.Code, r.Location()) } token := f.Tokens()[0] l, ok, err := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) if !ok || err != nil || l.State != store.EquipoConnected || l.Revision != 3 || l.ExpiresAt.Before(time.Now().Add(29*24*time.Hour)) { t.Fatalf("link: %+v %v %v", l, ok, err) } if strings.Contains(string(l.Sealed), token) || strings.Contains(string(l.Sealed), "equipo.person") { t.Fatal("the bearer is stored in the clear") } settings := a.get("/settings").Body if !strings.Contains(settings, "ConnectionConnected") || !strings.Contains(settings, `action="/ask/disconnect"`) { t.Errorf("Settings after connecting:\n%s", settings) } a.noLeak(token) } // GET /ask/connect only shows: a cross-site link or prefetch cannot finish // the exchange. The JSON check is what the page's script posts. func TestConnectPageIsReadOnly(t *testing.T) { a, f := newAskApp(t) r := a.post("/ask/connect", url.Values{"next": {"ask"}}) m := codeRE.FindStringSubmatch(a.get(r.Location()).Body) if m == nil { t.Fatal("no code") } if err := f.Approve(m[1]); err != nil { t.Fatal(err) } a.pollable() if page := a.get(r.Location()); page.Code != 200 || codeRE.FindString(page.Body) == "" { t.Fatalf("page: %d", page.Code) } if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 0 { t.Fatalf("GET exchanged %d times", n) } if r := a.postFrom("https://evil.example", "/ask/connect/check", url.Values{"next": {"ask"}}); r.Code != 403 { t.Fatalf("cross-site check: %d", r.Code) } req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/connect/check", strings.NewReader("next=ask")) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", a.origin) req.Header.Set("Accept", "application/json") res := a.do(req) if res.Code != 200 || !strings.Contains(res.Body, `"state":"ready"`) || !strings.Contains(res.Body, `"next":"/ask"`) { t.Fatalf("JSON check: %d %s", res.Code, res.Body) } } // Two checks at once: only one asks Equipo. func TestConnectConcurrentChecksExchangeOnce(t *testing.T) { a, f := newAskApp(t) a.post("/ask/connect", url.Values{"next": {"ask"}}) entered, release := f.HoldNextExchange() done := make(chan Resp) go func() { done <- a.check("ask") }() select { case <-entered: case r := <-done: t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location()) case <-time.After(5 * time.Second): t.Fatal("the check never reached Equipo's exchange") } a.check("ask") release() <-done if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { t.Fatalf("exchanges: %d, want 1", n) } } // Disconnect while an exchange is in flight: the bearer that exchange // brings back is revoked, not stored. func TestDisconnectDuringExchangeLeavesNoBearer(t *testing.T) { a, f := newAskApp(t) r := a.post("/ask/connect", url.Values{"next": {"settings"}}) m := codeRE.FindStringSubmatch(a.get(r.Location()).Body) if err := f.Approve(m[1]); err != nil { t.Fatal(err) } l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) entered, release := f.HoldNextExchange() done := make(chan Resp) go func() { done <- a.check("settings") }() select { case <-entered: case r := <-done: t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location()) case <-time.After(5 * time.Second): t.Fatal("the check never reached Equipo's exchange") } if d := a.post("/ask/disconnect", nil); d.Code != 303 { t.Fatalf("disconnect: %d", d.Code) } release() if c := <-done; c.Location() == "/settings" && c.Code != 303 { t.Fatalf("check: %d", c.Code) } if _, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); found { t.Fatal("the exchange brought the link back after Disconnect") } if !f.Revoked(l.DeviceID) { t.Fatal("the bearer from the late exchange was not revoked") } } func TestConnectCodeExpires(t *testing.T) { a, f := newAskApp(t) a.post("/ask/connect", url.Values{"next": {"ask"}}) f.Expire() r := a.check("ask") if r.Code != 303 { t.Fatalf("check: %d", r.Code) } page := a.get(r.Location()) if page.Code != 200 || !strings.Contains(page.Body, "That code expired.") || !strings.Contains(page.Body, `action="/ask/connect"`) { t.Fatalf("expired: %d\n%s", page.Code, page.Body) } } // Every chat form carries a key made when the page was drawn, which Base // relays as the Idempotency-Key: a resubmitted form is the same request. func TestAskFormsCarryKeys(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskQuestion("Which branch?", "main") f.Hold = true a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}}) page := a.get("/ask").Body answer := formFields(t, page, "/ask/cards/"+id+"/answer") cancel := regexp.MustCompile(`action="(/ask/turns/[^/"]+/cancel)"`).FindStringSubmatch(page) if answer.Get("key") == "" || cancel == nil { t.Fatalf("forms:\n%s", page) } stop := formFields(t, page, cancel[1]) if stop.Get("key") == "" || stop.Get("key") == answer.Get("key") { t.Fatalf("stop key %q, answer key %q", stop.Get("key"), answer.Get("key")) } answer.Set("choice", "main") a.post("/ask/cards/"+id+"/answer", answer) a.post(cancel[1], stop) for path, key := range map[string]string{"/api/v1/assistant/cards/" + id + "/answer": answer.Get("key"), "/api/v1/assistant" + strings.TrimPrefix(cancel[1], "/ask"): stop.Get("key")} { if c := f.Calls(path); len(c) != 1 || c[0].Header.Get("Idempotency-Key") != key { t.Errorf("%s: %+v, want key %q", path, c, key) } } } func TestAskSendRelaysWithBearer(t *testing.T) { a, f := newAskApp(t) token := a.connectEquipo(f) page := a.get("/ask") key := formFields(t, page.Body, "/ask/messages").Get("key") if page.Code != 200 || key == "" { t.Fatalf("/ask: %d key=%q\n%s", page.Code, key, page.Body) } r := a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {key}}) if r.Code != 303 || r.Location() != "/ask" { t.Fatalf("send: %d %q", r.Code, r.Location()) } calls := f.Calls("/api/v1/assistant/messages") if len(calls) != 1 { t.Fatalf("sends: %d", len(calls)) } h := calls[0].Header if h.Get("Authorization") != "Bearer "+token || h.Get("Idempotency-Key") != key || h.Get("Cookie") != "" || h.Get("Origin") != "" { t.Errorf("relayed headers: %v", h) } if !strings.Contains(calls[0].Body, `"idempotency_key":"`+key+`"`) { t.Errorf("relayed body: %s", calls[0].Body) } // The same key again (a double press) sends nothing new. a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {key}}) var body string for i := 0; i < 100; i++ { if body = a.get("/ask").Body; strings.Contains(body, "Hello. What shall we work on?") { break } time.Sleep(20 * time.Millisecond) } if strings.Count(body, "What can I do") != 1 || !strings.Contains(body, "Hello. What shall we work on?") { t.Fatalf("conversation:\n%s", body) } // Scripts on: the same route answers JSON. req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/messages", strings.NewReader(url.Values{"text": {"Build me a quick website"}, "key": {"k-json"}}.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", a.origin) req.Header.Set("Accept", "application/json") res := a.do(req) var sent struct { Message struct{ Text string } Turn struct{ ID, State string } } if res.Code != 200 || json.Unmarshal([]byte(res.Body), &sent) != nil || sent.Message.Text != "Build me a quick website" || sent.Turn.ID == "" { t.Fatalf("JSON send: %d %s", res.Code, res.Body) } a.noLeak(token) } func TestAskRefusesCrossSitePost(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) if r := a.postFrom("https://evil.example", "/ask/messages", url.Values{"text": {"hi"}}); r.Code != 403 { t.Fatalf("cross-site send: %d", r.Code) } if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 { t.Fatalf("relayed a cross-site send") } } func TestAskScriptsOffCardAndCancel(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskQuestion("Which branch should I start from?", "main", "develop") page := a.get("/ask").Body action := "/ask/cards/" + id + "/answer" fields := formFields(t, page, action) if !strings.Contains(page, "Which branch should I start from?") || !strings.Contains(page, `name="choice" value="develop"`) { t.Fatalf("card:\n%s", page) } fields.Set("choice", "main") if r := a.post(action, fields); r.Code != 303 || r.Location() != "/ask" { t.Fatalf("answer: %d", r.Code) } ans := f.Calls("/api/v1/assistant/cards/" + id + "/answer") if len(ans) != 1 || ans[0].Body != `{"choice":"main","revision":1}`+"\n" && ans[0].Body != `{"choice":"main","revision":1}` { t.Fatalf("answer relayed: %+v", ans) } f.Hold = true a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}}) page = a.get("/ask").Body m := regexp.MustCompile(`action="(/ask/turns/([^/"]+)/cancel)"`).FindStringSubmatch(page) if m == nil || !strings.Contains(page, ``) { t.Fatalf("no stop button or refresh for a running turn:\n%s", page) } if r := a.post(m[1], nil); r.Code != 303 { t.Fatalf("cancel: %d", r.Code) } if f.Turn(m[2]) != "cancelled" { t.Fatalf("turn %s is %q", m[2], f.Turn(m[2])) } } // buttonRE is a
") { t.Fatalf("no reconnect:\n%s", page) } l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) if l.State != store.EquipoLost { t.Fatalf("state %q", l.State) } if s := a.get("/settings").Body; !strings.Contains(s, ">Set it up again") { t.Errorf("Settings:\n%s", s) } var st struct{ State string } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "reconnect" { t.Errorf("state: %s", r.Body) } } func TestAskExpiredBearerNeedsReconnect(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) if _, err := a.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil { t.Fatal(err) } before := len(f.Calls("")) if page := a.get("/ask").Body; !strings.Contains(page, ">Set it up again") { t.Fatalf("no reconnect:\n%s", page) } if len(f.Calls("")) != before { t.Error("Base used an expired bearer") } } func TestDisconnectRevokesDevice(t *testing.T) { a, f := newAskApp(t) token := a.connectEquipo(f) l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) if r := a.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" { t.Fatalf("disconnect: %d %q", r.Code, r.Location()) } calls := f.Calls("/api/v1/auth/devices/" + l.DeviceID) if len(calls) != 1 || calls[0].Method != http.MethodDelete || calls[0].Header.Get("If-Match") != `"3"` || calls[0].Header.Get("Authorization") != "Bearer "+token || !f.Revoked(l.DeviceID) { t.Fatalf("revoke: %+v", calls) } if _, ok, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); ok { t.Fatal("link kept") } if s := a.get("/settings").Body; !strings.Contains(s, "ConnectionNot set up") { t.Errorf("Settings:\n%s", s) } } // The panel's stream: Equipo's chat events relayed, nothing else of Equipo. func TestAskEventsRelay(t *testing.T) { a, f := newAskApp(t) token := a.connectEquipo(f) var st struct { State string Cursor int64 } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "ready" { t.Fatalf("state: %s", r.Body) } f.Emit("runner", map[string]any{"id": "R1", "online": false}) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+strconv64(st.Cursor), nil) res, err := a.client.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() if res.StatusCode != 200 || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") { t.Fatalf("events: %d %s", res.StatusCode, res.Header.Get("Content-Type")) } a.post("/ask/messages", url.Values{"text": {"What can I do"}}) types := map[string]int{} sc := bufio.NewScanner(res.Body) var stream strings.Builder for sc.Scan() { line := sc.Text() stream.WriteString(line + "\n") if typ, ok := strings.CutPrefix(line, "event: "); ok { types[typ]++ } if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"state":"replied"`) { break } } if types["runner"] != 0 || types["delta"] == 0 || types["message"] < 2 || types["turn"] == 0 { t.Fatalf("relayed %v:\n%s", types, stream.String()) } if strings.Contains(stream.String(), token) { t.Fatal("the stream carried the bearer") } up := f.Calls("/api/v1/assistant/events") if len(up) == 0 || up[0].Header.Get("Authorization") != "Bearer "+token || up[0].Query != "job_states=paused&after="+strconv64(st.Cursor) { t.Fatalf("upstream: %+v", up) } } // waitEntered waits for a held exchange to reach Equipo. func waitEntered(t *testing.T, entered <-chan struct{}, done <-chan Resp) { t.Helper() select { case <-entered: case r := <-done: t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location()) case <-time.After(5 * time.Second): t.Fatal("the check never reached Equipo's exchange") } } // An exchange slower than the poll interval still holds the link: a check // after the interval does not start a second one. func TestCheckDuringSlowExchangeDoesNotExchange(t *testing.T) { a, f := newAskApp(t) a.post("/ask/connect", url.Values{"next": {"ask"}}) entered, release := f.HoldNextExchange() done := make(chan Resp) go func() { done <- a.check("ask") }() waitEntered(t, entered, done) a.pollable() // the interval has passed; the exchange has not ended a.check("ask") release() <-done if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { t.Fatalf("exchanges: %d, want 1", n) } } // When the link is already connected to the same device (a duplicate // exchange succeeded first), a late success leaves that connection alone. func TestDuplicateExchangeKeepsConnection(t *testing.T) { a, f := newAskApp(t) r := a.post("/ask/connect", url.Values{"next": {"ask"}}) m := codeRE.FindStringSubmatch(a.get(r.Location()).Body) if err := f.Approve(m[1]); err != nil { t.Fatal(err) } l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) entered, release := f.HoldNextExchange() done := make(chan Resp) go func() { done <- a.check("ask") }() waitEntered(t, entered, done) if _, err := a.DB.Exec(`UPDATE equipo_links SET state = ?`, store.EquipoConnected); err != nil { t.Fatal(err) } release() <-done if f.Revoked(l.DeviceID) { t.Fatal("a duplicate success revoked the live connection") } if n := len(f.Hosts()); n != 0 { t.Fatalf("a duplicate success registered the host again: %d PUTs", n) } if got, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); !found || got.State != store.EquipoConnected { t.Fatalf("link: %+v %v", got, found) } } // If Base cannot store the bearer, it revokes the device in Equipo and // says to start again: never "connected" with a credential it lost. func TestConnectStoreFailureRevokes(t *testing.T) { a, f := newAskApp(t) r := a.post("/ask/connect", url.Values{"next": {"settings"}}) m := codeRE.FindStringSubmatch(a.get(r.Location()).Body) if err := f.Approve(m[1]); err != nil { t.Fatal(err) } l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) if _, err := a.DB.Exec(`CREATE TRIGGER no_bearer BEFORE UPDATE OF state ON equipo_links WHEN NEW.state = 'connected' BEGIN SELECT RAISE(ABORT, 'disk full'); END`); err != nil { t.Fatal(err) } c := a.check("settings") if c.Code != 303 || c.Location() == "/settings" || !strings.Contains(c.Location(), "ended=failed") { t.Fatalf("check: %d %q, want start again", c.Code, c.Location()) } if !f.Revoked(l.DeviceID) { t.Fatal("the device whose bearer was lost was not revoked") } if page := a.get(c.Location()).Body; !strings.Contains(page, "That didn't work. Start again.") { t.Fatalf("page:\n%s", page) } } var tagRE = regexp.MustCompile(`(?s)<[^>]*>`) var linkTagRE = regexp.MustCompile(`]*)?>`) // textOf is a page's text: its tags, and so every attribute value, gone. func textOf(body string) string { body = linkTagRE.ReplaceAllString(body, "") return strings.Join(strings.Fields(html.UnescapeString(tagRE.ReplaceAllString(body, " "))), " ") } var blockREs = []*regexp.Regexp{ regexp.MustCompile(`(?s)
]*)>(.*?)
`), regexp.MustCompile(`(?s)

]*)>(.*?)

`), } // visibleBlocks are the chat's state blocks on a page that are not hidden, // by state: what the person sees before any script runs. func visibleBlocks(body string) map[string]string { out := map[string]string{} for _, re := range blockREs { for _, m := range re.FindAllStringSubmatch(body, -1) { if !strings.Contains(m[2], " hidden") { out[m[1]] = textOf(m[3]) } } } return out } // shows asserts that on page (a body) exactly the block for state shows // among the setup blocks (or the runner note for a runner state) and that // its text is want. func shows(t *testing.T, where, body, state, want string) { t.Helper() vis := visibleBlocks(body) for k := range vis { if k != state { t.Errorf("%s: the %q block shows in state %s", where, k, state) } } if got, ok := vis[state]; !ok || !strings.Contains(got, want) { t.Errorf("%s: the visible %q block says %q, want %q", where, state, got, want) } } // elementText is the text of the first element on a page matching pattern. func elementText(t *testing.T, where, body, pattern string) string { t.Helper() m := regexp.MustCompile(`(?s)` + pattern).FindStringSubmatch(body) if m == nil { t.Errorf("%s: no element matching %s:\n%s", where, pattern, textOf(body)) return "" } return textOf(m[1]) } // expect asserts that the first element matching pattern says want. func expect(t *testing.T, where, body, pattern, want string) { t.Helper() if got := elementText(t, where, body, pattern); got != want { t.Errorf("%s: %q, want %q", where, got, want) } } // askStates puts the owner's Ask in each state in turn and calls fn with // the pages of that state: Home, /ask, the connect page, Settings. func askStates(t *testing.T, fn func(state string, a *testApp, f *equipotest.Fake, pages map[string]string)) { t.Helper() const setup = "/ask/connect?next=ask" pages := func(a *testApp) map[string]string { ask := a.get("/ask").Body // first: it is what moves a lost or runnerless state along return map[string]string{"/": a.get("/").Body, "/ask": ask, "setup": a.get(setup).Body, "/settings": a.get("/settings").Body} } a, f := newAskApp(t) fn("connect", a, f, pages(a)) for _, ended := range []string{"expired", "refused", "failed"} { fn(ended, a, f, map[string]string{"setup": a.get(setup + "&ended=" + ended).Body}) } a.post("/ask/connect", url.Values{"next": {"ask"}}) fn("pending", a, f, pages(a)) fn("pending, problem", a, f, map[string]string{"setup": a.get(setup + "&problem=1").Body}) a, f = newAskApp(t) f.FailNextBegin() fn("setup unavailable", a, f, map[string]string{"setup": a.post("/ask/connect", url.Values{"next": {"ask"}}).Body}) a, f = newAskApp(t) a.connectEquipo(f) fn("ready", a, f, pages(a)) fn("not sent", a, f, map[string]string{"/ask": a.get("/ask?problem=1").Body}) f.FailSnapshots(true) fn("unavailable", a, f, pages(a)) f.FailSnapshots(false) f.NoRunner() fn("norunner", a, f, pages(a)) f.RunnerTooOld() // Too old shows when a send is refused 409: that page, with the text kept. fn("oldrunner", a, f, map[string]string{"/ask": a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old"}}).Body}) f.RevokeAll() fn("reconnect", a, f, pages(a)) } // Base never names Equipo in the chat, its setup or Settings: no word of it // in any page's text, and no ⋯ menu. func TestAskNamesNoEquipo(t *testing.T) { askStates(t, func(state string, _ *testApp, _ *equipotest.Fake, pages map[string]string) { for page, body := range pages { if strings.Contains(strings.ToLower(textOf(body)), "equipo") { t.Errorf("%s in state %s names Equipo:\n%s", page, state, textOf(body)) } if strings.Contains(body, "ask-more") || strings.Contains(body, "ask-menu") { t.Errorf("%s in state %s has the ⋯ menu", page, state) } } }) } // Every approved text shows where Paul's table puts it, in the element that // is visible in that state: the panel on Home and /ask (the state's block // shows, every other is hidden), the setup page and Settings. func TestAskApprovedWords(t *testing.T) { askStates(t, func(state string, a *testApp, f *equipotest.Fake, pages map[string]string) { row := func(value string) { t.Helper() expect(t, state+" /settings", pages["/settings"], `
Connection(.*?)`, value) } // The row's control: its button or its link, by its text. settingsAction := func(want string) { t.Helper() expect(t, state+" /settings control", pages["/settings"], `
Connection.*?
\s*(?:]*>(?:]*>)*)?<(?:button|a) [^>]*class="btn ghost"[^>]*>(.*?)`, want) } setup := pages["setup"] title := func(want string) { expect(t, state+" setup title", setup, `(.*?)`, want+" · Acme") } switch state { case "connect": for _, p := range []string{"/", "/ask"} { shows(t, state+" "+p, pages[p], "connect", "Set up Ask Base to start asking. Set up Ask Base") expect(t, state+" "+p+" button", pages[p], `data-when="connect"[^>]*>.*?`, "Set up Ask Base") } title("Set up Ask Base") expect(t, state+" setup heading", setup, `

(.*?)

`, "Set up Ask Base") expect(t, state+" setup lead", setup, `\s*

(.*?)

`, "Set up Ask Base to start asking.") expect(t, state+" setup button", setup, ``, "Set up Ask Base") row("Not set up") settingsAction("Set up Ask Base") case "expired": expect(t, state+" setup lead", setup, `\s*

(.*?)

`, "That code expired. Start again to get a new one.") case "refused": expect(t, state+" setup lead", setup, `\s*

(.*?)

`, "That request wasn't accepted. Start again.") case "failed": expect(t, state+" setup lead", setup, `\s*

(.*?)

`, "That didn't work. Start again.") case "pending": for _, p := range []string{"/", "/ask"} { shows(t, state+" "+p, pages[p], "pending", "You started setting up Ask Base. Approve it to start asking. Finish setting up") expect(t, state+" "+p+" button", pages[p], `data-when="pending"[^>]*>.*?]*>(.*?)`, "Finish setting up") } title("Set up Ask Base") expect(t, state+" setup heading", setup, `

(.*?)

`, "Set up Ask Base") expect(t, state+" setup code line", setup, `\s*

(.*?)

`, "Check the request is from "+f.Label(codeRE.FindStringSubmatch(setup)[1])+", then type this code:") expect(t, state+" setup open", setup, `]*>(.*?)`, "Approve it") row("Waiting for your approval") settingsAction("Finish setting up") case "pending, problem": expect(t, state+" setup problem", setup, ``, "Ask Base isn't answering. It will keep trying.") case "setup unavailable": expect(t, state+" setup problem", setup, ``, "Ask Base isn't answering. Try again in a minute.") case "ready": if got := elementText(t, state+" /settings", pages["/settings"], `
Connection(.*?)`); !strings.HasPrefix(got, "Connected") { t.Errorf("ready /settings row: %q", got) } if len(visibleBlocks(pages["/ask"])) != 0 { t.Errorf("ready /ask shows a state block: %v", visibleBlocks(pages["/ask"])) } if s := a.get("/ask/state").Body; !strings.Contains(s, `"state":"ready"`) { t.Errorf("ready state: %s", s) } case "not sent": expect(t, state+" /ask", pages["/ask"], ``, "That didn't send. Try again.") case "unavailable": shows(t, state+" /ask", pages["/ask"], "unavailable", "Ask Base isn't answering. Try again in a minute.") // Home draws the panel from what it knows without calling Equipo; // the panel's script asks /ask/state and shows this block. if s := a.get("/ask/state").Body; !strings.Contains(s, `"state":"unavailable"`) { t.Errorf("unavailable state: %s", s) } if got := regexp.MustCompile(`data-when="unavailable"[^>]*>\s*

(.*?)

`).FindStringSubmatch(pages["/"]); got == nil || got[1] != "Ask Base isn't answering. Try again in a minute." { t.Errorf("Home's panel lacks the unavailable block: %q", got) } case "norunner": shows(t, state+" /ask", pages["/ask"], "norunner", "Ask Base isn't set up for you yet. Finish setting it up, then try again.") // Home draws from what it knows without calling Equipo; the // panel's script moves to this state from /ask/state. if s := a.get("/ask/state").Body; !strings.Contains(s, `"state":"norunner"`) { t.Errorf("norunner state: %s", s) } expect(t, state+" / panel's block", pages["/"], `data-when="norunner"[^>]*>(.*?)

`, "Ask Base isn't set up for you yet. Finish setting it up, then try again.") expect(t, state+" /ask link", pages["/ask"], `data-when="norunner"[^>]*>.*?(.*?)`, "Finish setting it up") case "oldrunner": shows(t, state+" /ask", pages["/ask"], "oldrunner", "Ask Base needs an update first. Update it, then try again.") expect(t, state+" / panel's block", a.get("/").Body, `data-when="oldrunner"[^>]*>(.*?)

`, "Ask Base needs an update first. Update it, then try again.") expect(t, state+" /ask link", pages["/ask"], `data-when="oldrunner"[^>]*>.*?(.*?)`, "Update it") case "reconnect": for _, p := range []string{"/", "/ask"} { shows(t, state+" "+p, pages[p], "reconnect", "Ask Base needs setting up again. Set it up again") expect(t, state+" "+p+" button", pages[p], `data-when="reconnect"[^>]*>.*?`, "Set it up again") } title("Set up Ask Base") expect(t, state+" setup lead", setup, `\s*

(.*?)

`, "Ask Base needs setting up again.") expect(t, state+" setup button", setup, ``, "Set it up again") row("Needs setting up again") settingsAction("Set it up again") } }) // While a turn runs: the status under the conversation, then waiting. a, f := newAskApp(t) a.connectEquipo(f) status := `

(.*?)

` f.Hold = true a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}}) page := a.get("/ask").Body expect(t, "answering /ask", page, status, "Thinking…") turn := regexp.MustCompile(`/ask/turns/([^/"]+)/cancel`).FindStringSubmatch(page) if turn == nil { t.Fatal("no turn running") } f.WaitTurn(turn[1]) a.pollable() expect(t, "waiting /ask", a.get("/ask").Body, status, "Ask Base can't answer right now. It will as soon as it can.") // The panel's script words: the same texts, and no Equipo in a string. js, err := os.ReadFile("../look/static/ask.js") if err != nil { t.Fatal(err) } for _, w := range []string{"Thinking…", "Ask Base can't answer right now. It will as soon as it can.", "That didn't send. Try again."} { if !strings.Contains(string(js), w) { t.Errorf("ask.js lacks %q", w) } } if regexp.MustCompile(`"[^"\n]*Equipo[^"\n]*"|ask-more`).MatchString(string(js)) { t.Error("ask.js still words Equipo to the person, or draws the ⋯ menu") } } // cardItem is the card with id as /ask draws it. func cardItem(t *testing.T, page, id string) string { t.Helper() m := regexp.MustCompile(`(?s)
  • ]*>.*?
  • `).FindString(page) if m == "" { t.Fatalf("no card %s in:\n%s", id, page) } return m } var goOptions = []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}} // Cards are drawn from their fields alone: a button is an option's label // posting its value, a link is one of the card's links, opening in a new // tab. An outcome and a confirm card draw the same way; Base has no words // of its own for any kind. func TestAskCardsAreDrawnFromFields(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) links := []equipo.Link{{Label: "See it", URL: "https://preview.example.test/"}} outcome := f.AskOutcome("This is ready. Go ahead?", goOptions, links) confirm := f.AskKind("confirm", "Send the invitation?", goOptions, links) task := f.AskKind("task", "Merge tk0001?", goOptions, nil) f.Say("Try [this](javascript:alert(1)), [that](/tasks/tk1) or bold.") page := a.get("/ask").Body if !strings.Contains(page, `
  • ") { t.Errorf("the Assistant's line is not plain text:\n%s", page) } for _, id := range []string{outcome, confirm} { card := cardItem(t, page, id) for _, want := range []string{ ``, ``, `See it`, } { if !strings.Contains(card, want) { t.Errorf("card %s lacks %s:\n%s", id, want, card) } } if fields := formFields(t, page, "/ask/cards/"+id+"/answer"); fields.Get("revision") != "1" { t.Errorf("card %s answers at revision %q", id, fields.Get("revision")) } } if strings.Contains(page, task) || strings.Contains(page, "Merge tk0001?") { t.Errorf("a task card was drawn:\n%s", page) } var st struct { Cards []struct { ID string Options []struct{ Value, Label string } Links []struct{ Label, URL string } } } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 2 || st.Cards[0].ID != outcome || len(st.Cards[0].Options) != 2 || st.Cards[0].Options[0].Label != "Go ahead" || len(st.Cards[0].Links) != 1 || st.Cards[0].Links[0].URL != "https://preview.example.test/" { t.Fatalf("state: %s", r.Body) } for _, file := range []string{"../web/ask_cards.go", "../look/static/ask.js", "../web/templates/partials/chat.html"} { raw, err := os.ReadFile(file) if err != nil { t.Fatal(err) } for _, word := range []string{"Merge", "Wait for checks", "Publishing"} { if strings.Contains(string(raw), word) { t.Errorf("%s says %q", file, word) } } } } // Answering posts the option's value, at the card's revision. An answered // outcome card says how it ended and brings no message and no turn (Equipo // answers with empty ones). An answer at a stale revision is not resent: // /ask shows the card as it is now. func TestAskAnswerRelaysValue(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskOutcome("This is ready. Go ahead?", goOptions, nil) answer := formFields(t, a.get("/ask").Body, "/ask/cards/"+id+"/answer") answer.Set("choice", "go") if r := a.post("/ask/cards/"+id+"/answer", answer); r.Code != 303 || r.Location() != "/ask" { t.Fatalf("answer: %d %q", r.Code, r.Location()) } if c := f.Calls("/api/v1/assistant/cards/" + id + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"go","revision":1}` { t.Fatalf("relayed: %+v", c) } page := a.get("/ask").Body if card := cardItem(t, page, id); !strings.Contains(card, `

    Go ahead

    `) || strings.Contains(card, "= len(hosts) { t.Fatalf("PUT host %d of %d", i, len(hosts)) } var in struct{ Origin, Token string } if hosts[i].Method != http.MethodPut || json.Unmarshal([]byte(hosts[i].Body), &in) != nil { t.Fatalf("PUT host: %+v", hosts[i]) } return in.Token, strings.TrimPrefix(hosts[i].Header.Get("Authorization"), "Bearer "), in.Origin } // hostMember is the member host token names, "" for nobody. func (a *testApp) hostMember(token string) string { a.t.Helper() m, ok, err := store.MemberByHostToken(context.Background(), a.DB, token) if err != nil { a.t.Fatal(err) } if !ok { return "" } return m.ID } func (a *testApp) hostRegistered() bool { a.t.Helper() ok, err := store.HostRegistered(context.Background(), a.DB, a.ownerID()) if err != nil { a.t.Fatal(err) } return ok } // quiet fails if the app logged any of secrets. func (a *testApp) quiet(secrets ...string) { a.t.Helper() logs := a.logs.String() for _, s := range secrets { if s != "" && strings.Contains(logs, s) { a.t.Fatalf("the log carried a secret:\n%s", logs) } } } // Once the member's connection is ready, Base mints them a host token and // gives it to Equipo, with their bearer and Base's own origin: once. // Reconnecting gives Equipo a new one, and the old one names nobody. func TestConnectRegistersHost(t *testing.T) { a, f := newAskApp(t) bearer := a.connectEquipo(f) if n := len(f.Hosts()); n != 1 { t.Fatalf("PUT host after connecting: %d, want 1", n) } first, sentWith, origin := hostOf(t, f, 0) if sentWith != bearer || origin != testOrigin || !strings.HasPrefix(first, "bh_") { t.Fatalf("PUT host: bearer ok %v, origin %q, token %q", sentWith == bearer, origin, first) } if a.hostMember(first) != a.ownerID() || !a.hostRegistered() { t.Fatalf("host token names %q, registered %v", a.hostMember(first), a.hostRegistered()) } a.get("/ask") a.get("/ask/state") if n := len(f.Hosts()); n != 1 { t.Fatalf("reading the chat registered again: %d PUTs", n) } a.approveEquipo(f) if n := len(f.Hosts()); n != 2 { t.Fatalf("PUT host after reconnecting: %d, want 2", n) } second, sentWith, _ := hostOf(t, f, 1) if second == first || sentWith == bearer { t.Fatal("reconnecting registered the old token or with the old bearer") } if a.hostMember(first) != "" || a.hostMember(second) != a.ownerID() { t.Fatalf("old token names %q, new names %q", a.hostMember(first), a.hostMember(second)) } a.noLeak(first) a.noLeak(second) a.quiet(first, second, bearer, sentWith) } // A member who connected before Base registered hosts has no host token: // their next read of the chat registers one, once. func TestHostRegisteredLazily(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) if err := store.DeleteHostToken(context.Background(), a.DB, a.ownerID()); err != nil { t.Fatal(err) } if page := a.get("/ask"); page.Code != 200 || len(f.Hosts()) != 2 { t.Fatalf("/ask: %d, PUTs %d, want 2", page.Code, len(f.Hosts())) } token, _, _ := hostOf(t, f, -1) if a.hostMember(token) != a.ownerID() || !a.hostRegistered() { t.Fatal("the lazy registration did not take") } a.get("/ask/state") a.get("/ask") if n := len(f.Hosts()); n != 2 { t.Fatalf("registered again: %d PUTs", n) } } // A refused registration does not break the chat or disconnect anyone: it // is logged (no token in it), and the next read tries again. func TestHostRegistrationFailureIsRetried(t *testing.T) { a, f := newAskApp(t) f.RefuseHost(http.StatusForbidden, "host_not_allowed") bearer := a.connectEquipo(f) if n := len(f.Hosts()); n != 1 || a.hostRegistered() { t.Fatalf("PUTs %d, registered %v", n, a.hostRegistered()) } if n := strings.Count(a.logs.String(), "host_not_allowed"); n != 1 { t.Fatalf("logged host_not_allowed %d times, want 1:\n%s", n, a.logs.String()) } if s := a.get("/settings").Body; !strings.Contains(s, `action="/ask/disconnect"`) { t.Fatalf("a refused registration disconnected the member:\n%s", s) } page := a.get("/ask") if page.Code != 200 || !strings.Contains(page.Body, `data-state="ready"`) || len(f.Hosts()) != 2 { t.Fatalf("/ask: %d, PUTs %d\n%s", page.Code, len(f.Hosts()), page.Body) } if n := strings.Count(a.logs.String(), "host_not_allowed"); n != 2 { t.Fatalf("logged host_not_allowed %d times after two tries", n) } if r := a.post("/ask/messages", url.Values{"text": {"What can I do"}}); r.Code != 303 || len(f.Calls("/api/v1/assistant/messages")) != 1 { t.Fatalf("send: %d", r.Code) } if l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); l.State != store.EquipoConnected { t.Fatalf("link %q", l.State) } f.RefuseHost(http.StatusServiceUnavailable, "unavailable") a.get("/ask/state") if len(f.Hosts()) != 3 || a.hostRegistered() { t.Fatalf("PUTs %d, registered %v", len(f.Hosts()), a.hostRegistered()) } f.RefuseHost(0, "") a.get("/ask") token, _, _ := hostOf(t, f, -1) if len(f.Hosts()) != 4 || !a.hostRegistered() || a.hostMember(token) != a.ownerID() { t.Fatalf("PUTs %d, registered %v", len(f.Hosts()), a.hostRegistered()) } a.get("/ask") if n := len(f.Hosts()); n != 4 { t.Fatalf("registered again once it took: %d PUTs", n) } var tried []string for i := range f.Hosts() { tok, _, _ := hostOf(t, f, i) tried = append(tried, tok) } a.quiet(append(tried, bearer)...) } // Disconnecting, and Equipo refusing the bearer, both forget the member's // host token. func TestDisconnectDropsHostToken(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) token, _, _ := hostOf(t, f, -1) if r := a.post("/ask/disconnect", nil); r.Code != 303 { t.Fatalf("disconnect: %d", r.Code) } if a.hostMember(token) != "" { t.Fatal("the host token outlived Disconnect") } a.approveEquipo(f) token, _, _ = hostOf(t, f, -1) if a.hostMember(token) != a.ownerID() { t.Fatal("connecting again registered nothing") } f.RevokeAll() if page := a.get("/ask").Body; !strings.Contains(page, ">Set it up again") { t.Fatalf("no reconnect:\n%s", page) } if a.hostMember(token) != "" { t.Fatal("the host token outlived a refused bearer") } } // noteFor is the runner note shown for state, with its attributes. func noteFor(t *testing.T, page, state string) string { t.Helper() m := regexp.MustCompile(`(?s)

    ]*>.*?

    `).FindString(page) if m == "" { t.Fatalf("no %s note in:\n%s", state, page) } return m } // postJSON posts form as the panel's script does. func (a *testApp) postJSON(target string, form url.Values) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", a.origin) req.Header.Set("Accept", "application/json") return a.do(req) } // Without a runner the chat says so, links to Equipo, keeps what the // person wrote and shows no message; a runner too old has its own note. // The panel's script hears the state. func TestAskNoRunner(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) f.Say("Hello.") f.NoRunner() page := a.get("/ask").Body note := noteFor(t, page, "norunner") if strings.Contains(note, " hidden") || !strings.Contains(note, `href="`+f.URL+`/"`) || !strings.Contains(page, `data-state="norunner"`) || !strings.Contains(page, "Hello.") { t.Fatalf("no-runner note:\n%s", page) } if !strings.Contains(noteFor(t, page, "oldrunner"), " hidden") { t.Fatal("the runner-too-old note shows") } var st struct{ State string } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "norunner" { t.Fatalf("state: %s", r.Body) } // Scripts off: the page comes back with the text in the field, the // same key, and no message. r := a.post("/ask/messages", url.Values{"text": {"Build me a quick website"}, "key": {"k-norunner"}}) if r.Code != http.StatusConflict || strings.Contains(noteFor(t, r.Body, "norunner"), " hidden") || !strings.Contains(r.Body, `>Build me a quick website`) || strings.Contains(r.Body, `
  • What can I do`) { t.Fatalf("send with a runner too old: %d\n%s", r.Code, r.Body) } if r := a.postJSON("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old-json"}}); r.Code != http.StatusConflict || strings.TrimSpace(r.Body) != `{"state":"oldrunner"}` { t.Fatalf("JSON send: %d %s", r.Code, r.Body) } if strings.Contains(a.get("/ask").Body, `
  • ]*>.*?
      .*?
  • `).FindString(page) if m == "" { t.Fatalf("no job %s in:\n%s", id, page) } return m } // A job is a pill in the conversation, never a card: the title, its status // beside it, and a summary named by both. Nothing in the chat names // Equipo, or links to the job's page there (only the job view's title // will, Task 19). func TestAskJobPill(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskJob("Building your website") page := a.get("/ask").Body if n := strings.Count(page, `
  • (.*?)`, "Building your website") expect(t, "stage", job, `(.*?)`, "Getting started") if !strings.Contains(job, ``) { t.Errorf("summary's name:\n%s", job) } if strings.Contains(page, `data-card="`+id+`"`) || strings.Contains(job, "pill-link") { t.Errorf("the job is drawn as a card, or links somewhere while working:\n%s", job) } if strings.Contains(strings.ToLower(textOf(page)), "equipo") { t.Errorf("the chat names Equipo:\n%s", textOf(page)) } // The job's page in Equipo is linked once: the job view's title. if n, in := strings.Count(page, f.URL+"/jobs/"), strings.Count(jobViewOf(t, job), f.URL+"/jobs/"); n != 1 || in != 1 { t.Errorf("the job's page is linked %d times, %d of them the job view's title:\n%s", n, in, page) } if !strings.Contains(page, `data-empty hidden`) { t.Errorf("the empty line shows beside a job") } var st struct { Cards []struct{ ID string } Jobs []struct { ID, State, Result string Cards []struct{ ID string } } } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 0 || len(st.Jobs) != 1 || st.Jobs[0].ID != id || st.Jobs[0].State != "working" || st.Jobs[0].Result != "Getting started" || st.Jobs[0].Cards == nil || !strings.Contains(r.Body, `"cards":[]`) { t.Fatalf("state: %s", r.Body) } } // jobViewOf is the job view inside a job's li. func jobViewOf(t *testing.T, job string) string { t.Helper() m := regexp.MustCompile(`(?s)
    ]*>.*?
    `).FindString(job) if m == "" { t.Fatalf("no job view in:\n%s", job) } return m } // The job view, inside the pill's
    (it opens there without // scripts): the title, linked to the job's page in Equipo in a new tab // with "Open in Equipo" as its tooltip (plan decision D3), the status, // one sentence more, and when it started (D19). A job with no page there // (a legacy hand-off, J7) has a plain title. Once there is something to // see, the view links to it as the pill does. func TestAskJobView(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskJob("Building your website") page := a.get("/ask").Body view := jobViewOf(t, jobItem(t, page, id)) if !strings.HasPrefix(view, `
    `) { t.Errorf("the view's name:\n%s", view) } title := regexp.MustCompile(`(?s)

    (.*?)

    `).FindStringSubmatch(view) link := regexp.MustCompile(`^Building your website]*aria-hidden="true">.*?$`) if title == nil || link.FindStringSubmatch(title[1]) == nil || !strings.HasPrefix(link.FindStringSubmatch(title[1])[1], f.URL+"/jobs/h_") { t.Errorf("the view's title is not its link to the job's page:\n%s", view) } expect(t, "status", view, `

    (.*?)

    `, "Getting started") expect(t, "detail", view, `

    (.*?)

    `, "Working out what's needed.") expect(t, "started", view, `

    (.*?)

    `, "Started just now") if !regexp.MustCompile(`Uses your other plan, at no extra cost.

    `) { t.Fatalf("no Carry on now in the view:\n%s", view) } fields := formFields(t, page, "/ask/cards/"+id+"/carry_on") if fields.Get("revision") != "3" || fields.Get("key") == "" { t.Errorf("Carry on now posts %v", fields) } css, _ := os.ReadFile("../look/static/app.css") for _, rule := range []string{`.job[data-state="paused"] { --st: var(--st-pause); }`, `--st-pause: #AEB8FF;`, `--st-pause: #4B55C9;`, `--st-pause: light-dark(#4B55C9, #AEB8FF);`} { if !strings.Contains(string(css), rule) { t.Errorf("app.css has no %s", rule) } } // Not offered: no form, the rest as before. other := f.AskJob("Invoice reminders") f.PauseJob(other, "Paused until midnight", "It has reached today's spending limit. It will carry on by itself at midnight (in 3 hours).", false) view = jobViewOf(t, jobItem(t, a.get("/ask").Body, other)) if strings.Contains(view, " time.Second { t.Errorf("%s took %v with the time-zone call hanging", page, took) } } zoneCalls(t, f, 1) } // An answer that settles it (a 2xx, or a 4xx other than 429: Fable's 422 // for a zone Equipo refuses, and an older Equipo's 404) is never sent // again; a failure (a 5xx, a 429) is not tried again for a while: one call // over a connect and three reads, either way. func TestAskZoneIsToldOnce(t *testing.T) { for _, tc := range []struct { status int code string }{{422, "invalid_input"}, {404, "not_found"}, {500, "internal"}, {503, "unavailable"}, {429, "rate_limited"}} { t.Run(strconv.Itoa(tc.status), func(t *testing.T) { a, f := newZonedAskApp(t) f.RefuseTimeZone(tc.status, tc.code) a.connectEquipo(f) zoneCalls(t, f, 1) for _, page := range []string{"/ask", "/", "/ask/state"} { if r := a.get(page); r.Code != 200 { t.Fatalf("%s: %d", page, r.Code) } } zoneCalls(t, f, 1) }) } } // A go-ahead or Publish card that belongs to a job is drawn under its // pill while open, and answers as any card does; answered, it is listed // in the job view. One whose job is not drawn is loose. A redrawn job (a // new revision) keeps the cards under it. func TestAskJobAttachesItsCards(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskJob("Building your website") f.SetJob(id, "ready", "Ready to try", "Have a look.", equipo.Link{Label: "Try it", URL: "https://preview.example.test/"}) goAhead := f.AskOutcomeFor(id, "This is ready. Go ahead?", goOptions, nil) loose := f.AskOutcomeFor("c_9999", "Publish it?", goOptions, nil) f.SetJob(id, "ready", "Ready to try", "Still ready.", equipo.Link{Label: "Try it", URL: "https://preview.example.test/"}) page := a.get("/ask").Body job := jobItem(t, page, id) if !strings.Contains(job, `data-revision="3"`) || !strings.Contains(job, `data-card="`+goAhead+`"`) || strings.Contains(job, `data-card="`+loose+`"`) { t.Fatalf("the job's cards:\n%s", job) } if card := cardItem(t, job, goAhead); !strings.Contains(card, `data-for="`+id+`"`) { t.Errorf("the attached card does not say whose it is:\n%s", card) } rest := strings.Replace(page, job, "", 1) if !strings.Contains(rest, `data-card="`+loose+`"`) { t.Errorf("the card of no drawn job is not loose:\n%s", page) } if strings.Index(page, job) > strings.Index(page, `data-card="`+loose+`"`) { t.Errorf("a loose card is drawn before the job") } answer := formFields(t, page, "/ask/cards/"+goAhead+"/answer") answer.Set("choice", "go") if r := a.post("/ask/cards/"+goAhead+"/answer", answer); r.Code != 303 || r.Location() != "/ask" { t.Fatalf("answer: %d %q", r.Code, r.Location()) } if c := f.Calls("/api/v1/assistant/cards/" + goAhead + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"go","revision":1}` { t.Fatalf("relayed: %+v", c) } // Answered, it is the job view's, as its question and how it ended. if view := jobViewOf(t, jobItem(t, a.get("/ask").Body, id)); !strings.Contains(view, `
  • This is ready. Go ahead?

    Go ahead

  • `) { t.Errorf("answered card in the job view:\n%s", view) } var st struct { Cards []struct{ ID string } Jobs []struct { ID string Cards []struct{ ID, Job string } } } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 1 || st.Cards[0].ID != loose || len(st.Jobs) != 1 || len(st.Jobs[0].Cards) != 1 || st.Jobs[0].Cards[0].ID != goAhead || st.Jobs[0].Cards[0].Job != id { t.Fatalf("state: %s", r.Body) } } // Paul's live check (2026-11-16): only a card that needs an answer is // drawn under its job's pill. A job's answered question and go-ahead are // listed in its view, under the detail, each as its question and its // result line with nothing to press; an open go-ahead stays under the // pill; the state carries every card of the job, for the script to // place. func TestAskJobSettledCardsInView(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) id := f.AskLegacyJob("Can you make me a website?") question := f.AskKindFor("question", id, "Which website?", []equipo.Option{{Value: "new", Label: "A new one"}}, nil) goAhead := f.AskOutcomeFor(id, "This is ready. Go ahead?", goOptions, nil) f.SetCard(question, "answered", "A new one") f.SetCard(goAhead, "answered", "Go ahead") f.SetJob(id, "stopped", "Stopped", "It can't go on until something is sorted out.") page := a.get("/ask").Body job := jobItem(t, page, id) if !strings.HasSuffix(job, `
    1. `) || strings.Contains(page, `class="msg card`) { t.Errorf("an ended card drawn as a card:\n%s", page) } view := jobViewOf(t, job) want := `

      It can't go on until something is sorted out.

        ` + `
      1. Which website?

        A new one

      2. ` + `
      3. This is ready. Go ahead?

        Go ahead

      ` if !strings.Contains(view, want) { t.Errorf("the job view's ended cards, want %s in:\n%s", want, view) } again := f.AskOutcomeFor(id, "Try it again?", goOptions, nil) job = jobItem(t, a.get("/ask").Body, id) if card := cardItem(t, job, again); !strings.Contains(card, `action="/ask/cards/`+again+`/answer"`) || strings.Contains(jobViewOf(t, job), again) { t.Errorf("the open go-ahead is not under the pill:\n%s", job) } var st struct { Jobs []struct { ID string Cards []struct{ ID, State string } } } if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Jobs) != 1 || len(st.Jobs[0].Cards) != 3 { t.Fatalf("state: %s", r.Body) } } // A team_update turn is the Assistant thinking about a job by itself: no // status line, no Stop, and not the turn the cancel form stops. func TestAskTeamUpdateTurnIsQuiet(t *testing.T) { a, f := newAskApp(t) a.connectEquipo(f) f.AskJob("Building your website") f.EmitTurn("team_update", "running") page := a.get("/ask").Body expect(t, "/ask", page, `

      (.*?)

      `, "") if !regexp.MustCompile(`