//go:build browser package browsertest import ( "fmt" "regexp" "strconv" "strings" "testing" "time" "github.com/chromedp/chromedp" "amadan.net/rastrillo/rastrillo/harness" "amadan.net/oficina/base/internal/equipo/equipotest" ) // thinkingSel is the Assistant's thinking bubble: on its side of the // conversation, where its answer will appear. const thinkingSel = `#ask-panel .thread > li.msg.coordinator.thinking` // countFramesJS counts the page's requestAnimationFrame calls from now on, // in window.__raf: the spark's loop is the only thing in the chat that // asks for frames while it waits. (chromedp's Poll asks for frames too: // count from after the last one.) const countFramesJS = `(() => { window.__raf = 0; if (!window.__rafWrapped) { const r = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = (cb) => { window.__raf++; return r(cb); }; window.__rafWrapped = true; } })()` // noGLJS makes this page's canvases refuse a WebGL context, as a browser // without WebGL does. const noGLJS = `(() => { const get = HTMLCanvasElement.prototype.getContext; HTMLCanvasElement.prototype.getContext = function (type, ...rest) { return /webgl/.test(type) ? null : get.call(this, type, ...rest); }; })()` type thinking struct { t *testing.T rig *harness.Rig f *equipotest.Fake } func (th thinking) wait(js string) { th.t.Helper() drive(th.t, th.rig, chromedp.Poll[chromedp.Void](js, chromedp.WithPollingTimeout(10*time.Second))) } func (th thinking) eval(js string) string { th.t.Helper() return harness.Evaluate[string](th.rig, js) } // send asks text and holds the turn running; it returns the turn's id, // once the bubble shows. func (th thinking) send(text string) string { th.t.Helper() th.f.Hold = true drive(th.t, th.rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), text+"\r")) th.wait(`!!document.querySelector(` + strconv.Quote(thinkingSel) + `) && !document.querySelector("#ask-panel form.composer button.stop").hidden`) m := regexp.MustCompile(`^/ask/turns/([^/]+)/cancel$`).FindStringSubmatch(th.eval(`document.querySelector("#ask-panel form.cancel").getAttribute("action")`)) if m == nil { th.t.Fatal("no turn to cancel while the bubble shows") } return m[1] } // statusJS is the status line above the field: its text, and whether it // takes any room. const statusJS = `(() => { const s = document.querySelector("#ask-panel .ask-status"); return JSON.stringify(s.textContent) + (s.getBoundingClientRect().height > 0 ? " shown" : " empty"); })()` // While the Assistant answers, its thinking bubble sits at the end of the // conversation: three soft dots shimmering through Base's palette, no // words, until Equipo says what it is doing; the status line above the // field stays empty; a spark runs round the bubble's edge on a WebGL // canvas made for it. The bubble becomes the reply in place, streamed or // not; Stop and a failure take it away; a team_update turn shows none; // scripts off, the status line says it as before. func TestAskThinkingBubble(t *testing.T) { rig, f := askBase(t) openPanel(t, rig) th := thinking{t, rig, f} if got := th.eval(`document.querySelectorAll("#ask-panel canvas, #ask-panel .thinking").length + ""`); got != "0" { t.Fatalf("idle, the chat holds %s canvases or bubbles", got) } id := th.send("What can I do") drive(t, rig, chromedp.Evaluate[chromedp.Void](countFramesJS), chromedp.Sleep(300*time.Millisecond)) if got := th.eval(`(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `), list = b.parentElement, p = []; if (list.lastElementChild !== b) p.push("not at the end of the conversation"); if (document.querySelectorAll("#ask-panel .thinking").length !== 1) p.push(document.querySelectorAll("#ask-panel .thinking").length + " bubbles"); if (b.textContent !== "") p.push("says " + JSON.stringify(b.textContent)); const d = b.querySelectorAll(":scope > .think-line > .dots > i"); if (d.length !== 3) p.push(d.length + " dots"); if (b.querySelector(".dots")?.getAttribute("aria-label") !== "Thinking…") p.push("the dots are not named for assistive tech"); for (const i of d) { const s = getComputedStyle(i); if (s.animationName !== "think-dot, think-hue") p.push("a dot is still: " + s.animationName); if (i.getBoundingClientRect().width < 4) p.push("a dot is " + i.getBoundingClientRect().width + "px"); } if (d.length === 3 && getComputedStyle(d[0]).animationDelay === getComputedStyle(d[2]).animationDelay) p.push("the dots move together"); if (b.getBoundingClientRect().left - list.getBoundingClientRect().left > 20) p.push("not on the Assistant's side"); if (b.classList.contains("no-gl")) p.push("fell back to the CSS sweep"); const c = b.querySelector("canvas"); if (!c) return p.concat("no spark").join("; "); const dpr = Math.min(devicePixelRatio || 1, 2); if (Math.abs(c.width - Math.round((b.offsetWidth + 16) * dpr)) > 1 || Math.abs(c.height - Math.round((b.offsetHeight + 16) * dpr)) > 1) p.push("canvas " + c.width + "x" + c.height + " for a bubble " + b.offsetWidth + "x" + b.offsetHeight + " at " + dpr + "x"); if (getComputedStyle(c).pointerEvents !== "none") p.push("the canvas takes the pointer"); if (c.getAttribute("aria-hidden") !== "true") p.push("the canvas is not hidden from assistive tech"); if (!window.__raf) p.push("no frames: the spark is not running"); return p.join("; "); })()`); got != "" { t.Errorf("thinking: %s", got) } if got := th.eval(statusJS); got != `"" empty` { t.Errorf("thinking, the status line above the field is %s", got) } rig.Screen("#ask-panel", "the Assistant's thinking bubble") // Equipo's activity line shows in the bubble, not above the field. f.Emit("activity", map[string]string{"turn_id": id, "label": "Looking at what I can do…"}) th.wait(`document.querySelector(` + strconv.Quote(thinkingSel) + `)?.textContent === "Looking at what I can do…"`) if got := th.eval(statusJS); got != `"" empty` { t.Errorf("with an activity line, the status line is %s", got) } if n := th.eval(`document.querySelectorAll("#ask-panel .thinking").length + ""`); n != "1" { t.Errorf("with an activity line, %s bubbles", n) } // The reply, whole: the bubble becomes it, where it is. same := func(text string) { t.Helper() th.wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.dataset.id && m.textContent === ` + strconv.Quote(text) + `) && !document.querySelector("#ask-panel .think-line")`) if got := th.eval(`(() => { const b = window.__b, p = [], r = b.getBoundingClientRect(); const all = [...document.querySelectorAll("#ask-panel .msg.coordinator")].filter(m => m.textContent === ` + strconv.Quote(text) + `); if (all.length !== 1) p.push(all.length + " messages say it"); if (all[0] !== b) p.push("drawn as a new element"); if (!b.isConnected || [...b.parentElement.children].indexOf(b) !== window.__at) p.push("moved from " + window.__at); if (Math.abs(r.left - window.__r.left) > 0.5 || (Math.abs(r.top - window.__r.top) > 1 && Math.abs(r.bottom - window.__r.bottom) > 1)) p.push("jumped from " + JSON.stringify(window.__r) + " to " + JSON.stringify(r)); if (b.matches(".thinking, .draft") || b.querySelector(".think-line")) p.push("still thinking: " + b.outerHTML); if (document.querySelector("#ask-panel .thinking")) p.push("a bubble still shows"); return p.join("; "); })()`); got != "" { t.Errorf("the reply %q: %s", text, got) } // The spark fades and its loop ends. th.wait(`!document.querySelector("#ask-panel canvas")`) drive(t, rig, chromedp.Evaluate[chromedp.Void](countFramesJS), chromedp.Sleep(300*time.Millisecond)) if n := harness.Evaluate[int](rig, `window.__raf`); n != 0 { t.Errorf("answered, the page asked for %d frames", n) } if got := th.eval(statusJS); got != `"" empty` { t.Errorf("answered, the status line is %s", got) } } mark := chromedp.Evaluate[chromedp.Void](`(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `); window.__b = b; window.__at = [...b.parentElement.children].indexOf(b); window.__r = b.getBoundingClientRect(); })()`) drive(t, rig, mark) f.Answer(id, "Here's what I can do.", false) same("Here's what I can do.") // Streamed: the words fill the bubble, which then becomes the reply. id = th.send("And what else?") drive(t, rig, mark) f.Answer(id, "Plan work, check on a project, or start a task.", true) same("Plan work, check on a project, or start a task.") // Scripts off, the status line says it, as before; back on, the bubble // is drawn again. said := th.eval(`document.querySelectorAll("#ask-panel .msg.coordinator").length + ""`) id = th.send("Build me a site") drive(t, rig, scriptsDisabled(true), chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(`.ask-page textarea`))) if got := harness.Evaluate[string](rig, `(() => { const s = document.querySelector(".ask-page .ask-status"); return s.textContent + " " + s.checkVisibility() + " " + document.querySelectorAll(".thinking").length; })()`); got != "Thinking… true 0" { t.Errorf("scripts off, while answering: %s, want the status line and no bubble", got) } drive(t, rig, scriptsDisabled(false)) openPanel(t, rig) th.wait(`(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `); return b && b.textContent === "" && b.querySelectorAll(".dots > i").length === 3; })()`) // Stop takes the bubble away, and its spark with it. drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .thinking") && document.querySelector("#ask-panel form.composer button.stop").hidden`) if got := th.eval(`document.querySelectorAll("#ask-panel canvas").length + " " + document.querySelectorAll("#ask-panel .msg.coordinator").length`); got != "0 "+said { t.Errorf("stopped: canvases and Assistant lines %s, want 0 %s", got, said) } if got := th.eval(statusJS); got != `"" empty` { t.Errorf("stopped, the status line is %s", got) } if f.Turn(id) != "cancelled" { t.Errorf("Stop left the turn %s", f.Turn(id)) } // A failure takes it away too, and says so where it always has. id = th.send("Try this") f.FailTurn(id) th.wait(`!document.querySelector("#ask-panel .thinking")`) if got := th.eval(statusJS); got != `"That didn't get an answer. Try again." shown` { t.Errorf("failed, the status line is %s", got) } if n := th.eval(`document.querySelectorAll("#ask-panel canvas").length + ""`); n != "0" { t.Errorf("failed, %s canvases", n) } // Failing after some words have streamed in takes them away too. id = th.send("Try this again") f.Stream(id, "Half an answer that never") th.wait(`document.querySelector("#ask-panel .msg.draft")?.textContent === "Half an answer that never"`) f.FailTurn(id) th.wait(`document.querySelector("#ask-panel form.composer button.stop").hidden`) drive(t, rig, chromedp.Sleep(200*time.Millisecond)) if got := th.eval(`document.querySelectorAll("#ask-panel .thinking, #ask-panel .draft, #ask-panel canvas").length + " " + [...document.querySelectorAll("#ask-panel .msg.coordinator")].filter(m => m.textContent.includes("Half an answer")).length`); got != "0 0" { t.Errorf("failed while streaming: bubbles, drafts and canvases, then lines with its words %s, want 0 0", got) } if got := th.eval(statusJS); got != `"That didn't get an answer. Try again." shown` { t.Errorf("failed while streaming, the status line is %s", got) } // A team_update turn is quiet: no bubble. f.Hold = false quiet := f.EmitTurn("team_update", "running") f.Emit("activity", map[string]string{"turn_id": quiet, "label": "Looking at the job"}) f.Say("Have a look.") th.wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent === "Have a look.")`) drive(t, rig, chromedp.Sleep(200*time.Millisecond)) if got := th.eval(`document.querySelectorAll("#ask-panel .thinking, #ask-panel canvas").length + " " + document.querySelector("#ask-panel form.composer button.stop").hidden`); got != "0 true" { t.Errorf("with a team_update turn running: bubbles and canvases, Stop hidden %s", got) } // An ordinary send, answered at once: the turn's events (and its first // words) can come before the send's own answer, which carries the turn // as it was queued. Once the reply is in, nothing is left thinking. drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do\r")) th.wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.dataset.id && m.textContent.includes("What would you like to do?"))`) drive(t, rig, chromedp.Sleep(800*time.Millisecond)) if got := th.eval(`document.querySelectorAll("#ask-panel .thinking, #ask-panel .draft, #ask-panel .think-line, #ask-panel canvas").length + " " + document.querySelector("#ask-panel form.composer button.stop").hidden + " " + JSON.stringify(document.querySelector("#ask-panel .ask-status").textContent)`); got != `0 true ""` { t.Errorf("answered at once: bubbles, drafts and canvases, Stop hidden, status %s", got) } } // With reduced motion the bubble glows, still, and its dots hold still in // teal, violet and rose: no spark, no frames. Without // WebGL, or when its context is lost, a CSS sweep runs round the edge // instead. func TestAskThinkingStillAndFallback(t *testing.T) { rig, f := askBase(t) t.Run("reduced motion", func(t *testing.T) { th := thinking{t, rig, f} drive(t, rig, reducedMotion("dark", true)) defer drive(t, rig, reducedMotion("dark", false)) openPanel(t, rig) th.send("What can I do") drive(t, rig, chromedp.Evaluate[chromedp.Void](countFramesJS), chromedp.Sleep(400*time.Millisecond)) if got := th.eval(`(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `), s = getComputedStyle(b, "::before"), p = []; if (b.querySelector("canvas")) p.push("a spark canvas"); if (window.__raf) p.push(window.__raf + " frames"); if (s.animationName !== "none") p.push("the edge moves: " + s.animationName); if (!(Number(s.opacity) > 0)) p.push("no glow on the edge"); const d = [...b.querySelectorAll(".dots > i")]; if (d.length !== 3) p.push(d.length + " dots"); for (const i of d) { const c = getComputedStyle(i); if (c.animationName !== "none" || i.getAnimations().length) p.push("a dot moves: " + c.animationName); if (!(Number(c.opacity) > 0.3)) p.push("a dot is faint: " + c.opacity); } if (d.length === 3 && getComputedStyle(d[0]).backgroundColor === getComputedStyle(d[2]).backgroundColor) p.push("the still dots are one colour"); return p.join("; "); })()`); got != "" { t.Errorf("reduced motion, thinking: %s", got) } drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .thinking")`) }) t.Run("no WebGL", func(t *testing.T) { th := thinking{t, rig, f} openPanel(t, rig) drive(t, rig, chromedp.Evaluate[chromedp.Void](noGLJS)) th.send("What can I do") th.wait(`document.querySelector(` + strconv.Quote(thinkingSel) + `).matches(".no-gl")`) if got := th.eval(`(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `), s = getComputedStyle(b, "::before"); return b.classList.contains("no-gl") + " " + !!b.querySelector("canvas") + " " + s.animationName; })()`); got != "true false sweep" { t.Errorf("without WebGL: fallback, canvas, edge animation %s; want true false sweep", got) } rig.Screen("#ask-panel", "the thinking bubble without WebGL") drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .thinking")`) }) t.Run("context lost", func(t *testing.T) { th := thinking{t, rig, f} openPanel(t, rig) th.send("What can I do") th.wait(`!!document.querySelector(` + strconv.Quote(thinkingSel+" canvas") + `)`) drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelector(`+strconv.Quote(thinkingSel+" canvas")+`).getContext("webgl").getExtension("WEBGL_lose_context").loseContext()`)) th.wait(`(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `); return b.classList.contains("no-gl") && !b.querySelector("canvas"); })()`) drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .thinking")`) }) } // The composer's focus is a thin teal-to-violet edge round the field that // drifts, over a soft glow that breathes, in place of the outline; no // spark. With reduced motion both hold still. func TestAskComposerFocusEdge(t *testing.T) { rig, f := askBase(t) th := thinking{t, rig, f} openPanel(t, rig) edge := `(() => { const ta = document.querySelector("#ask-text"), s = getComputedStyle(ta), e = getComputedStyle(ta.parentElement, "::after"); return [document.activeElement === ta, e.opacity, s.outlineStyle, s.boxShadow !== "none", s.animationName, e.animationName, e.animationPlayState, /conic-gradient/.test(e.backgroundImage), e.getPropertyValue("--ring").trim(), e.top, document.querySelectorAll("#ask-panel form.composer canvas, #ask-panel form.composer .spark").length].join(" "); })()` drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelector("#ask-text").focus()`)) th.wait(`getComputedStyle(document.querySelector("#ask-text").parentElement, "::after").opacity === "1"`) if got, want := th.eval(edge), "true 1 none true breathe-glow edge-turn running true 2px -3px 0"; got != want { t.Errorf("focused: %s, want %s", got, want) } rig.Screen("#ask-panel", "the composer's focus edge") drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelector("#ask-text").blur()`)) th.wait(`getComputedStyle(document.querySelector("#ask-text").parentElement, "::after").opacity === "0"`) if got := th.eval(`getComputedStyle(document.querySelector("#ask-text")).boxShadow`); got != "none" { t.Errorf("blurred, the field's glow is %s", got) } drive(t, rig, reducedMotion("dark", true), chromedp.Evaluate[chromedp.Void](`document.querySelector("#ask-text").focus()`)) defer drive(t, rig, reducedMotion("dark", false)) th.wait(`getComputedStyle(document.querySelector("#ask-text").parentElement, "::after").opacity === "1"`) if got, want := th.eval(edge), "true 1 none true none none running true 2px -3px 0"; got != want { t.Errorf("reduced motion, focused: %s, want %s", got, want) } } // TestAskThinkingShots keeps the thinking bubble and the focus edge at // 1280 and 390, dark and light, in BASE_BROWSER_ARTIFACTS when it is set. func TestAskThinkingShots(t *testing.T) { rig, f := askBase(t) th := thinking{t, rig, f} for _, size := range []struct { name string view chromedp.Action[chromedp.Void] }{ {"1280", chromedp.EmulateViewport(1280, 800)}, {"390", chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3))}, } { for _, scheme := range []string{"dark", "light"} { drive(t, rig, size.view, reducedMotion(scheme, false)) if size.name == "390" { drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`a.base-btn`)), chromedp.Click(chromedp.CSS(`a.base-btn`)), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)), chromedp.Poll[chromedp.Void](readJS, chromedp.WithPollingTimeout(5*time.Second)), chromedp.Sleep(500*time.Millisecond)) } else { openPanel(t, rig) } name := fmt.Sprintf("%s-%s", size.name, scheme) drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelector("#ask-text").focus()`), chromedp.Sleep(700*time.Millisecond)) viewportShot(t, rig, name+"-focus") id := th.send("Can you make me a website?") f.Emit("activity", map[string]string{"turn_id": id, "label": "Looking at what I can do…"}) drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`), chromedp.Sleep(1200*time.Millisecond)) viewportShot(t, rig, name+"-thinking") drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .thinking")`) } } } // Equipo's delta offsets count UTF-8 bytes: a reply with letters beyond // ASCII streams into the bubble whole, every piece after the first é or ’ // included, before the reply itself arrives. func TestAskStreamCountsBytes(t *testing.T) { rig, f := askBase(t) openPanel(t, rig) th := thinking{t, rig, f} const text = "café ’quoted’ – done" id := th.send("Say something") f.Stream(id, text) drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector("#ask-panel .msg.draft")?.textContent === `+strconv.Quote(text), chromedp.WithPollingTimeout(5*time.Second))) if got := th.eval(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].filter(m => m.dataset.id).length + " " + document.querySelectorAll("#ask-panel .msg.coordinator").length`); got != "0 1" { t.Errorf("streamed, before the reply: delivered and drawn Assistant lines %s, want 0 1", got) } f.Answer(id, text, false) th.wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.dataset.id && m.textContent === ` + strconv.Quote(text) + `)`) if n := th.eval(`document.querySelectorAll("#ask-panel .msg.coordinator").length + ""`); n != "1" { t.Errorf("answered: %s Assistant lines, want 1", n) } } // watchJS keeps the thinking bubble in window.__b, where it is, and from // now on, frame by frame, the page's times (performance.now) at which g // first shows in it, its line laid out and not transparent (window.__g), // and then first starts to go: fading out, or replaced (window.__x). func watchJS(g string) string { return `(() => { const b = document.querySelector(` + strconv.Quote(thinkingSel) + `), g = ` + strconv.Quote(g) + `; window.__b = b; window.__at = [...b.parentElement.children].indexOf(b); window.__r = b.getBoundingClientRect(); window.__g = 0; window.__x = 0; const look = () => { const l = b.querySelector(":scope > .think-line"), now = performance.now(); const s = l && getComputedStyle(l), says = b.textContent === g, kid = l && [...l.children].find(c => c.textContent === g); if (!window.__g && says && kid && s.display !== "none" && Number(s.opacity) > 0 && Number(getComputedStyle(kid).opacity) > 0) window.__g = now; const fading = l && l.getAnimations({ subtree: true }).some(a => { const k = a.effect.getKeyframes(); return (a.effect.target === l || a.effect.target === kid) && Number(k[0].opacity) === 1 && Number(k[k.length - 1].opacity) === 0; }); if (window.__g && !window.__x && (!says || fading)) window.__x = now; if (!window.__x && b.isConnected) requestAnimationFrame(look); }; requestAnimationFrame(look); })()` } // inPlaceJS reports how the watched bubble is not the reply text, where it // was. func inPlaceJS(text string) string { return `(() => { const b = window.__b, p = [], r = b.getBoundingClientRect(); if (!b.isConnected || [...b.parentElement.children].indexOf(b) !== window.__at) p.push("moved from " + window.__at); if (b.textContent !== ` + strconv.Quote(text) + ` || !b.dataset.id) p.push("says " + JSON.stringify(b.textContent)); if (Math.abs(r.left - window.__r.left) > 0.5) p.push("jumped from " + window.__r.left + " to " + r.left); if (document.querySelector("#ask-panel .thinking, #ask-panel .draft")) p.push("still thinking"); return p.join("; "); })()` } // Equipo's glance, a first line on the turn in flight, takes the dots' // place in the bubble, fading in, and stays over Equipo's activity lines. // A reply that comes soon after waits until the glance has shown for 1.5 // s, then takes its place where it is; a reply that comes later takes it // at once. A glance after the turn's first words, for a team_update turn, // or for a turn the page is not answering shows nowhere. Glances are live // only, as Equipo sends them: no id, and a page that comes back never sees // one again. func TestAskGlance(t *testing.T) { rig, f := askBase(t) openPanel(t, rig) th := thinking{t, rig, f} const glance = "Checking your projects" // The glance takes the dots' place, fading in, and stays. id := th.send("What's on today?") drive(t, rig, chromedp.Evaluate[chromedp.Void](watchJS(glance))) f.Glance(id, " "+glance+"\n") th.wait(`window.__g > 0`) th.wait(`(() => { const l = document.querySelector(` + strconv.Quote(thinkingSel+" .think-line") + `); return l && l.getAnimations({ subtree: true }).some(a => a.playState === "running" && a.effect.target.textContent === ` + strconv.Quote(glance) + ` && Number(a.effect.getKeyframes()[0].opacity) === 0); })()`) th.wait(`!window.__b.querySelector(":scope > .think-line > .dots")`) // faded out under the glance if got := th.eval(`(() => { const b = window.__b, p = []; if (b.querySelector(":scope > .think-line > .dots")) p.push("the wordless dots still show"); if (!b.matches(".thinking") || !b.querySelector("canvas")) p.push("no longer thinking, with its spark"); if (document.querySelectorAll("#ask-panel .thinking").length !== 1) p.push(document.querySelectorAll("#ask-panel .thinking").length + " bubbles"); if (document.querySelector("#ask-panel .ask-status").textContent) p.push("the status line says " + document.querySelector("#ask-panel .ask-status").textContent); return p.join("; "); })()`); got != "" { t.Errorf("with a glance: %s", got) } rig.Screen("#ask-panel", "the thinking bubble with Equipo's glance") f.Emit("activity", map[string]string{"turn_id": id, "label": "Looking at what I can do…"}) // A reply 200 ms after the glance waits until it has shown 1.5 s, then // takes its place. g := harness.Evaluate[float64](rig, `window.__g`) for harness.Evaluate[float64](rig, `performance.now()`) < g+200 { time.Sleep(10 * time.Millisecond) } const soon = "Two meetings and a review." f.Answer(id, soon, true) th.wait(`window.__b.dataset.id && window.__b.textContent === ` + strconv.Quote(soon) + ` && !document.querySelector("#ask-panel .think-line")`) if held := harness.Evaluate[float64](rig, `window.__x - window.__g`); held < 1480 || held > 2300 { t.Errorf("a reply 200 ms after the glance showed began to replace it %.0f ms after it showed, want about 1500", held) } if got := th.eval(inPlaceJS(soon)); got != "" { t.Errorf("the reply soon after a glance: %s", got) } // A reply 3 s after the glance takes its place at once. id = th.send("And tomorrow?") drive(t, rig, chromedp.Evaluate[chromedp.Void](watchJS(glance))) f.Glance(id, glance) th.wait(`window.__g > 0`) f.Emit("activity", map[string]string{"turn_id": id, "label": "Looking at what I can do…"}) drive(t, rig, chromedp.Sleep(3*time.Second)) if got := th.eval(`window.__b.textContent`); got != glance { t.Errorf("3 s after the glance (an activity line came), the bubble says %q", got) } const later = "Nothing yet." drive(t, rig, chromedp.Evaluate[chromedp.Void](`window.__sent = performance.now()`)) f.Answer(id, later, false) th.wait(`window.__b.dataset.id && window.__b.textContent === ` + strconv.Quote(later) + ` && !document.querySelector("#ask-panel .think-line")`) if took := harness.Evaluate[float64](rig, `window.__x - window.__sent`); took > 700 { t.Errorf("a reply 3 s after the glance took %.0f ms to replace it", took) } if got := th.eval(inPlaceJS(later)); got != "" { t.Errorf("the reply 3 s after a glance: %s", got) } // Without a glance, an activity line still takes the dots' place. id = th.send("What else?") f.Emit("activity", map[string]string{"turn_id": id, "label": "Looking at what I can do…"}) th.wait(`document.querySelector(` + strconv.Quote(thinkingSel) + `)?.textContent === "Looking at what I can do…"`) // A glance after the first words shows nowhere. f.Stream(id, "Half an answer") th.wait(`document.querySelector("#ask-panel .msg.draft")?.textContent === "Half an answer"`) f.Glance(id, "A late glance") drive(t, rig, chromedp.Sleep(500*time.Millisecond)) if got := th.eval(`document.querySelector("#ask-panel .msg.draft")?.textContent + " " + document.querySelector("#ask-panel").textContent.includes("A late glance")`); got != "Half an answer false" { t.Errorf("a glance after the first words: draft and glance shown %s", got) } drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .draft, #ask-panel .thinking") && document.querySelector("#ask-panel form.composer button.stop").hidden`) // A glance for a turn the page is not answering shows nowhere, nor for // a team_update turn, even on a page that has come back since (whose // stream has not seen the turn start). id = th.send("One more") f.Hold = false quiet := f.EmitTurn("team_update", "running") f.Glance(quiet, "Checking the job") drive(t, rig, chromedp.Sleep(300*time.Millisecond)) openPanel(t, rig) th.wait(`document.querySelectorAll(` + strconv.Quote(thinkingSel) + `).length === 1`) f.Glance(quiet, "Checking the job") f.Glance("t_9999", "Someone else's turn") drive(t, rig, chromedp.Sleep(500*time.Millisecond)) if got := th.eval(`(() => { const p = document.querySelector("#ask-panel"), b = document.querySelectorAll(` + strconv.Quote(thinkingSel) + `); return [p.textContent.includes("Checking the job"), p.textContent.includes("Someone else"), b.length, b[0] && b[0].querySelectorAll(".dots > i").length].join(" "); })()`); got != "false false 1 3" { t.Errorf("glances for other turns: quiet shown, other shown, bubbles, dots %s; want false false 1 3", got) } f.Glance(id, glance) th.wait(`document.querySelector(` + strconv.Quote(thinkingSel) + `)?.textContent === ` + strconv.Quote(glance)) // A glance is live only (no id, never sent again) and never kept: the // page that comes back shows the dots, and the events after it still // arrive. openPanel(t, rig) th.wait(`document.querySelectorAll(` + strconv.Quote(thinkingSel+" .dots > i") + `).length === 3`) drive(t, rig, chromedp.Sleep(300*time.Millisecond)) if got := th.eval(`document.querySelector("#ask-panel").textContent.includes(` + strconv.Quote(glance) + `) + ""`); got != "false" { t.Errorf("after coming back, the glance shows again") } f.Answer(id, "All done.", false) th.wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.dataset.id && m.textContent === "All done.") && !document.querySelector("#ask-panel .thinking")`) } // glanceJS reports how the watched bubble's glance (window.__b) does not // read as a status: secondary ink (want), italic, one line, the three dots // after its words, hidden from assistive tech, shimmering or (still) not. func glanceJS(want string, still bool) string { return `(() => { const b = window.__b, say = b.querySelector(":scope > .think-line > .say"), p = []; if (!say) return "no status words"; const w = say.querySelector(":scope > .words"), d = [...say.querySelectorAll(":scope > .dots > i")], s = getComputedStyle(say); if (s.fontStyle !== "italic" || getComputedStyle(w).fontStyle !== "italic") p.push("upright"); if (s.color !== ` + strconv.Quote(want) + `) p.push("ink " + s.color); if (getComputedStyle(w).whiteSpace !== "nowrap") p.push("wraps"); if (d.length !== 3) p.push(d.length + " dots after the words"); if (say.querySelector(".dots")?.getAttribute("aria-hidden") !== "true") p.push("the dots are read out"); if (d.length && d[0].getBoundingClientRect().left < w.getBoundingClientRect().right - 0.5) p.push("the dots are not after the words"); for (const i of d) { const c = getComputedStyle(i), moving = c.animationName === "think-dot, think-hue"; if (moving === ` + strconv.FormatBool(still) + `) p.push("a dot: " + c.animationName); if (i.getBoundingClientRect().width < 4 || !(Number(c.opacity) > 0.3)) p.push("a dot hardly shows"); } return p.join("; "); })()` } // A glance (or an activity line) is a status, not a reply: secondary ink, // italic, AA on the bubble in dark and light, and the soft dots after it, // still shimmering, so the Assistant is plainly still working (holding // still with reduced motion). The reply that takes its place is upright, // in full ink, with no dots. func TestAskGlanceReadsAsStatus(t *testing.T) { rig, f := askBase(t) th := thinking{t, rig, f} const glance, reply = "Yo, Paul.", "Here is what I found." for _, c := range []struct { scheme string still bool haze, frost string }{ {"dark", false, "rgb(221, 227, 240)", "rgb(238, 242, 248)"}, {"light", false, "rgb(74, 82, 117)", "rgb(30, 36, 64)"}, {"dark", true, "rgb(221, 227, 240)", "rgb(238, 242, 248)"}, } { when := c.scheme + map[bool]string{false: "", true: ", reduced motion"}[c.still] drive(t, rig, chromedp.EmulateViewport(1280, 800), reducedMotion(c.scheme, c.still)) openPanel(t, rig) id := th.send("Anything new?") drive(t, rig, chromedp.Evaluate[chromedp.Void](watchJS(glance))) f.Glance(id, glance) th.wait(`window.__g > 0 && !window.__b.querySelector(":scope > .think-line > .dots") && !window.__b.getAnimations({ subtree: true }).some(a => !(a instanceof CSSAnimation))`) if got := th.eval(glanceJS(c.haze, c.still)); got != "" { t.Errorf("%s, the glance: %s", when, got) } if !c.still { worst, need, where := textContrast(t, rig, thinkingSel+" .say") t.Logf("%s: the glance's contrast %.2f (%q)", when, worst, where) if worst < need { t.Errorf("%s: the glance %q has contrast %.2f, needs %.1f", when, where, worst, need) } rig.Screen("#ask-panel", "the glance as a status, "+when) } f.Answer(id, reply, false) th.wait(`window.__b.dataset.id && window.__b.textContent === ` + strconv.Quote(reply) + ` && !document.querySelector("#ask-panel .think-line") && !window.__b.getAnimations({ subtree: true }).length`) if got := th.eval(`(() => { const b = window.__b, p = []; for (const e of [b, ...b.querySelectorAll("*")]) { const s = getComputedStyle(e); if (s.fontStyle !== "normal") p.push(e.tagName + " " + s.fontStyle); if (s.color !== ` + strconv.Quote(c.frost) + `) p.push(e.tagName + " ink " + s.color); } if (b.querySelector(".dots, .say")) p.push("status left in it: " + b.innerHTML); return p.join("; "); })()`); got != "" { t.Errorf("%s, the reply: %s", when, got) } } drive(t, rig, reducedMotion("dark", false)) } // steadyJS watches the thinking bubble frame by frame from now on, until // window.__stop: in window.__steady, every frame's problem (no words or // dots in view, the line's text empty once words have come, the bubble's // height changing, its width shrinking), and in window.__frames how many // frames it saw, and in window.__anims how many animations were started // in it. const steadyJS = `(() => { const b = document.querySelector("#ask-panel .thread > li.msg.coordinator.thinking"), l = b.querySelector(":scope > .think-line"); const h0 = b.getBoundingClientRect().height; let w = b.getBoundingClientRect().width, worded = false; window.__steady = []; window.__frames = 0; window.__stop = false; window.__anims = 0; if (!window.__animWrapped) { const animate = Element.prototype.animate; window.__animWrapped = true; Element.prototype.animate = function (...args) { if (this.closest && this.closest(".thinking")) window.__anims++; return animate.apply(this, args); }; } const look = () => { const r = b.getBoundingClientRect(), p = []; window.__frames++; if (![...l.children].some(c => Number(getComputedStyle(c).opacity) > 0)) p.push("nothing in view"); if (l.textContent) worded = true; else if (worded) p.push("the line is empty"); if (Math.abs(r.height - h0) > 0.5) p.push("height " + r.height + ", was " + h0); if (r.width < w - 0.5) p.push("width " + r.width + ", was " + w); w = Math.max(w, r.width); if (p.length && window.__steady.length < 20) window.__steady.push(p.join(", ")); if (!window.__stop && b.isConnected) requestAnimationFrame(look); }; requestAnimationFrame(look); })()` // While the Assistant thinks, its bubble holds steady as its line changes // (dots, then one activity line after another, long and short): the new // words fade in over the old as they fade out, never a blank moment; the // line stays on one line (a long one ends in an ellipsis); the bubble's // height holds and its width only grows, easing. With reduced motion the // swaps are instant, by the same size rules. func TestAskThinkingHoldsSteady(t *testing.T) { rig, f := askBase(t) long := "Reading through every one of your projects, their open tasks, recent changes and the notes your team left on each of them"[:120] lines := []string{"Looking at what I can do…", "Checking", long, "Reading your recent projects and what changed in them…"} for _, still := range []bool{false, true} { name := map[bool]string{false: "moving", true: "reduced motion"}[still] t.Run(name, func(t *testing.T) { th := thinking{t, rig, f} drive(t, rig, reducedMotion("dark", still)) defer drive(t, rig, reducedMotion("dark", false)) openPanel(t, rig) id := th.send("What's going on?") drive(t, rig, chromedp.Sleep(300*time.Millisecond), chromedp.Evaluate[chromedp.Void](steadyJS)) for i, line := range lines { f.Emit("activity", map[string]string{"turn_id": id, "label": line}) if i == 1 { // One comes hard on the last's heels, mid-crossfade. drive(t, rig, chromedp.Sleep(100*time.Millisecond)) continue } th.wait(`document.querySelector(` + strconv.Quote(thinkingSel+" .think-line") + `).textContent === ` + strconv.Quote(line)) if line == long { if got := th.eval(`(() => { const l = document.querySelector(` + strconv.Quote(thinkingSel+" .think-line") + `), c = l.lastElementChild.querySelector(".words"), s = getComputedStyle(c); const d = l.lastElementChild.querySelector(".dots").getBoundingClientRect(), b = l.parentElement.getBoundingClientRect(); return [c.getClientRects().length, Math.round(c.getBoundingClientRect().height) <= Math.ceil(parseFloat(s.lineHeight)), c.scrollWidth > c.clientWidth, s.textOverflow, d.width > 0 && d.left >= c.getBoundingClientRect().right - 0.5 && d.right <= b.right].join(" "); })()`); got != "1 true true ellipsis true" { t.Errorf("the 120-character line: boxes, one line high, clipped, overflow, dots in view after it %s; want 1 true true ellipsis true", got) } } drive(t, rig, chromedp.Sleep(400*time.Millisecond)) } drive(t, rig, chromedp.Evaluate[chromedp.Void](`window.__stop = true`)) if got := th.eval(`JSON.stringify(window.__steady)`); got != "[]" { t.Errorf("thinking through %d lines: %s", len(lines), got) } if n := harness.Evaluate[int](rig, `window.__frames`); n < 20 { t.Errorf("watched only %d frames", n) } if n := harness.Evaluate[int](rig, `window.__anims`); (n == 0) != still { t.Errorf("reduced motion %v: %d animations in the bubble", still, n) } if !still { rig.Screen("#ask-panel", "the thinking bubble after a long activity line") } drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.stop`))) th.wait(`!document.querySelector("#ask-panel .thinking")`) }) } } // A streamed reply shows formatted as it arrives: bold, a link and a list // item split across deltas never show a "**", "[" or "](" mid-stream (an // opener with no closer yet is plain words, a link on its way shows its // words), and the reply that settles is drawn as the same reply that // came whole. func TestAskStreamFormatsAsItArrives(t *testing.T) { rig, f := askBase(t) openPanel(t, rig) th := thinking{t, rig, f} const text = "Here is **bold text** and a [guide page](https://example.com/guide) too.\n- first *item* here\n- second [more](https://example.com/more)\n" parts := []string{"Here is *", "*bo", "ld te", "xt**", " and a [gu", "ide page", "](http", "s://example.com/gu", "ide) too.\n-", " first *it", "em* here\n", "- sec", "ond [more]", "(https://example.com/more)", "\n"} if strings.Join(parts, "") != text { t.Fatal("the test's pieces are not its text") } id := th.send("Say it formatted") th.eval(`(() => { window.__seen = []; window.__bad = []; const look = () => { for (const d of document.querySelectorAll("#ask-panel .msg.draft")) { const t = d.textContent; window.__seen.push(d.innerHTML); if (/\*\*|\[|\]\(/.test(t)) window.__bad.push(t); } }; new MutationObserver(look).observe(document.querySelector("#ask-panel"), { childList: true, subtree: true, characterData: true }); return "ok"; })()`) f.StreamParts(id, parts) th.wait(`document.querySelector("#ask-panel .msg.draft strong") && document.querySelector("#ask-panel .msg.draft li:last-child a[href$=\"/more\"]")`) if got := th.eval(`JSON.stringify(window.__bad)`); got != "[]" { t.Errorf("markup showed while streaming: %s", got) } if got := th.eval(`window.__seen.length + ""`); got == "0" { t.Error("nothing was drawn as it streamed") } last := th.eval(`(document.querySelector("#ask-panel .msg.draft > .think-line") || document.querySelector("#ask-panel .msg.draft")).innerHTML`) f.Answer(id, text, false) th.wait(`document.querySelector("#ask-panel .msg.coordinator[data-id] strong")`) streamed := th.eval(`(() => { const m = [...document.querySelectorAll("#ask-panel .msg.coordinator")].find(m => m.dataset.id && m.querySelector("strong")); return (m.querySelector(":scope > .think-line") || m).innerHTML })()`) if streamed != last { t.Errorf("the settled reply differs from the last draft:\n%s\n%s", streamed, last) } // The same reply that was never streamed. id2 := th.send("Say it again") f.Answer(id2, text, false) th.wait(`document.querySelectorAll("#ask-panel .msg.coordinator[data-id] strong").length === 2`) whole := th.eval(`(() => { const m = [...document.querySelectorAll("#ask-panel .msg.coordinator")].filter(m => m.dataset.id && m.querySelector("strong"))[1]; return (m.querySelector(":scope > .think-line") || m).innerHTML })()`) if streamed != whole { t.Errorf("streamed and whole replies differ:\n%s\n%s", streamed, whole) } if !strings.Contains(whole, "bold text") || !strings.Contains(whole, `href="https://example.com/guide"`) || strings.Count(whole, "
  • ") != 2 { t.Errorf("the reply is not formatted: %s", whole) } }