oficina / base Public

The composer attaches files: paperclip, paste, drop, chips, viewer (Task 8)

Human

Prompt

Build Base's half of files in Ask, slice 1, task by task from the approved plan, tests first; fold in B7 and B8.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

ask-attach.js (imported by ask.js from the composer's data-attach): the paperclip and picker, paste (files attach only with no words of their own: B5, B8), drop with an outline, chips with progress, two uploads at a time with 503s retried after Retry-After, client-side refusals of size, count and HEIC, Remove (aborts or deletes), the discard beacon that skips a send in flight and pageshow-persisted clearing (B7), the thread's files row and a modal viewer. ask.js hooks: send waits for uploads and carries ids, files-only sends, unavailable and stale answers on the chips, keepalive for a send with files. Words from data-w-* on the composer. Browser tests for each.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 10bc21d89f5c633b6638ef4e4fb282c92d399de6 parent befeef8
5 files changed, +1,246 −8
  • internal/browsertest/attach_test.go +622 −0
  • internal/look/static/app.css +47 −0
  • internal/look/static/ask-attach.js +507 −0
  • internal/look/static/ask.js +69 −7
  • internal/web/templates/partials/chat.html +1 −1
diff --git a/internal/browsertest/attach_test.go b/internal/browsertest/attach_test.go
new file mode 100644
index 0000000..ffd6853
--- /dev/null
+++ b/internal/browsertest/attach_test.go
@@ -0,0 +1,622 @@
+//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{`<a class="thumb" href="/ask/attachments/` + ids[0] + `" data-attachment="` + ids[0] + `"><img src="/ask/attachments/` + ids[0] + `/preview" alt="shot.png" width="64" height="48"></a>`,
+ `<a class="file" href="/ask/attachments/` + ids[1] + `" download="" aria-label="note.md, 19 B. Download">`, `<span class="file-name">brief.pdf</span>`} {
+ 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": `<meta charset="utf-8"><img src="https://example.com/a.png">`}); !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 := `<table><tr><td><b>Revenue</b></td><td>120</td></tr></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 during the upload aborts it
+// (and Base deletes what Equipo took), 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()
+ waitFor(t, "Base deleted the aborted upload", func() bool { return len(f.Uploads()) == 0 && len(f.Calls("/api/v1/attachments")) == 1 })
+ 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`)))
+ waitFor(t, "Remove deleted the upload", func() bool { return len(f.Uploads()) == 0 })
+ 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)
+ 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 != "That file is over 10 MB." || c[1].Meta != "HEIC photos can't be read yet. Share it as a JPEG and try again." ||
+ c[2].Meta != "Ask takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON and PDF files." {
+ t.Fatalf("refusals: %+v", c)
+ }
+ if n := len(f.Calls("/api/v1/attachments")); n != 1 {
+ t.Fatalf("%d uploads reached Equipo, want 1 (the JSON)", 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: Ask takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON and 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 != "At most 5 files in one 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." {
+ t.Fatalf("chip: %+v", c)
+ }
+ 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)
+ }
+ 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()
+ drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-panel textarea`), "Keep this"), chromedp.Click(chromedp.CSS(`#ask-panel button.send`)))
+ <-entered
+ drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
+ time.Sleep(300 * time.Millisecond)
+ release()
+ waitFor(t, "the message landed with its file", func() bool {
+ _, _, _, msg, ok := f.Upload(id)
+ return ok && msg != ""
+ })
+ 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")
+}
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index a52d5f7..7121d31 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -744,6 +744,50 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt
.composer .send svg { fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }
.composer .stop svg { fill: currentColor; }
@keyframes pop { from { opacity: 0; transform: scale(.6); } }
+/* Files in the composer (ask-attach.js, only with scripts). The paperclip
+ sits left of Send, a quiet glyph in the same 44px target. The chips sit
+ above the field, wrapping (on a phone, one line that scrolls sideways):
+ each a mark (the file's
+ page, a progress ring while it uploads, then an image's thumbnail), its
+ name and a line (its size, Uploading…, or why it won't go), and Remove.
+ Files dragged over the composer outline it, saying they can be dropped. */
+.composer { flex-wrap: wrap; position: relative; }
+.composer .actions .attach { background: none; color: var(--haze); }
+.composer .actions .attach:hover { color: var(--frost); }
+.composer .actions .attach svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
+.chips { flex: 0 0 100%; min-width: 0; display: flex; flex-wrap: wrap; gap: 8px; max-height: 196px; overflow-y: auto; padding: 2px 2px 4px; }
+.chips[hidden] { display: none; }
+.chip { flex: none; display: flex; align-items: center; gap: 8px; max-width: min(220px, 100%); min-height: 48px; padding: 4px 2px 4px 6px; border-radius: 12px;
+ background: var(--chip); box-shadow: inset 0 0 0 1px var(--chip-edge); }
+.chip.bad { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--st-stop) 70%, transparent); max-width: min(300px, 100%); }
+.chip-mark { position: relative; flex: none; width: 36px; height: 36px; border-radius: 8px; display: grid; place-items: center; overflow: hidden; color: var(--haze); }
+.chip-mark > img { width: 100%; height: 100%; object-fit: cover; }
+.chip-mark .file-mark { width: 20px; height: 20px; }
+.chip-ring { position: absolute; inset: 0; display: grid; place-items: center; background: color-mix(in srgb, var(--chip) 70%, transparent); }
+.chip-ring[hidden] { display: none; }
+.chip-ring svg { width: 30px; height: 30px; transform: rotate(-90deg); }
+.chip-ring circle { fill: none; stroke-width: 2.4; }
+.chip-ring .track { stroke: var(--chip-edge); }
+.chip-ring .arc { stroke: var(--focus); stroke-linecap: round; stroke-dasharray: 0 100; transition: stroke-dasharray .2s; }
+.chip-text { min-width: 0; display: flex; flex-direction: column; line-height: 17px; }
+.chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13.5px; font-weight: 500; }
+.chip-meta { color: var(--haze); font-size: 12px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; white-space: normal; }
+.chip.bad .chip-meta { color: var(--frost); display: block; }
+.chip-remove { flex: none; width: 44px; height: 44px; margin: -4px 0; padding: 0; border: 0; border-radius: 50%; display: grid; place-items: center; cursor: pointer;
+ color: var(--haze); background: none; }
+.chip-remove:hover { color: var(--frost); }
+.chip-remove svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
+.composer.dropping::after { content: attr(data-drop); position: absolute; inset: 4px 8px 8px; border-radius: 14px; display: grid; place-items: center; pointer-events: none;
+ font-size: 14px; font-weight: 600; color: var(--frost); background: color-mix(in srgb, var(--chip) 85%, transparent);
+ outline: 2px dashed var(--focus); outline-offset: -2px; }
+/* The viewer: a thumbnail's image full size, over a dimmed page, with
+ Close. */
+.viewer { max-width: min(92vw, 1200px); max-height: 92vh; padding: 0; border: 0; border-radius: 14px; overflow: visible; background: transparent; }
+.viewer::backdrop { background: rgba(6, 8, 20, .72); }
+.viewer img { display: block; min-width: min(240px, 92vw); max-width: min(92vw, 1200px); max-height: 92vh; border-radius: 14px; object-fit: contain; background: var(--menu-base); }
+.viewer-close { position: fixed; top: 16px; right: 16px; width: 44px; height: 44px; padding: 0; border: 0; border-radius: 50%; display: grid; place-items: center;
+ cursor: pointer; color: #fff; background: rgba(6, 8, 20, .6); }
+.viewer-close svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
/* An edge, not a fill: the composer's focus edge and the thinking bubble's
paint a gradient over their whole box and show it only through this mask,
--ring thick round the box's edge and following its corners (--r-tl,
@@ -901,6 +945,9 @@ main { min-height: 100dvh; }
.jobview[popover]::before { content: ""; display: block; width: 36px; height: 4px; margin: 0 auto 2px; border-radius: 2px; background: var(--rule); transform: translateX(-6px); }
.jobview[popover] .jv-go { width: calc(100% - 12px); justify-content: center; }
.jv-title svg { opacity: 1; }
+ /* The chips are one line that scrolls sideways. */
+ .chips { flex-wrap: nowrap; max-height: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: none; }
+ .chip { max-width: 200px; }
}
/* Phones, beyond Home: the inner pages and /ask. */
diff --git a/internal/look/static/ask-attach.js b/internal/look/static/ask-attach.js
new file mode 100644
index 0000000..2267f15
--- /dev/null
+++ b/internal/look/static/ask-attach.js
@@ -0,0 +1,507 @@
+// Files in Ask: the paperclip, paste and drop, the chips above the field
+// while files upload, and the viewer a thumbnail opens. ask.js imports it
+// (data-attach on the composer) and hooks it in: a send carries the chips'
+// ids, and the thread draws a message's files (filesRow) as the server
+// does (chat.html, ask-files). Without scripts none of this exists: the
+// thread still shows files, and a thumbnail opens the image itself.
+//
+// Base keeps no byte: each file goes to POST /ask/attachments, which
+// relays it to Equipo, and comes back as an id. The server's word is
+// final: only the size, the count and HEIC are refused here first, in its
+// words. Files upload two at a time, in order; a busy answer (503) is
+// tried again after its Retry-After, five times at most. Remove deletes
+// the upload; the page's unsent uploads are deleted as it goes away
+// (a beacon), apart from those of a send still on its way. Text is only
+// ever set with textContent.
+
+const MAX_FILES = 5;
+const MAX_BYTES = 10 << 20;
+const AT_ONCE = 2;
+const RETRIES = 5;
+const ACCEPT = "image/png,image/jpeg,image/webp,image/gif,application/pdf,text/plain,text/markdown,text/csv,application/json,.md,.markdown,.csv,.json,.txt";
+// The page of a file, its corner folded (chat.html, ask-file-mark).
+const FILE_MARK = "M14 3.5H7.5a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2V8zM14 3.5V8h4.5";
+const CLIP = "M20.5 11.5l-8.1 8.1a5 5 0 0 1-7.1-7.1l8.5-8.5a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.5a1.7 1.7 0 0 1-2.4-2.4l7.8-7.8";
+const CROSS = "M7 7l10 10M17 7L7 17";
+
+const svgNS = "http://www.w3.org/2000/svg";
+function icon(d, cls) {
+ const svg = document.createElementNS(svgNS, "svg");
+ svg.setAttribute("viewBox", "0 0 24 24");
+ svg.setAttribute("aria-hidden", "true");
+ if (cls) svg.setAttribute("class", cls);
+ const path = document.createElementNS(svgNS, "path");
+ path.setAttribute("d", d);
+ svg.append(path);
+ return svg;
+}
+function el(tag, cls, text) {
+ const e = document.createElement(tag);
+ if (cls) e.className = cls;
+ if (text !== undefined) e.textContent = text;
+ return e;
+}
+// fill puts values in a sentence's {name}s.
+function fill(s, values) {
+ return s.replace(/\{(\w+)\}/g, (m, k) => (k in values ? values[k] : m));
+}
+const href = (id, preview) => `/ask/attachments/${encodeURIComponent(id)}${preview ? "/preview" : ""}`;
+
+// fileSize is a size as the server writes it (ask_files.go, fileSize):
+// bytes, whole KB, then MB to one place, half up, 1024 to the K, in the
+// page's locale.
+export function fileSize(n) {
+ const lang = document.documentElement.lang || "en";
+ const whole = new Intl.NumberFormat(lang);
+ if (n < 1024) return whole.format(Math.max(n, 0)) + " B";
+ if (n < 1048576) return whole.format(Math.floor((n + 512) / 1024)) + " KB";
+ const tenths = Math.floor((n * 10 + 524288) / 1048576);
+ return new Intl.NumberFormat(lang, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(tenths / 10) + " MB";
+}
+
+// filesRow is a message's files as chat.html's ask-files draws them:
+// thumbnails, then a pill per other file. words are the composer's.
+export function filesRow(list, words) {
+ const row = el("div", "files");
+ row.setAttribute("role", "group");
+ row.setAttribute("aria-label", words.files);
+ for (const a of list) {
+ if (a.kind !== "image") continue;
+ const link = el("a", "thumb");
+ link.href = href(a.id);
+ link.dataset.attachment = a.id;
+ const img = document.createElement("img");
+ img.src = href(a.id, true);
+ img.alt = a.name;
+ if (a.width && a.height) {
+ img.width = a.width;
+ img.height = a.height;
+ }
+ link.append(img);
+ row.append(link);
+ }
+ for (const a of list) {
+ if (a.kind === "image") continue;
+ const link = el("a", "file");
+ link.href = href(a.id);
+ link.setAttribute("download", "");
+ const size = fileSize(a.size);
+ link.setAttribute("aria-label", fill(words.pill, { name: a.name, size }));
+ link.append(icon(FILE_MARK, "file-mark"), el("span", "file-name", a.name), el("span", "file-size", size));
+ row.append(link);
+ }
+ return row;
+}
+
+// wordsOf reads the composer's data-w-* words.
+export function wordsOf(composer) {
+ const out = {};
+ for (const [k, v] of Object.entries(composer.dataset)) {
+ if (k.startsWith("w") && k.length > 1 && k[1] === k[1].toUpperCase()) out[k[1].toLowerCase() + k.slice(2)] = v;
+ }
+ return out;
+}
+
+// What Equipo's refusals say, by code.
+const refusals = {
+ attachment_too_large: "tooLarge", attachment_type: "type", attachment_heic: "heic",
+ attachment_pixels: "pixels", attachment_limit: "limit", busy: "busy",
+};
+
+// attach wires files into the composer of root. hooks:
+// changed() the chips changed (Send may show, or go);
+// lost(state) an upload heard Ask isn't connected (connect, pending,
+// reconnect): the chat shows that state.
+// It answers the composer's side of files:
+// enable(on) can_attach: the paperclip shows, and drop and paste
+// attach, only while on;
+// count() chips that would go with a send;
+// ready() a promise of their ids, in chip order, once every upload
+// has settled;
+// sending(ids, on) a send with ids is on its way (the beacon leaves them);
+// sent(ids) they went: their chips go;
+// refused(why, ids) the send was refused for its files: "unavailable" or
+// "stale", said on their chips;
+// paste(e) a paste with files and no words of its own attaches
+// them (true), else leaves it to the text path (false).
+export function attach(root, hooks) {
+ const composer = root.querySelector("form.composer");
+ const field = composer.querySelector("textarea");
+ const actions = composer.querySelector(".actions");
+ const thread = root.querySelector(".thread");
+ const words = wordsOf(composer);
+ let enabled = false;
+ const items = []; // every chip, in order
+ const inflight = new Set(); // ids of a send on its way
+ let running = 0;
+
+ // The paperclip, left of Send; the picker it opens.
+ const picker = document.createElement("input");
+ picker.type = "file";
+ picker.multiple = true;
+ picker.accept = ACCEPT;
+ picker.hidden = true;
+ picker.tabIndex = -1;
+ picker.setAttribute("aria-hidden", "true");
+ const clip = el("button", "attach");
+ clip.type = "button";
+ clip.hidden = true;
+ clip.setAttribute("aria-label", words.attach);
+ clip.title = words.attach;
+ clip.append(icon(CLIP));
+ actions.prepend(clip);
+ composer.append(picker);
+ clip.addEventListener("click", () => picker.click());
+ picker.addEventListener("change", () => {
+ add([...picker.files]);
+ picker.value = "";
+ });
+
+ // The chips, above the field; a live region for what happens to them.
+ const chips = el("div", "chips");
+ chips.setAttribute("role", "list");
+ chips.setAttribute("aria-label", words.files);
+ chips.hidden = true;
+ composer.prepend(chips);
+ const live = el("p", "sr-only");
+ live.setAttribute("aria-live", "polite");
+ composer.append(live);
+ function announce(text) {
+ live.textContent = "";
+ setTimeout(() => { live.textContent = text; }, 50);
+ }
+
+ function enable(on) {
+ enabled = !!on;
+ clip.hidden = !enabled;
+ if (!enabled) composer.classList.remove("dropping");
+ }
+ enable(composer.hasAttribute("data-can-attach"));
+
+ // A chip's state: queued, uploading, done, or one that won't go
+ // (refused: never uploaded; failed: the upload didn't take; stale: an
+ // upload Equipo no longer has). unavailable is a done chip the runner
+ // couldn't take, which a later send tries again.
+ const goes = (it) => ["queued", "uploading", "done", "unavailable"].includes(it.state);
+ function count() {
+ return items.filter(goes).length;
+ }
+
+ function chipOf(file) {
+ const it = { file, name: file.name || "file", size: file.size, type: file.type, state: "queued", id: "", xhr: null, removed: false, tries: 0 };
+ const li = el("div", "chip");
+ li.setAttribute("role", "listitem");
+ const mark = el("span", "chip-mark");
+ mark.append(icon(FILE_MARK, "file-mark"));
+ const ring = el("span", "chip-ring");
+ ring.setAttribute("role", "progressbar");
+ ring.setAttribute("aria-valuemin", "0");
+ ring.setAttribute("aria-valuemax", "100");
+ ring.setAttribute("aria-valuenow", "0");
+ ring.setAttribute("aria-label", words.uploading);
+ const svg = document.createElementNS(svgNS, "svg");
+ svg.setAttribute("viewBox", "0 0 24 24");
+ svg.setAttribute("aria-hidden", "true");
+ const track = document.createElementNS(svgNS, "circle");
+ const arc = document.createElementNS(svgNS, "circle");
+ for (const c of [track, arc]) {
+ c.setAttribute("cx", "12");
+ c.setAttribute("cy", "12");
+ c.setAttribute("r", "9");
+ }
+ track.setAttribute("class", "track");
+ arc.setAttribute("class", "arc");
+ arc.setAttribute("pathLength", "100");
+ svg.append(track, arc);
+ ring.append(svg);
+ mark.append(ring);
+ const text = el("span", "chip-text");
+ const name = el("span", "chip-name", it.name);
+ const meta = el("span", "chip-meta", fileSize(it.size));
+ text.append(name, meta);
+ const remove = el("button", "chip-remove");
+ remove.type = "button";
+ remove.setAttribute("aria-label", fill(words.remove, { name: it.name }));
+ remove.title = fill(words.remove, { name: it.name });
+ remove.append(icon(CROSS));
+ remove.addEventListener("click", () => drop(it, true));
+ li.append(mark, text, remove);
+ Object.assign(it, { li, mark, ring, arc, meta });
+ return it;
+ }
+
+ // show draws a chip's state, with line under its name (its size when
+ // there is nothing to say).
+ function show(it, state, line) {
+ it.state = state;
+ it.li.dataset.state = state;
+ it.ring.hidden = state !== "uploading" && state !== "queued";
+ it.meta.textContent = line || (state === "uploading" || state === "queued" ? words.uploading : fileSize(it.size));
+ it.li.classList.toggle("bad", ["refused", "failed", "stale", "unavailable"].includes(state));
+ hooks.changed();
+ settle();
+ }
+ function progress(it, pct) {
+ it.ring.setAttribute("aria-valuenow", String(Math.round(pct)));
+ it.arc.style.strokeDasharray = `${pct} 100`;
+ }
+
+ const heic = (f) => /^image\/hei[cf]/i.test(f.type) || /\.hei[cf]$/i.test(f.name || "");
+ const isPDF = (it) => it.type === "application/pdf" || /\.pdf$/i.test(it.name);
+
+ function add(files) {
+ if (!enabled || !files.length) return;
+ for (const file of files) {
+ const it = chipOf(file);
+ items.push(it);
+ chips.append(it.li);
+ let refuse = "";
+ if (items.filter(goes).length > MAX_FILES) refuse = words.tooMany;
+ else if (file.size > MAX_BYTES) refuse = words.tooLarge;
+ else if (heic(file)) refuse = words.heic;
+ if (refuse) {
+ show(it, "refused", refuse);
+ announce(fill(words.notAttached, { name: it.name, reason: refuse }));
+ } else show(it, "queued");
+ }
+ chips.hidden = items.length === 0;
+ chips.lastElementChild?.scrollIntoView?.({ block: "nearest", inline: "end" });
+ pump();
+ }
+
+ // pump starts the next queued uploads, AT_ONCE at a time, in order.
+ function pump() {
+ for (const it of items) {
+ if (running >= AT_ONCE) return;
+ if (it.state === "queued" && !it.waiting) upload(it);
+ }
+ }
+
+ function upload(it) {
+ running++;
+ show(it, "uploading");
+ progress(it, 0);
+ const xhr = new XMLHttpRequest();
+ it.xhr = xhr;
+ xhr.open("POST", "/ask/attachments");
+ xhr.setRequestHeader("Accept", "application/json");
+ xhr.setRequestHeader("Content-Type", it.type || "application/octet-stream");
+ xhr.setRequestHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeURIComponent(it.name).replace(/['()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()));
+ xhr.upload.onprogress = (e) => { if (e.lengthComputable) progress(it, (e.loaded / e.total) * 100); };
+ const finish = () => {
+ running--;
+ it.xhr = null;
+ pump();
+ };
+ xhr.onload = () => {
+ finish();
+ if (it.removed) return;
+ let out = {};
+ try { out = JSON.parse(xhr.responseText); } catch {}
+ if (xhr.status === 201 && out.id) {
+ it.id = out.id;
+ it.kind = out.kind;
+ show(it, "done", isPDF(it) ? words.pdf : "");
+ if (out.kind === "image") {
+ const img = document.createElement("img");
+ img.src = href(out.id, true);
+ img.alt = "";
+ it.mark.replaceChildren(img);
+ }
+ announce(fill(words.attached, { name: it.name }));
+ return;
+ }
+ if (xhr.status === 503 && it.tries < RETRIES) {
+ it.tries++;
+ const after = Math.min(Math.max(Number(xhr.getResponseHeader("Retry-After")) || 2, 1), 10);
+ it.waiting = true;
+ show(it, "queued");
+ setTimeout(() => { it.waiting = false; pump(); }, after * 1000);
+ return;
+ }
+ if (["connect", "pending", "reconnect"].includes(out.state)) hooks.lost(out.state);
+ const reason = words[refusals[out.code]] || words.failed;
+ show(it, refusals[out.code] ? "refused" : "failed", reason);
+ announce(fill(words.notAttached, { name: it.name, reason }));
+ };
+ xhr.onerror = () => {
+ finish();
+ if (it.removed) return;
+ show(it, "failed", words.failed);
+ announce(fill(words.notAttached, { name: it.name, reason: words.failed }));
+ };
+ xhr.onabort = finish;
+ xhr.send(it.file);
+ }
+
+ // drop takes a chip away: Remove aborts its upload, or deletes the
+ // upload it made (Equipo's own 404 counts as done). focus moves to the
+ // next chip, or the field.
+ function drop(it, focus) {
+ const at = items.indexOf(it);
+ if (at < 0) return;
+ items.splice(at, 1);
+ it.removed = true;
+ if (it.xhr) it.xhr.abort();
+ else if (it.id && !inflight.has(it.id)) {
+ fetch(href(it.id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {});
+ }
+ it.li.remove();
+ chips.hidden = items.length === 0;
+ if (focus) {
+ const next = items[at] || items[at - 1];
+ (next ? next.li.querySelector(".chip-remove") : field).focus();
+ }
+ hooks.changed();
+ settle();
+ pump();
+ }
+
+ // ready waits for every upload to settle, and answers the ids that go,
+ // in chip order.
+ let waiters = [];
+ function settle() {
+ if (items.some((it) => it.state === "queued" || it.state === "uploading")) return;
+ const ids = items.filter((it) => it.state === "done" || it.state === "unavailable").map((it) => it.id);
+ for (const w of waiters) w(ids);
+ waiters = [];
+ }
+ function ready() {
+ return new Promise((resolve) => {
+ waiters.push(resolve);
+ settle();
+ });
+ }
+ function sending(ids, on) {
+ for (const id of ids) on ? inflight.add(id) : inflight.delete(id);
+ }
+ function sent(ids) {
+ for (const it of [...items]) {
+ if (ids.includes(it.id)) {
+ items.splice(items.indexOf(it), 1);
+ it.li.remove();
+ }
+ }
+ chips.hidden = items.length === 0;
+ hooks.changed();
+ }
+ // refused: the send's files were refused. unavailable keeps them (a
+ // later send tries them again, and the paperclip goes, can_attach being
+ // false); stale marks them gone: Remove clears them.
+ function refused(why, ids) {
+ for (const it of items) {
+ if (!ids.includes(it.id)) continue;
+ if (why === "unavailable") show(it, "unavailable", words.unavailable);
+ else show(it, "stale", words.stale);
+ }
+ if (why === "unavailable") enable(false);
+ }
+
+ // A paste with files attaches them only when it has no words of its
+ // own (D8, Fable B5 and B8): HTML with text, or plain text beyond the
+ // files' own names (a file copied in the Finder may come with its name),
+ // is words, and the text path pastes it.
+ function paste(e) {
+ const d = e.clipboardData;
+ if (!enabled || !d || !d.files || !d.files.length) return false;
+ const files = [...d.files];
+ const html = d.getData("text/html");
+ if (html && new DOMParser().parseFromString(html, "text/html").body.textContent.trim()) return false;
+ const names = new Set(files.map((f) => f.name.trim()));
+ const own = (line) => {
+ let last = line.split("/").pop();
+ try { last = decodeURIComponent(last); } catch {}
+ return names.has(line) || names.has(last);
+ };
+ const plain = d.getData("text/plain");
+ if (plain && plain.split(/\r?\n/).map((l) => l.trim()).some((l) => l && !own(l))) return false;
+ e.preventDefault();
+ add(files);
+ return true;
+ }
+
+ // Drop: an outline while files are dragged over the composer.
+ let depth = 0;
+ const dragging = (e) => enabled && e.dataTransfer && [...e.dataTransfer.types].includes("Files");
+ composer.dataset.drop = words.drop;
+ composer.addEventListener("dragenter", (e) => {
+ if (!dragging(e)) return;
+ e.preventDefault();
+ depth++;
+ composer.classList.add("dropping");
+ });
+ composer.addEventListener("dragover", (e) => {
+ if (!dragging(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ });
+ composer.addEventListener("dragleave", () => {
+ if (depth > 0 && --depth === 0) composer.classList.remove("dropping");
+ });
+ composer.addEventListener("drop", (e) => {
+ depth = 0;
+ composer.classList.remove("dropping");
+ if (!dragging(e)) return;
+ e.preventDefault();
+ add([...e.dataTransfer.files]);
+ });
+
+ // The page goes: its unsent uploads are deleted, as best Base can,
+ // apart from a send's on its way (Fable B7). Kept for Back, it comes back
+ // without its chips, whose uploads are gone; the words stay.
+ addEventListener("pagehide", () => {
+ const ids = items.filter((it) => it.id && !inflight.has(it.id) && it.state !== "stale").map((it) => it.id);
+ if (!ids.length) return;
+ navigator.sendBeacon("/ask/attachments/discard", new URLSearchParams(ids.map((id) => ["id", id])));
+ });
+ addEventListener("pageshow", (e) => {
+ if (!e.persisted) return;
+ for (const it of items) {
+ it.removed = true;
+ if (it.xhr) it.xhr.abort();
+ it.li.remove();
+ }
+ items.length = 0;
+ chips.hidden = true;
+ hooks.changed();
+ });
+
+ // The viewer: a thumbnail in the thread opens its image full size, in a
+ // sheet that holds focus until Close (or Escape) gives it back.
+ const viewer = el("dialog", "viewer");
+ const shut = el("button", "round viewer-close");
+ shut.type = "button";
+ shut.setAttribute("aria-label", words.close);
+ shut.append(icon(CROSS));
+ const full = document.createElement("img");
+ viewer.append(shut, full);
+ document.body.append(viewer);
+ let back = null;
+ thread.addEventListener("click", (e) => {
+ const thumb = e.target.closest("a.thumb[data-attachment]");
+ if (!thumb || e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
+ e.preventDefault();
+ back = thumb;
+ const img = thumb.querySelector("img");
+ full.src = href(thumb.dataset.attachment);
+ full.alt = img ? img.alt : "";
+ viewer.setAttribute("aria-label", full.alt);
+ viewer.showModal();
+ shut.focus();
+ });
+ shut.addEventListener("click", () => viewer.close());
+ viewer.addEventListener("click", (e) => { if (e.target === viewer) viewer.close(); });
+ viewer.addEventListener("keydown", (e) => {
+ if (e.key === "Tab") {
+ e.preventDefault();
+ shut.focus();
+ }
+ });
+ viewer.addEventListener("close", () => {
+ full.removeAttribute("src");
+ if (back && back.isConnected) back.focus({ preventScroll: true });
+ back = null;
+ });
+
+ return { enable, count, ready, sending, sent, refused, paste, words };
+}
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 141ef04..b030de0 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -25,6 +25,21 @@ function start(root) {
let turn = null;
let retry = 0;
+ // Files (ask-attach.js, the module data-attach names): the paperclip,
+ // paste, drop and the chips, offered only while can_attach. files is
+ // null until the module is in; the chat works without it. A message of
+ // files alone has no words, so the field is never required here (it is
+ // without scripts, which can't attach).
+ let files = null;
+ let canAttach = composer.hasAttribute("data-can-attach");
+ const attachMod = composer.dataset.attach ? import(composer.dataset.attach).then((m) => {
+ files = m.attach(root, { changed: () => paint(), lost: (state) => { quiet(); show(state); } });
+ files.enable(canAttach);
+ paint();
+ return m;
+ }, () => null) : Promise.resolve(null);
+ field.required = false;
+
const json = { Accept: "application/json" };
// A phone: Home's chat comes up full screen, and a job view is a sheet.
const phone = matchMedia("(max-width: 640px)");
@@ -113,6 +128,10 @@ function start(root) {
// Assistant's (rich), with emphasis only at word boundaries
// (strictEmphasis).
rich(li, m.text, m.role === "person");
+ // A person's files sit above their words, drawn as chat.html draws them.
+ if (m.role === "person" && m.attachments && m.attachments.length) {
+ attachMod.then((mod) => { if (mod) li.prepend(mod.filesRow(m.attachments, mod.wordsOf(composer))); });
+ }
const draft = m.role !== "person" && (item("data-draft", m.turn_id) || bubbles.get(m.turn_id));
if (draft && draft.querySelector(":scope > .think-line")) become(draft, li);
else if (draft) draft.replaceWith(li);
@@ -1455,7 +1474,7 @@ function start(root) {
function paint() {
const had = document.activeElement;
stop.hidden = !turn;
- send.hidden = !!turn || !field.value.trim();
+ send.hidden = !!turn || (!field.value.trim() && !(files && files.count()));
if ((had === send && send.hidden) || (had === stop && stop.hidden)) field.focus();
}
field.addEventListener("input", paint);
@@ -1567,6 +1586,8 @@ function start(root) {
return;
}
show(s.state);
+ canAttach = !!s.can_attach;
+ if (files) files.enable(canAttach);
if (!chatting(s.state) || !live()) return;
// An open job view stays open, with focus in it if it was.
const focused = viewing && item("data-job", viewing)?.querySelector(".jobview")?.contains(document.activeElement);
@@ -1606,14 +1627,27 @@ function start(root) {
// says a failure to try again itself, not the status line).
// lastStatus is the HTTP status of the latest post that got an answer,
// lastState the state it answered with.
+ // lastFiles is what it said of a send's files: "unavailable" or "stale"
+ // (the chips say so), else "". A list in extra goes as one field per
+ // item; a send with files is kept alive if the page goes, so the
+ // beacon's leaving its files out (ask-attach.js) never loses it.
let lastStatus = 0;
let lastState = "";
+ let lastFiles = "";
async function post(form, extra, quiet) {
lastStatus = 0;
lastState = "";
+ lastFiles = "";
const body = new URLSearchParams(new FormData(form));
body.delete("key");
- for (const [k, v] of Object.entries(extra || {})) body.set(k, v);
+ for (const [k, v] of Object.entries(extra || {})) {
+ if (!Array.isArray(v)) {
+ body.set(k, v);
+ continue;
+ }
+ body.delete(k);
+ for (const item of v) body.append(k, item);
+ }
const sig = body.toString();
let req = sending.get(form);
if (req && req.busy) return null;
@@ -1623,10 +1657,11 @@ function start(root) {
body.set("key", req.key);
let known = false;
try {
- const res = await fetch(form.action, { method: "POST", headers: json, body });
+ const res = await fetch(form.action, { method: "POST", headers: json, body, keepalive: body.has("attachments") });
const out = await res.json();
lastStatus = res.status;
lastState = out.state || "";
+ lastFiles = out.files || "";
known = res.status !== 502;
if (res.ok) {
// It went through: a runner answers again, so its note goes.
@@ -1639,7 +1674,7 @@ function start(root) {
// Otherwise the conversation stays, with a line to try again (a 409
// is stale: the next events show how things are).
if (["connect", "pending", "reconnect", ...runnerless].includes(out.state)) show(out.state);
- else if (res.status !== 409 && !quiet) status.textContent = "That didn't send. Try again.";
+ else if (res.status !== 409 && !lastFiles && !quiet) status.textContent = "That didn't send. Try again.";
} catch {
if (!quiet) status.textContent = "That didn't send. Try again.";
} finally {
@@ -1649,12 +1684,37 @@ function start(root) {
return null;
}
+ // Send waits for the chips' uploads, then sends once with their ids in
+ // chip order. Files refused at send keep Ask ready: the chips say why
+ // (unavailable: the paperclip goes; stale: attach it again), and the
+ // words stay in the field.
+ let settling = false;
composer.addEventListener("submit", async (e) => {
e.preventDefault();
- if (!field.value.trim()) return;
- const sent = await post(composer);
- if (!sent) return;
+ const withFiles = !!(files && files.count());
+ if ((!field.value.trim() && !withFiles) || settling) return;
+ let ids = [];
+ if (withFiles) {
+ settling = true;
+ try {
+ ids = await files.ready();
+ } finally {
+ settling = false;
+ }
+ if (!field.value.trim() && !ids.length) return;
+ files.sending(ids, true);
+ }
+ const sent = await post(composer, ids.length ? { attachments: ids } : null);
+ if (ids.length) files.sending(ids, false);
+ if (!sent) {
+ if (ids.length && lastFiles) {
+ files.refused(lastFiles, ids);
+ if (lastFiles === "unavailable") canAttach = false;
+ }
+ return;
+ }
field.value = "";
+ if (ids.length) files.sent(ids);
paint();
// Sending always goes to the bottom, wherever the person had scrolled.
pinned = true;
@@ -1677,6 +1737,8 @@ function start(root) {
// chat draws (pasteMarkdown); a plain one, or one whose HTML carries no
// formatting, is left to the browser.
field.addEventListener("paste", (e) => {
+ // Files with no words of their own attach (ask-attach.js, paste).
+ if (files && files.paste(e)) return;
const html = e.clipboardData && e.clipboardData.getData("text/html");
const md = html ? pasteMarkdown(html) : null;
if (md === null) return;
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html
index dcc82cd..239ac45 100644
--- a/internal/web/templates/partials/chat.html
+++ b/internal/web/templates/partials/chat.html
@@ -62,5 +62,5 @@
<p class="ask-status" role="status">{{.Status}}</p>
</div>
{{/* The composer: Send (an arrow) and, while a turn runs, Stop (a square) sit inside the field's end. Stop posts the cancel form beside it. Without scripts Send always shows; the panel's script hides it while the field is empty, and while a turn runs. Password managers are told it is no login (autocomplete off, and 1Password's, LastPass's and Dashlane's own marks); spell-check and the keyboard are untouched. */}}<form class="cancel" id="ask-cancel" method="post" action="{{with .Turn}}/ask/turns/{{.ID}}/cancel{{else}}/ask{{end}}"><input type="hidden" name="key" value="{{newKey}}"></form>
-<form class="composer" method="post" action="/ask/messages"><input type="hidden" name="key" value="{{.Key}}"><label class="sr-only" for="ask-text">Message</label><div class="field"><textarea class="input" id="ask-text" name="text" rows="1" required maxlength="16000" placeholder="Ask Base anything" autocomplete="off" data-1p-ignore data-lpignore="true" data-form-type="other">{{.Text}}</textarea><div class="actions"><button class="send" type="submit" aria-label="Send" title="Send"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19V5M6 11l6-6 6 6"/></svg></button><button class="stop" type="submit" form="ask-cancel" aria-label="Stop" title="Stop"{{if not .Turn}} hidden{{end}}><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="6.5" y="6.5" width="11" height="11" rx="2"/></svg></button></div></div></form>
+{{/* The composer's words for files (copy review 13, pending) are on it as data-w-*, for ask-attach.js, which adds the paperclip, the chips and the viewer only with scripts, and only while the snapshot says can_attach (data-can-attach); data-attach is its module. */}}<form class="composer" method="post" action="/ask/messages" data-attach="{{asset "static/ask-attach.js"}}"{{if .CanAttach}} data-can-attach{{end}} data-w-attach="Attach files" data-w-drop="Drop files to attach them" data-w-uploading="Uploading…" data-w-remove="Remove {name}" data-w-failed="Couldn't upload. Try again." data-w-too-many="At most 5 files in one message." data-w-pdf="Ask can't read PDFs yet." data-w-unavailable="Files can't be read right now. Remove them to send your message." data-w-stale="This file has expired. Attach it again." data-w-too-large="That file is over 10 MB." data-w-type="Ask takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON and PDF files." data-w-heic="HEIC photos can't be read yet. Share it as a JPEG and try again." data-w-pixels="That image is too large: at most 12,000 pixels on a side and 40 megapixels." data-w-limit="Too many files are waiting to send. Send or remove some first." data-w-busy="Too many uploads at once. Try again in a moment." data-w-attached="{name} attached" data-w-not-attached="{name} not attached: {reason}" data-w-files="Attached files" data-w-pill="{name}, {size}. Download" data-w-close="Close"><input type="hidden" name="key" value="{{.Key}}"><label class="sr-only" for="ask-text">Message</label><div class="field"><textarea class="input" id="ask-text" name="text" rows="1" required maxlength="16000" placeholder="Ask Base anything" autocomplete="off" data-1p-ignore data-lpignore="true" data-form-type="other">{{.Text}}</textarea><div class="actions"><button class="send" type="submit" aria-label="Send" title="Send"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19V5M6 11l6-6 6 6"/></svg></button><button class="stop" type="submit" form="ask-cancel" aria-label="Stop" title="Stop"{{if not .Turn}} hidden{{end}}><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="6.5" y="6.5" width="11" height="11" rx="2"/></svg></button></div></div></form>
</div>{{end}}