//go:build browser
package browsertest
import (
"bytes"
"encoding/json"
"image"
"image/color"
"image/png"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/kb"
"amadan.net/rastrillo/rastrillo/harness"
"amadan.net/oficina/base/internal/equipo/equipotest"
)
// Files in Ask (plan Task 8): the paperclip, paste, drop, the chips and
// the viewer, against the fake Equipo.
// attachFiles writes the files the tests attach, made here: a 64×48 PNG,
// a note, a PDF, a file Equipo refuses as a type, one over 10 MiB, and a
// HEIC.
func attachFiles(t *testing.T) map[string]string {
t.Helper()
dir := t.TempDir()
img := image.NewNRGBA(image.Rect(0, 0, 64, 48))
for x := 0; x < 64; x++ {
for y := 0; y < 48; y++ {
img.Set(x, y, color.NRGBA{R: uint8(x * 4), G: 160, B: uint8(y * 5), A: 255})
}
}
var shot bytes.Buffer
if err := png.Encode(&shot, img); err != nil {
t.Fatal(err)
}
files := map[string][]byte{
"shot.png": shot.Bytes(),
"note.md": []byte("# Notes\n\nQ3 is up.\n"),
"brief.pdf": []byte("%PDF-1.4\n1 0 obj << >> endobj\ntrailer << >>\n%%EOF\n"),
"data.json": {0x00, 0x01, 0x02, 0xff, 0xfe},
"big.txt": bytes.Repeat([]byte("a"), 10<<20+1),
"photo.heic": append([]byte("\x00\x00\x00\x18ftypheic"), make([]byte, 64)...),
}
out := map[string]string{}
for name, data := range files {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, data, 0o644); err != nil {
t.Fatal(err)
}
out[name] = p
}
for i := 1; i <= 6; i++ {
p := filepath.Join(dir, "n"+strconv.Itoa(i)+".txt")
if err := os.WriteFile(p, []byte("note "+strconv.Itoa(i)), 0o644); err != nil {
t.Fatal(err)
}
out["n"+strconv.Itoa(i)+".txt"] = p
}
return out
}
// attachReady is Ask with a runner that takes files, the panel open and
// its paperclip showing.
func attachReady(t *testing.T) (*harness.Rig, *equipotest.Fake) {
t.Helper()
rig, f := askBase(t)
f.FilesReady(true)
openPanel(t, rig)
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
return rig, f
}
// pick chooses files in the paperclip's picker, as a person would.
func pick(t *testing.T, rig *harness.Rig, paths ...string) {
t.Helper()
drive(t, rig, chromedp.SetUploadFiles(chromedp.CSS(`#ask-panel form.composer input[type=file]`), paths, chromedp.NodeReady))
}
// chip is one chip as the page shows it.
type chip struct {
Name string `json:"name"`
State string `json:"state"`
Meta string `json:"meta"`
Thumb string `json:"thumb"`
Ring string `json:"ring"`
}
const chipsJS = `JSON.stringify([...document.querySelectorAll("#ask-panel .chips .chip")].map((c) => ({
name: c.querySelector(".chip-name").textContent, state: c.dataset.state || "", meta: c.querySelector(".chip-meta").textContent,
thumb: c.querySelector(".chip-mark > img")?.getAttribute("src") || "",
ring: c.querySelector(".chip-ring:not([hidden])")?.getAttribute("aria-valuenow") ?? "" })))`
func chipsOf(t *testing.T, rig *harness.Rig) []chip {
t.Helper()
var out []chip
if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, chipsJS)), &out); err != nil {
t.Fatal(err)
}
return out
}
// waitChips waits until ok holds of the chips.
func waitChips(t *testing.T, rig *harness.Rig, what string, ok func([]chip) bool) []chip {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for {
c := chipsOf(t, rig)
if ok(c) {
return c
}
if time.Now().After(deadline) {
t.Fatalf("chips never %s: %+v", what, c)
}
time.Sleep(40 * time.Millisecond)
}
}
func allDone(n int) func([]chip) bool {
return func(c []chip) bool {
if len(c) != n {
return false
}
for _, x := range c {
if x.State != "done" {
return false
}
}
return true
}
}
// lastSend is the attachments and text of the newest message Equipo was
// sent.
func lastSend(t *testing.T, f *equipotest.Fake) (text string, files []string) {
t.Helper()
calls := f.Calls("/api/v1/assistant/messages")
if len(calls) == 0 {
t.Fatal("nothing was sent")
}
var in struct {
Text string `json:"text"`
Attachments []string `json:"attachments"`
}
if err := json.Unmarshal([]byte(calls[len(calls)-1].Body), &in); err != nil {
t.Fatal(err)
}
return in.Text, in.Attachments
}
func waitFor(t *testing.T, what string, ok func() bool) {
t.Helper()
for i := 0; !ok(); i++ {
if i > 400 {
t.Fatalf("never %s", what)
}
time.Sleep(25 * time.Millisecond)
}
}
// The paperclip picks files; each uploads as a chip, an image's chip shows
// its thumbnail from Base, a PDF's says Ask can't read it yet; Send sends
// them in chip order with the words, and the thread shows them as the
// server draws them. A thumbnail opens the viewer, which holds focus
// until Escape gives it back.
func TestAskAttachPicker(t *testing.T) {
paths := attachFiles(t)
rig, f := attachReady(t)
rig.Screen("#ask-panel", "Ask with the paperclip")
pick(t, rig, paths["shot.png"], paths["note.md"], paths["brief.pdf"])
c := waitChips(t, rig, "done", allDone(3))
if c[0].Name != "shot.png" || !strings.HasPrefix(c[0].Thumb, "/ask/attachments/at_") || !strings.HasSuffix(c[0].Thumb, "/preview") ||
c[2].Meta != "Ask can’t read PDFs yet." || c[1].Thumb != "" {
t.Fatalf("chips: %+v", c)
}
waitFor(t, "an upload announced", func() bool {
return strings.HasSuffix(harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`), " attached")
})
rig.Screen("#ask-panel", "three files attached")
viewportShot(t, rig, "attach-chips")
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "What do these say?"),
chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
waitChips(t, rig, "cleared", func(c []chip) bool { return len(c) == 0 })
text, ids := lastSend(t, f)
uploads := f.Uploads()
if text != "What do these say?" || len(ids) != 3 || len(uploads) != 3 {
t.Fatalf("sent %q %v; Equipo holds %v", text, ids, uploads)
}
for i, want := range []string{"shot.png", "note.md", "brief.pdf"} {
if _, name, _, msg, ok := f.Upload(ids[i]); !ok || name != want || msg == "" {
t.Errorf("file %d: %q sent with %q", i, name, msg)
}
}
_, _, _, sentIn, _ := f.Upload(ids[0])
row := `#ask-panel .thread li.msg.person[data-id='` + sentIn + `'] .files`
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(row+` a.thumb img`)))
got := harness.Evaluate[string](rig, `document.querySelector("`+row+`").outerHTML`)
for _, want := range []string{`
`,
``, `brief.pdf`} {
if !strings.Contains(got, want) {
t.Errorf("thread row lacks %s:\n%s", want, got)
}
}
if !harness.Evaluate[bool](rig, `document.querySelector("`+row+` a.thumb img").naturalWidth === 64`) {
t.Error("the thumbnail didn't load from Base")
}
rig.Screen("#ask-panel", "the message with its files")
viewportShot(t, rig, "attach-thread")
// The viewer.
drive(t, rig, chromedp.Click(chromedp.CSS(row+` a.thumb`)), chromedp.WaitVisible(chromedp.CSS(`dialog.viewer img`)))
if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("dialog.viewer .viewer-close") && document.querySelector("dialog.viewer").open`) {
t.Fatal("the viewer didn't take focus")
}
if !harness.Evaluate[bool](rig, `document.querySelector("dialog.viewer img").getAttribute("src") === "/ask/attachments/`+ids[0]+`"`) {
t.Error("the viewer isn't showing the image")
}
rig.Screen("body", "the viewer")
viewportShot(t, rig, "attach-viewer")
drive(t, rig, chromedp.KeyEvent(kb.Tab), chromedp.KeyEvent(kb.Tab))
if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("dialog.viewer .viewer-close")`) {
t.Error("Tab left the viewer")
}
drive(t, rig, chromedp.KeyEvent(kb.Escape))
waitFor(t, "the viewer closed", func() bool { return !harness.Evaluate[bool](rig, `document.querySelector("dialog.viewer").open`) })
if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("`+row+` a.thumb")`) {
t.Error("focus didn't go back to the thumbnail")
}
// Files with no words send, once the answer is in.
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel button.attach`)))
waitFor(t, "the turn ended", func() bool {
return harness.Evaluate[bool](rig, `document.querySelector("#ask-panel button.stop").hidden`)
})
pick(t, rig, paths["note.md"])
waitChips(t, rig, "done", allDone(1))
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
waitChips(t, rig, "cleared", func(c []chip) bool { return len(c) == 0 })
if text, ids := lastSend(t, f); text != "" || len(ids) != 1 {
t.Fatalf("files alone: %q %v", text, ids)
}
// The Ask page has the paperclip too.
drive(t, rig, chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(`.ask-chat .actions .attach`)))
rig.Screen("main", "the Ask page with the paperclip")
}
// pasteJS dispatches a paste into the field carrying files (made here:
// "png" a tiny PNG named shot.png, "md" a note named Quarterly notes.md)
// and text of each type given, and answers whether the page took it and
// what the field holds after.
func pasteJS(files []string, data map[string]string) string {
var b strings.Builder
b.WriteString(`(() => {
const f = document.querySelector("#ask-panel textarea");
f.focus(); f.value = "";
const d = new DataTransfer();
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="), (c) => c.charCodeAt(0));`)
for _, f := range files {
switch f {
case "png":
b.WriteString(`d.items.add(new File([png], "shot.png", { type: "image/png" }));`)
case "md":
b.WriteString(`d.items.add(new File(["# Q3"], "Quarterly notes.md", { type: "text/markdown" }));`)
}
}
for typ, v := range data {
b.WriteString(`d.setData(` + strconv.Quote(typ) + `, ` + strconv.Quote(v) + `);`)
}
b.WriteString(`const e = new ClipboardEvent("paste", { clipboardData: d, bubbles: true, cancelable: true });
f.dispatchEvent(e);
return JSON.stringify({ prevented: e.defaultPrevented, value: f.value });
})()`)
return b.String()
}
type pasted struct {
Prevented bool `json:"prevented"`
Value string `json:"value"`
}
func paste(t *testing.T, rig *harness.Rig, files []string, data map[string]string) pasted {
t.Helper()
var p pasted
if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, pasteJS(files, data))), &p); err != nil {
t.Fatal(err)
}
return p
}
// clearChips removes every chip, as a person would.
func clearChips(t *testing.T, rig *harness.Rig) {
t.Helper()
harness.Evaluate[bool](rig, `(() => { document.querySelectorAll("#ask-panel .chip-remove").forEach((b) => b.click()); return true; })()`)
waitChips(t, rig, "cleared", func(c []chip) bool { return len(c) == 0 })
}
// A paste with files and no words of its own attaches them; a paste with
// words pastes the words and attaches nothing (Fable B5, B8).
func TestAskAttachPaste(t *testing.T) {
rig, _ := attachReady(t)
// A screenshot alone attaches, and types nothing.
if p := paste(t, rig, []string{"png"}, nil); !p.Prevented || p.Value != "" {
t.Fatalf("screenshot: %+v", p)
}
waitChips(t, rig, "done", allDone(1))
clearChips(t, rig)
// A file copied in the Finder, as a browser may hand it over with its
// name as text, attaches, and its name is not typed.
if p := paste(t, rig, []string{"md"}, map[string]string{"text/plain": "Quarterly notes.md"}); !p.Prevented || p.Value != "" {
t.Fatalf("finder file: %+v", p)
}
if c := waitChips(t, rig, "done", allDone(1)); c[0].Name != "Quarterly notes.md" {
t.Fatalf("finder file chip: %+v", c)
}
clearChips(t, rig)
// Copy Image in a browser: an image and HTML with no words attaches.
if p := paste(t, rig, []string{"png"}, map[string]string{"text/html": `
`}); !p.Prevented {
t.Fatalf("copied image: %+v", p)
}
waitChips(t, rig, "done", allDone(1))
clearChips(t, rig)
// A table from Excel or Numbers comes with a picture of itself: the
// table pastes as Markdown, and nothing is attached.
table := `
`
if p := paste(t, rig, []string{"png"}, map[string]string{"text/html": table, "text/plain": "Revenue\t120"}); !p.Prevented || !strings.Contains(p.Value, "**Revenue**") {
t.Fatalf("table: %+v", p)
}
// Words with a picture beside them paste the words (the browser's own
// paste: not taken here).
if p := paste(t, rig, []string{"png"}, map[string]string{"text/plain": "Quarterly notes for Q3"}); p.Prevented {
t.Fatalf("words: %+v", p)
}
time.Sleep(300 * time.Millisecond)
if c := chipsOf(t, rig); len(c) != 0 {
t.Fatalf("words attached a file: %+v", c)
}
}
// Without a runner that takes files there is no paperclip, and paste and
// drop attach nothing.
func TestAskAttachNotOffered(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
if harness.Evaluate[bool](rig, `!!document.querySelector("#ask-panel .actions .attach")?.checkVisibility()`) {
t.Fatal("a paperclip without can_attach")
}
if p := paste(t, rig, []string{"png"}, nil); p.Prevented {
t.Fatalf("paste: %+v", p)
}
harness.Evaluate[bool](rig, dropJS(true))
time.Sleep(300 * time.Millisecond)
if c := chipsOf(t, rig); len(c) != 0 || len(f.Calls("/api/v1/attachments")) != 0 {
t.Fatalf("attached without can_attach: %+v", c)
}
}
// dropJS drags a note over the composer and, with release, drops it;
// it answers whether the outline showed during the drag.
func dropJS(release bool) string {
js := `(() => {
const c = document.querySelector("#ask-panel form.composer");
const d = new DataTransfer();
d.items.add(new File(["dropped"], "dropped.txt", { type: "text/plain" }));
const at = c.querySelector("textarea");
at.dispatchEvent(new DragEvent("dragenter", { dataTransfer: d, bubbles: true, cancelable: true }));
at.dispatchEvent(new DragEvent("dragover", { dataTransfer: d, bubbles: true, cancelable: true }));
const shown = c.classList.contains("dropping");`
if release {
js += `at.dispatchEvent(new DragEvent("drop", { dataTransfer: d, bubbles: true, cancelable: true }));`
}
return js + `return shown; })()`
}
// Files dropped on the composer attach; an outline shows during the drag
// and goes after.
func TestAskAttachDrop(t *testing.T) {
rig, _ := attachReady(t)
if !harness.Evaluate[bool](rig, dropJS(false)) {
t.Fatal("no outline during the drag")
}
rig.Screen("#ask-panel", "files dragged over the composer")
viewportShot(t, rig, "attach-drop")
harness.Evaluate[bool](rig, `(() => { document.querySelector("#ask-panel textarea").dispatchEvent(new DragEvent("dragleave", { bubbles: true })); return true; })()`)
harness.Evaluate[bool](rig, dropJS(true))
if c := waitChips(t, rig, "done", allDone(1)); c[0].Name != "dropped.txt" {
t.Fatalf("chips: %+v", c)
}
if harness.Evaluate[bool](rig, `document.querySelector("#ask-panel form.composer").classList.contains("dropping")`) {
t.Fatal("the outline stayed")
}
}
// A chip shows its upload's progress; Remove once its bytes have gone
// deletes the upload as it lands, Remove after deletes it; a removed
// file is never sent. Send waits for uploads, then sends once, in chip
// order.
func TestAskAttachProgressAndRemove(t *testing.T) {
paths := attachFiles(t)
rig, f := attachReady(t)
entered, release := f.HoldNextUpload()
pick(t, rig, paths["n1.txt"])
<-entered
c := waitChips(t, rig, "uploading", func(c []chip) bool { return len(c) == 1 && c[0].State == "uploading" })
if c[0].Meta != "Uploading…" || c[0].Ring == "" {
t.Fatalf("uploading chip: %+v", c)
}
rig.Screen("#ask-panel", "a file uploading")
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .chip-remove`)))
waitChips(t, rig, "gone", func(c []chip) bool { return len(c) == 0 })
release()
deletes := func() int {
n := 0
for _, c := range f.Calls("") {
if c.Method == http.MethodDelete && strings.HasPrefix(c.Path, "/api/v1/attachments/") {
n++
}
}
return n
}
for i := 0; deletes() != 1 || len(f.Uploads()) != 0; i++ {
if i > 200 {
var calls []string
for _, c := range f.Calls("") {
calls = append(calls, c.Method+" "+c.Path)
}
t.Fatalf("the removed upload wasn't deleted: held %v; calls %v", f.Uploads(), calls)
}
time.Sleep(25 * time.Millisecond)
}
pick(t, rig, paths["n2.txt"])
waitChips(t, rig, "done", allDone(1))
held := f.Uploads()[0]
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .chip-remove`)))
for i := 0; len(f.Uploads()) != 0; i++ {
if i > 200 {
_, name, _, _, _ := f.Upload(f.Uploads()[0])
t.Fatalf("Remove left %v (%s); %d deletes; chips %+v", f.Uploads(), name, deletes(), chipsOf(t, rig))
}
time.Sleep(25 * time.Millisecond)
}
if calls := f.Calls("/api/v1/attachments/" + held); len(calls) != 1 || calls[0].Method != http.MethodDelete {
t.Fatalf("delete: %+v", calls)
}
if !harness.Evaluate[bool](rig, `document.activeElement === document.querySelector("#ask-panel textarea")`) {
t.Error("focus didn't go to the field after the last Remove")
}
// Send waits for the uploads.
entered, release = f.HoldNextUpload()
pick(t, rig, paths["n3.txt"], paths["n4.txt"])
<-entered
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Both of these"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
time.Sleep(300 * time.Millisecond)
if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
t.Fatalf("sent before the uploads finished: %d", n)
}
release()
waitFor(t, "the send", func() bool { return len(f.Calls("/api/v1/assistant/messages")) == 1 })
time.Sleep(200 * time.Millisecond)
_, ids := lastSend(t, f)
if len(ids) != 2 || len(f.Calls("/api/v1/assistant/messages")) != 1 {
t.Fatalf("sent %v", ids)
}
for i, want := range []string{"n3.txt", "n4.txt"} {
if _, name, _, _, _ := f.Upload(ids[i]); name != want {
t.Errorf("file %d is %q", i, name)
}
}
}
// Five files upload at most two at a time, and a busy answer is tried
// again by itself (Fable B3).
func TestAskAttachQueue(t *testing.T) {
paths := attachFiles(t)
rig, f := attachReady(t)
rig.Allow(http.MethodPost, "/ask/attachments", http.StatusServiceUnavailable)
f.SlowUploads(250 * time.Millisecond)
f.BusyNextUpload()
pick(t, rig, paths["n1.txt"], paths["n2.txt"], paths["n3.txt"], paths["n4.txt"], paths["n5.txt"])
waitChips(t, rig, "done", allDone(5))
if most := f.UploadsAtOnce(); most > 2 {
t.Fatalf("%d uploads at once", most)
}
if n := len(f.Calls("/api/v1/attachments")); n != 6 {
t.Fatalf("%d uploads reached Equipo, want 6 (one busy, tried again)", n)
}
}
// Over 10 MB, a sixth file and a HEIC are refused on the chip with no
// request; Equipo's own refusal shows in its words; each is announced.
func TestAskAttachRefusals(t *testing.T) {
paths := attachFiles(t)
rig, f := attachReady(t)
rig.Allow(http.MethodPost, "/ask/attachments", http.StatusUnsupportedMediaType)
// A file refused while Send waits for it: nothing goes, and the words
// stay.
entered, release := f.HoldNextUpload()
pick(t, rig, paths["data.json"])
<-entered
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "What's in this?"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
release()
waitChips(t, rig, "refused", func(c []chip) bool { return len(c) == 1 && c[0].State == "refused" })
time.Sleep(300 * time.Millisecond)
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?" {
t.Fatalf("sent without its file: %d", n)
}
harness.Evaluate[bool](rig, `(() => { document.querySelector("#ask-panel textarea").value = ""; return true; })()`)
clearChips(t, rig)
pick(t, rig, paths["big.txt"], paths["photo.heic"], paths["data.json"])
c := waitChips(t, rig, "settled", func(c []chip) bool {
return len(c) == 3 && c[0].State == "refused" && c[1].State == "refused" && c[2].State == "refused"
})
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." ||
c[2].Meta != "Attach images (PNG, JPEG, WebP or GIF) or text, Markdown, CSV, JSON or PDF files." {
t.Fatalf("refusals: %+v", c)
}
if n := len(f.Calls("/api/v1/attachments")); n != 2 {
t.Fatalf("%d uploads reached Equipo, want 2 (the JSON, twice)", n)
}
waitFor(t, "a refusal announced", func() bool {
return harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`) ==
"data.json not attached: Attach images (PNG, JPEG, WebP or GIF) or text, Markdown, CSV, JSON or PDF files."
})
rig.Screen("#ask-panel", "refused files")
viewportShot(t, rig, "attach-refused")
clearChips(t, rig)
pick(t, rig, paths["n1.txt"], paths["n2.txt"], paths["n3.txt"], paths["n4.txt"], paths["n5.txt"], paths["n6.txt"])
c = waitChips(t, rig, "settled", func(c []chip) bool { return len(c) == 6 && c[4].State == "done" })
if c[5].State != "refused" || c[5].Meta != "You can attach up to 5 files to a message." {
t.Fatalf("sixth: %+v", c[5])
}
}
// Files refused at send keep Ask ready (Fable B1, B2): a runner that can't
// take them takes the paperclip away and says so on the chips, and the
// words go once they are removed; an expired upload says attach it again;
// a failed send keeps the chips.
func TestAskAttachSendRefused(t *testing.T) {
paths := attachFiles(t)
rig, f := attachReady(t)
rig.Allow(http.MethodPost, "/ask/messages", http.StatusConflict)
rig.Allow(http.MethodPost, "/ask/messages", http.StatusUnprocessableEntity)
pick(t, rig, paths["note.md"])
waitChips(t, rig, "done", allDone(1))
f.FilesReady(false)
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Read this"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
c := waitChips(t, rig, "unavailable", func(c []chip) bool { return len(c) == 1 && c[0].State == "unavailable" })
if c[0].Meta != "Files can’t be read right now. Remove them to send your message without them." {
t.Fatalf("chip: %+v", c)
}
// Said to a screen reader too (Fable S1).
waitFor(t, "the refusal announced", func() bool {
return harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`) ==
"Files can’t be read right now. Remove them to send your message without them."
})
if harness.Evaluate[bool](rig, `document.querySelector("#ask-panel .actions .attach").checkVisibility()`) ||
harness.Evaluate[string](rig, `document.querySelector("#ask-panel").dataset.state`) != "ready" ||
harness.Evaluate[bool](rig, `document.querySelector("#ask-panel [data-when=oldrunner]").checkVisibility()`) ||
harness.Evaluate[string](rig, `document.querySelector("#ask-panel textarea").value`) != "Read this" {
t.Fatal("refused files took Ask out of ready, kept the paperclip or lost the words")
}
rig.Screen("#ask-panel", "files refused at send")
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .chip-remove`)), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
waitFor(t, "the words went", func() bool {
text, ids := lastSend(t, f)
return text == "Read this" && len(ids) == 0 && len(f.Calls("/api/v1/assistant/messages")) == 2
})
// An expired upload: attach it again.
f.FilesReady(true)
openPanel(t, rig)
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
pick(t, rig, paths["n1.txt"])
waitChips(t, rig, "done", allDone(1))
f.ExpireUploads()
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
c = waitChips(t, rig, "stale", func(c []chip) bool { return len(c) == 1 && c[0].State == "stale" })
if c[0].Meta != "This file has expired. Attach it again." || harness.Evaluate[string](rig, `document.querySelector("#ask-panel .ask-status").textContent`) != "" {
t.Fatalf("stale: %+v", c)
}
waitFor(t, "the expiry announced", func() bool {
return harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.composer [aria-live]").textContent`) == "This file has expired. Attach it again."
})
clearChips(t, rig)
// A send that never arrives keeps its chips.
pick(t, rig, paths["n2.txt"])
waitChips(t, rig, "done", allDone(1))
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Again"))
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; })()`)
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
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)))
if c := chipsOf(t, rig); len(c) != 1 || c[0].State != "done" {
t.Fatalf("after a failed send: %+v", c)
}
}
// The page's unsent uploads are deleted as it goes, but never those of a
// send on its way (Fable B7); back from the cache, its chips are gone and
// its words stay.
func TestAskAttachBeacon(t *testing.T) {
paths := attachFiles(t)
rig, f := attachReady(t)
pick(t, rig, paths["n1.txt"], paths["n2.txt"])
waitChips(t, rig, "done", allDone(2))
drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
waitFor(t, "the beacon's deletes", func() bool { return len(f.Uploads()) == 0 })
// A send on its way keeps its files.
openPanel(t, rig)
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
pick(t, rig, paths["n3.txt"])
waitChips(t, rig, "done", allDone(1))
id := f.Uploads()[0]
entered, release := f.HoldNextSend()
// Enter twice: the second press neither sends again nor lets go of the
// first send's files.
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Keep this"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
<-entered
harness.Evaluate[bool](rig, `(() => { document.querySelector("#ask-panel form.composer").requestSubmit(); return true; })()`)
time.Sleep(200 * time.Millisecond)
drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
time.Sleep(300 * time.Millisecond)
release()
for i := 0; ; i++ {
_, _, _, msg, ok := f.Upload(id)
if ok && msg != "" {
break
}
if i > 200 {
var calls []string
for _, c := range f.Calls("") {
calls = append(calls, c.Method+" "+c.Path+" "+c.Body)
}
t.Fatalf("the message never landed with its file %s (held %v): %v", id, ok, calls[len(calls)-min(len(calls), 8):])
}
time.Sleep(25 * time.Millisecond)
}
for _, c := range f.Calls("/api/v1/attachments/" + id) {
if c.Method == http.MethodDelete {
t.Fatal("the beacon deleted a file of a send on its way")
}
}
// Back from the cache: no chips, the words kept.
openPanel(t, rig)
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(`#ask-panel .actions .attach`)))
pick(t, rig, paths["n4.txt"])
waitChips(t, rig, "done", allDone(1))
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "half written"))
harness.Evaluate[bool](rig, `(() => { dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })); return true; })()`)
if c := chipsOf(t, rig); len(c) != 0 || harness.Evaluate[string](rig, `document.querySelector("#ask-panel textarea").value`) != "half written" {
t.Fatalf("back from the cache: %+v", c)
}
}
// On a phone the chips are one line that scrolls sideways, and the
// paperclip is a full 44px target.
func TestAskAttachMobile(t *testing.T) {
paths := attachFiles(t)
rig, f, _ := askBaseOn(t, nil, chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3)))
f.FilesReady(true)
drive(t, rig, chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(`.ask-chat .actions .attach`)))
if got := harness.Evaluate[string](rig, `(() => { const b = document.querySelector(".ask-chat .actions .attach"); return b.offsetWidth + "x" + b.offsetHeight; })()`); got != "44x44" {
t.Errorf("paperclip %s", got)
}
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))
drive(t, rig, chromedp.Poll[chromedp.Void](`[...document.querySelectorAll(".chips .chip")].filter((c) => c.dataset.state === "done").length === 4`, chromedp.WithPollingTimeout(10*time.Second)))
if !harness.Evaluate[bool](rig, `(() => { const c = document.querySelector(".chips"); return c.scrollWidth > c.clientWidth && getComputedStyle(c).overflowX === "auto" && c.getBoundingClientRect().height < 70; })()`) {
t.Error("the chips don't scroll sideways")
}
noOverflow(t, rig, "/ask with four chips")
mobileShot(t, rig, "attach-mobile")
}
// A turn that fails for its files says why in the status line, live and
// read afresh; any other failure keeps its line.
func TestAskAttachTurnFailures(t *testing.T) {
rig, f := attachReady(t)
f.Hold = true
status := `document.querySelector("#ask-panel .ask-status").textContent`
for _, tc := range []struct{ reason, want string }{
{"attachment_unavailable", "A file didn’t arrive whole. Attach it again."},
{"runner_storage_full", "There’s no room left for these files. Try fewer or smaller ones."},
{"runner_too_old", "Files can’t be read right now. Send it again without them."},
{"model_error", "That didn't get an answer. Try again."},
} {
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "about "+tc.reason), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)),
chromedp.WaitVisible(chromedp.CSS(`#ask-panel button.stop`)))
var id string
waitFor(t, "the turn running", func() bool {
snap := harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.cancel").getAttribute("action")`)
id = strings.TrimSuffix(strings.TrimPrefix(snap, "/ask/turns/"), "/cancel")
return id != snap && f.Turn(id) == "running"
})
f.FailTurnFor(id, tc.reason)
drive(t, rig, chromedp.Poll[chromedp.Void](status+` === `+strconv.Quote(tc.want), chromedp.WithPollingTimeout(5*time.Second)))
}
// Read afresh, a generic failure has no line, and a file's keeps its own.
openPanel(t, rig)
if got := harness.Evaluate[string](rig, status); got != "" {
t.Errorf("read afresh after a generic failure: %q", got)
}
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "one more"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)),
chromedp.WaitVisible(chromedp.CSS(`#ask-panel button.stop`)))
action := harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.cancel").getAttribute("action")`)
id := strings.TrimSuffix(strings.TrimPrefix(action, "/ask/turns/"), "/cancel")
waitFor(t, "the turn running", func() bool { return f.Turn(id) == "running" })
f.FailTurnFor(id, "attachment_unavailable")
openPanel(t, rig)
if got := harness.Evaluate[string](rig, status); got != "A file didn’t arrive whole. Attach it again." {
t.Errorf("read afresh after a file's failure: %q", got)
}
}