//go:build browser package browsertest import ( "encoding/json" "os" "strconv" "strings" "testing" "time" "github.com/chromedp/chromedp" "amadan.net/rastrillo/rastrillo/harness" ) // pasteSample is one of testdata/paste.json's clipboards: its HTML and the // Markdown it pastes as (null: the plain text, left to the browser). The // app's PasteMarkdownTests check the same samples. type pasteSample struct { Name string `json:"name"` HTML string `json:"html"` // "" for the app's RTF samples Markdown *string `json:"markdown"` } // A rich paste into the composer becomes the Markdown the chat draws (Paul, // 2026-11-26), and Undo takes it back; a paste whose HTML formats nothing // is the browser's own. func TestAskPasteMarkdown(t *testing.T) { raw, err := os.ReadFile("testdata/paste.json") if err != nil { t.Fatal(err) } var samples []pasteSample if err := json.Unmarshal(raw, &samples); err != nil { t.Fatal(err) } rig, _ := askBase(t) openPanel(t, rig) type result struct { Prevented bool `json:"prevented"` Value string `json:"value"` } paste := func(before, html string) result { t.Helper() js := `(() => { const f = document.querySelector("#ask-text"); f.focus(); f.value = ` + strconv.Quote(before) + `; f.setSelectionRange(f.value.length, f.value.length); const data = new DataTransfer(); data.setData("text/html", ` + strconv.Quote(html) + `); data.setData("text/plain", "plain"); const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); f.dispatchEvent(e); return JSON.stringify({ prevented: e.defaultPrevented, value: f.value }); })()` var r result if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, js)), &r); err != nil { t.Fatal(err) } return r } for _, s := range samples { if s.HTML == "" { continue } got := paste("", s.HTML) switch { case s.Markdown == nil && (got.Prevented || got.Value != ""): t.Errorf("%s: pasted %q, want the browser's own paste", s.Name, got.Value) case s.Markdown != nil && (!got.Prevented || got.Value != *s.Markdown): t.Errorf("%s:\n got %q\nwant %q", s.Name, got.Value, *s.Markdown) } } // At the cursor, after what is there; and Undo takes the paste back. if got := paste("Note: ", samples[0].HTML); got.Value != "Note: "+*samples[0].Markdown { t.Errorf("pasted after text: %q", got.Value) } if got := harness.Evaluate[string](rig, `(document.execCommand("undo"), document.querySelector("#ask-text").value)`); got != "Note: " { t.Errorf("after Undo: %q", got) } } // Fable's S5 and S6: a big or hostile paste never freezes the tab. The // walk is linear and stops once the Markdown passes the field's 16,000 // characters; nesting past 32 levels is flattened. func TestAskPasteIsBounded(t *testing.T) { rig, _ := askBase(t) openPanel(t, rig) // The whole paste, the field's own insert included. got := harness.Evaluate[string](rig, `(() => { const f = document.querySelector("#ask-text"); const run = (html) => { f.focus(); f.value = ""; const data = new DataTransfer(); data.setData("text/html", html); const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); const t0 = performance.now(); f.dispatchEvent(e); return { ms: performance.now() - t0, value: f.value }; }; const out = []; { const items = run(""); if (items.ms > 200) out.push("50,000 items took " + Math.round(items.ms) + " ms"); if (!items.value.startsWith("- **item**\n- **item**") || items.value.length > 16100) out.push("items pasted " + items.value.length + " characters"); const deep = run("
".repeat(5000) + "deep" + "
".repeat(5000)); if (deep.ms > 500) out.push("5,000 levels took " + Math.round(deep.ms) + " ms"); if (deep.value !== "**deep**") out.push("deep pasted " + JSON.stringify(deep.value.slice(0, 40))); } return out.join("; "); })()`) if got != "" { t.Error(got) } } // Fable's R1: the whole paste of about 4,000 lines, the field's own // insert included (nothing stubbed), is quick, and the field holds all of // it, with the panel's listeners told. func TestAskLongPasteIsQuick(t *testing.T) { rig, _ := askBase(t) openPanel(t, rig) var r struct { MS float64 `json:"ms"` Value string `json:"value"` Input bool `json:"input"` } raw := harness.Evaluate[string](rig, `(() => { const f = document.querySelector("#ask-text"); f.focus(); f.value = ""; let input = false; f.addEventListener("input", () => { input = true; }, { once: true }); const data = new DataTransfer(); data.setData("text/html", "

