oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package browsertest
4
5import (
6 "bytes"
7 "encoding/json"
8 "image"
9 "image/color"
10 "image/png"
11 "net/http"
12 "os"
13 "path/filepath"
14 "strconv"
15 "strings"
16 "testing"
17 "time"
18
19 "github.com/chromedp/chromedp"
20 "github.com/chromedp/chromedp/kb"
21
22 "amadan.net/rastrillo/rastrillo/harness"
23
24 "amadan.net/oficina/base/internal/equipo/equipotest"
25)
26
27// Files in Ask (plan Task 8): the paperclip, paste, drop, the chips and
28// the viewer, against the fake Equipo.
29
30// attachFiles writes the files the tests attach, made here: a 64×48 PNG,
31// a note, a PDF, a file Equipo refuses as a type, one over 10 MiB, and a
32// HEIC.
33func attachFiles(t *testing.T) map[string]string {
34 t.Helper()
35 dir := t.TempDir()
36 img := image.NewNRGBA(image.Rect(0, 0, 64, 48))
37 for x := 0; x < 64; x++ {
38 for y := 0; y < 48; y++ {
39 img.Set(x, y, color.NRGBA{R: uint8(x * 4), G: 160, B: uint8(y * 5), A: 255})
40 }
41 }
42 var shot bytes.Buffer
43 if err := png.Encode(&shot, img); err != nil {
44 t.Fatal(err)
45 }
46 files := map[string][]byte{
47 "shot.png": shot.Bytes(),
48 "note.md": []byte("# Notes\n\nQ3 is up.\n"),
49 "brief.pdf": []byte("%PDF-1.4\n1 0 obj << >> endobj\ntrailer << >>\n%%EOF\n"),
50 "data.json": {0x00, 0x01, 0x02, 0xff, 0xfe},
51 "big.txt": bytes.Repeat([]byte("a"), 10<<20+1),
52 "photo.heic": append([]byte("\x00\x00\x00\x18ftypheic"), make([]byte, 64)...),
53 }
54 out := map[string]string{}
55 for name, data := range files {
56 p := filepath.Join(dir, name)
57 if err := os.WriteFile(p, data, 0o644); err != nil {
58 t.Fatal(err)
59 }
60 out[name] = p
61 }
62 for i := 1; i <= 6; i++ {
63 p := filepath.Join(dir, "n"+strconv.Itoa(i)+".txt")
64 if err := os.WriteFile(p, []byte("note "+strconv.Itoa(i)), 0o644); err != nil {
65 t.Fatal(err)
66 }
67 out["n"+strconv.Itoa(i)+".txt"] = p
68 }
69 return out
70}
71
72// attachReady is Ask with a runner that takes files, the panel open and
73// its paperclip showing.
74func attachReady(t *testing.T) (*harness.Rig, *equipotest.Fake) {
75 t.Helper()
76 rig, f := askBase(t)
77 f.FilesReady(true)
78 openPanel(t, rig)
79 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
80 return rig, f
81}
82
83// pick chooses files in the paperclip's picker, as a person would.
84func pick(t *testing.T, rig *harness.Rig, paths ...string) {
85 t.Helper()
86 drive(t, rig, chromedp.SetUploadFiles(chromedp.CSS(`#ask-panel form.composer input[type=file]`), paths, chromedp.NodeReady))
87}
88
89// chip is one chip as the page shows it.
90type chip struct {
91 Name string `json:"name"`
92 State string `json:"state"`
93 Meta string `json:"meta"`
94 Thumb string `json:"thumb"`
95 Ring string `json:"ring"`
96}
97
98const chipsJS = `JSON.stringify([...document.querySelectorAll("#ask-panel .chips .chip")].map((c) => ({
99 name: c.querySelector(".chip-name").textContent, state: c.dataset.state || "", meta: c.querySelector(".chip-meta").textContent,
100 thumb: c.querySelector(".chip-mark > img")?.getAttribute("src") || "",
101 ring: c.querySelector(".chip-ring:not([hidden])")?.getAttribute("aria-valuenow") ?? "" })))`
102
103func chipsOf(t *testing.T, rig *harness.Rig) []chip {
104 t.Helper()
105 var out []chip
106 if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, chipsJS)), &out); err != nil {
107 t.Fatal(err)
108 }
109 return out
110}
111
112// waitChips waits until ok holds of the chips.
113func waitChips(t *testing.T, rig *harness.Rig, what string, ok func([]chip) bool) []chip {
114 t.Helper()
115 deadline := time.Now().Add(15 * time.Second)
116 for {
117 c := chipsOf(t, rig)
118 if ok(c) {
119 return c
120 }
121 if time.Now().After(deadline) {
122 t.Fatalf("chips never %s: %+v", what, c)
123 }
124 time.Sleep(40 * time.Millisecond)
125 }
126}
127
128func allDone(n int) func([]chip) bool {
129 return func(c []chip) bool {
130 if len(c) != n {
131 return false
132 }
133 for _, x := range c {
134 if x.State != "done" {
135 return false
136 }
137 }
138 return true
139 }
140}
141
142// lastSend is the attachments and text of the newest message Equipo was
143// sent.
144func lastSend(t *testing.T, f *equipotest.Fake) (text string, files []string) {
145 t.Helper()
146 calls := f.Calls("/api/v1/assistant/messages")
147 if len(calls) == 0 {
148 t.Fatal("nothing was sent")
149 }
150 var in struct {
151 Text string `json:"text"`
152 Attachments []string `json:"attachments"`
153 }
154 if err := json.Unmarshal([]byte(calls[len(calls)-1].Body), &in); err != nil {
155 t.Fatal(err)
156 }
157 return in.Text, in.Attachments
158}
159
160func waitFor(t *testing.T, what string, ok func() bool) {
161 t.Helper()
162 for i := 0; !ok(); i++ {
163 if i > 400 {
164 t.Fatalf("never %s", what)
165 }
166 time.Sleep(25 * time.Millisecond)
167 }
168}
169
170// The paperclip picks files; each uploads as a chip, an image's chip shows
171// its thumbnail from Base, a PDF's says Ask can't read it yet; Send sends
172// them in chip order with the words, and the thread shows them as the
173// server draws them. A thumbnail opens the viewer, which holds focus
174// until Escape gives it back.
175func TestAskAttachPicker(t *testing.T) {
176 paths := attachFiles(t)
177 rig, f := attachReady(t)
178 rig.Screen("#ask-panel", "Ask with the paperclip")
179 pick(t, rig, paths["shot.png"], paths["note.md"], paths["brief.pdf"])
180 c := waitChips(t, rig, "done", allDone(3))
181 if c[0].Name != "shot.png" || !strings.HasPrefix(c[0].Thumb, "/ask/attachments/at_") || !strings.HasSuffix(c[0].Thumb, "/preview") ||
182 c[2].Meta != "Ask can’t read PDFs yet." || c[1].Thumb != "" {
183 t.Fatalf("chips: %+v", c)
184 }
185 waitFor(t, "an upload announced", func() bool {
186 return strings.HasSuffix(harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`), " attached")
187 })
188 rig.Screen("#ask-panel", "three files attached")
189 viewportShot(t, rig, "attach-chips")
190 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "What do these say?"),
191 chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
192 waitChips(t, rig, "cleared", func(c []chip) bool { return len(c) == 0 })
193 text, ids := lastSend(t, f)
194 uploads := f.Uploads()
195 if text != "What do these say?" || len(ids) != 3 || len(uploads) != 3 {
196 t.Fatalf("sent %q %v; Equipo holds %v", text, ids, uploads)
197 }
198 for i, want := range []string{"shot.png", "note.md", "brief.pdf"} {
199 if _, name, _, msg, ok := f.Upload(ids[i]); !ok || name != want || msg == "" {
200 t.Errorf("file %d: %q sent with %q", i, name, msg)
201 }
202 }
203 _, _, _, sentIn, _ := f.Upload(ids[0])
204 row := `#ask-panel .thread li.msg.person[data-id='` + sentIn + `'] .files`
205 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(row+` a.thumb img`)))
206 got := harness.Evaluate[string](rig, `document.querySelector("`+row+`").outerHTML`)
207 for _, want := range []string{`<a class="thumb" href="/ask/attachments/` + ids[0] + `" data-attachment="` + ids[0] + `"><img loading="lazy" src="/ask/attachments/` + ids[0] + `/preview" alt="shot.png" width="64" height="48"></a>`,
208 `<a class="file" href="/ask/attachments/` + ids[1] + `" download="" aria-label="note.md, 19 B. Download">`, `<span class="file-name">brief.pdf</span>`} {
209 if !strings.Contains(got, want) {
210 t.Errorf("thread row lacks %s:\n%s", want, got)
211 }
212 }
213 if !harness.Evaluate[bool](rig, `document.querySelector("`+row+` a.thumb img").naturalWidth === 64`) {
214 t.Error("the thumbnail didn't load from Base")
215 }
216 rig.Screen("#ask-panel", "the message with its files")
217 viewportShot(t, rig, "attach-thread")
218
219 // The viewer.
220 drive(t, rig, chromedp.Click(chromedp.CSS(row+` a.thumb`)), chromedp.WaitVisible(chromedp.CSS(`dialog.viewer img`)))
221 if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("dialog.viewer .viewer-close") && document.querySelector("dialog.viewer").open`) {
222 t.Fatal("the viewer didn't take focus")
223 }
224 if !harness.Evaluate[bool](rig, `document.querySelector("dialog.viewer img").getAttribute("src") === "/ask/attachments/`+ids[0]+`"`) {
225 t.Error("the viewer isn't showing the image")
226 }
227 rig.Screen("body", "the viewer")
228 viewportShot(t, rig, "attach-viewer")
229 drive(t, rig, chromedp.KeyEvent(kb.Tab), chromedp.KeyEvent(kb.Tab))
230 if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("dialog.viewer .viewer-close")`) {
231 t.Error("Tab left the viewer")
232 }
233 drive(t, rig, chromedp.KeyEvent(kb.Escape))
234 waitFor(t, "the viewer closed", func() bool { return !harness.Evaluate[bool](rig, `document.querySelector("dialog.viewer").open`) })
235 if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("`+row+` a.thumb")`) {
236 t.Error("focus didn't go back to the thumbnail")
237 }
238
239 // Files with no words send, once the answer is in.
240 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel button.attach`)))
241 waitFor(t, "the turn ended", func() bool {
242 return harness.Evaluate[bool](rig, `document.querySelector("#ask-panel button.stop").hidden`)
243 })
244 pick(t, rig, paths["note.md"])
245 waitChips(t, rig, "done", allDone(1))
246 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
247 waitChips(t, rig, "cleared", func(c []chip) bool { return len(c) == 0 })
248 if text, ids := lastSend(t, f); text != "" || len(ids) != 1 {
249 t.Fatalf("files alone: %q %v", text, ids)
250 }
251
252 // The Ask page has the paperclip too.
253 drive(t, rig, chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(`.ask-chat .actions .attach`)))
254 rig.Screen("main", "the Ask page with the paperclip")
255}
256
257// pasteJS dispatches a paste into the field carrying files (made here:
258// "png" a tiny PNG named shot.png, "md" a note named Quarterly notes.md)
259// and text of each type given, and answers whether the page took it and
260// what the field holds after.
261func pasteJS(files []string, data map[string]string) string {
262 var b strings.Builder
263 b.WriteString(`(() => {
264 const f = document.querySelector("#ask-panel textarea");
265 f.focus(); f.value = "";
266 const d = new DataTransfer();
267 const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="), (c) => c.charCodeAt(0));`)
268 for _, f := range files {
269 switch f {
270 case "png":
271 b.WriteString(`d.items.add(new File([png], "shot.png", { type: "image/png" }));`)
272 case "md":
273 b.WriteString(`d.items.add(new File(["# Q3"], "Quarterly notes.md", { type: "text/markdown" }));`)
274 }
275 }
276 for typ, v := range data {
277 b.WriteString(`d.setData(` + strconv.Quote(typ) + `, ` + strconv.Quote(v) + `);`)
278 }
279 b.WriteString(`const e = new ClipboardEvent("paste", { clipboardData: d, bubbles: true, cancelable: true });
280 f.dispatchEvent(e);
281 return JSON.stringify({ prevented: e.defaultPrevented, value: f.value });
282 })()`)
283 return b.String()
284}
285
286type pasted struct {
287 Prevented bool `json:"prevented"`
288 Value string `json:"value"`
289}
290
291func paste(t *testing.T, rig *harness.Rig, files []string, data map[string]string) pasted {
292 t.Helper()
293 var p pasted
294 if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, pasteJS(files, data))), &p); err != nil {
295 t.Fatal(err)
296 }
297 return p
298}
299
300// clearChips removes every chip, as a person would.
301func clearChips(t *testing.T, rig *harness.Rig) {
302 t.Helper()
303 harness.Evaluate[bool](rig, `(() => { document.querySelectorAll("#ask-panel .chip-remove").forEach((b) => b.click()); return true; })()`)
304 waitChips(t, rig, "cleared", func(c []chip) bool { return len(c) == 0 })
305}
306
307// A paste with files and no words of its own attaches them; a paste with
308// words pastes the words and attaches nothing (Fable B5, B8).
309func TestAskAttachPaste(t *testing.T) {
310 rig, _ := attachReady(t)
311 // A screenshot alone attaches, and types nothing.
312 if p := paste(t, rig, []string{"png"}, nil); !p.Prevented || p.Value != "" {
313 t.Fatalf("screenshot: %+v", p)
314 }
315 waitChips(t, rig, "done", allDone(1))
316 clearChips(t, rig)
317 // A file copied in the Finder, as a browser may hand it over with its
318 // name as text, attaches, and its name is not typed.
319 if p := paste(t, rig, []string{"md"}, map[string]string{"text/plain": "Quarterly notes.md"}); !p.Prevented || p.Value != "" {
320 t.Fatalf("finder file: %+v", p)
321 }
322 if c := waitChips(t, rig, "done", allDone(1)); c[0].Name != "Quarterly notes.md" {
323 t.Fatalf("finder file chip: %+v", c)
324 }
325 clearChips(t, rig)
326 // Copy Image in a browser: an image and HTML with no words attaches.
327 if p := paste(t, rig, []string{"png"}, map[string]string{"text/html": `<meta charset="utf-8"><img src="https://example.com/a.png">`}); !p.Prevented {
328 t.Fatalf("copied image: %+v", p)
329 }
330 waitChips(t, rig, "done", allDone(1))
331 clearChips(t, rig)
332 // A table from Excel or Numbers comes with a picture of itself: the
333 // table pastes as Markdown, and nothing is attached.
334 table := `<table><tr><td><b>Revenue</b></td><td>120</td></tr></table>`
335 if p := paste(t, rig, []string{"png"}, map[string]string{"text/html": table, "text/plain": "Revenue\t120"}); !p.Prevented || !strings.Contains(p.Value, "**Revenue**") {
336 t.Fatalf("table: %+v", p)
337 }
338 // Words with a picture beside them paste the words (the browser's own
339 // paste: not taken here).
340 if p := paste(t, rig, []string{"png"}, map[string]string{"text/plain": "Quarterly notes for Q3"}); p.Prevented {
341 t.Fatalf("words: %+v", p)
342 }
343 time.Sleep(300 * time.Millisecond)
344 if c := chipsOf(t, rig); len(c) != 0 {
345 t.Fatalf("words attached a file: %+v", c)
346 }
347}
348
349// Without a runner that takes files there is no paperclip, and paste and
350// drop attach nothing.
351func TestAskAttachNotOffered(t *testing.T) {
352 rig, f := askBase(t)
353 openPanel(t, rig)
354 if harness.Evaluate[bool](rig, `!!document.querySelector("#ask-panel .actions .attach")?.checkVisibility()`) {
355 t.Fatal("a paperclip without can_attach")
356 }
357 if p := paste(t, rig, []string{"png"}, nil); p.Prevented {
358 t.Fatalf("paste: %+v", p)
359 }
360 harness.Evaluate[bool](rig, dropJS(true))
361 time.Sleep(300 * time.Millisecond)
362 if c := chipsOf(t, rig); len(c) != 0 || len(f.Calls("/api/v1/attachments")) != 0 {
363 t.Fatalf("attached without can_attach: %+v", c)
364 }
365}
366
367// dropJS drags a note over the composer and, with release, drops it;
368// it answers whether the outline showed during the drag.
369func dropJS(release bool) string {
370 js := `(() => {
371 const c = document.querySelector("#ask-panel form.composer");
372 const d = new DataTransfer();
373 d.items.add(new File(["dropped"], "dropped.txt", { type: "text/plain" }));
374 const at = c.querySelector("textarea");
375 at.dispatchEvent(new DragEvent("dragenter", { dataTransfer: d, bubbles: true, cancelable: true }));
376 at.dispatchEvent(new DragEvent("dragover", { dataTransfer: d, bubbles: true, cancelable: true }));
377 const shown = c.classList.contains("dropping");`
378 if release {
379 js += `at.dispatchEvent(new DragEvent("drop", { dataTransfer: d, bubbles: true, cancelable: true }));`
380 }
381 return js + `return shown; })()`
382}
383
384// Files dropped on the composer attach; an outline shows during the drag
385// and goes after.
386func TestAskAttachDrop(t *testing.T) {
387 rig, _ := attachReady(t)
388 if !harness.Evaluate[bool](rig, dropJS(false)) {
389 t.Fatal("no outline during the drag")
390 }
391 rig.Screen("#ask-panel", "files dragged over the composer")
392 viewportShot(t, rig, "attach-drop")
393 harness.Evaluate[bool](rig, `(() => { document.querySelector("#ask-panel textarea").dispatchEvent(new DragEvent("dragleave", { bubbles: true })); return true; })()`)
394 harness.Evaluate[bool](rig, dropJS(true))
395 if c := waitChips(t, rig, "done", allDone(1)); c[0].Name != "dropped.txt" {
396 t.Fatalf("chips: %+v", c)
397 }
398 if harness.Evaluate[bool](rig, `document.querySelector("#ask-panel form.composer").classList.contains("dropping")`) {
399 t.Fatal("the outline stayed")
400 }
401}
402
403// A chip shows its upload's progress; Remove once its bytes have gone
404// deletes the upload as it lands, Remove after deletes it; a removed
405// file is never sent. Send waits for uploads, then sends once, in chip
406// order.
407func TestAskAttachProgressAndRemove(t *testing.T) {
408 paths := attachFiles(t)
409 rig, f := attachReady(t)
410 entered, release := f.HoldNextUpload()
411 pick(t, rig, paths["n1.txt"])
412 <-entered
413 c := waitChips(t, rig, "uploading", func(c []chip) bool { return len(c) == 1 && c[0].State == "uploading" })
414 if c[0].Meta != "Uploading…" || c[0].Ring == "" {
415 t.Fatalf("uploading chip: %+v", c)
416 }
417 rig.Screen("#ask-panel", "a file uploading")
418 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .chip-remove`)))
419 waitChips(t, rig, "gone", func(c []chip) bool { return len(c) == 0 })
420 release()
421 deletes := func() int {
422 n := 0
423 for _, c := range f.Calls("") {
424 if c.Method == http.MethodDelete && strings.HasPrefix(c.Path, "/api/v1/attachments/") {
425 n++
426 }
427 }
428 return n
429 }
430 for i := 0; deletes() != 1 || len(f.Uploads()) != 0; i++ {
431 if i > 200 {
432 var calls []string
433 for _, c := range f.Calls("") {
434 calls = append(calls, c.Method+" "+c.Path)
435 }
436 t.Fatalf("the removed upload wasn't deleted: held %v; calls %v", f.Uploads(), calls)
437 }
438 time.Sleep(25 * time.Millisecond)
439 }
440 pick(t, rig, paths["n2.txt"])
441 waitChips(t, rig, "done", allDone(1))
442 held := f.Uploads()[0]
443 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .chip-remove`)))
444 for i := 0; len(f.Uploads()) != 0; i++ {
445 if i > 200 {
446 _, name, _, _, _ := f.Upload(f.Uploads()[0])
447 t.Fatalf("Remove left %v (%s); %d deletes; chips %+v", f.Uploads(), name, deletes(), chipsOf(t, rig))
448 }
449 time.Sleep(25 * time.Millisecond)
450 }
451 if calls := f.Calls("/api/v1/attachments/" + held); len(calls) != 1 || calls[0].Method != http.MethodDelete {
452 t.Fatalf("delete: %+v", calls)
453 }
454 if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("#ask-panel textarea")`) {
455 t.Error("focus didn't go to the field after the last Remove")
456 }
457
458 // Send waits for the uploads.
459 entered, release = f.HoldNextUpload()
460 pick(t, rig, paths["n3.txt"], paths["n4.txt"])
461 <-entered
462 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Both of these"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
463 time.Sleep(300 * time.Millisecond)
464 if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
465 t.Fatalf("sent before the uploads finished: %d", n)
466 }
467 release()
468 waitFor(t, "the send", func() bool { return len(f.Calls("/api/v1/assistant/messages")) == 1 })
469 time.Sleep(200 * time.Millisecond)
470 _, ids := lastSend(t, f)
471 if len(ids) != 2 || len(f.Calls("/api/v1/assistant/messages")) != 1 {
472 t.Fatalf("sent %v", ids)
473 }
474 for i, want := range []string{"n3.txt", "n4.txt"} {
475 if _, name, _, _, _ := f.Upload(ids[i]); name != want {
476 t.Errorf("file %d is %q", i, name)
477 }
478 }
479}
480
481// Five files upload at most two at a time, and a busy answer is tried
482// again by itself (Fable B3).
483func TestAskAttachQueue(t *testing.T) {
484 paths := attachFiles(t)
485 rig, f := attachReady(t)
486 rig.Allow(http.MethodPost, "/ask/attachments", http.StatusServiceUnavailable)
487 f.SlowUploads(250 * time.Millisecond)
488 f.BusyNextUpload()
489 pick(t, rig, paths["n1.txt"], paths["n2.txt"], paths["n3.txt"], paths["n4.txt"], paths["n5.txt"])
490 waitChips(t, rig, "done", allDone(5))
491 if most := f.UploadsAtOnce(); most > 2 {
492 t.Fatalf("%d uploads at once", most)
493 }
494 if n := len(f.Calls("/api/v1/attachments")); n != 6 {
495 t.Fatalf("%d uploads reached Equipo, want 6 (one busy, tried again)", n)
496 }
497}
498
499// Over 10 MB, a sixth file and a HEIC are refused on the chip with no
500// request; Equipo's own refusal shows in its words; each is announced.
501func TestAskAttachRefusals(t *testing.T) {
502 paths := attachFiles(t)
503 rig, f := attachReady(t)
504 rig.Allow(http.MethodPost, "/ask/attachments", http.StatusUnsupportedMediaType)
505 // A file refused while Send waits for it: nothing goes, and the words
506 // stay.
507 entered, release := f.HoldNextUpload()
508 pick(t, rig, paths["data.json"])
509 <-entered
510 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "What's in this?"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
511 release()
512 waitChips(t, rig, "refused", func(c []chip) bool { return len(c) == 1 && c[0].State == "refused" })
513 time.Sleep(300 * time.Millisecond)
514 if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 || harness.Evaluate[string](rig, `document.querySelector("#ask-panel textarea").value`) != "What's in this?" {
515 t.Fatalf("sent without its file: %d", n)
516 }
517 harness.Evaluate[bool](rig, `(() => { document.querySelector("#ask-panel textarea").value = ""; return true; })()`)
518 clearChips(t, rig)
519 pick(t, rig, paths["big.txt"], paths["photo.heic"], paths["data.json"])
520 c := waitChips(t, rig, "settled", func(c []chip) bool {
521 return len(c) == 3 && c[0].State == "refused" && c[1].State == "refused" && c[2].State == "refused"
522 })
523 if c[0].Meta != "This file is over the 10 MB limit." || c[1].Meta != "HEIC photos can’t be read yet. Share it as a JPEG and try again." ||
524 c[2].Meta != "Attach images (PNG, JPEG, WebP or GIF) or text, Markdown, CSV, JSON or PDF files." {
525 t.Fatalf("refusals: %+v", c)
526 }
527 if n := len(f.Calls("/api/v1/attachments")); n != 2 {
528 t.Fatalf("%d uploads reached Equipo, want 2 (the JSON, twice)", n)
529 }
530 waitFor(t, "a refusal announced", func() bool {
531 return harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`) ==
532 "data.json not attached: Attach images (PNG, JPEG, WebP or GIF) or text, Markdown, CSV, JSON or PDF files."
533 })
534 rig.Screen("#ask-panel", "refused files")
535 viewportShot(t, rig, "attach-refused")
536 clearChips(t, rig)
537 pick(t, rig, paths["n1.txt"], paths["n2.txt"], paths["n3.txt"], paths["n4.txt"], paths["n5.txt"], paths["n6.txt"])
538 c = waitChips(t, rig, "settled", func(c []chip) bool { return len(c) == 6 && c[4].State == "done" })
539 if c[5].State != "refused" || c[5].Meta != "You can attach up to 5 files to a message." {
540 t.Fatalf("sixth: %+v", c[5])
541 }
542}
543
544// Files refused at send keep Ask ready (Fable B1, B2): a runner that can't
545// take them takes the paperclip away and says so on the chips, and the
546// words go once they are removed; an expired upload says attach it again;
547// a failed send keeps the chips.
548func TestAskAttachSendRefused(t *testing.T) {
549 paths := attachFiles(t)
550 rig, f := attachReady(t)
551 rig.Allow(http.MethodPost, "/ask/messages", http.StatusConflict)
552 rig.Allow(http.MethodPost, "/ask/messages", http.StatusUnprocessableEntity)
553 pick(t, rig, paths["note.md"])
554 waitChips(t, rig, "done", allDone(1))
555 f.FilesReady(false)
556 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Read this"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
557 c := waitChips(t, rig, "unavailable", func(c []chip) bool { return len(c) == 1 && c[0].State == "unavailable" })
558 if c[0].Meta != "Files can’t be read right now. Remove them to send your message without them." {
559 t.Fatalf("chip: %+v", c)
560 }
561 // Said to a screen reader too (Fable S1).
562 waitFor(t, "the refusal announced", func() bool {
563 return harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`) ==
564 "Files can’t be read right now. Remove them to send your message without them."
565 })
566 if harness.Evaluate[bool](rig, `document.querySelector("#ask-panel .actions .attach").checkVisibility()`) ||
567 harness.Evaluate[string](rig, `document.querySelector("#ask-panel").dataset.state`) != "ready" ||
568 harness.Evaluate[bool](rig, `document.querySelector("#ask-panel [data-when=oldrunner]").checkVisibility()`) ||
569 harness.Evaluate[string](rig, `document.querySelector("#ask-panel textarea").value`) != "Read this" {
570 t.Fatal("refused files took Ask out of ready, kept the paperclip or lost the words")
571 }
572 rig.Screen("#ask-panel", "files refused at send")
573 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .chip-remove`)), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
574 waitFor(t, "the words went", func() bool {
575 text, ids := lastSend(t, f)
576 return text == "Read this" && len(ids) == 0 && len(f.Calls("/api/v1/assistant/messages")) == 2
577 })
578
579 // An expired upload: attach it again.
580 f.FilesReady(true)
581 openPanel(t, rig)
582 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
583 pick(t, rig, paths["n1.txt"])
584 waitChips(t, rig, "done", allDone(1))
585 f.ExpireUploads()
586 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
587 c = waitChips(t, rig, "stale", func(c []chip) bool { return len(c) == 1 && c[0].State == "stale" })
588 if c[0].Meta != "This file has expired. Attach it again." || harness.Evaluate[string](rig, `document.querySelector("#ask-panel .ask-status").textContent`) != "" {
589 t.Fatalf("stale: %+v", c)
590 }
591 waitFor(t, "the expiry announced", func() bool {
592 return harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`) == "This file has expired. Attach it again."
593 })
594 clearChips(t, rig)
595
596 // A send that never arrives keeps its chips.
597 pick(t, rig, paths["n2.txt"])
598 waitChips(t, rig, "done", allDone(1))
599 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Again"))
600 harness.Evaluate[bool](rig, `(() => { const real = window.fetch; window.fetch = (u, o) => String(u).includes("/ask/messages") ? Promise.reject(new TypeError("offline")) : real(u, o); return true; })()`)
601 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
602 drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector("#ask-panel .ask-status").textContent === "That didn't send. Try again."`, chromedp.WithPollingTimeout(5*time.Second)))
603 if c := chipsOf(t, rig); len(c) != 1 || c[0].State != "done" {
604 t.Fatalf("after a failed send: %+v", c)
605 }
606}
607
608// The page's unsent uploads are deleted as it goes, but never those of a
609// send on its way (Fable B7); back from the cache, its chips are gone and
610// its words stay.
611func TestAskAttachBeacon(t *testing.T) {
612 paths := attachFiles(t)
613 rig, f := attachReady(t)
614 pick(t, rig, paths["n1.txt"], paths["n2.txt"])
615 waitChips(t, rig, "done", allDone(2))
616 drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
617 waitFor(t, "the beacon's deletes", func() bool { return len(f.Uploads()) == 0 })
618
619 // A send on its way keeps its files.
620 openPanel(t, rig)
621 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
622 pick(t, rig, paths["n3.txt"])
623 waitChips(t, rig, "done", allDone(1))
624 id := f.Uploads()[0]
625 entered, release := f.HoldNextSend()
626 // Enter twice: the second press neither sends again nor lets go of the
627 // first send's files.
628 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Keep this"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
629 <-entered
630 harness.Evaluate[bool](rig, `(() => { document.querySelector("#ask-panel form.composer").requestSubmit(); return true; })()`)
631 time.Sleep(200 * time.Millisecond)
632 drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
633 time.Sleep(300 * time.Millisecond)
634 release()
635 for i := 0; ; i++ {
636 _, _, _, msg, ok := f.Upload(id)
637 if ok && msg != "" {
638 break
639 }
640 if i > 200 {
641 var calls []string
642 for _, c := range f.Calls("") {
643 calls = append(calls, c.Method+" "+c.Path+" "+c.Body)
644 }
645 t.Fatalf("the message never landed with its file %s (held %v): %v", id, ok, calls[len(calls)-min(len(calls), 8):])
646 }
647 time.Sleep(25 * time.Millisecond)
648 }
649 for _, c := range f.Calls("/api/v1/attachments/" + id) {
650 if c.Method == http.MethodDelete {
651 t.Fatal("the beacon deleted a file of a send on its way")
652 }
653 }
654
655 // Back from the cache: no chips, the words kept.
656 openPanel(t, rig)
657 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
658 pick(t, rig, paths["n4.txt"])
659 waitChips(t, rig, "done", allDone(1))
660 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "half written"))
661 harness.Evaluate[bool](rig, `(() => { dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })); return true; })()`)
662 if c := chipsOf(t, rig); len(c) != 0 || harness.Evaluate[string](rig, `document.querySelector("#ask-panel textarea").value`) != "half written" {
663 t.Fatalf("back from the cache: %+v", c)
664 }
665}
666
667// On a phone the chips are one line that scrolls sideways, and the
668// paperclip is a full 44px target.
669func TestAskAttachMobile(t *testing.T) {
670 paths := attachFiles(t)
671 rig, f, _ := askBaseOn(t, nil, chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3)))
672 f.FilesReady(true)
673 drive(t, rig, chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(`.ask-chat .actions .attach`)))
674 if got := harness.Evaluate[string](rig, `(() => { const b = document.querySelector(".ask-chat .actions .attach"); return b.offsetWidth + "x" + b.offsetHeight; })()`); got != "44x44" {
675 t.Errorf("paperclip %s", got)
676 }
677 drive(t, rig, chromedp.SetUploadFiles(chromedp.CSS(`form.composer input[type=file]`), []string{paths["n1.txt"], paths["n2.txt"], paths["n3.txt"], paths["n4.txt"]}, chromedp.NodeReady))
678 drive(t, rig, chromedp.Poll[chromedp.Void](`[...document.querySelectorAll(".chips .chip")].filter((c) => c.dataset.state === "done").length === 4`, chromedp.WithPollingTimeout(10*time.Second)))
679 if !harness.Evaluate[bool](rig, `(() => { const c = document.querySelector(".chips"); return c.scrollWidth > c.clientWidth && getComputedStyle(c).overflowX === "auto" && c.getBoundingClientRect().height < 70; })()`) {
680 t.Error("the chips don't scroll sideways")
681 }
682 noOverflow(t, rig, "/ask with four chips")
683 mobileShot(t, rig, "attach-mobile")
684}
685
686// A turn that fails for its files says why in the status line, live and
687// read afresh; any other failure keeps its line.
688func TestAskAttachTurnFailures(t *testing.T) {
689 rig, f := attachReady(t)
690 f.Hold = true
691 status := `document.querySelector("#ask-panel .ask-status").textContent`
692 for _, tc := range []struct{ reason, want string }{
693 {"attachment_unavailable", "A file didn’t arrive whole. Attach it again."},
694 {"runner_storage_full", "There’s no room left for these files. Try fewer or smaller ones."},
695 {"runner_too_old", "Files can’t be read right now. Send it again without them."},
696 {"model_error", "That didn't get an answer. Try again."},
697 } {
698 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "about "+tc.reason), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)),
699 chromedp.WaitVisible(chromedp.CSS(`#ask-panel button.stop`)))
700 var id string
701 waitFor(t, "the turn running", func() bool {
702 snap := harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.cancel").getAttribute("action")`)
703 id = strings.TrimSuffix(strings.TrimPrefix(snap, "/ask/turns/"), "/cancel")
704 return id != snap && f.Turn(id) == "running"
705 })
706 f.FailTurnFor(id, tc.reason)
707 drive(t, rig, chromedp.Poll[chromedp.Void](status+` === `+strconv.Quote(tc.want), chromedp.WithPollingTimeout(5*time.Second)))
708 }
709 // Read afresh, a generic failure has no line, and a file's keeps its own.
710 openPanel(t, rig)
711 if got := harness.Evaluate[string](rig, status); got != "" {
712 t.Errorf("read afresh after a generic failure: %q", got)
713 }
714 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "one more"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)),
715 chromedp.WaitVisible(chromedp.CSS(`#ask-panel button.stop`)))
716 action := harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.cancel").getAttribute("action")`)
717 id := strings.TrimSuffix(strings.TrimPrefix(action, "/ask/turns/"), "/cancel")
718 waitFor(t, "the turn running", func() bool { return f.Turn(id) == "running" })
719 f.FailTurnFor(id, "attachment_unavailable")
720 openPanel(t, rig)
721 if got := harness.Evaluate[string](rig, status); got != "A file didn’t arrive whole. Attach it again." {
722 t.Errorf("read afresh after a file's failure: %q", got)
723 }
724}
725