oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package webtest
2
3import (
4 "bufio"
5 "context"
6 "database/sql"
7 "encoding/json"
8 "html"
9 "net/http"
10 "net/url"
11 "os"
12 "regexp"
13 "strconv"
14 "strings"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/base/internal/config"
19 "amadan.net/oficina/base/internal/equipo"
20 "amadan.net/oficina/base/internal/equipo/equipotest"
21 "amadan.net/oficina/base/internal/store"
22 "amadan.net/oficina/base/internal/web"
23)
24
25func strconv64(n int64) string { return strconv.FormatInt(n, 10) }
26
27// newAskApp is Base with "Ask Base anything" on, answered by a fake Equipo,
28// and the owner signed in.
29func newAskApp(t *testing.T) (*testApp, *equipotest.Fake) {
30 t.Helper()
31 f := equipotest.New(t)
32 a := newAppConfigured(t, func(*sql.DB, config.Config) web.Installer { return noInstaller{} }, time.UTC,
33 func(c *config.Config) { c.EquipoOrigin = f.URL })
34 a.signedInOwner()
35 return a, f
36}
37
38var codeRE = regexp.MustCompile(`<p class="code"[^>]*>([A-Z0-9]{8})</p>`)
39
40// ownerID is the bootstrapped owner's member id.
41func (a *testApp) ownerID() string {
42 a.t.Helper()
43 m, ok, err := store.MemberByEmail(context.Background(), a.DB, ownerAddress)
44 if err != nil || !ok {
45 a.t.Fatalf("owner: %v %v", ok, err)
46 }
47 return m.ID
48}
49
50// pollable makes Base's last look at Equipo old enough to look again.
51func (a *testApp) pollable() {
52 a.t.Helper()
53 if _, err := a.DB.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-10*time.Second).UTC()); err != nil {
54 a.t.Fatal(err)
55 }
56}
57
58// connectEquipo connects the owner from Settings the way a person does:
59// Connect Equipo, approve the code in Equipo, come back. It returns the
60// bearer Equipo issued.
61func (a *testApp) connectEquipo(f *equipotest.Fake) string {
62 a.t.Helper()
63 a.approveEquipo(f)
64 tokens := f.Tokens()
65 if len(tokens) != 1 {
66 a.t.Fatalf("tokens: %v", tokens)
67 }
68 return tokens[0]
69}
70
71// approveEquipo is connectEquipo without asking which bearer Equipo
72// issued: it connects again just as well.
73func (a *testApp) approveEquipo(f *equipotest.Fake) {
74 a.t.Helper()
75 r := a.post("/ask/connect", url.Values{"next": {"settings"}})
76 if r.Code != 303 || r.Location() != "/ask/connect?next=settings" {
77 a.t.Fatalf("connect: %d %q\n%s", r.Code, r.Location(), r.Body)
78 }
79 page := a.get(r.Location())
80 m := codeRE.FindStringSubmatch(page.Body)
81 if page.Code != 200 || m == nil {
82 a.t.Fatalf("pending page: %d\n%s", page.Code, page.Body)
83 }
84 if err := f.Approve(m[1]); err != nil {
85 a.t.Fatal(err)
86 }
87 a.pollable()
88 if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" {
89 a.t.Fatalf("after approval: %d %q\n%s", r.Code, r.Location(), r.Body)
90 }
91}
92
93// check presses "Check again" on the connect page.
94func (a *testApp) check(next string) Resp {
95 a.t.Helper()
96 return a.post("/ask/connect/check", url.Values{"next": {next}})
97}
98
99// noLeak fails if any response so far carried token: body, header or cookie.
100func (a *testApp) noLeak(token string) {
101 a.t.Helper()
102 for _, r := range a.seen {
103 if strings.Contains(r.Body, token) {
104 a.t.Fatalf("a response body carried the bearer:\n%s", r.Body)
105 }
106 for k, vs := range r.Header {
107 for _, v := range vs {
108 if strings.Contains(v, token) {
109 a.t.Fatalf("header %s carried the bearer", k)
110 }
111 }
112 }
113 }
114}
115
116func TestAskOffWithoutEquipo(t *testing.T) {
117 a := newApp(t)
118 a.signedInOwner()
119 // Home has no chat column, no Base button and no field.
120 home := a.get("/").Body
121 if strings.Contains(home, `class="ask`) || strings.Contains(home, "base-btn") || strings.Contains(home, `/ask`) ||
122 strings.Contains(home, "<aside") || strings.Contains(home, "<dialog") {
123 t.Errorf("chat is not off:\n%s", home)
124 }
125 if r := a.get("/ask"); r.Code != 404 {
126 t.Errorf("/ask: %d", r.Code)
127 }
128 if strings.Contains(a.get("/settings").Body, "Equipo") {
129 t.Error("Settings offers Equipo with the chat off")
130 }
131}
132
133func TestAskFieldOpensChat(t *testing.T) {
134 a, _ := newAskApp(t)
135 home := a.get("/").Body
136 for _, want := range []string{`<button class="ask-field" type="submit" data-ask-open aria-controls="ask-panel"><span>Ask Base anything</span>`,
137 `<button class="base-btn" type="submit" data-ask-open aria-controls="ask-panel" aria-label="Ask Base"`, `<aside id="ask-panel"`, `action="/ask/connect"`} {
138 if !strings.Contains(home, want) {
139 t.Errorf("Home lacks %q:\n%s", want, home)
140 }
141 }
142 settings := a.get("/settings").Body
143 for _, want := range []string{"Connection<small>Not set up</small>", `action="/ask/connect"`, ">Set up Ask Base</button>"} {
144 if !strings.Contains(settings, want) {
145 t.Errorf("Settings lacks %q:\n%s", want, settings)
146 }
147 }
148}
149
150func TestConnectEquipo(t *testing.T) {
151 a, f := newAskApp(t)
152 r := a.post("/ask/connect", url.Values{"next": {"settings"}})
153 if r.Code != 303 {
154 t.Fatalf("connect: %d\n%s", r.Code, r.Body)
155 }
156 begin := f.Calls("/api/v1/auth/devices")
157 if len(begin) != 1 || !strings.Contains(begin[0].Body, `"label":"Base (Acme)"`) {
158 t.Fatalf("begin: %+v", begin)
159 }
160 page := a.get(r.Location())
161 m := codeRE.FindStringSubmatch(page.Body)
162 if m == nil || f.Label(m[1]) != "Base (Acme)" {
163 t.Fatalf("no user code:\n%s", page.Body)
164 }
165 for _, want := range []string{f.URL + "/auth/devices/", `<form method="post" action="/ask/connect/check"`, ">Check again</button>"} {
166 if !strings.Contains(html.UnescapeString(page.Body), want) {
167 t.Errorf("pending page lacks %q:\n%s", want, page.Body)
168 }
169 }
170 // Checking asks once; checking again inside Equipo's five seconds does not.
171 if r := a.check("settings"); r.Code != 303 || r.Location() != "/ask/connect?next=settings" {
172 t.Fatalf("check while pending: %d %q", r.Code, r.Location())
173 }
174 a.check("settings")
175 if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 {
176 t.Fatalf("exchanges: %d, want 1", n)
177 }
178 if err := f.Approve(m[1]); err != nil {
179 t.Fatal(err)
180 }
181 a.pollable()
182 if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" {
183 t.Fatalf("after approval: %d %q", r.Code, r.Location())
184 }
185 token := f.Tokens()[0]
186 l, ok, err := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
187 if !ok || err != nil || l.State != store.EquipoConnected || l.Revision != 3 || l.ExpiresAt.Before(time.Now().Add(29*24*time.Hour)) {
188 t.Fatalf("link: %+v %v %v", l, ok, err)
189 }
190 if strings.Contains(string(l.Sealed), token) || strings.Contains(string(l.Sealed), "equipo.person") {
191 t.Fatal("the bearer is stored in the clear")
192 }
193 settings := a.get("/settings").Body
194 if !strings.Contains(settings, "Connection<small>Connected</small>") || !strings.Contains(settings, `action="/ask/disconnect"`) {
195 t.Errorf("Settings after connecting:\n%s", settings)
196 }
197 a.noLeak(token)
198}
199
200// GET /ask/connect only shows: a cross-site link or prefetch cannot finish
201// the exchange. The JSON check is what the page's script posts.
202func TestConnectPageIsReadOnly(t *testing.T) {
203 a, f := newAskApp(t)
204 r := a.post("/ask/connect", url.Values{"next": {"ask"}})
205 m := codeRE.FindStringSubmatch(a.get(r.Location()).Body)
206 if m == nil {
207 t.Fatal("no code")
208 }
209 if err := f.Approve(m[1]); err != nil {
210 t.Fatal(err)
211 }
212 a.pollable()
213 if page := a.get(r.Location()); page.Code != 200 || codeRE.FindString(page.Body) == "" {
214 t.Fatalf("page: %d", page.Code)
215 }
216 if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 0 {
217 t.Fatalf("GET exchanged %d times", n)
218 }
219 if r := a.postFrom("https://evil.example", "/ask/connect/check", url.Values{"next": {"ask"}}); r.Code != 403 {
220 t.Fatalf("cross-site check: %d", r.Code)
221 }
222 req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/connect/check", strings.NewReader("next=ask"))
223 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
224 req.Header.Set("Origin", a.origin)
225 req.Header.Set("Accept", "application/json")
226 res := a.do(req)
227 if res.Code != 200 || !strings.Contains(res.Body, `"state":"ready"`) || !strings.Contains(res.Body, `"next":"/ask"`) {
228 t.Fatalf("JSON check: %d %s", res.Code, res.Body)
229 }
230}
231
232// Two checks at once: only one asks Equipo.
233func TestConnectConcurrentChecksExchangeOnce(t *testing.T) {
234 a, f := newAskApp(t)
235 a.post("/ask/connect", url.Values{"next": {"ask"}})
236 entered, release := f.HoldNextExchange()
237 done := make(chan Resp)
238 go func() { done <- a.check("ask") }()
239 select {
240 case <-entered:
241 case r := <-done:
242 t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location())
243 case <-time.After(5 * time.Second):
244 t.Fatal("the check never reached Equipo's exchange")
245 }
246 a.check("ask")
247 release()
248 <-done
249 if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 {
250 t.Fatalf("exchanges: %d, want 1", n)
251 }
252}
253
254// Disconnect while an exchange is in flight: the bearer that exchange
255// brings back is revoked, not stored.
256func TestDisconnectDuringExchangeLeavesNoBearer(t *testing.T) {
257 a, f := newAskApp(t)
258 r := a.post("/ask/connect", url.Values{"next": {"settings"}})
259 m := codeRE.FindStringSubmatch(a.get(r.Location()).Body)
260 if err := f.Approve(m[1]); err != nil {
261 t.Fatal(err)
262 }
263 l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
264 entered, release := f.HoldNextExchange()
265 done := make(chan Resp)
266 go func() { done <- a.check("settings") }()
267 select {
268 case <-entered:
269 case r := <-done:
270 t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location())
271 case <-time.After(5 * time.Second):
272 t.Fatal("the check never reached Equipo's exchange")
273 }
274 if d := a.post("/ask/disconnect", nil); d.Code != 303 {
275 t.Fatalf("disconnect: %d", d.Code)
276 }
277 release()
278 if c := <-done; c.Location() == "/settings" && c.Code != 303 {
279 t.Fatalf("check: %d", c.Code)
280 }
281 if _, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); found {
282 t.Fatal("the exchange brought the link back after Disconnect")
283 }
284 if !f.Revoked(l.DeviceID) {
285 t.Fatal("the bearer from the late exchange was not revoked")
286 }
287}
288
289func TestConnectCodeExpires(t *testing.T) {
290 a, f := newAskApp(t)
291 a.post("/ask/connect", url.Values{"next": {"ask"}})
292 f.Expire()
293 r := a.check("ask")
294 if r.Code != 303 {
295 t.Fatalf("check: %d", r.Code)
296 }
297 page := a.get(r.Location())
298 if page.Code != 200 || !strings.Contains(page.Body, "That code expired.") || !strings.Contains(page.Body, `action="/ask/connect"`) {
299 t.Fatalf("expired: %d\n%s", page.Code, page.Body)
300 }
301}
302
303// Every chat form carries a key made when the page was drawn, which Base
304// relays as the Idempotency-Key: a resubmitted form is the same request.
305func TestAskFormsCarryKeys(t *testing.T) {
306 a, f := newAskApp(t)
307 a.connectEquipo(f)
308 id := f.AskQuestion("Which branch?", "main")
309 f.Hold = true
310 a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}})
311 page := a.get("/ask").Body
312 answer := formFields(t, page, "/ask/cards/"+id+"/answer")
313 cancel := regexp.MustCompile(`action="(/ask/turns/[^/"]+/cancel)"`).FindStringSubmatch(page)
314 if answer.Get("key") == "" || cancel == nil {
315 t.Fatalf("forms:\n%s", page)
316 }
317 stop := formFields(t, page, cancel[1])
318 if stop.Get("key") == "" || stop.Get("key") == answer.Get("key") {
319 t.Fatalf("stop key %q, answer key %q", stop.Get("key"), answer.Get("key"))
320 }
321 answer.Set("choice", "main")
322 a.post("/ask/cards/"+id+"/answer", answer)
323 a.post(cancel[1], stop)
324 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")} {
325 if c := f.Calls(path); len(c) != 1 || c[0].Header.Get("Idempotency-Key") != key {
326 t.Errorf("%s: %+v, want key %q", path, c, key)
327 }
328 }
329}
330
331func TestAskSendRelaysWithBearer(t *testing.T) {
332 a, f := newAskApp(t)
333 token := a.connectEquipo(f)
334 page := a.get("/ask")
335 key := formFields(t, page.Body, "/ask/messages").Get("key")
336 if page.Code != 200 || key == "" {
337 t.Fatalf("/ask: %d key=%q\n%s", page.Code, key, page.Body)
338 }
339 r := a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {key}})
340 if r.Code != 303 || r.Location() != "/ask" {
341 t.Fatalf("send: %d %q", r.Code, r.Location())
342 }
343 calls := f.Calls("/api/v1/assistant/messages")
344 if len(calls) != 1 {
345 t.Fatalf("sends: %d", len(calls))
346 }
347 h := calls[0].Header
348 if h.Get("Authorization") != "Bearer "+token || h.Get("Idempotency-Key") != key || h.Get("Cookie") != "" || h.Get("Origin") != "" {
349 t.Errorf("relayed headers: %v", h)
350 }
351 if !strings.Contains(calls[0].Body, `"idempotency_key":"`+key+`"`) {
352 t.Errorf("relayed body: %s", calls[0].Body)
353 }
354 // The same key again (a double press) sends nothing new.
355 a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {key}})
356 var body string
357 for i := 0; i < 100; i++ {
358 if body = a.get("/ask").Body; strings.Contains(body, "Hello. What shall we work on?") {
359 break
360 }
361 time.Sleep(20 * time.Millisecond)
362 }
363 if strings.Count(body, "What can I do") != 1 || !strings.Contains(body, "Hello. What shall we work on?") {
364 t.Fatalf("conversation:\n%s", body)
365 }
366 // Scripts on: the same route answers JSON.
367 req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/messages", strings.NewReader(url.Values{"text": {"Build me a quick website"}, "key": {"k-json"}}.Encode()))
368 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
369 req.Header.Set("Origin", a.origin)
370 req.Header.Set("Accept", "application/json")
371 res := a.do(req)
372 var sent struct {
373 Message struct{ Text string }
374 Turn struct{ ID, State string }
375 }
376 if res.Code != 200 || json.Unmarshal([]byte(res.Body), &sent) != nil || sent.Message.Text != "Build me a quick website" || sent.Turn.ID == "" {
377 t.Fatalf("JSON send: %d %s", res.Code, res.Body)
378 }
379 a.noLeak(token)
380}
381
382func TestAskRefusesCrossSitePost(t *testing.T) {
383 a, f := newAskApp(t)
384 a.connectEquipo(f)
385 if r := a.postFrom("https://evil.example", "/ask/messages", url.Values{"text": {"hi"}}); r.Code != 403 {
386 t.Fatalf("cross-site send: %d", r.Code)
387 }
388 if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
389 t.Fatalf("relayed a cross-site send")
390 }
391}
392
393func TestAskScriptsOffCardAndCancel(t *testing.T) {
394 a, f := newAskApp(t)
395 a.connectEquipo(f)
396 id := f.AskQuestion("Which branch should I start from?", "main", "develop")
397 page := a.get("/ask").Body
398 action := "/ask/cards/" + id + "/answer"
399 fields := formFields(t, page, action)
400 if !strings.Contains(page, "Which branch should I start from?") || !strings.Contains(page, `name="choice" value="develop"`) {
401 t.Fatalf("card:\n%s", page)
402 }
403 fields.Set("choice", "main")
404 if r := a.post(action, fields); r.Code != 303 || r.Location() != "/ask" {
405 t.Fatalf("answer: %d", r.Code)
406 }
407 ans := f.Calls("/api/v1/assistant/cards/" + id + "/answer")
408 if len(ans) != 1 || ans[0].Body != `{"choice":"main","revision":1}`+"\n" && ans[0].Body != `{"choice":"main","revision":1}` {
409 t.Fatalf("answer relayed: %+v", ans)
410 }
411
412 f.Hold = true
413 a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}})
414 page = a.get("/ask").Body
415 m := regexp.MustCompile(`action="(/ask/turns/([^/"]+)/cancel)"`).FindStringSubmatch(page)
416 if m == nil || !strings.Contains(page, `<noscript><meta http-equiv="refresh" content="5"></noscript>`) {
417 t.Fatalf("no stop button or refresh for a running turn:\n%s", page)
418 }
419 if r := a.post(m[1], nil); r.Code != 303 {
420 t.Fatalf("cancel: %d", r.Code)
421 }
422 if f.Turn(m[2]) != "cancelled" {
423 t.Fatalf("turn %s is %q", m[2], f.Turn(m[2]))
424 }
425}
426
427// buttonRE is a <button>'s opening tag; buttonAttrRE one of its
428// attributes, valued or bare (hidden).
429var (
430 buttonRE = regexp.MustCompile(`<button([^>]*)>`)
431 buttonAttrRE = regexp.MustCompile(`([\w-]+)(?:="([^"]*)")?`)
432)
433
434// buttons are the attributes of each <button> in markup.
435func buttons(markup string) []map[string]string {
436 var out []map[string]string
437 for _, b := range buttonRE.FindAllStringSubmatch(markup, -1) {
438 attrs := map[string]string{}
439 for _, kv := range buttonAttrRE.FindAllStringSubmatch(b[1], -1) {
440 attrs[kv[1]] = html.UnescapeString(kv[2])
441 }
442 out = append(out, attrs)
443 }
444 return out
445}
446
447// With scripts off the composer is still a form that sends: its Send is an
448// icon button labelled "Send", drawn (not hidden) whatever the field holds;
449// while a turn runs, a Stop icon button posts the turn's cancel form, and
450// Send stays, so a person can still write.
451func TestAskScriptsOffComposer(t *testing.T) {
452 a, f := newAskApp(t)
453 a.connectEquipo(f)
454 composer := func(page string) string {
455 m := regexp.MustCompile(`(?s)<form class="composer"[^>]*action="/ask/messages"[^>]*>(.*?)</form>`).FindStringSubmatch(page)
456 if m == nil {
457 t.Fatalf("no composer posting to /ask/messages in:\n%s", page)
458 }
459 return m[1]
460 }
461 find := func(markup, label string) map[string]string {
462 for _, b := range buttons(markup) {
463 if b["aria-label"] == label {
464 return b
465 }
466 }
467 return nil
468 }
469 send := find(composer(a.get("/ask").Body), "Send")
470 if send == nil || send["type"] != "submit" || send["title"] != "Send" {
471 t.Fatalf("the composer's Send button: %v", send)
472 }
473 if _, hidden := send["hidden"]; hidden {
474 t.Fatal("Send is hidden with scripts off")
475 }
476 if stop := find(composer(a.get("/ask").Body), "Stop"); stop != nil {
477 if _, hidden := stop["hidden"]; !hidden {
478 t.Fatal("a Stop button shows with no turn running")
479 }
480 }
481
482 f.Hold = true
483 a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}})
484 page := a.get("/ask").Body
485 stop := find(composer(page), "Stop")
486 if stop == nil || stop["type"] != "submit" || stop["title"] != "Stop" || stop["form"] == "" {
487 t.Fatalf("the composer's Stop button while answering: %v", stop)
488 }
489 if _, hidden := stop["hidden"]; hidden {
490 t.Fatal("Stop is hidden while a turn runs")
491 }
492 if send := find(composer(page), "Send"); send == nil {
493 t.Fatal("no Send while answering, scripts off")
494 } else if _, hidden := send["hidden"]; hidden {
495 t.Fatal("Send is hidden while answering, scripts off")
496 }
497 m := regexp.MustCompile(`<form[^>]*id="` + regexp.QuoteMeta(stop["form"]) + `"[^>]*action="(/ask/turns/([^/"]+)/cancel)"`).FindStringSubmatch(page)
498 if m == nil {
499 t.Fatalf("Stop's form %q is not a cancel form:\n%s", stop["form"], page)
500 }
501 if r := a.post(m[1], formFields(t, page, m[1])); r.Code != 303 || f.Turn(m[2]) != "cancelled" {
502 t.Fatalf("cancel: %d, turn %q", r.Code, f.Turn(m[2]))
503 }
504}
505
506func TestAskNeedsReconnectAfter401(t *testing.T) {
507 a, f := newAskApp(t)
508 a.connectEquipo(f)
509 f.RevokeAll()
510 page := a.get("/ask").Body
511 if !strings.Contains(page, ">Set it up again</button>") {
512 t.Fatalf("no reconnect:\n%s", page)
513 }
514 l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
515 if l.State != store.EquipoLost {
516 t.Fatalf("state %q", l.State)
517 }
518 if s := a.get("/settings").Body; !strings.Contains(s, ">Set it up again</button>") {
519 t.Errorf("Settings:\n%s", s)
520 }
521 var st struct{ State string }
522 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "reconnect" {
523 t.Errorf("state: %s", r.Body)
524 }
525}
526
527func TestAskExpiredBearerNeedsReconnect(t *testing.T) {
528 a, f := newAskApp(t)
529 a.connectEquipo(f)
530 if _, err := a.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
531 t.Fatal(err)
532 }
533 before := len(f.Calls(""))
534 if page := a.get("/ask").Body; !strings.Contains(page, ">Set it up again</button>") {
535 t.Fatalf("no reconnect:\n%s", page)
536 }
537 if len(f.Calls("")) != before {
538 t.Error("Base used an expired bearer")
539 }
540}
541
542func TestDisconnectRevokesDevice(t *testing.T) {
543 a, f := newAskApp(t)
544 token := a.connectEquipo(f)
545 l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
546 if r := a.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" {
547 t.Fatalf("disconnect: %d %q", r.Code, r.Location())
548 }
549 calls := f.Calls("/api/v1/auth/devices/" + l.DeviceID)
550 if len(calls) != 1 || calls[0].Method != http.MethodDelete || calls[0].Header.Get("If-Match") != `"3"` ||
551 calls[0].Header.Get("Authorization") != "Bearer "+token || !f.Revoked(l.DeviceID) {
552 t.Fatalf("revoke: %+v", calls)
553 }
554 if _, ok, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); ok {
555 t.Fatal("link kept")
556 }
557 if s := a.get("/settings").Body; !strings.Contains(s, "Connection<small>Not set up</small>") {
558 t.Errorf("Settings:\n%s", s)
559 }
560}
561
562// The panel's stream: Equipo's chat events relayed, nothing else of Equipo.
563func TestAskEventsRelay(t *testing.T) {
564 a, f := newAskApp(t)
565 token := a.connectEquipo(f)
566 var st struct {
567 State string
568 Cursor int64
569 }
570 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "ready" {
571 t.Fatalf("state: %s", r.Body)
572 }
573 f.Emit("runner", map[string]any{"id": "R1", "online": false})
574 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
575 defer cancel()
576 req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+strconv64(st.Cursor), nil)
577 res, err := a.client.Do(req)
578 if err != nil {
579 t.Fatal(err)
580 }
581 defer res.Body.Close()
582 if res.StatusCode != 200 || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") {
583 t.Fatalf("events: %d %s", res.StatusCode, res.Header.Get("Content-Type"))
584 }
585 a.post("/ask/messages", url.Values{"text": {"What can I do"}})
586 types := map[string]int{}
587 sc := bufio.NewScanner(res.Body)
588 var stream strings.Builder
589 for sc.Scan() {
590 line := sc.Text()
591 stream.WriteString(line + "\n")
592 if typ, ok := strings.CutPrefix(line, "event: "); ok {
593 types[typ]++
594 }
595 if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"state":"replied"`) {
596 break
597 }
598 }
599 if types["runner"] != 0 || types["delta"] == 0 || types["message"] < 2 || types["turn"] == 0 {
600 t.Fatalf("relayed %v:\n%s", types, stream.String())
601 }
602 if strings.Contains(stream.String(), token) {
603 t.Fatal("the stream carried the bearer")
604 }
605 up := f.Calls("/api/v1/assistant/events")
606 if len(up) == 0 || up[0].Header.Get("Authorization") != "Bearer "+token || up[0].Query != "job_states=paused&after="+strconv64(st.Cursor) {
607 t.Fatalf("upstream: %+v", up)
608 }
609}
610
611// waitEntered waits for a held exchange to reach Equipo.
612func waitEntered(t *testing.T, entered <-chan struct{}, done <-chan Resp) {
613 t.Helper()
614 select {
615 case <-entered:
616 case r := <-done:
617 t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location())
618 case <-time.After(5 * time.Second):
619 t.Fatal("the check never reached Equipo's exchange")
620 }
621}
622
623// An exchange slower than the poll interval still holds the link: a check
624// after the interval does not start a second one.
625func TestCheckDuringSlowExchangeDoesNotExchange(t *testing.T) {
626 a, f := newAskApp(t)
627 a.post("/ask/connect", url.Values{"next": {"ask"}})
628 entered, release := f.HoldNextExchange()
629 done := make(chan Resp)
630 go func() { done <- a.check("ask") }()
631 waitEntered(t, entered, done)
632 a.pollable() // the interval has passed; the exchange has not ended
633 a.check("ask")
634 release()
635 <-done
636 if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 {
637 t.Fatalf("exchanges: %d, want 1", n)
638 }
639}
640
641// When the link is already connected to the same device (a duplicate
642// exchange succeeded first), a late success leaves that connection alone.
643func TestDuplicateExchangeKeepsConnection(t *testing.T) {
644 a, f := newAskApp(t)
645 r := a.post("/ask/connect", url.Values{"next": {"ask"}})
646 m := codeRE.FindStringSubmatch(a.get(r.Location()).Body)
647 if err := f.Approve(m[1]); err != nil {
648 t.Fatal(err)
649 }
650 l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
651 entered, release := f.HoldNextExchange()
652 done := make(chan Resp)
653 go func() { done <- a.check("ask") }()
654 waitEntered(t, entered, done)
655 if _, err := a.DB.Exec(`UPDATE equipo_links SET state = ?`, store.EquipoConnected); err != nil {
656 t.Fatal(err)
657 }
658 release()
659 <-done
660 if f.Revoked(l.DeviceID) {
661 t.Fatal("a duplicate success revoked the live connection")
662 }
663 if n := len(f.Hosts()); n != 0 {
664 t.Fatalf("a duplicate success registered the host again: %d PUTs", n)
665 }
666 if got, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); !found || got.State != store.EquipoConnected {
667 t.Fatalf("link: %+v %v", got, found)
668 }
669}
670
671// If Base cannot store the bearer, it revokes the device in Equipo and
672// says to start again: never "connected" with a credential it lost.
673func TestConnectStoreFailureRevokes(t *testing.T) {
674 a, f := newAskApp(t)
675 r := a.post("/ask/connect", url.Values{"next": {"settings"}})
676 m := codeRE.FindStringSubmatch(a.get(r.Location()).Body)
677 if err := f.Approve(m[1]); err != nil {
678 t.Fatal(err)
679 }
680 l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
681 if _, err := a.DB.Exec(`CREATE TRIGGER no_bearer BEFORE UPDATE OF state ON equipo_links
682 WHEN NEW.state = 'connected' BEGIN SELECT RAISE(ABORT, 'disk full'); END`); err != nil {
683 t.Fatal(err)
684 }
685 c := a.check("settings")
686 if c.Code != 303 || c.Location() == "/settings" || !strings.Contains(c.Location(), "ended=failed") {
687 t.Fatalf("check: %d %q, want start again", c.Code, c.Location())
688 }
689 if !f.Revoked(l.DeviceID) {
690 t.Fatal("the device whose bearer was lost was not revoked")
691 }
692 if page := a.get(c.Location()).Body; !strings.Contains(page, "That didn't work. Start again.") {
693 t.Fatalf("page:\n%s", page)
694 }
695}
696
697var tagRE = regexp.MustCompile(`(?s)<[^>]*>`)
698
699var linkTagRE = regexp.MustCompile(`</?a(\s[^>]*)?>`)
700
701// textOf is a page's text: its tags, and so every attribute value, gone.
702func textOf(body string) string {
703 body = linkTagRE.ReplaceAllString(body, "")
704 return strings.Join(strings.Fields(html.UnescapeString(tagRE.ReplaceAllString(body, " "))), " ")
705}
706
707var blockREs = []*regexp.Regexp{
708 regexp.MustCompile(`(?s)<div class="ask-note" data-when="([^"]*)"([^>]*)>(.*?)</div>`),
709 regexp.MustCompile(`(?s)<p class="ask-problem ask-runner" data-when="([^"]*)"([^>]*)>(.*?)</p>`),
710}
711
712// visibleBlocks are the chat's state blocks on a page that are not hidden,
713// by state: what the person sees before any script runs.
714func visibleBlocks(body string) map[string]string {
715 out := map[string]string{}
716 for _, re := range blockREs {
717 for _, m := range re.FindAllStringSubmatch(body, -1) {
718 if !strings.Contains(m[2], " hidden") {
719 out[m[1]] = textOf(m[3])
720 }
721 }
722 }
723 return out
724}
725
726// shows asserts that on page (a body) exactly the block for state shows
727// among the setup blocks (or the runner note for a runner state) and that
728// its text is want.
729func shows(t *testing.T, where, body, state, want string) {
730 t.Helper()
731 vis := visibleBlocks(body)
732 for k := range vis {
733 if k != state {
734 t.Errorf("%s: the %q block shows in state %s", where, k, state)
735 }
736 }
737 if got, ok := vis[state]; !ok || !strings.Contains(got, want) {
738 t.Errorf("%s: the visible %q block says %q, want %q", where, state, got, want)
739 }
740}
741
742// elementText is the text of the first element on a page matching pattern.
743func elementText(t *testing.T, where, body, pattern string) string {
744 t.Helper()
745 m := regexp.MustCompile(`(?s)` + pattern).FindStringSubmatch(body)
746 if m == nil {
747 t.Errorf("%s: no element matching %s:\n%s", where, pattern, textOf(body))
748 return ""
749 }
750 return textOf(m[1])
751}
752
753// expect asserts that the first element matching pattern says want.
754func expect(t *testing.T, where, body, pattern, want string) {
755 t.Helper()
756 if got := elementText(t, where, body, pattern); got != want {
757 t.Errorf("%s: %q, want %q", where, got, want)
758 }
759}
760
761// askStates puts the owner's Ask in each state in turn and calls fn with
762// the pages of that state: Home, /ask, the connect page, Settings.
763func askStates(t *testing.T, fn func(state string, a *testApp, f *equipotest.Fake, pages map[string]string)) {
764 t.Helper()
765 const setup = "/ask/connect?next=ask"
766 pages := func(a *testApp) map[string]string {
767 ask := a.get("/ask").Body // first: it is what moves a lost or runnerless state along
768 return map[string]string{"/": a.get("/").Body, "/ask": ask,
769 "setup": a.get(setup).Body, "/settings": a.get("/settings").Body}
770 }
771 a, f := newAskApp(t)
772 fn("connect", a, f, pages(a))
773 for _, ended := range []string{"expired", "refused", "failed"} {
774 fn(ended, a, f, map[string]string{"setup": a.get(setup + "&ended=" + ended).Body})
775 }
776 a.post("/ask/connect", url.Values{"next": {"ask"}})
777 fn("pending", a, f, pages(a))
778 fn("pending, problem", a, f, map[string]string{"setup": a.get(setup + "&problem=1").Body})
779 a, f = newAskApp(t)
780 f.FailNextBegin()
781 fn("setup unavailable", a, f, map[string]string{"setup": a.post("/ask/connect", url.Values{"next": {"ask"}}).Body})
782 a, f = newAskApp(t)
783 a.connectEquipo(f)
784 fn("ready", a, f, pages(a))
785 fn("not sent", a, f, map[string]string{"/ask": a.get("/ask?problem=1").Body})
786 f.FailSnapshots(true)
787 fn("unavailable", a, f, pages(a))
788 f.FailSnapshots(false)
789 f.NoRunner()
790 fn("norunner", a, f, pages(a))
791 f.RunnerTooOld()
792 // Too old shows when a send is refused 409: that page, with the text kept.
793 fn("oldrunner", a, f, map[string]string{"/ask": a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old"}}).Body})
794 f.RevokeAll()
795 fn("reconnect", a, f, pages(a))
796}
797
798// Base never names Equipo in the chat, its setup or Settings: no word of it
799// in any page's text, and no ⋯ menu.
800func TestAskNamesNoEquipo(t *testing.T) {
801 askStates(t, func(state string, _ *testApp, _ *equipotest.Fake, pages map[string]string) {
802 for page, body := range pages {
803 if strings.Contains(strings.ToLower(textOf(body)), "equipo") {
804 t.Errorf("%s in state %s names Equipo:\n%s", page, state, textOf(body))
805 }
806 if strings.Contains(body, "ask-more") || strings.Contains(body, "ask-menu") {
807 t.Errorf("%s in state %s has the ⋯ menu", page, state)
808 }
809 }
810 })
811}
812
813// Every approved text shows where Paul's table puts it, in the element that
814// is visible in that state: the panel on Home and /ask (the state's block
815// shows, every other is hidden), the setup page and Settings.
816func TestAskApprovedWords(t *testing.T) {
817 askStates(t, func(state string, a *testApp, f *equipotest.Fake, pages map[string]string) {
818 row := func(value string) {
819 t.Helper()
820 expect(t, state+" /settings", pages["/settings"], `<div class="who">Connection<small>(.*?)</small>`, value)
821 }
822 // The row's control: its button or its link, by its text.
823 settingsAction := func(want string) {
824 t.Helper()
825 expect(t, state+" /settings control", pages["/settings"],
826 `<div class="who">Connection<small>.*?</small></div>\s*(?:<form[^>]*>(?:<input[^>]*>)*)?<(?:button|a) [^>]*class="btn ghost"[^>]*>(.*?)</(?:button|a)>`, want)
827 }
828 setup := pages["setup"]
829 title := func(want string) { expect(t, state+" setup title", setup, `<title>(.*?)</title>`, want+" · Acme") }
830 switch state {
831 case "connect":
832 for _, p := range []string{"/", "/ask"} {
833 shows(t, state+" "+p, pages[p], "connect", "Set up Ask Base to start asking. Set up Ask Base")
834 expect(t, state+" "+p+" button", pages[p], `data-when="connect"[^>]*>.*?<button class="btn" type="submit">(.*?)</button>`, "Set up Ask Base")
835 }
836 title("Set up Ask Base")
837 expect(t, state+" setup heading", setup, `<h2>(.*?)</h2>`, "Set up Ask Base")
838 expect(t, state+" setup lead", setup, `</h2>\s*<p>(.*?)</p>`, "Set up Ask Base to start asking.")
839 expect(t, state+" setup button", setup, `<button class="btn full" type="submit">(.*?)</button>`, "Set up Ask Base")
840 row("Not set up")
841 settingsAction("Set up Ask Base")
842 case "expired":
843 expect(t, state+" setup lead", setup, `</h2>\s*<p>(.*?)</p>`, "That code expired. Start again to get a new one.")
844 case "refused":
845 expect(t, state+" setup lead", setup, `</h2>\s*<p>(.*?)</p>`, "That request wasn't accepted. Start again.")
846 case "failed":
847 expect(t, state+" setup lead", setup, `</h2>\s*<p>(.*?)</p>`, "That didn't work. Start again.")
848 case "pending":
849 for _, p := range []string{"/", "/ask"} {
850 shows(t, state+" "+p, pages[p], "pending", "You started setting up Ask Base. Approve it to start asking. Finish setting up")
851 expect(t, state+" "+p+" button", pages[p], `data-when="pending"[^>]*>.*?<a class="btn"[^>]*>(.*?)</a>`, "Finish setting up")
852 }
853 title("Set up Ask Base")
854 expect(t, state+" setup heading", setup, `<h2>(.*?)</h2>`, "Set up Ask Base")
855 expect(t, state+" setup code line", setup, `</h2>\s*<p>(.*?)</p>`, "Check the request is from "+f.Label(codeRE.FindStringSubmatch(setup)[1])+", then type this code:")
856 expect(t, state+" setup open", setup, `<a class="btn full"[^>]*>(.*?)</a>`, "Approve it")
857 row("Waiting for your approval")
858 settingsAction("Finish setting up")
859 case "pending, problem":
860 expect(t, state+" setup problem", setup, `<p class="status" role="alert">(.*?)</p>`, "Ask Base isn't answering. It will keep trying.")
861 case "setup unavailable":
862 expect(t, state+" setup problem", setup, `<p class="status" role="alert">(.*?)</p>`, "Ask Base isn't answering. Try again in a minute.")
863 case "ready":
864 if got := elementText(t, state+" /settings", pages["/settings"], `<div class="who">Connection<small>(.*?)</small>`); !strings.HasPrefix(got, "Connected") {
865 t.Errorf("ready /settings row: %q", got)
866 }
867 if len(visibleBlocks(pages["/ask"])) != 0 {
868 t.Errorf("ready /ask shows a state block: %v", visibleBlocks(pages["/ask"]))
869 }
870 if s := a.get("/ask/state").Body; !strings.Contains(s, `"state":"ready"`) {
871 t.Errorf("ready state: %s", s)
872 }
873 case "not sent":
874 expect(t, state+" /ask", pages["/ask"], `<p class="ask-problem" role="alert">(.*?)</p>`, "That didn't send. Try again.")
875 case "unavailable":
876 shows(t, state+" /ask", pages["/ask"], "unavailable", "Ask Base isn't answering. Try again in a minute.")
877 // Home draws the panel from what it knows without calling Equipo;
878 // the panel's script asks /ask/state and shows this block.
879 if s := a.get("/ask/state").Body; !strings.Contains(s, `"state":"unavailable"`) {
880 t.Errorf("unavailable state: %s", s)
881 }
882 if got := regexp.MustCompile(`data-when="unavailable"[^>]*>\s*<p>(.*?)</p>`).FindStringSubmatch(pages["/"]); got == nil || got[1] != "Ask Base isn't answering. Try again in a minute." {
883 t.Errorf("Home's panel lacks the unavailable block: %q", got)
884 }
885 case "norunner":
886 shows(t, state+" /ask", pages["/ask"], "norunner", "Ask Base isn't set up for you yet. Finish setting it up, then try again.")
887 // Home draws from what it knows without calling Equipo; the
888 // panel's script moves to this state from /ask/state.
889 if s := a.get("/ask/state").Body; !strings.Contains(s, `"state":"norunner"`) {
890 t.Errorf("norunner state: %s", s)
891 }
892 expect(t, state+" / panel's block", pages["/"], `data-when="norunner"[^>]*>(.*?)</p>`, "Ask Base isn't set up for you yet. Finish setting it up, then try again.")
893 expect(t, state+" /ask link", pages["/ask"], `data-when="norunner"[^>]*>.*?<a href="[^"]*" target="_blank" rel="noopener">(.*?)</a>`, "Finish setting it up")
894 case "oldrunner":
895 shows(t, state+" /ask", pages["/ask"], "oldrunner", "Ask Base needs an update first. Update it, then try again.")
896 expect(t, state+" / panel's block", a.get("/").Body, `data-when="oldrunner"[^>]*>(.*?)</p>`, "Ask Base needs an update first. Update it, then try again.")
897 expect(t, state+" /ask link", pages["/ask"], `data-when="oldrunner"[^>]*>.*?<a href="[^"]*" target="_blank" rel="noopener">(.*?)</a>`, "Update it")
898 case "reconnect":
899 for _, p := range []string{"/", "/ask"} {
900 shows(t, state+" "+p, pages[p], "reconnect", "Ask Base needs setting up again. Set it up again")
901 expect(t, state+" "+p+" button", pages[p], `data-when="reconnect"[^>]*>.*?<button class="btn" type="submit">(.*?)</button>`, "Set it up again")
902 }
903 title("Set up Ask Base")
904 expect(t, state+" setup lead", setup, `</h2>\s*<p>(.*?)</p>`, "Ask Base needs setting up again.")
905 expect(t, state+" setup button", setup, `<button class="btn full" type="submit">(.*?)</button>`, "Set it up again")
906 row("Needs setting up again")
907 settingsAction("Set it up again")
908 }
909 })
910
911 // While a turn runs: the status under the conversation, then waiting.
912 a, f := newAskApp(t)
913 a.connectEquipo(f)
914 status := `<p class="ask-status" role="status">(.*?)</p>`
915 f.Hold = true
916 a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}})
917 page := a.get("/ask").Body
918 expect(t, "answering /ask", page, status, "Thinking…")
919 turn := regexp.MustCompile(`/ask/turns/([^/"]+)/cancel`).FindStringSubmatch(page)
920 if turn == nil {
921 t.Fatal("no turn running")
922 }
923 f.WaitTurn(turn[1])
924 a.pollable()
925 expect(t, "waiting /ask", a.get("/ask").Body, status, "Ask Base can't answer right now. It will as soon as it can.")
926
927 // The panel's script words: the same texts, and no Equipo in a string.
928 js, err := os.ReadFile("../look/static/ask.js")
929 if err != nil {
930 t.Fatal(err)
931 }
932 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."} {
933 if !strings.Contains(string(js), w) {
934 t.Errorf("ask.js lacks %q", w)
935 }
936 }
937 if regexp.MustCompile(`"[^"\n]*Equipo[^"\n]*"|ask-more`).MatchString(string(js)) {
938 t.Error("ask.js still words Equipo to the person, or draws the ⋯ menu")
939 }
940}
941
942// cardItem is the card with id as /ask draws it.
943func cardItem(t *testing.T, page, id string) string {
944 t.Helper()
945 m := regexp.MustCompile(`(?s)<li class="msg card card-[a-z]+" data-card="` + regexp.QuoteMeta(id) + `"[^>]*>.*?</li>`).FindString(page)
946 if m == "" {
947 t.Fatalf("no card %s in:\n%s", id, page)
948 }
949 return m
950}
951
952var goOptions = []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}}
953
954// Cards are drawn from their fields alone: a button is an option's label
955// posting its value, a link is one of the card's links, opening in a new
956// tab. An outcome and a confirm card draw the same way; Base has no words
957// of its own for any kind.
958func TestAskCardsAreDrawnFromFields(t *testing.T) {
959 a, f := newAskApp(t)
960 a.connectEquipo(f)
961 links := []equipo.Link{{Label: "See it", URL: "https://preview.example.test/"}}
962 outcome := f.AskOutcome("This is ready. Go ahead?", goOptions, links)
963 confirm := f.AskKind("confirm", "Send the invitation?", goOptions, links)
964 task := f.AskKind("task", "Merge tk0001?", goOptions, nil)
965 f.Say("Try [this](javascript:alert(1)), [that](/tasks/tk1) or <b>bold</b>.")
966 page := a.get("/ask").Body
967 if !strings.Contains(page, `<li class="msg coordinator" data-id="`) ||
968 !strings.Contains(page, "Try [this](javascript:alert(1)), [that](/tasks/tk1) or &lt;b&gt;bold&lt;/b&gt;.</li>") {
969 t.Errorf("the Assistant's line is not plain text:\n%s", page)
970 }
971 for _, id := range []string{outcome, confirm} {
972 card := cardItem(t, page, id)
973 for _, want := range []string{
974 `<button class="btn ghost" type="submit" name="choice" value="go">Go ahead</button>`,
975 `<button class="btn ghost" type="submit" name="choice" value="later">Not yet</button>`,
976 `<a class="card-link" href="https://preview.example.test/" target="_blank" rel="noopener">See it</a>`,
977 } {
978 if !strings.Contains(card, want) {
979 t.Errorf("card %s lacks %s:\n%s", id, want, card)
980 }
981 }
982 if fields := formFields(t, page, "/ask/cards/"+id+"/answer"); fields.Get("revision") != "1" {
983 t.Errorf("card %s answers at revision %q", id, fields.Get("revision"))
984 }
985 }
986 if strings.Contains(page, task) || strings.Contains(page, "Merge tk0001?") {
987 t.Errorf("a task card was drawn:\n%s", page)
988 }
989 var st struct {
990 Cards []struct {
991 ID string
992 Options []struct{ Value, Label string }
993 Links []struct{ Label, URL string }
994 }
995 }
996 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 2 ||
997 st.Cards[0].ID != outcome || len(st.Cards[0].Options) != 2 || st.Cards[0].Options[0].Label != "Go ahead" ||
998 len(st.Cards[0].Links) != 1 || st.Cards[0].Links[0].URL != "https://preview.example.test/" {
999 t.Fatalf("state: %s", r.Body)
1000 }
1001 for _, file := range []string{"../web/ask_cards.go", "../look/static/ask.js", "../web/templates/partials/chat.html"} {
1002 raw, err := os.ReadFile(file)
1003 if err != nil {
1004 t.Fatal(err)
1005 }
1006 for _, word := range []string{"Merge", "Wait for checks", "Publishing"} {
1007 if strings.Contains(string(raw), word) {
1008 t.Errorf("%s says %q", file, word)
1009 }
1010 }
1011 }
1012}
1013
1014// Answering posts the option's value, at the card's revision. An answered
1015// outcome card says how it ended and brings no message and no turn (Equipo
1016// answers with empty ones). An answer at a stale revision is not resent:
1017// /ask shows the card as it is now.
1018func TestAskAnswerRelaysValue(t *testing.T) {
1019 a, f := newAskApp(t)
1020 a.connectEquipo(f)
1021 id := f.AskOutcome("This is ready. Go ahead?", goOptions, nil)
1022 answer := formFields(t, a.get("/ask").Body, "/ask/cards/"+id+"/answer")
1023 answer.Set("choice", "go")
1024 if r := a.post("/ask/cards/"+id+"/answer", answer); r.Code != 303 || r.Location() != "/ask" {
1025 t.Fatalf("answer: %d %q", r.Code, r.Location())
1026 }
1027 if c := f.Calls("/api/v1/assistant/cards/" + id + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"go","revision":1}` {
1028 t.Fatalf("relayed: %+v", c)
1029 }
1030 page := a.get("/ask").Body
1031 if card := cardItem(t, page, id); !strings.Contains(card, `<p class="card-state">Go ahead</p>`) || strings.Contains(card, "<form") {
1032 t.Errorf("answered card:\n%s", card)
1033 }
1034 if strings.Contains(page, `<li class="msg person"`) || strings.Contains(page, `class="stop" method="post" action="/ask/turns/`) {
1035 t.Errorf("an answered outcome card left a bubble or a turn:\n%s", page)
1036 }
1037
1038 // Scripts on: the answer is the card, and no message or turn at all.
1039 other := f.AskOutcome("Publish it?", goOptions, nil)
1040 req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/cards/"+other+"/answer",
1041 strings.NewReader(url.Values{"choice": {"later"}, "revision": {"1"}, "key": {"k-out"}}.Encode()))
1042 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
1043 req.Header.Set("Origin", a.origin)
1044 req.Header.Set("Accept", "application/json")
1045 res := a.do(req)
1046 var out struct {
1047 Card struct{ ID, State, Result string }
1048 Message *struct{}
1049 Turn *struct{}
1050 }
1051 if res.Code != 200 || json.Unmarshal([]byte(res.Body), &out) != nil || out.Card.ID != other || out.Card.State != "answered" ||
1052 out.Card.Result != "Not yet" || out.Message != nil || out.Turn != nil {
1053 t.Fatalf("JSON answer: %d %s", res.Code, res.Body)
1054 }
1055
1056 // Stale: the card moved on unseen. One call, a 409, and /ask shows the
1057 // card at its new revision.
1058 q := f.AskQuestion("Which one?", "red", "blue")
1059 stale := formFields(t, a.get("/ask").Body, "/ask/cards/"+q+"/answer")
1060 f.SetCard(q, "open", "")
1061 stale.Set("choice", "red")
1062 if r := a.post("/ask/cards/"+q+"/answer", stale); r.Code != 303 || r.Location() != "/ask" {
1063 t.Fatalf("stale answer: %d %q", r.Code, r.Location())
1064 }
1065 if c := f.Calls("/api/v1/assistant/cards/" + q + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"red","revision":1}` {
1066 t.Fatalf("stale answers: %+v", c)
1067 }
1068 if fresh := formFields(t, a.get("/ask").Body, "/ask/cards/"+q+"/answer"); fresh.Get("revision") != "2" {
1069 t.Fatalf("after the 409 the card is at revision %q, want 2", fresh.Get("revision"))
1070 }
1071}
1072
1073// hostOf is the host token in Equipo's PUT host call i (the last when
1074// i is -1), with the bearer and origin it came with.
1075func hostOf(t *testing.T, f *equipotest.Fake, i int) (token, bearer, origin string) {
1076 t.Helper()
1077 hosts := f.Hosts()
1078 if i < 0 {
1079 i = len(hosts) + i
1080 }
1081 if i < 0 || i >= len(hosts) {
1082 t.Fatalf("PUT host %d of %d", i, len(hosts))
1083 }
1084 var in struct{ Origin, Token string }
1085 if hosts[i].Method != http.MethodPut || json.Unmarshal([]byte(hosts[i].Body), &in) != nil {
1086 t.Fatalf("PUT host: %+v", hosts[i])
1087 }
1088 return in.Token, strings.TrimPrefix(hosts[i].Header.Get("Authorization"), "Bearer "), in.Origin
1089}
1090
1091// hostMember is the member host token names, "" for nobody.
1092func (a *testApp) hostMember(token string) string {
1093 a.t.Helper()
1094 m, ok, err := store.MemberByHostToken(context.Background(), a.DB, token)
1095 if err != nil {
1096 a.t.Fatal(err)
1097 }
1098 if !ok {
1099 return ""
1100 }
1101 return m.ID
1102}
1103
1104func (a *testApp) hostRegistered() bool {
1105 a.t.Helper()
1106 ok, err := store.HostRegistered(context.Background(), a.DB, a.ownerID())
1107 if err != nil {
1108 a.t.Fatal(err)
1109 }
1110 return ok
1111}
1112
1113// quiet fails if the app logged any of secrets.
1114func (a *testApp) quiet(secrets ...string) {
1115 a.t.Helper()
1116 logs := a.logs.String()
1117 for _, s := range secrets {
1118 if s != "" && strings.Contains(logs, s) {
1119 a.t.Fatalf("the log carried a secret:\n%s", logs)
1120 }
1121 }
1122}
1123
1124// Once the member's connection is ready, Base mints them a host token and
1125// gives it to Equipo, with their bearer and Base's own origin: once.
1126// Reconnecting gives Equipo a new one, and the old one names nobody.
1127func TestConnectRegistersHost(t *testing.T) {
1128 a, f := newAskApp(t)
1129 bearer := a.connectEquipo(f)
1130 if n := len(f.Hosts()); n != 1 {
1131 t.Fatalf("PUT host after connecting: %d, want 1", n)
1132 }
1133 first, sentWith, origin := hostOf(t, f, 0)
1134 if sentWith != bearer || origin != testOrigin || !strings.HasPrefix(first, "bh_") {
1135 t.Fatalf("PUT host: bearer ok %v, origin %q, token %q", sentWith == bearer, origin, first)
1136 }
1137 if a.hostMember(first) != a.ownerID() || !a.hostRegistered() {
1138 t.Fatalf("host token names %q, registered %v", a.hostMember(first), a.hostRegistered())
1139 }
1140 a.get("/ask")
1141 a.get("/ask/state")
1142 if n := len(f.Hosts()); n != 1 {
1143 t.Fatalf("reading the chat registered again: %d PUTs", n)
1144 }
1145
1146 a.approveEquipo(f)
1147 if n := len(f.Hosts()); n != 2 {
1148 t.Fatalf("PUT host after reconnecting: %d, want 2", n)
1149 }
1150 second, sentWith, _ := hostOf(t, f, 1)
1151 if second == first || sentWith == bearer {
1152 t.Fatal("reconnecting registered the old token or with the old bearer")
1153 }
1154 if a.hostMember(first) != "" || a.hostMember(second) != a.ownerID() {
1155 t.Fatalf("old token names %q, new names %q", a.hostMember(first), a.hostMember(second))
1156 }
1157 a.noLeak(first)
1158 a.noLeak(second)
1159 a.quiet(first, second, bearer, sentWith)
1160}
1161
1162// A member who connected before Base registered hosts has no host token:
1163// their next read of the chat registers one, once.
1164func TestHostRegisteredLazily(t *testing.T) {
1165 a, f := newAskApp(t)
1166 a.connectEquipo(f)
1167 if err := store.DeleteHostToken(context.Background(), a.DB, a.ownerID()); err != nil {
1168 t.Fatal(err)
1169 }
1170 if page := a.get("/ask"); page.Code != 200 || len(f.Hosts()) != 2 {
1171 t.Fatalf("/ask: %d, PUTs %d, want 2", page.Code, len(f.Hosts()))
1172 }
1173 token, _, _ := hostOf(t, f, -1)
1174 if a.hostMember(token) != a.ownerID() || !a.hostRegistered() {
1175 t.Fatal("the lazy registration did not take")
1176 }
1177 a.get("/ask/state")
1178 a.get("/ask")
1179 if n := len(f.Hosts()); n != 2 {
1180 t.Fatalf("registered again: %d PUTs", n)
1181 }
1182}
1183
1184// A refused registration does not break the chat or disconnect anyone: it
1185// is logged (no token in it), and the next read tries again.
1186func TestHostRegistrationFailureIsRetried(t *testing.T) {
1187 a, f := newAskApp(t)
1188 f.RefuseHost(http.StatusForbidden, "host_not_allowed")
1189 bearer := a.connectEquipo(f)
1190 if n := len(f.Hosts()); n != 1 || a.hostRegistered() {
1191 t.Fatalf("PUTs %d, registered %v", n, a.hostRegistered())
1192 }
1193 if n := strings.Count(a.logs.String(), "host_not_allowed"); n != 1 {
1194 t.Fatalf("logged host_not_allowed %d times, want 1:\n%s", n, a.logs.String())
1195 }
1196 if s := a.get("/settings").Body; !strings.Contains(s, `action="/ask/disconnect"`) {
1197 t.Fatalf("a refused registration disconnected the member:\n%s", s)
1198 }
1199 page := a.get("/ask")
1200 if page.Code != 200 || !strings.Contains(page.Body, `data-state="ready"`) || len(f.Hosts()) != 2 {
1201 t.Fatalf("/ask: %d, PUTs %d\n%s", page.Code, len(f.Hosts()), page.Body)
1202 }
1203 if n := strings.Count(a.logs.String(), "host_not_allowed"); n != 2 {
1204 t.Fatalf("logged host_not_allowed %d times after two tries", n)
1205 }
1206 if r := a.post("/ask/messages", url.Values{"text": {"What can I do"}}); r.Code != 303 || len(f.Calls("/api/v1/assistant/messages")) != 1 {
1207 t.Fatalf("send: %d", r.Code)
1208 }
1209 if l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); l.State != store.EquipoConnected {
1210 t.Fatalf("link %q", l.State)
1211 }
1212
1213 f.RefuseHost(http.StatusServiceUnavailable, "unavailable")
1214 a.get("/ask/state")
1215 if len(f.Hosts()) != 3 || a.hostRegistered() {
1216 t.Fatalf("PUTs %d, registered %v", len(f.Hosts()), a.hostRegistered())
1217 }
1218 f.RefuseHost(0, "")
1219 a.get("/ask")
1220 token, _, _ := hostOf(t, f, -1)
1221 if len(f.Hosts()) != 4 || !a.hostRegistered() || a.hostMember(token) != a.ownerID() {
1222 t.Fatalf("PUTs %d, registered %v", len(f.Hosts()), a.hostRegistered())
1223 }
1224 a.get("/ask")
1225 if n := len(f.Hosts()); n != 4 {
1226 t.Fatalf("registered again once it took: %d PUTs", n)
1227 }
1228 var tried []string
1229 for i := range f.Hosts() {
1230 tok, _, _ := hostOf(t, f, i)
1231 tried = append(tried, tok)
1232 }
1233 a.quiet(append(tried, bearer)...)
1234}
1235
1236// Disconnecting, and Equipo refusing the bearer, both forget the member's
1237// host token.
1238func TestDisconnectDropsHostToken(t *testing.T) {
1239 a, f := newAskApp(t)
1240 a.connectEquipo(f)
1241 token, _, _ := hostOf(t, f, -1)
1242 if r := a.post("/ask/disconnect", nil); r.Code != 303 {
1243 t.Fatalf("disconnect: %d", r.Code)
1244 }
1245 if a.hostMember(token) != "" {
1246 t.Fatal("the host token outlived Disconnect")
1247 }
1248
1249 a.approveEquipo(f)
1250 token, _, _ = hostOf(t, f, -1)
1251 if a.hostMember(token) != a.ownerID() {
1252 t.Fatal("connecting again registered nothing")
1253 }
1254 f.RevokeAll()
1255 if page := a.get("/ask").Body; !strings.Contains(page, ">Set it up again</button>") {
1256 t.Fatalf("no reconnect:\n%s", page)
1257 }
1258 if a.hostMember(token) != "" {
1259 t.Fatal("the host token outlived a refused bearer")
1260 }
1261}
1262
1263// noteFor is the runner note shown for state, with its attributes.
1264func noteFor(t *testing.T, page, state string) string {
1265 t.Helper()
1266 m := regexp.MustCompile(`(?s)<p class="ask-problem ask-runner" data-when="` + state + `"[^>]*>.*?</p>`).FindString(page)
1267 if m == "" {
1268 t.Fatalf("no %s note in:\n%s", state, page)
1269 }
1270 return m
1271}
1272
1273// postJSON posts form as the panel's script does.
1274func (a *testApp) postJSON(target string, form url.Values) Resp {
1275 a.t.Helper()
1276 req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
1277 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
1278 req.Header.Set("Origin", a.origin)
1279 req.Header.Set("Accept", "application/json")
1280 return a.do(req)
1281}
1282
1283// Without a runner the chat says so, links to Equipo, keeps what the
1284// person wrote and shows no message; a runner too old has its own note.
1285// The panel's script hears the state.
1286func TestAskNoRunner(t *testing.T) {
1287 a, f := newAskApp(t)
1288 a.connectEquipo(f)
1289 f.Say("Hello.")
1290 f.NoRunner()
1291 page := a.get("/ask").Body
1292 note := noteFor(t, page, "norunner")
1293 if strings.Contains(note, " hidden") || !strings.Contains(note, `href="`+f.URL+`/"`) ||
1294 !strings.Contains(page, `data-state="norunner"`) || !strings.Contains(page, "Hello.") {
1295 t.Fatalf("no-runner note:\n%s", page)
1296 }
1297 if !strings.Contains(noteFor(t, page, "oldrunner"), " hidden") {
1298 t.Fatal("the runner-too-old note shows")
1299 }
1300 var st struct{ State string }
1301 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "norunner" {
1302 t.Fatalf("state: %s", r.Body)
1303 }
1304
1305 // Scripts off: the page comes back with the text in the field, the
1306 // same key, and no message.
1307 r := a.post("/ask/messages", url.Values{"text": {"Build me a quick website"}, "key": {"k-norunner"}})
1308 if r.Code != http.StatusConflict || strings.Contains(noteFor(t, r.Body, "norunner"), " hidden") ||
1309 !strings.Contains(r.Body, `>Build me a quick website</textarea>`) || strings.Contains(r.Body, `<li class="msg person"`) ||
1310 formFields(t, r.Body, "/ask/messages").Get("key") != "k-norunner" {
1311 t.Fatalf("send without a runner: %d\n%s", r.Code, r.Body)
1312 }
1313 // Scripts on: the state.
1314 if r := a.postJSON("/ask/messages", url.Values{"text": {"Build me a quick website"}, "key": {"k-json"}}); r.Code != http.StatusConflict ||
1315 strings.TrimSpace(r.Body) != `{"state":"norunner"}` {
1316 t.Fatalf("JSON send: %d %s", r.Code, r.Body)
1317 }
1318 q := f.AskQuestion("Which one?", "red", "blue")
1319 if r := a.postJSON("/ask/cards/"+q+"/answer", url.Values{"choice": {"red"}, "revision": {"1"}, "key": {"k-card"}}); r.Code != http.StatusConflict ||
1320 strings.TrimSpace(r.Body) != `{"state":"norunner"}` {
1321 t.Fatalf("JSON answer: %d %s", r.Code, r.Body)
1322 }
1323
1324 f.RunnerTooOld()
1325 r = a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old"}})
1326 if r.Code != http.StatusConflict || strings.Contains(noteFor(t, r.Body, "oldrunner"), " hidden") ||
1327 !strings.Contains(noteFor(t, r.Body, "norunner"), " hidden") || !strings.Contains(r.Body, `>What can I do</textarea>`) {
1328 t.Fatalf("send with a runner too old: %d\n%s", r.Code, r.Body)
1329 }
1330 if r := a.postJSON("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old-json"}}); r.Code != http.StatusConflict ||
1331 strings.TrimSpace(r.Body) != `{"state":"oldrunner"}` {
1332 t.Fatalf("JSON send: %d %s", r.Code, r.Body)
1333 }
1334 if strings.Contains(a.get("/ask").Body, `<li class="msg person"`) {
1335 t.Fatal("a refused message shows")
1336 }
1337}
1338
1339// hostRows is how many host tokens the owner has (0 or 1).
1340func (a *testApp) hostRows() int {
1341 a.t.Helper()
1342 var n int
1343 if err := a.DB.QueryRow(`SELECT count(*) FROM host_tokens WHERE member_id = ?`, a.ownerID()).Scan(&n); err != nil {
1344 a.t.Fatal(err)
1345 }
1346 return n
1347}
1348
1349// A read of the chat that was already under way when the member
1350// disconnected, or started connecting again, finishes after it: it must
1351// not leave a host token behind for a connection that is gone.
1352func TestStaleReadLeavesNoHostToken(t *testing.T) {
1353 a, f := newAskApp(t)
1354 for _, step := range []struct {
1355 name string
1356 act func() Resp
1357 }{
1358 {"disconnect", func() Resp { return a.post("/ask/disconnect", nil) }},
1359 {"connect again", func() Resp { return a.post("/ask/connect", url.Values{"next": {"settings"}}) }},
1360 } {
1361 a.approveEquipo(f)
1362 if err := store.DeleteHostToken(context.Background(), a.DB, a.ownerID()); err != nil {
1363 t.Fatal(err)
1364 }
1365 entered, release := f.HoldNextSnapshot()
1366 done := make(chan Resp)
1367 go func() { done <- a.get("/ask") }()
1368 waitEntered(t, entered, done)
1369 if r := step.act(); r.Code != 303 {
1370 t.Fatalf("%s: %d", step.name, r.Code)
1371 }
1372 release()
1373 <-done
1374 if n := a.hostRows(); n != 0 {
1375 t.Fatalf("after %s, a stale read left %d host token", step.name, n)
1376 }
1377 }
1378 for i := range f.Hosts() {
1379 if tok, _, _ := hostOf(t, f, i); a.hostMember(tok) != "" {
1380 t.Fatalf("host token %d still names the member", i)
1381 }
1382 }
1383}
1384
1385// Disconnect succeeds only if the host token goes with the link: when
1386// Base cannot forget the token, the member stays connected and is told
1387// it didn't work.
1388func TestDisconnectFailsWhileTokenStays(t *testing.T) {
1389 a, f := newAskApp(t)
1390 a.connectEquipo(f)
1391 token, _, _ := hostOf(t, f, -1)
1392 if _, err := a.DB.Exec(`CREATE TRIGGER keep_host BEFORE DELETE ON host_tokens BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil {
1393 t.Fatal(err)
1394 }
1395 if r := a.post("/ask/disconnect", nil); r.Code == 303 {
1396 t.Fatal("Disconnect reported success while the host token stays")
1397 }
1398 if a.hostMember(token) != a.ownerID() {
1399 t.Fatal("the token went although forgetting it failed")
1400 }
1401 if s := a.get("/settings").Body; !strings.Contains(s, `action="/ask/disconnect"`) {
1402 t.Fatalf("Settings says disconnected while Base still holds the token:\n%s", s)
1403 }
1404 if _, err := a.DB.Exec(`DROP TRIGGER keep_host`); err != nil {
1405 t.Fatal(err)
1406 }
1407 if r := a.post("/ask/disconnect", nil); r.Code != 303 || a.hostMember(token) != "" {
1408 t.Fatalf("disconnect: %d, token names %q", r.Code, a.hostMember(token))
1409 }
1410}
1411
1412// Reconnecting revokes the old device first; if Equipo then fails to
1413// start the new sign-in, the old host token must already name nobody.
1414func TestReconnectFailureDropsHostToken(t *testing.T) {
1415 a, f := newAskApp(t)
1416 a.connectEquipo(f)
1417 token, _, _ := hostOf(t, f, -1)
1418 f.FailNextBegin()
1419 if r := a.post("/ask/connect", url.Values{"next": {"settings"}}); r.Code != http.StatusBadGateway {
1420 t.Fatalf("connect with Equipo down: %d", r.Code)
1421 }
1422 if a.hostMember(token) != "" {
1423 t.Fatal("the revoked connection's host token still names the member")
1424 }
1425 if s := a.get("/settings").Body; strings.Contains(s, `action="/ask/disconnect"`) {
1426 t.Fatalf("Settings shows a revoked connection as connected:\n%s", s)
1427 }
1428}
1429
1430// jobItem is the job with id as /ask draws it: its li, pill and cards.
1431func jobItem(t *testing.T, page, id string) string {
1432 t.Helper()
1433 m := regexp.MustCompile(`(?s)<li class="job" data-job="` + regexp.QuoteMeta(id) + `"[^>]*>.*?<ol class="job-cards">.*?</ol></li>`).FindString(page)
1434 if m == "" {
1435 t.Fatalf("no job %s in:\n%s", id, page)
1436 }
1437 return m
1438}
1439
1440// A job is a pill in the conversation, never a card: the title, its status
1441// beside it, and a summary named by both. Nothing in the chat names
1442// Equipo, or links to the job's page there (only the job view's title
1443// will, Task 19).
1444func TestAskJobPill(t *testing.T) {
1445 a, f := newAskApp(t)
1446 a.connectEquipo(f)
1447 id := f.AskJob("Building your website")
1448 page := a.get("/ask").Body
1449 if n := strings.Count(page, `<li class="job" `); n != 1 {
1450 t.Fatalf("%d jobs drawn:\n%s", n, page)
1451 }
1452 job := jobItem(t, page, id)
1453 if !strings.Contains(job, `data-state="working"`) || !strings.Contains(job, `data-revision="1"`) {
1454 t.Errorf("job's attributes:\n%s", job)
1455 }
1456 expect(t, "title", job, `<span class="pill-title">(.*?)</span>`, "Building your website")
1457 expect(t, "stage", job, `<span class="pill-stage">(.*?)</span>`, "Getting started")
1458 if !strings.Contains(job, `<summary class="pill-main" aria-label="Building your website, Getting started">`) {
1459 t.Errorf("summary's name:\n%s", job)
1460 }
1461 if strings.Contains(page, `data-card="`+id+`"`) || strings.Contains(job, "pill-link") {
1462 t.Errorf("the job is drawn as a card, or links somewhere while working:\n%s", job)
1463 }
1464 if strings.Contains(strings.ToLower(textOf(page)), "equipo") {
1465 t.Errorf("the chat names Equipo:\n%s", textOf(page))
1466 }
1467 // The job's page in Equipo is linked once: the job view's title.
1468 if n, in := strings.Count(page, f.URL+"/jobs/"), strings.Count(jobViewOf(t, job), f.URL+"/jobs/"); n != 1 || in != 1 {
1469 t.Errorf("the job's page is linked %d times, %d of them the job view's title:\n%s", n, in, page)
1470 }
1471 if !strings.Contains(page, `data-empty hidden`) {
1472 t.Errorf("the empty line shows beside a job")
1473 }
1474 var st struct {
1475 Cards []struct{ ID string }
1476 Jobs []struct {
1477 ID, State, Result string
1478 Cards []struct{ ID string }
1479 }
1480 }
1481 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 0 || len(st.Jobs) != 1 ||
1482 st.Jobs[0].ID != id || st.Jobs[0].State != "working" || st.Jobs[0].Result != "Getting started" ||
1483 st.Jobs[0].Cards == nil || !strings.Contains(r.Body, `"cards":[]`) {
1484 t.Fatalf("state: %s", r.Body)
1485 }
1486}
1487
1488// jobViewOf is the job view inside a job's li.
1489func jobViewOf(t *testing.T, job string) string {
1490 t.Helper()
1491 m := regexp.MustCompile(`(?s)<section class="jobview"[^>]*>.*?</section>`).FindString(job)
1492 if m == "" {
1493 t.Fatalf("no job view in:\n%s", job)
1494 }
1495 return m
1496}
1497
1498// The job view, inside the pill's <details> (it opens there without
1499// scripts): the title, linked to the job's page in Equipo in a new tab
1500// with "Open in Equipo" as its tooltip (plan decision D3), the status,
1501// one sentence more, and when it started (D19). A job with no page there
1502// (a legacy hand-off, J7) has a plain title. Once there is something to
1503// see, the view links to it as the pill does.
1504func TestAskJobView(t *testing.T) {
1505 a, f := newAskApp(t)
1506 a.connectEquipo(f)
1507 id := f.AskJob("Building your website")
1508 page := a.get("/ask").Body
1509 view := jobViewOf(t, jobItem(t, page, id))
1510 if !strings.HasPrefix(view, `<section class="jobview" aria-label="Building your website">`) {
1511 t.Errorf("the view's name:\n%s", view)
1512 }
1513 title := regexp.MustCompile(`(?s)<h3>(.*?)</h3>`).FindStringSubmatch(view)
1514 link := regexp.MustCompile(`^<a class="jv-title" href="([^"]*)" title="Open in Equipo" target="_blank" rel="noopener">Building your website<svg [^>]*aria-hidden="true">.*?</svg></a>$`)
1515 if title == nil || link.FindStringSubmatch(title[1]) == nil || !strings.HasPrefix(link.FindStringSubmatch(title[1])[1], f.URL+"/jobs/h_") {
1516 t.Errorf("the view's title is not its link to the job's page:\n%s", view)
1517 }
1518 expect(t, "status", view, `<p class="jv-stage">(.*?)</p>`, "Getting started")
1519 expect(t, "detail", view, `<p class="jv-detail">(.*?)</p>`, "Working out what's needed.")
1520 expect(t, "started", view, `<p class="jv-started">(.*?)</p>`, "Started just now")
1521 if !regexp.MustCompile(`<button class="round" type="button" data-job-close aria-label="Close" hidden>`).MatchString(view) {
1522 t.Errorf("Close is not there for the script, or shows without it:\n%s", view)
1523 }
1524 if strings.Contains(view, "jv-go") {
1525 t.Errorf("a working job's view links to its work:\n%s", view)
1526 }
1527 if strings.Contains(strings.ToLower(textOf(view)), "equipo") {
1528 t.Errorf("the view names Equipo in its text: %s", textOf(view))
1529 }
1530
1531 legacy := f.AskLegacyJob("Fixing the login")
1532 view = jobViewOf(t, jobItem(t, a.get("/ask").Body, legacy))
1533 expect(t, "legacy title", view, `(?s)<h3>(.*?)</h3>`, "Fixing the login")
1534 if strings.Contains(view, "<a ") {
1535 t.Errorf("a job with no page in Equipo links somewhere:\n%s", view)
1536 }
1537
1538 f.SetJob(id, "ready", "Ready to try", "Have a look.", equipo.Link{Label: "Try it", URL: "https://preview.example.test/"})
1539 view = jobViewOf(t, jobItem(t, a.get("/ask").Body, id))
1540 expect(t, "ready status", view, `<p class="jv-stage">(.*?)</p>`, "Ready to try")
1541 expect(t, "ready detail", view, `<p class="jv-detail">(.*?)</p>`, "Have a look.")
1542 if !strings.Contains(view, `<a class="jv-go" href="https://preview.example.test/" target="_blank" rel="noopener">Try it</a>`) {
1543 t.Errorf("a ready job's view does not link to its work:\n%s", view)
1544 }
1545 if title := regexp.MustCompile(`(?s)<h3>(.*?)</h3>`).FindStringSubmatch(view); title == nil || !link.MatchString(title[1]) {
1546 t.Errorf("a ready job's title lost its link:\n%s", view)
1547 }
1548}
1549
1550// The pill shows the status in every state, and a link beside it only
1551// once there is something to see: ready (the preview) and done (the site).
1552func TestAskJobStates(t *testing.T) {
1553 preview := equipo.Link{Label: "Try it", URL: "https://preview.example.test/"}
1554 site := equipo.Link{Label: "Open your site", URL: "https://site.example.test/"}
1555 for _, tc := range []struct {
1556 state, result string
1557 links []equipo.Link
1558 link, href string
1559 }{
1560 {"asking", "One question for you", nil, "", ""},
1561 {"asking", "One question for you", []equipo.Link{preview}, "", ""},
1562 {"ready", "Ready to try", []equipo.Link{preview}, "Try it", preview.URL},
1563 {"done", "Done", []equipo.Link{site}, "Open your site", site.URL},
1564 {"stopped", "Stopped", nil, "", ""},
1565 } {
1566 a, f := newAskApp(t)
1567 a.connectEquipo(f)
1568 id := f.AskJob("Building your website")
1569 f.SetJob(id, tc.state, tc.result, "One sentence more.", tc.links...)
1570 job := jobItem(t, a.get("/ask").Body, id)
1571 where := tc.state + " " + strconv.Itoa(len(tc.links))
1572 if !strings.Contains(job, `data-state="`+tc.state+`"`) || !strings.Contains(job, `data-revision="2"`) {
1573 t.Errorf("%s: attributes:\n%s", where, job)
1574 }
1575 expect(t, where, job, `<span class="pill-stage">(.*?)</span>`, tc.result)
1576 if !strings.Contains(job, `aria-label="Building your website, `+tc.result+`"`) {
1577 t.Errorf("%s: summary's name:\n%s", where, job)
1578 }
1579 got := regexp.MustCompile(`<a class="pill-link" href="([^"]*)" target="_blank" rel="noopener">(.*?)</a>`).FindStringSubmatch(job)
1580 switch {
1581 case tc.link == "" && got != nil:
1582 t.Errorf("%s: a pill link %q", where, got[0])
1583 case tc.link != "" && (got == nil || got[1] != tc.href || got[2] != tc.link):
1584 t.Errorf("%s: pill link %q, want %s to %s:\n%s", where, got, tc.link, tc.href, job)
1585 }
1586 if n := strings.Count(job, `class="state-mark" aria-hidden="true"`); n < 1 {
1587 t.Errorf("%s: no state mark", where)
1588 }
1589 if hasSVG := strings.Contains(regexp.MustCompile(`(?s)<span class="state-mark"[^>]*>(.*?)</span>`).FindStringSubmatch(job)[1], "<svg"); hasSVG == (tc.state == "working") {
1590 t.Errorf("%s: state mark's icon %v", where, hasSVG)
1591 }
1592 }
1593}
1594
1595// A paused job (Equipo's "paused", its status and sentence in the person's
1596// time zone, as given): the pill's clock mark on the calm indigo, its
1597// status, and in the view the sentence and, when the card offers it,
1598// "Carry on now" with the line under it, posting the card's revision and
1599// a key. Not offered, the view has no form. Stopped has a mark of its own
1600// (a square), never paused's or the old pause bars.
1601func TestAskJobPaused(t *testing.T) {
1602 const clock = `<path d="M19.2 12a7.2 7.2 0 1 1-14.4 0a7.2 7.2 0 1 1 14.4 0zM12 8.6V12l2.4 1.6"/>`
1603 const square = `<path d="M9 7.5h6a1.5 1.5 0 0 1 1.5 1.5v6a1.5 1.5 0 0 1-1.5 1.5H9a1.5 1.5 0 0 1-1.5-1.5V9A1.5 1.5 0 0 1 9 7.5z"/>`
1604 a, f := newAskApp(t)
1605 a.connectEquipo(f)
1606 id := f.AskJob("Bakery website")
1607 f.PauseJob(id, "Paused until 21:00", "It has reached the limit on its plan for now. It will carry on by itself at 21:00 (in 9 hours).", true)
1608 page := a.get("/ask").Body
1609 job := jobItem(t, page, id)
1610 if !strings.Contains(job, `data-state="paused"`) {
1611 t.Errorf("paused job's state:\n%s", job)
1612 }
1613 expect(t, "stage", job, `<span class="pill-stage">(.*?)</span>`, "Paused until 21:00")
1614 if !strings.Contains(job, `<summary class="pill-main" aria-label="Bakery website, Paused until 21:00">`) {
1615 t.Errorf("summary's name:\n%s", job)
1616 }
1617 if n := strings.Count(job, clock); n != 2 {
1618 t.Errorf("the clock mark is drawn %d times (pill and view):\n%s", n, job)
1619 }
1620 view := jobViewOf(t, job)
1621 expect(t, "status", view, `<p class="jv-stage">(.*?)</p>`, "Paused until 21:00")
1622 expect(t, "detail", view, `<p class="jv-detail">(.*?)</p>`, "It has reached the limit on its plan for now. It will carry on by itself at 21:00 (in 9 hours).")
1623 form := regexp.MustCompile(`(?s)<form class="jv-act" method="post" action="/ask/cards/` + id + `/carry_on">(.*?)</form>`).FindStringSubmatch(view)
1624 if form == nil || !strings.Contains(form[1], `<button class="btn ghost" type="submit">Carry on now</button><small>Uses your other plan, at no extra cost.</small><p class="jv-error" role="status"></p>`) {
1625 t.Fatalf("no Carry on now in the view:\n%s", view)
1626 }
1627 fields := formFields(t, page, "/ask/cards/"+id+"/carry_on")
1628 if fields.Get("revision") != "3" || fields.Get("key") == "" {
1629 t.Errorf("Carry on now posts %v", fields)
1630 }
1631 css, _ := os.ReadFile("../look/static/app.css")
1632 for _, rule := range []string{`.job[data-state="paused"] { --st: var(--st-pause); }`, `--st-pause: #AEB8FF;`, `--st-pause: #4B55C9;`, `--st-pause: light-dark(#4B55C9, #AEB8FF);`} {
1633 if !strings.Contains(string(css), rule) {
1634 t.Errorf("app.css has no %s", rule)
1635 }
1636 }
1637
1638 // Not offered: no form, the rest as before.
1639 other := f.AskJob("Invoice reminders")
1640 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)
1641 view = jobViewOf(t, jobItem(t, a.get("/ask").Body, other))
1642 if strings.Contains(view, "<form") || strings.Contains(view, "Carry on now") {
1643 t.Errorf("Carry on now without carry_on:\n%s", view)
1644 }
1645
1646 // Stopped: a square, distinct from paused's clock.
1647 f.SetJob(other, "stopped", "Stopped", "It needs you.")
1648 job = jobItem(t, a.get("/ask").Body, other)
1649 if !strings.Contains(job, square) || strings.Contains(job, clock) || strings.Contains(job, "M9.5 7.5v9M14.5 7.5v9") {
1650 t.Errorf("stopped's mark:\n%s", job)
1651 }
1652 // ask.js draws the same words, and it and the native app the same marks.
1653 js, _ := os.ReadFile("../look/static/ask.js")
1654 for _, words := range []string{`"Carry on now"`, `"Uses your other plan, at no extra cost."`, `"That didn't send. Try again."`} {
1655 if !strings.Contains(string(js), words) {
1656 t.Errorf("ask.js has no %s", words)
1657 }
1658 }
1659 for _, file := range []string{"../look/static/ask.js", "../../native/apple/Sources/BaseKit/Look/Marks.swift"} {
1660 raw, _ := os.ReadFile(file)
1661 for _, d := range []string{clock, square} {
1662 if d = regexp.MustCompile(`d="([^"]*)"`).FindStringSubmatch(d)[1]; !strings.Contains(string(raw), `"`+d+`"`) {
1663 t.Errorf("%s has no %s", file, d)
1664 }
1665 }
1666 }
1667}
1668
1669// Carry on now, without scripts: the form posts once to Equipo with its
1670// key (the body's idempotency_key and the Idempotency-Key header) and the
1671// revision shown, and /ask shows the job carrying on. The same form sent
1672// again is the same request. At a stale revision Equipo's 409 is not
1673// resent: /ask draws the card as it is now. A job that is no longer paused,
1674// or no longer offers it, is a 409 too. Scripts on, the answer is the card.
1675func TestAskCarryOnNow(t *testing.T) {
1676 a, f := newAskApp(t)
1677 a.connectEquipo(f)
1678 id := f.AskJob("Bakery website")
1679 f.PauseJob(id, "Paused until 21:00", "It will carry on by itself at 21:00 (in 9 hours).", true)
1680 path := "/ask/cards/" + id + "/carry_on"
1681 form := formFields(t, a.get("/ask").Body, path)
1682 for i := range 2 {
1683 if r := a.post(path, form); r.Code != 303 || r.Location() != "/ask" {
1684 t.Fatalf("carry on %d: %d %q", i, r.Code, r.Location())
1685 }
1686 }
1687 calls := f.Calls("/api/v1/assistant" + path[len("/ask"):])
1688 want := `{"idempotency_key":"` + form.Get("key") + `","revision":3}`
1689 if len(calls) != 2 || strings.TrimSpace(calls[0].Body) != want || calls[1].Body != calls[0].Body ||
1690 calls[0].Header.Get("Idempotency-Key") != form.Get("key") {
1691 t.Fatalf("relayed: %+v, want twice %s", calls, want)
1692 }
1693 job := jobItem(t, a.get("/ask").Body, id)
1694 if !strings.Contains(job, `data-state="working"`) || strings.Contains(job, "Carry on now") {
1695 t.Errorf("after Carry on now:\n%s", job)
1696 }
1697
1698 // Stale: the job moved on unseen. One call, a 409, and /ask draws it anew.
1699 other := f.AskJob("Invoice reminders")
1700 f.PauseJob(other, "Paused until 21:00", "It will carry on by itself at 21:00 (in 9 hours).", true)
1701 path = "/ask/cards/" + other + "/carry_on"
1702 stale := formFields(t, a.get("/ask").Body, path)
1703 f.PauseJob(other, "Paused until 22:00", "It will carry on by itself at 22:00 (in 10 hours).", true)
1704 if r := a.post(path, stale); r.Code != 303 || r.Location() != "/ask" {
1705 t.Fatalf("stale: %d %q", r.Code, r.Location())
1706 }
1707 if n := len(f.Calls("/api/v1/assistant/cards/" + other + "/carry_on")); n != 1 {
1708 t.Errorf("a stale Carry on now went %d times", n)
1709 }
1710 fresh := formFields(t, a.get("/ask").Body, path)
1711 if fresh.Get("revision") != "4" {
1712 t.Errorf("after the 409 the job is at revision %q, want 4", fresh.Get("revision"))
1713 }
1714
1715 // Scripts on: the card, at its new revision.
1716 json409 := func(form url.Values) Resp {
1717 req, _ := http.NewRequest(http.MethodPost, a.base+path, strings.NewReader(form.Encode()))
1718 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
1719 req.Header.Set("Origin", a.origin)
1720 req.Header.Set("Accept", "application/json")
1721 return a.do(req)
1722 }
1723 res := json409(fresh)
1724 var out struct{ Card struct{ ID, State string } }
1725 if res.Code != 200 || json.Unmarshal([]byte(res.Body), &out) != nil || out.Card.ID != other || out.Card.State != "working" {
1726 t.Fatalf("JSON carry on: %d %s", res.Code, res.Body)
1727 }
1728 // No longer paused, then paused without the offer: 409s, the panel reads afresh.
1729 fresh.Set("key", "k-again")
1730 fresh.Set("revision", "5")
1731 if r := json409(fresh); r.Code != 409 || strings.TrimSpace(r.Body) != `{"state":"ready"}` {
1732 t.Errorf("not paused: %d %s", r.Code, r.Body)
1733 }
1734 f.PauseJob(other, "Paused until 23:00", "It will carry on by itself at 23:00.", false)
1735 fresh.Set("key", "k-third")
1736 fresh.Set("revision", "6")
1737 if r := json409(fresh); r.Code != 409 || strings.TrimSpace(r.Body) != `{"state":"ready"}` {
1738 t.Errorf("carry on unavailable: %d %s", r.Code, r.Body)
1739 }
1740 // No such job card for the person (Equipo's 404) is final, never "try
1741 // again": stale for the panel, /ask without a problem for a form.
1742 path = "/ask/cards/c_nothing/carry_on"
1743 if r := json409(url.Values{"revision": {"1"}, "key": {"k-gone"}}); r.Code != 409 || strings.TrimSpace(r.Body) != `{"state":"ready"}` {
1744 t.Errorf("no such card: %d %s", r.Code, r.Body)
1745 }
1746 if r := a.post(path, url.Values{"revision": {"1"}, "key": {"k-gone-2"}}); r.Code != 303 || r.Location() != "/ask" {
1747 t.Errorf("no such card, without scripts: %d %q", r.Code, r.Location())
1748 }
1749}
1750
1751// zoneCalls waits up to two seconds for Equipo to have had n PUT
1752// time-zone calls (Base makes them on their own, off the page's path), and
1753// returns them; then it waits a little more and fails if any more came.
1754func zoneCalls(t *testing.T, f *equipotest.Fake, n int) []equipotest.Call {
1755 t.Helper()
1756 const path = "/api/v1/assistant/time-zone"
1757 for end := time.Now().Add(2 * time.Second); len(f.Calls(path)) < n && time.Now().Before(end); {
1758 time.Sleep(10 * time.Millisecond)
1759 }
1760 time.Sleep(100 * time.Millisecond)
1761 calls := f.Calls(path)
1762 if len(calls) != n {
1763 t.Fatalf("%d time-zone calls, want %d: %+v", len(calls), n, calls)
1764 }
1765 return calls
1766}
1767
1768// newZonedAskApp is newAskApp with BASE_TIMEZONE at Europe/Madrid.
1769func newZonedAskApp(t *testing.T) (*testApp, *equipotest.Fake) {
1770 t.Helper()
1771 madrid, err := time.LoadLocation("Europe/Madrid")
1772 if err != nil {
1773 t.Fatal(err)
1774 }
1775 f := equipotest.New(t)
1776 a := newAppConfigured(t, func(*sql.DB, config.Config) web.Installer { return noInstaller{} }, madrid,
1777 func(c *config.Config) { c.EquipoOrigin = f.URL })
1778 a.signedInOwner()
1779 return a, f
1780}
1781
1782// Base tells Equipo the team's time zone (BASE_TIMEZONE), so the
1783// Assistant's times are in it, only if the person has none of their own
1784// (only_if_unset): once a connection is made, not again on every read.
1785// Base opts in to the paused job state on the snapshot and the event
1786// stream (job_states=paused).
1787func TestAskSendsTheTeamZoneAndOptsInToPaused(t *testing.T) {
1788 a, f := newZonedAskApp(t)
1789 a.connectEquipo(f)
1790 a.get("/ask")
1791 a.get("/ask")
1792 zones := zoneCalls(t, f, 1)
1793 if zones[0].Method != http.MethodPut || strings.TrimSpace(zones[0].Body) != `{"only_if_unset":true,"time_zone":"Europe/Madrid"}` ||
1794 f.TimeZone() != "Europe/Madrid" {
1795 t.Errorf("time zone told: %+v, Equipo has %q", zones, f.TimeZone())
1796 }
1797 snaps := f.Calls("/api/v1/assistant/snapshot")
1798 if len(snaps) == 0 {
1799 t.Fatal("no snapshot read")
1800 }
1801 for _, c := range snaps {
1802 if c.Query != "job_states=paused" {
1803 t.Errorf("snapshot's query %q", c.Query)
1804 }
1805 }
1806 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
1807 defer cancel()
1808 req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after=40", nil)
1809 res, err := a.client.Do(req)
1810 if err != nil {
1811 t.Fatal(err)
1812 }
1813 // Its first line comes once Equipo's stream has opened.
1814 if line, _ := bufio.NewReader(res.Body).ReadString('\n'); res.StatusCode != 200 || line == "" {
1815 t.Fatalf("events: %d %q", res.StatusCode, line)
1816 }
1817 res.Body.Close()
1818 events := f.Calls("/api/v1/assistant/events")
1819 if len(events) == 0 || events[0].Query != "job_states=paused&after=40" {
1820 t.Errorf("events: %+v", events)
1821 }
1822}
1823
1824// Fable's re-review R2: a new connection tells Equipo again (its bearer is
1825// new), once, and reads after it do not.
1826func TestAskZoneAgainOnANewConnection(t *testing.T) {
1827 a, f := newZonedAskApp(t)
1828 a.connectEquipo(f)
1829 a.get("/ask")
1830 zoneCalls(t, f, 1)
1831 a.approveEquipo(f)
1832 a.get("/ask")
1833 a.get("/")
1834 calls := zoneCalls(t, f, 2)
1835 if calls[0].Header.Get("Authorization") == calls[1].Header.Get("Authorization") {
1836 t.Error("the second call did not use the new connection's bearer")
1837 }
1838}
1839
1840// A zone one of the person's own devices set wins: Base's is only for
1841// when they have none.
1842func TestAskZoneNeverOverridesThePersons(t *testing.T) {
1843 a, f := newZonedAskApp(t)
1844 f.SetTimeZone("Europe/Berlin")
1845 a.connectEquipo(f)
1846 a.get("/ask")
1847 zoneCalls(t, f, 1)
1848 if f.TimeZone() != "Europe/Berlin" {
1849 t.Errorf("Base replaced the person's zone: %q", f.TimeZone())
1850 }
1851}
1852
1853// Fable's review S1: the time-zone call never holds up a page. With it
1854// hanging, /ask, Home and /ask/state each answer at once, and it is one
1855// call, not one per read.
1856func TestAskZoneNeverHoldsThePage(t *testing.T) {
1857 a, f := newZonedAskApp(t)
1858 release := f.HoldTimeZone()
1859 defer release()
1860 a.connectEquipo(f)
1861 for _, page := range []string{"/ask", "/", "/ask/state", "/ask"} {
1862 start := time.Now()
1863 if r := a.get(page); r.Code != 200 {
1864 t.Fatalf("%s: %d", page, r.Code)
1865 }
1866 if took := time.Since(start); took > time.Second {
1867 t.Errorf("%s took %v with the time-zone call hanging", page, took)
1868 }
1869 }
1870 zoneCalls(t, f, 1)
1871}
1872
1873// An answer that settles it (a 2xx, or a 4xx other than 429: Fable's 422
1874// for a zone Equipo refuses, and an older Equipo's 404) is never sent
1875// again; a failure (a 5xx, a 429) is not tried again for a while: one call
1876// over a connect and three reads, either way.
1877func TestAskZoneIsToldOnce(t *testing.T) {
1878 for _, tc := range []struct {
1879 status int
1880 code string
1881 }{{422, "invalid_input"}, {404, "not_found"}, {500, "internal"}, {503, "unavailable"}, {429, "rate_limited"}} {
1882 t.Run(strconv.Itoa(tc.status), func(t *testing.T) {
1883 a, f := newZonedAskApp(t)
1884 f.RefuseTimeZone(tc.status, tc.code)
1885 a.connectEquipo(f)
1886 zoneCalls(t, f, 1)
1887 for _, page := range []string{"/ask", "/", "/ask/state"} {
1888 if r := a.get(page); r.Code != 200 {
1889 t.Fatalf("%s: %d", page, r.Code)
1890 }
1891 }
1892 zoneCalls(t, f, 1)
1893 })
1894 }
1895}
1896
1897// A go-ahead or Publish card that belongs to a job is drawn under its
1898// pill while open, and answers as any card does; answered, it is listed
1899// in the job view. One whose job is not drawn is loose. A redrawn job (a
1900// new revision) keeps the cards under it.
1901func TestAskJobAttachesItsCards(t *testing.T) {
1902 a, f := newAskApp(t)
1903 a.connectEquipo(f)
1904 id := f.AskJob("Building your website")
1905 f.SetJob(id, "ready", "Ready to try", "Have a look.", equipo.Link{Label: "Try it", URL: "https://preview.example.test/"})
1906 goAhead := f.AskOutcomeFor(id, "This is ready. Go ahead?", goOptions, nil)
1907 loose := f.AskOutcomeFor("c_9999", "Publish it?", goOptions, nil)
1908 f.SetJob(id, "ready", "Ready to try", "Still ready.", equipo.Link{Label: "Try it", URL: "https://preview.example.test/"})
1909 page := a.get("/ask").Body
1910 job := jobItem(t, page, id)
1911 if !strings.Contains(job, `data-revision="3"`) || !strings.Contains(job, `data-card="`+goAhead+`"`) || strings.Contains(job, `data-card="`+loose+`"`) {
1912 t.Fatalf("the job's cards:\n%s", job)
1913 }
1914 if card := cardItem(t, job, goAhead); !strings.Contains(card, `data-for="`+id+`"`) {
1915 t.Errorf("the attached card does not say whose it is:\n%s", card)
1916 }
1917 rest := strings.Replace(page, job, "", 1)
1918 if !strings.Contains(rest, `data-card="`+loose+`"`) {
1919 t.Errorf("the card of no drawn job is not loose:\n%s", page)
1920 }
1921 if strings.Index(page, job) > strings.Index(page, `data-card="`+loose+`"`) {
1922 t.Errorf("a loose card is drawn before the job")
1923 }
1924 answer := formFields(t, page, "/ask/cards/"+goAhead+"/answer")
1925 answer.Set("choice", "go")
1926 if r := a.post("/ask/cards/"+goAhead+"/answer", answer); r.Code != 303 || r.Location() != "/ask" {
1927 t.Fatalf("answer: %d %q", r.Code, r.Location())
1928 }
1929 if c := f.Calls("/api/v1/assistant/cards/" + goAhead + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"go","revision":1}` {
1930 t.Fatalf("relayed: %+v", c)
1931 }
1932 // Answered, it is the job view's, as its question and how it ended.
1933 if view := jobViewOf(t, jobItem(t, a.get("/ask").Body, id)); !strings.Contains(view, `<li class="jv-card" data-card="`+goAhead+`" data-revision="2" data-for="`+id+`"><p class="jv-q">This is ready. Go ahead?</p><p class="jv-result">Go ahead</p></li>`) {
1934 t.Errorf("answered card in the job view:\n%s", view)
1935 }
1936 var st struct {
1937 Cards []struct{ ID string }
1938 Jobs []struct {
1939 ID string
1940 Cards []struct{ ID, Job string }
1941 }
1942 }
1943 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 1 || st.Cards[0].ID != loose ||
1944 len(st.Jobs) != 1 || len(st.Jobs[0].Cards) != 1 || st.Jobs[0].Cards[0].ID != goAhead || st.Jobs[0].Cards[0].Job != id {
1945 t.Fatalf("state: %s", r.Body)
1946 }
1947}
1948
1949// Paul's live check (2026-11-16): only a card that needs an answer is
1950// drawn under its job's pill. A job's answered question and go-ahead are
1951// listed in its view, under the detail, each as its question and its
1952// result line with nothing to press; an open go-ahead stays under the
1953// pill; the state carries every card of the job, for the script to
1954// place.
1955func TestAskJobSettledCardsInView(t *testing.T) {
1956 a, f := newAskApp(t)
1957 a.connectEquipo(f)
1958 id := f.AskLegacyJob("Can you make me a website?")
1959 question := f.AskKindFor("question", id, "Which website?", []equipo.Option{{Value: "new", Label: "A new one"}}, nil)
1960 goAhead := f.AskOutcomeFor(id, "This is ready. Go ahead?", goOptions, nil)
1961 f.SetCard(question, "answered", "A new one")
1962 f.SetCard(goAhead, "answered", "Go ahead")
1963 f.SetJob(id, "stopped", "Stopped", "It can't go on until something is sorted out.")
1964 page := a.get("/ask").Body
1965 job := jobItem(t, page, id)
1966 if !strings.HasSuffix(job, `<ol class="job-cards"></ol></li>`) || strings.Contains(page, `class="msg card`) {
1967 t.Errorf("an ended card drawn as a card:\n%s", page)
1968 }
1969 view := jobViewOf(t, job)
1970 want := `<p class="jv-detail">It can&#39;t go on until something is sorted out.</p><ol class="jv-cards">` +
1971 `<li class="jv-card" data-card="` + question + `" data-revision="2" data-for="` + id + `"><p class="jv-q">Which website?</p><p class="jv-result">A new one</p></li>` +
1972 `<li class="jv-card" data-card="` + goAhead + `" data-revision="2" data-for="` + id + `"><p class="jv-q">This is ready. Go ahead?</p><p class="jv-result">Go ahead</p></li></ol>`
1973 if !strings.Contains(view, want) {
1974 t.Errorf("the job view's ended cards, want %s in:\n%s", want, view)
1975 }
1976 again := f.AskOutcomeFor(id, "Try it again?", goOptions, nil)
1977 job = jobItem(t, a.get("/ask").Body, id)
1978 if card := cardItem(t, job, again); !strings.Contains(card, `action="/ask/cards/`+again+`/answer"`) || strings.Contains(jobViewOf(t, job), again) {
1979 t.Errorf("the open go-ahead is not under the pill:\n%s", job)
1980 }
1981 var st struct {
1982 Jobs []struct {
1983 ID string
1984 Cards []struct{ ID, State string }
1985 }
1986 }
1987 if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Jobs) != 1 || len(st.Jobs[0].Cards) != 3 {
1988 t.Fatalf("state: %s", r.Body)
1989 }
1990}
1991
1992// A team_update turn is the Assistant thinking about a job by itself: no
1993// status line, no Stop, and not the turn the cancel form stops.
1994func TestAskTeamUpdateTurnIsQuiet(t *testing.T) {
1995 a, f := newAskApp(t)
1996 a.connectEquipo(f)
1997 f.AskJob("Building your website")
1998 f.EmitTurn("team_update", "running")
1999 page := a.get("/ask").Body
2000 expect(t, "/ask", page, `<p class="ask-status" role="status">(.*?)</p>`, "")
2001 if !regexp.MustCompile(`<button class="stop"[^>]* hidden>`).MatchString(page) || strings.Contains(page, "/cancel") ||
2002 strings.Contains(page, `http-equiv="refresh"`) {
2003 t.Errorf("a team_update turn shows Stop or counts as the turn in flight:\n%s", page)
2004 }
2005 if r := a.get("/ask/state"); !strings.Contains(r.Body, `"turn":null`) || !strings.Contains(r.Body, `"status":""`) {
2006 t.Errorf("state: %s", r.Body)
2007 }
2008 // The person's own turn still shows beside it.
2009 f.Hold = true
2010 a.post("/ask/messages", url.Values{"text": {"How is it going?"}})
2011 page = a.get("/ask").Body
2012 expect(t, "/ask with the person's turn", page, `<p class="ask-status" role="status">(.*?)</p>`, "Thinking…")
2013}
2014
2015// The person's own messages are drawn in the Assistant's little Markdown,
2016// under its rules (Paul, 2026-11-26): bold, lists and safe links; raw HTML
2017// and unsafe links stay text, and plain words are exactly as written.
2018func TestAskPersonMessagesAreMarkdown(t *testing.T) {
2019 a, f := newAskApp(t)
2020 a.connectEquipo(f)
2021 for _, text := range []string{
2022 "**Bold** and <b>x</b>:\n- [Menu](https://fennel.example/menu)\n- [x](javascript:alert(1))",
2023 "Two lines\nhere, 2*3 and a_b_c",
2024 } {
2025 a.post("/ask/messages", url.Values{"text": {text}})
2026 }
2027 page := a.get("/ask").Body
2028 person := regexp.MustCompile(`(?s)<li class="msg person" data-id="[^"]+">(.*?)</li>\n`).FindAllStringSubmatch(page, -1)
2029 if len(person) != 2 {
2030 t.Fatalf("person messages: %d\n%s", len(person), page)
2031 }
2032 if want := `<strong>Bold</strong> and &lt;b&gt;x&lt;/b&gt;:<ul><li><a href="https://fennel.example/menu" target="_blank" rel="noopener">Menu</a></li><li>[x](javascript:alert(1))</li></ul>`; person[0][1] != want {
2033 t.Errorf("Markdown:\n got %s\nwant %s", person[0][1], want)
2034 }
2035 if want := "Two lines\nhere, 2*3 and a_b_c"; person[1][1] != want {
2036 t.Errorf("plain words:\n got %q\nwant %q", person[1][1], want)
2037 }
2038}
2039