Rows

" + Array.from({ length: 4000 }, (_, i) => "
r" + (i % 10) + "
").join("")); const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); const t0 = performance.now(); f.dispatchEvent(e); return JSON.stringify({ ms: performance.now() - t0, value: f.value, input }); })()`) if err := json.Unmarshal([]byte(raw), &r); err != nil { t.Fatal(err) } var want strings.Builder want.WriteString("**Rows**\n") for i := range 4000 { want.WriteString("\nr" + strconv.Itoa(i%10)) } if r.Value != want.String() { t.Errorf("pasted %d characters, want %d", len(r.Value), want.Len()) } if r.MS > 500 { t.Errorf("4,000 lines took %.0f ms", r.MS) } if !r.Input { t.Error("no input event: the panel's listeners weren't told") } } // The person's own messages are drawn in the Assistant's little Markdown, // with emphasis only at word boundaries, by the script and the server // alike (internal/web/testdata/person.json, which the server's and the // app's tests check too); plain words stay plain text, and unsafe links // stay text. func TestAskPersonMarkdown(t *testing.T) { raw, err := os.ReadFile("../web/testdata/person.json") if err != nil { t.Fatal(err) } var cases []struct{ Text, HTML string } if err := json.Unmarshal(raw, &cases); err != nil { t.Fatal(err) } said := make([]string, len(cases)) for i, c := range cases { said[i] = c.Text } rig, _ := askBase(t) openPanel(t, rig) for i, s := range said { drive(t, rig, chromedp.Evaluate[chromedp.Void](`(() => { const f = document.querySelector("#ask-text"); f.value = `+strconv.Quote(s)+`; f.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector("#ask-panel form.composer").requestSubmit() })()`)) n := strconv.Itoa(i + 1) drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === `+n+ ` && document.querySelectorAll("#ask-panel .msg.coordinator").length === `+n+` && document.querySelector("#ask-panel button.stop").hidden`, chromedp.WithPollingTimeout(10*time.Second))) } got := harness.Evaluate[string](rig, `(async () => { const page = new DOMParser().parseFromString(await (await fetch("/ask")).text(), "text/html"); const out = []; for (const m of document.querySelectorAll("#ask-panel .msg.person")) { const s = page.querySelector('.msg.person[data-id="' + CSS.escape(m.dataset.id) + '"]'); if (!s) out.push(m.dataset.id + ": not on /ask"); else if (s.innerHTML !== m.innerHTML) out.push(JSON.stringify(m.textContent) + "\n script " + m.innerHTML + "\n server " + s.innerHTML); } return out.join("\n"); })()`, chromedp.EvalAwaitPromise) if got != "" { t.Errorf("the script and the server draw differently:\n%s", got) } var drawn []string if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `JSON.stringify([...document.querySelectorAll("#ask-panel .msg.person")].map(m => m.innerHTML))`)), &drawn); err != nil { t.Fatal(err) } for i, c := range cases { if i < len(drawn) && drawn[i] != c.HTML { t.Errorf("%q drawn\n %s\nwant %s", c.Text, drawn[i], c.HTML) } } // Their links keep the bubble's ink; their lists have markers. if got := harness.Evaluate[string](rig, `(() => { const a = document.querySelector("#ask-panel .msg.person a"), p = []; if (getComputedStyle(a).color !== getComputedStyle(a.closest(".msg")).color) p.push("link colour " + getComputedStyle(a).color); for (const l of document.querySelectorAll("#ask-panel .msg.person ul, #ask-panel .msg.person ol")) if (!/^(disc|decimal)$/.test(getComputedStyle(l).listStyleType)) p.push(l.tagName + " " + getComputedStyle(l).listStyleType); return p.join("; "); })()`); got != "" { t.Errorf("person styles: %s", got) } rig.Screen("#ask-panel", "the person's messages in simple Markdown") }