//go:build browser
package browsertest
import (
"context"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"testing"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/input"
"github.com/chromedp/chromedp"
"amadan.net/rastrillo/rastrillo/harness"
"amadan.net/oficina/base/internal/config"
"amadan.net/oficina/base/internal/equipo/equipotest"
)
// askBase is Base answered by a fake Equipo, the owner signed in and
// connected to it from Settings: Set up Ask Base, approve the code in
// Equipo, Check again.
func askBase(t *testing.T) (*harness.Rig, *equipotest.Fake) {
t.Helper()
rig, f, _ := askBaseWith(t, nil)
return rig, f
}
// askBaseWith is askBase with a last say over Base's configuration.
func askBaseWith(t *testing.T, tweak func(*config.Config)) (*harness.Rig, *equipotest.Fake, *baseApp) {
t.Helper()
return askBaseOn(t, tweak, nil)
}
// askBaseOn is askBaseWith on a screen of view's size, set before anything
// loads (a phone: taps then land where they are drawn); nil is 1280x800,
// set after signing in.
func askBaseOn(t *testing.T, tweak func(*config.Config), view chromedp.Action[chromedp.Void]) (*harness.Rig, *equipotest.Fake, *baseApp) {
t.Helper()
f := equipotest.New(t)
f.Reply = func(string) string {
return "You can ask me to plan work, check on a project, or start a task. What would you like to do?"
}
var b *baseApp
rig := newRig(t, func(origin string) http.Handler {
cfg := baseConfig(origin)
cfg.EquipoOrigin = f.URL
if tweak != nil {
tweak(&cfg)
}
b = newBase(t, cfg)
return b.handler
})
if view != nil {
drive(t, rig, view)
}
signInByEmail(t, rig, rig.Origin, b.mail)
if view == nil {
drive(t, rig, chromedp.EmulateViewport(1280, 800))
}
connect := `form[action="/ask/connect"] button`
drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(connect)),
chromedp.Click(chromedp.CSS(connect)), chromedp.WaitVisible(chromedp.CSS(`p.code`)))
rig.Screen(".card", "Set up Ask Base, waiting for approval")
code := harness.Evaluate[string](rig, `document.querySelector("p.code").textContent`)
if !regexp.MustCompile(`^[A-Z0-9]{8}$`).MatchString(code) {
t.Fatalf("code %q", code)
}
if err := f.Approve(code); err != nil {
t.Fatal(err)
}
if _, err := b.db.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
t.Fatal(err)
}
drive(t, rig, chromedp.Click(chromedp.CSS(`form[action="/ask/connect/check"] button`)),
chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
rig.Screen(".sheet", "Settings, Ask Base set up")
return rig, f, b
}
// settledJS is true once the docked chat is open and done moving.
const settledJS = `(() => { const d = document.querySelector("#ask-panel"), s = getComputedStyle(d);
return d.checkVisibility({ visibilityProperty: true }) && s.opacity === "1" && (s.transform === "none" || s.transform === "matrix(1, 0, 0, 1, 0, 0)"); })()`
// readJS is true once the chat has read the conversation afresh (its
// /ask/state answer is in), so what a test does next is not undone by it.
const readJS = `performance.getEntriesByType("resource").some((e) => e.name.includes("/ask/state") && e.responseEnd > 0)`
// openPanel goes to Home, where on a wide screen Ask Base is docked open,
// and waits for the chat to settle and read the conversation.
func openPanel(t *testing.T, rig *harness.Rig) {
t.Helper()
drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)),
chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(5*time.Second)),
chromedp.Poll[chromedp.Void](readJS, chromedp.WithPollingTimeout(5*time.Second)), chromedp.Sleep(100*time.Millisecond))
}
// slash presses "/" as a keyboard does: one keydown carrying the text, so
// a page that handles the keydown types nothing.
func slash() chromedp.Action[chromedp.Void] {
return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
for _, typ := range []input.DispatchKeyEventType{input.DispatchKeyEventTypeKeyDown, input.DispatchKeyEventTypeKeyUp} {
k := input.DispatchKeyEventParams{Type: typ, Key: "/", Code: "Slash", WindowsVirtualKeyCode: 191, NativeVirtualKeyCode: 191}
if typ == input.DispatchKeyEventTypeKeyDown {
k.Text, k.UnmodifiedText = "/", "/"
}
if _, err := cdp.Call(ctx, target, input.DispatchKeyEvent, k); err != nil {
return err
}
}
return nil
})
}
// askClosed waits until the member's close of the docked chat is kept (or
// its reopening, for false): the script posts it by fetch.
func askClosed(t *testing.T, b *baseApp, want bool) {
t.Helper()
for i := 0; ; i++ {
var closed bool
if err := b.db.QueryRow(`SELECT ask_closed FROM members ORDER BY invited_at LIMIT 1`).Scan(&closed); err != nil {
t.Fatal(err)
}
if closed == want {
return
}
if i > 100 {
t.Fatalf("ask_closed is %v, want %v", closed, want)
}
time.Sleep(20 * time.Millisecond)
}
}
// A double press sends once, and sending again after an answer was lost
// on the way back reuses the key, so Equipo does the work once.
func TestAskPanelSendsOnce(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
send := `#ask-panel form.composer button.send`
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Build me a quick website"),
chromedp.Evaluate[chromedp.Void](`(() => { const b = document.querySelector("`+send+`"); b.click(); b.click(); })()`),
chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === 1`, chromedp.WithPollingTimeout(5*time.Second)))
if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
t.Fatalf("a double press sent %d requests", n)
}
f.FailNextSend()
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Put a meeting in my calendar with doc@tito.io for 2pm on Tuesday"),
chromedp.Click(chromedp.CSS(send)),
chromedp.Poll[chromedp.Void](`document.querySelector("#ask-panel .ask-status").textContent.includes("didn't send")`, chromedp.WithPollingTimeout(5*time.Second)),
chromedp.Click(chromedp.CSS(send)),
// A send that got its answer clears the field.
chromedp.Poll[chromedp.Void](`document.querySelector("#ask-text").value === ""`, chromedp.WithPollingTimeout(5*time.Second)))
if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 2 {
t.Errorf("person messages shown: %d, want 2", got)
}
calls := f.Calls("/api/v1/assistant/messages")
if len(calls) != 3 || calls[1].Header.Get("Idempotency-Key") != calls[2].Header.Get("Idempotency-Key") ||
calls[0].Header.Get("Idempotency-Key") == calls[1].Header.Get("Idempotency-Key") {
t.Fatalf("keys: %v", keys(calls))
}
}
// Without a runner that can answer, the panel says so with a link to
// Equipo; a send keeps what the person wrote in the field and shows no
// message; a runner too old has its own note.
func TestAskPanelNoRunner(t *testing.T) {
rig, f := askBase(t)
f.NoRunner()
openPanel(t, rig)
note := `#ask-panel .ask-runner[data-when="norunner"]`
old := `#ask-panel .ask-runner[data-when="oldrunner"]`
drive(t, rig, chromedp.WaitVisible(chromedp.CSS(note)))
if !harness.Evaluate[bool](rig, `!!document.querySelector(`+strconv.Quote(note+` a[href="`+f.URL+`/"][target="_blank"]`)+`)`) {
t.Fatal("the no-runner note has no link to finish setting up")
}
rig.Screen("#ask-panel", "the panel without a runner")
// Each send moves the panel from one note to the other.
const text = "Build me a quick website"
f.RunnerTooOld()
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), text),
chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
chromedp.WaitVisible(chromedp.CSS(old)), chromedp.WaitNotVisible(chromedp.CSS(note)))
f.NoRunner()
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
chromedp.WaitVisible(chromedp.CSS(note)), chromedp.WaitNotVisible(chromedp.CSS(old)))
if n := len(f.Calls("/api/v1/assistant/messages")); n != 2 {
t.Fatalf("sends relayed: %d, want 2", n)
}
if got := harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`); got != text {
t.Errorf("the field holds %q, want %q", got, text)
}
if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); n != 0 {
t.Errorf("person messages shown: %d", n)
}
if got := harness.Evaluate[string](rig, `document.querySelector("#ask-panel .ask-status").textContent`); got != "" {
t.Errorf("status line %q", got)
}
}
// Home's panel draws the states it learns from the script: each shows its
// approved words in the one visible note, and every other note is hidden.
func TestAskPanelStatesShowApprovedWords(t *testing.T) {
const notes = `#ask-panel .ask-note, #ask-panel .ask-runner`
visible := func(t *testing.T, rig *harness.Rig) string {
return harness.Evaluate[string](rig, `[...document.querySelectorAll(`+strconv.Quote(notes)+`)]
.filter(el => el.checkVisibility()).map(el => el.dataset.when + "=" + el.textContent.replace(/\s+/g, " ").trim()).join("|")`)
}
openOnly := func(rig *harness.Rig, when string) {
drive(t, rig, chromedp.Navigate(rig.Origin+"/"),
chromedp.WaitVisible(chromedp.CSS(`#ask-panel .ask-note[data-when="`+when+`"], #ask-panel .ask-runner[data-when="`+when+`"]`)))
}
t.Run("unavailable", func(t *testing.T) {
rig, f := askBase(t)
f.FailSnapshots(true)
openOnly(rig, "unavailable")
if got, want := visible(t, rig), "unavailable=Ask Base isn't answering. Try again in a minute."; got != want {
t.Errorf("visible notes %q, want %q", got, want)
}
})
t.Run("norunner", func(t *testing.T) {
rig, f := askBase(t)
f.NoRunner()
openOnly(rig, "norunner")
if got, want := visible(t, rig), "norunner=Ask Base isn't set up for you yet. Finish setting it up, then try again."; got != want {
t.Errorf("visible notes %q, want %q", got, want)
}
})
t.Run("oldrunner", func(t *testing.T) {
rig, f := askBase(t)
f.NoRunner()
openOnly(rig, "norunner")
f.RunnerTooOld()
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Build me a quick website"),
chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
chromedp.WaitVisible(chromedp.CSS(`#ask-panel .ask-runner[data-when="oldrunner"]`)))
if got, want := visible(t, rig), "oldrunner=Ask Base needs an update first. Update it, then try again."; got != want {
t.Errorf("visible notes %q, want %q", got, want)
}
})
}
func keys(calls []equipotest.Call) []string {
var out []string
for _, c := range calls {
out = append(out, c.Header.Get("Idempotency-Key"))
}
return out
}
// On a wide screen Home opens with Ask Base docked open on the right, from
// under the header to the foot of the screen, beside Home; the greeting's
// field has folded away and the Base button is hidden. The owner asks one
// thing and sees the reply stream in, and "/" puts focus in the composer
// from anywhere but a field.
func TestAskDockedOpenByDefault(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
if got := harness.Evaluate[string](rig, `(() => {
const problems = [], vw = document.documentElement.clientWidth, vh = innerHeight;
const p = document.querySelector("#ask-panel").getBoundingClientRect(), bar = document.querySelector(".topbar").getBoundingClientRect();
const home = document.querySelector("main.home").getBoundingClientRect(), apps = document.querySelector("nav.apps").getBoundingClientRect();
const w = Math.min(440, Math.max(360, vw * 0.3));
if (Math.abs(p.width - w) > 1) problems.push("width " + p.width + ", want " + w);
if (p.top < bar.bottom || p.top > bar.bottom + 24) problems.push("top " + p.top + ", the header ends at " + bar.bottom);
if (p.bottom > vh || vh - p.bottom > 24) problems.push("bottom " + p.bottom + " of " + vh);
if (p.right > vw || vw - p.right > 24) problems.push("right " + p.right + " of " + vw);
if (p.left < home.right - 0.5 || p.left < apps.right) problems.push("left " + p.left + ", Home ends at " + home.right + ", the apps at " + apps.right);
if (document.documentElement.classList.contains("desk-closed")) problems.push("drawn closed");
const field = document.querySelector(".ask-field"), btn = document.querySelector(".base-btn");
if (field.checkVisibility({ visibilityProperty: true }) || !field.closest(".ask-slot").inert) problems.push("the greeting's field shows");
if (btn.checkVisibility({ visibilityProperty: true })) problems.push("the Base button shows");
if (document.documentElement.scrollWidth > vw) problems.push("page overflows");
return problems.join("; ");
})()`); got != "" {
t.Errorf("the docked chat at 1280x800: %s", got)
}
if here := harness.Read(rig, chromedp.Location()); here != rig.Origin+"/" {
t.Fatalf("Home moved to %s", here)
}
// "/" from anywhere but a field puts focus in the composer.
drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`), slash())
if got := harness.Evaluate[string](rig, `document.activeElement.id + "|" + document.querySelector("#ask-text").value`); got != "ask-text|" {
t.Errorf(`after "/" focus and the field are %q, want the empty message field`, got)
}
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"), slash())
if got := harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`); got != "What can I do/" {
t.Errorf(`"/" in the field typed %q`, got)
}
drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelector("#ask-text").value = "What can I do"`),
chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
chromedp.Poll[chromedp.Void](`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent.includes("What would you like to do?") && m.dataset.id)`,
chromedp.WithPollingTimeout(10*time.Second)))
rig.Screen("#ask-panel", "the docked chat with one question answered")
if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 1 {
t.Errorf("person messages shown: %d", got)
}
if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
t.Errorf("messages sent to Equipo: %d", n)
}
if dir := os.Getenv("BASE_BROWSER_ARTIFACTS"); dir != "" {
var png []byte
drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
var err error
png, err = chromedp.FullScreenshot(100)(ctx, target)
return err
}))
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "7-ask-panel.png"), png, 0o644); err != nil {
t.Fatal(err)
}
}
// There is no ⋯ menu: the header holds the title and Close.
if harness.Evaluate[bool](rig, `!!document.querySelector("#ask-panel .ask-head summary, #ask-panel .ask-head a")`) {
t.Error("the panel's header still has a menu or a link")
}
}
// Home never waits on Equipo: closed, Home reads nothing and the script
// reads the conversation as the chat opens (an empty one saying so);
// open, with the read stalled, Home comes up well inside the client's own
// 20 s with the chat open, and the script reads the conversation in.
func TestAskHomeDoesNotWaitOnEquipo(t *testing.T) {
rig, f, b := askBaseWith(t, nil)
openPanel(t, rig)
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel [data-ask-close]`)))
askClosed(t, b, true)
before := len(f.Calls("/api/v1/assistant/snapshot"))
drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`button.base-btn`)), chromedp.Sleep(300*time.Millisecond))
if n := len(f.Calls("/api/v1/assistant/snapshot")) - before; n != 0 {
t.Errorf("Home with the chat closed read the conversation %d times", n)
}
drive(t, rig, chromedp.Click(chromedp.CSS(`button.base-btn`)),
chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(5*time.Second)),
chromedp.Poll[chromedp.Void](readJS, chromedp.WithPollingTimeout(5*time.Second)), chromedp.Sleep(100*time.Millisecond))
if got := harness.Evaluate[string](rig, `(() => { const e = document.querySelector("#ask-panel [data-empty]");
return e.hidden + " " + document.querySelectorAll("#ask-panel .thread > li").length; })()`); got != "false 0" {
t.Errorf("opened on an empty conversation, the empty line hidden and lines: %s", got)
}
askClosed(t, b, false)
f.Say("Your week is clear.")
entered, hold := f.HoldNextSnapshot()
release := sync.OnceFunc(hold)
defer release()
start := time.Now()
drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)))
if took := time.Since(start); took > 5*time.Second {
t.Errorf("Home took %v with the conversation's read stalled", took)
}
select {
case <-entered:
default:
t.Fatal("Home never read the conversation")
}
drive(t, rig, chromedp.Poll[chromedp.Void](`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent === "Your week is clear.")`,
chromedp.WithPollingTimeout(10*time.Second)))
if !harness.Evaluate[bool](rig, settledJS) || harness.Evaluate[bool](rig, `!document.querySelector("#ask-panel [data-empty]").hidden`) {
t.Error("the chat is not open with its conversation")
}
release()
}
// The X slides the docked chat out and Home takes the width (the apps grid
// gains a column); the Base button shows, with focus. A reload keeps it
// closed. The Base button, or "/", brings it back, and a reload keeps it
// open. With reduced motion it opens and closes without moving.
func TestAskDockClosePersists(t *testing.T) {
apps := teamApps(t)
rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
installAll(t, b)
drive(t, rig, chromedp.EmulateViewport(900, 800))
openPanel(t, rig)
appsRight := func() float64 {
return harness.Evaluate[float64](rig, `document.querySelector("nav.apps").getBoundingClientRect().right`)
}
gone := `(() => { const d = document.querySelector("#ask-panel"); return document.documentElement.classList.contains("desk-closed") && !d.checkVisibility({ visibilityProperty: true }) })()`
closedJS := `(() => { const problems = [], vw = document.documentElement.clientWidth;
if (!document.documentElement.classList.contains("desk-closed")) problems.push("not desk-closed");
if (document.querySelector("#ask-panel").checkVisibility({ visibilityProperty: true })) problems.push("the chat shows");
if (!document.querySelector("#ask-panel").inert) problems.push("the chat is not inert");
if (!document.querySelector(".base-btn").checkVisibility({ visibilityProperty: true })) problems.push("no Base button");
if (!document.querySelector(".ask-field").checkVisibility({ visibilityProperty: true })) problems.push("no field under the greeting");
const home = document.querySelector("main.home").getBoundingClientRect();
if (vw - home.right > 1) problems.push("Home ends at " + home.right + " of " + vw);
return problems.join("; "); })()`
open := appsRight()
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)),
chromedp.Poll[chromedp.Void](gone, chromedp.WithPollingTimeout(3*time.Second)))
if got := harness.Evaluate[string](rig, closedJS); got != "" {
t.Errorf("closed: %s", got)
}
if got := appsRight(); got <= open+48 {
t.Errorf("closed, the apps end at %v, open at %v: Home did not take the width", got, open)
}
if got := harness.Evaluate[string](rig, `document.activeElement.className`); got != "base-btn" {
t.Errorf("after X focus is on %q, want the Base button", got)
}
askClosed(t, b, true)
layoutShot(t, rig, "desktop-chat-closed-dark")
// Reloaded, it is closed from the first paint.
drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(".base-btn")))
if got := harness.Evaluate[string](rig, closedJS); got != "" {
t.Errorf("reloaded: %s", got)
}
// The Base button reopens it, focus in the composer; a reload keeps it.
drive(t, rig, chromedp.Click(chromedp.CSS(".base-btn")), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)))
if got := harness.Evaluate[string](rig, `document.activeElement.id`); got != "ask-text" {
t.Errorf("reopened, focus is on %q, want the message field", got)
}
askClosed(t, b, false)
openPanel(t, rig)
if harness.Evaluate[bool](rig, `document.documentElement.classList.contains("desk-closed")`) {
t.Error("reopened and reloaded, it is closed")
}
// Closed again, "/" reopens it.
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)),
chromedp.Poll[chromedp.Void](gone, chromedp.WithPollingTimeout(3*time.Second)))
askClosed(t, b, true)
drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(".base-btn")),
slash(), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)))
if got := harness.Evaluate[string](rig, `document.activeElement.id`); got != "ask-text" {
t.Errorf(`opened by "/", focus is on %q`, got)
}
askClosed(t, b, false)
openPanel(t, rig)
// With reduced motion nothing moves: it just goes, and just comes back.
drive(t, rig, reducedMotion("dark", true))
if got := harness.Evaluate[string](rig, `getComputedStyle(document.querySelector("#ask-panel")).transitionDuration`); got != "0s" {
t.Errorf("with reduced motion the chat's transition-duration is %q, want 0s", got)
}
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)))
if !harness.Evaluate[bool](rig, gone) {
t.Error("with reduced motion the chat did not close at once")
}
drive(t, rig, chromedp.Click(chromedp.CSS(".base-btn")))
if !harness.Evaluate[bool](rig, settledJS) {
t.Error("with reduced motion the chat did not open at once")
}
drive(t, rig, reducedMotion("dark", false))
askClosed(t, b, false)
}
// The composer is the familiar one: no Send until something is typed, then
// a round arrow inside the field's end that sends on a click or on Enter;
// while Equipo answers, a square Stop takes its place and cancels the turn.
func TestAskComposerSendAndStop(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
const send, stop = `#ask-panel form.composer button.send`, `#ask-panel form.composer button.stop`
shown := func(sel string) string {
return `(() => { const b = document.querySelector(` + strconv.Quote(sel) + `);
return !!b && b.checkVisibility({ visibilityProperty: true }) && b.getBoundingClientRect().width > 0 })()`
}
buttons := func() string {
return harness.Evaluate[string](rig, `"send " + `+shown(send)+` + ", stop " + `+shown(stop))
}
wait := func(js string) {
t.Helper()
drive(t, rig, chromedp.Poll[chromedp.Void](js, chromedp.WithPollingTimeout(10*time.Second)))
}
// Once the panel has finished opening.
wait(`(() => { const s = getComputedStyle(document.querySelector("#ask-panel")); return s.opacity === "1" && s.transform === "none" })()`)
if got := buttons(); got != "send false, stop false" {
t.Fatalf("empty field: %s", got)
}
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), " "), chromedp.Sleep(200*time.Millisecond))
if got := buttons(); got != "send false, stop false" {
t.Fatalf("only spaces typed: %s", got)
}
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"))
wait(shown(send))
// The arrow sits inside the field's right end, named Send.
if got := harness.Evaluate[string](rig, `(() => {
const b = document.querySelector(`+strconv.Quote(send)+`), f = document.querySelector("#ask-text");
for (const a of b.getAnimations()) a.finish(); // measured once it has grown in
const r = b.getBoundingClientRect(), x = f.getBoundingClientRect(), p = [];
if (b.getAttribute("aria-label") !== "Send" || b.title !== "Send") p.push("named " + b.getAttribute("aria-label") + "/" + b.title);
if (b.textContent.trim() !== "") p.push("has text " + b.textContent.trim());
if (!b.querySelector("svg")) p.push("no icon");
if (r.left < x.left || r.right > x.right + 0.5 || r.top < x.top - 0.5 || r.bottom > x.bottom + 0.5) p.push("outside the field");
if (x.right - r.right > 8) p.push(Math.round(x.right - r.right) + "px from the field's end");
return p.join("; ");
})()`); got != "" {
t.Errorf("the Send button: %s", got)
}
// Sent by a click; while Equipo answers, Stop is where Send was, the
// thinking bubble says so (the status line above the field is empty),
// and no other Stop shows.
f.Hold = true
drive(t, rig, chromedp.Click(chromedp.CSS(send)))
// (The turn's events can come before the send's answer, which clears
// the field.)
wait(`document.querySelectorAll("#ask-panel .msg.person").length === 1 && document.querySelector("#ask-text").value === "" && ` + shown(stop))
if got := harness.Evaluate[string](rig, `(() => {
const b = document.querySelector(`+strconv.Quote(stop)+`), p = [];
if (b.getAttribute("aria-label") !== "Stop" || b.title !== "Stop") p.push("named " + b.getAttribute("aria-label") + "/" + b.title);
if (!b.querySelector("svg")) p.push("no icon");
if (`+shown(send)+`) p.push("Send shows too");
if (document.querySelector("#ask-text").value !== "") p.push("the field still holds text");
const others = [...document.querySelectorAll("#ask-panel button")].filter(x => x !== b && /Stop/.test(x.textContent) && x.checkVisibility());
if (others.length) p.push(others.length + " other Stop buttons");
const st = document.querySelector("#ask-panel .ask-status");
if (st.textContent !== "") p.push("status " + st.textContent);
const bubble = document.querySelector("#ask-panel .thread > li:last-child.thinking");
if (!bubble || bubble.textContent !== "" || bubble.querySelectorAll(".dots > i").length !== 3) p.push("bubble " + (bubble && bubble.innerHTML));
return p.join("; ");
})()`); got != "" {
t.Errorf("while answering: %s", got)
}
action := harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.cancel").getAttribute("action")`)
m := regexp.MustCompile(`^/ask/turns/([^/]+)/cancel$`).FindStringSubmatch(action)
if m == nil {
t.Fatalf("cancel form posts to %q", action)
}
rig.Screen("#ask-panel", "the panel while Equipo answers, with Stop in the field")
drive(t, rig, chromedp.Click(chromedp.CSS(stop)))
wait(`!` + shown(stop) + ` && document.querySelector("#ask-panel .ask-status").textContent === ""`)
for i := 0; f.Turn(m[1]) != "cancelled"; i++ {
if i > 100 {
t.Fatalf("Stop left the turn %q", f.Turn(m[1]))
}
time.Sleep(20 * time.Millisecond)
}
if got := buttons(); got != "send false, stop false" {
t.Errorf("after Stop, the field empty: %s", got)
}
f.Hold = false
// Enter sends too.
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "And what else?\r"))
wait(`document.querySelectorAll("#ask-panel .msg.person").length === 2`)
if n := len(f.Calls("/api/v1/assistant/messages")); n != 2 {
t.Errorf("messages sent: %d, want 2", n)
}
}
// The key events' modifier bits.
const altKey, shiftKey = 1, 8
// enter presses Enter as a keyboard does, with modifiers and the key code
// an input method's Enter carries (229) or Enter's own (13).
func enter(modifiers, keyCode int64) chromedp.Action[chromedp.Void] {
return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
for _, typ := range []input.DispatchKeyEventType{input.DispatchKeyEventTypeKeyDown, input.DispatchKeyEventTypeKeyUp} {
k := input.DispatchKeyEventParams{Type: typ, Key: "Enter", Code: "Enter", Modifiers: modifiers,
WindowsVirtualKeyCode: keyCode, NativeVirtualKeyCode: keyCode}
if typ == input.DispatchKeyEventTypeKeyDown && keyCode != 229 { // the input method's own text
k.Text, k.UnmodifiedText = "\r", "\r"
}
if _, err := cdp.Call(ctx, target, input.DispatchKeyEvent, k); err != nil {
return err
}
}
return nil
})
}
// Paul's Base Mac bug, checked on the web: Enter sends; Shift Enter and
// Option (Alt) Enter are a new line where the cursor is; an input
// method's Enter (Safari's keyCode 229) finishes its word and sends
// nothing.
func TestAskComposerNewLines(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
value := func() string { return harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`) }
at := func(n int) chromedp.Action[chromedp.Void] {
return chromedp.Evaluate[chromedp.Void](`(() => { const f = document.querySelector("#ask-text"); f.focus(); f.setSelectionRange(` + strconv.Itoa(n) + `, ` + strconv.Itoa(n) + `) })()`)
}
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Flour delivery"), at(5), enter(shiftKey, 13))
if got := value(); got != "Flour\n delivery" {
t.Errorf("Shift Enter mid-text: %q", got)
}
drive(t, rig, at(len("Flour\n delivery")), enter(altKey, 13))
if got := value(); got != "Flour\n delivery\n" {
t.Errorf("Option Enter at the end: %q", got)
}
drive(t, rig, enter(0, 229), chromedp.Sleep(300*time.Millisecond))
if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
t.Fatalf("sent %d messages before a plain Enter", n)
}
drive(t, rig, enter(0, 13), chromedp.Sleep(300*time.Millisecond))
drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector("#ask-text").value === ""`, chromedp.WithPollingTimeout(10*time.Second)))
if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
t.Errorf("messages sent: %d, want 1", n)
}
}
// holdDock wraps the page's fetch so its /ask/dock posts follow plan, one
// step per post: held for some milliseconds, then sent, or answered 500
// without reaching Base. window.__dock lists the bodies posted.
// It first waits for any post already on its way to settle.
func holdDock(plan string) chromedp.Action[chromedp.Void] {
return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
if _, err := chromedp.Poll[chromedp.Void](`!window.__out`, chromedp.WithPollingTimeout(3*time.Second))(ctx, target); err != nil {
return err
}
_, err := chromedp.Evaluate[chromedp.Void](`(() => {
window.__dock = []; window.__plan = `+plan+`; window.__out = 0;
const real = window.__fetch = window.__fetch || window.fetch;
window.fetch = async (url, opts) => {
if (!String(url).includes("/ask/dock")) return real(url, opts);
const p = window.__plan.shift() || {};
window.__dock.push(String(opts.body));
window.__out++;
try {
if (p.hold) await new Promise((r) => setTimeout(r, p.hold));
if (p.fail) return new Response("", { status: 500 });
return await real(url, opts);
} finally {
setTimeout(() => window.__out--);
}
};
})()`)(ctx, target)
return err
})
}
// toggles presses the X (0) and the Base button (1) in order, at once.
func toggles(seq string) chromedp.Action[chromedp.Void] {
return chromedp.Evaluate[chromedp.Void](`(() => { for (const c of ` + strconv.Quote(seq) + `)
document.querySelector(c === "0" ? "#ask-panel form.dock-close" : "form.base-btn-form").requestSubmit(); })()`)
}
// The docked chat's saves go one at a time and the last choice wins: a
// close held on its way, then an open, ends open on the server, and
// presses made while one is on its way send only the latest.
func TestAskDockSavesInOrder(t *testing.T) {
rig, _, b := askBaseWith(t, nil)
openPanel(t, rig)
drive(t, rig, holdDock(`[{ hold: 400 }]`), toggles("01"))
askClosed(t, b, false)
drive(t, rig, chromedp.Sleep(600*time.Millisecond))
askClosed(t, b, false)
if got := harness.Evaluate[string](rig, `window.__dock.join(" ") + " | " + document.documentElement.classList.contains("desk-closed")`); got != "open=0 open=1 | false" {
t.Errorf("close then open: posted and drawn %q, want open=0 open=1 | false", got)
}
// Close (held), open, close, open: two posts, the held close and the
// last choice, ending open.
drive(t, rig, holdDock(`[{ hold: 400 }]`), toggles("0101"),
chromedp.Poll[chromedp.Void](`window.__dock.length === 2`, chromedp.WithPollingTimeout(3*time.Second)), chromedp.Sleep(300*time.Millisecond))
askClosed(t, b, false)
if got := harness.Evaluate[string](rig, `window.__dock.join(" ")`); got != "open=0 open=1" {
t.Errorf("four presses posted %q, want the held close then the last choice", got)
}
drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("#ask-panel textarea")))
if harness.Evaluate[bool](rig, `document.documentElement.classList.contains("desk-closed")`) {
t.Error("reloaded, the last choice (open) did not hold")
}
}
// A save that fails leaves the screen as the person chose it and is not
// taken as kept: a choice made while it was on its way is sent once it
// fails, and with none the next press saves.
func TestAskDockSaveFails(t *testing.T) {
rig, _, b := askBaseWith(t, nil)
openPanel(t, rig)
// Close fails at once: the chat stays closed on screen, the server
// still holds open; the next press (open) saves.
drive(t, rig, holdDock(`[{ fail: true }]`), toggles("0"), chromedp.Sleep(300*time.Millisecond))
if !harness.Evaluate[bool](rig, `document.documentElement.classList.contains("desk-closed")`) {
t.Error("a failed save moved the chat back")
}
askClosed(t, b, false)
drive(t, rig, toggles("1"), chromedp.Poll[chromedp.Void](`window.__dock.length === 2`, chromedp.WithPollingTimeout(3*time.Second)))
askClosed(t, b, false)
drive(t, rig, toggles("0"))
askClosed(t, b, true)
// Open fails after a while; meanwhile close, then open again: once it
// fails, the last choice (open) is sent, though it is what failed.
drive(t, rig, holdDock(`[{ hold: 400, fail: true }]`), toggles("101"),
chromedp.Poll[chromedp.Void](`window.__dock.length === 2`, chromedp.WithPollingTimeout(3*time.Second)))
askClosed(t, b, false)
if got := harness.Evaluate[string](rig, `window.__dock.join(" ") + " | " + document.documentElement.classList.contains("desk-closed")`); got != "open=1 open=1 | false" {
t.Errorf("posted and drawn %q, want the failed open, then open again, drawn open", got)
}
}
// The Assistant's little Markdown (plan decision D16) is drawn the same by
// the panel's script, for a line that arrives while it is open, as by the
// server, for /ask: each message's HTML is the same, unsafe links and raw
// HTML included. The last few lines are where a script and a server most
// easily part: carriage returns and NULs (which an HTML page cannot
// hold), letters beyond ASCII next to an _, and
// lists of each kind back to back.
func TestAskMarkdownMatchesServer(t *testing.T) {
said := []string{
"**Done.** Your site is up",
"*soon*",
"_soon_",
"a_b_c",
"**x**",
"Three things:\n- Docs\n- Sheets\n- [Calendar](https://cal.test/)",
"1. One\n2. Two",
"3) Three",
"- [x](javascript:alert(1))",
"** not bold **",
"# Heading",
"Line one\r\n- a *b*\r\n- **c**\r\nafter\r\n",
"é_x_ ü _ä_ _x_y 日本_語_ *😀* **😀 a** _😀_",
"- a\n\nb\n* c\n1. d\n0) e\n- f\n1000. g\n- \n",
"See https://a.test/_x_ and [*it*](https://b.test/?q=1&r=2) then *after*
",
"***x*** __y__ *a**b* **a*b** _a__b_ *\t*",
"A\rB\x00C\r\n\r\n- d\re",
}
rig, f := askBase(t)
openPanel(t, rig)
for _, s := range said {
f.Say(s)
}
drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.coordinator").length === `+strconv.Itoa(len(said)),
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.coordinator")) {
const s = page.querySelector('.msg.coordinator[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)
}
if n := harness.Evaluate[int](rig, `document.querySelectorAll('#ask-panel .msg a[href^="javascript"], #ask-panel .msg img, #ask-panel .msg b').length`); n != 0 {
t.Errorf("unsafe markup drawn: %d", n)
}
// The thread is a list without markers; the Assistant's lists have them.
if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .msg ul, #ask-panel .msg ol")]
.map(l => l.tagName + "=" + getComputedStyle(l).listStyleType).filter(s => s !== "UL=disc" && s !== "OL=decimal").join(" ")`); got != "" {
t.Errorf("lists without their markers: %s", got)
}
rig.Screen("#ask-panel", "the Assistant's simple Markdown")
}
const focusedJS = `document.activeElement && document.activeElement.id`
// The composer has focus when the page opens on a wide screen with the
// chat open and ready, and only then.
func TestAskFocusesFieldOnLoad(t *testing.T) {
load := func(t *testing.T, rig *harness.Rig, path string) string {
t.Helper()
drive(t, rig, chromedp.Navigate(rig.Origin+path), chromedp.WaitVisible(chromedp.CSS(`body`)), chromedp.Sleep(500*time.Millisecond))
return harness.Evaluate[string](rig, focusedJS)
}
t.Run("desktop open", func(t *testing.T) {
rig, _ := askBase(t)
if got := load(t, rig, "/"); got != "ask-text" {
t.Errorf("focus is %q, want the composer", got)
}
if y := harness.Evaluate[float64](rig, `scrollY`); y != 0 {
t.Errorf("the page scrolled to %v", y)
}
if got := load(t, rig, "/ask"); got != "ask-text" {
t.Errorf("/ask focus is %q, want the composer", got)
}
})
t.Run("desktop closed", func(t *testing.T) {
rig, _, b := askBaseWith(t, nil)
openPanel(t, rig)
drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)))
askClosed(t, b, true)
if got := load(t, rig, "/"); got == "ask-text" {
t.Error("the closed chat's composer took focus")
}
})
t.Run("phone", func(t *testing.T) {
rig, _, _ := askBaseOn(t, nil, chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3)))
if got := load(t, rig, "/"); got == "ask-text" {
t.Error("the composer took focus on a phone")
}
if got := load(t, rig, "/ask"); got == "ask-text" {
t.Error("/ask's composer took focus on a phone")
}
})
t.Run("not connected", func(t *testing.T) {
var b *baseApp
rig := newRig(t, func(origin string) http.Handler {
b = newBase(t, baseConfig(origin))
return b.handler
})
signInByEmail(t, rig, rig.Origin, b.mail)
drive(t, rig, chromedp.EmulateViewport(1280, 800))
for _, path := range []string{"/", "/ask"} {
if got := load(t, rig, path); got == "ask-text" {
t.Errorf("%s: the composer took focus without a connection", path)
}
}
})
}