oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package browsertest
4
5import (
6 "context"
7 "net/http"
8 "os"
9 "path/filepath"
10 "regexp"
11 "strconv"
12 "sync"
13 "testing"
14 "time"
15
16 "github.com/chromedp/cdproto/cdp"
17 "github.com/chromedp/cdproto/input"
18 "github.com/chromedp/chromedp"
19
20 "amadan.net/rastrillo/rastrillo/harness"
21
22 "amadan.net/oficina/base/internal/config"
23 "amadan.net/oficina/base/internal/equipo/equipotest"
24)
25
26// askBase is Base answered by a fake Equipo, the owner signed in and
27// connected to it from Settings: Set up Ask Base, approve the code in
28// Equipo, Check again.
29func askBase(t *testing.T) (*harness.Rig, *equipotest.Fake) {
30 t.Helper()
31 rig, f, _ := askBaseWith(t, nil)
32 return rig, f
33}
34
35// askBaseWith is askBase with a last say over Base's configuration.
36func askBaseWith(t *testing.T, tweak func(*config.Config)) (*harness.Rig, *equipotest.Fake, *baseApp) {
37 t.Helper()
38 return askBaseOn(t, tweak, nil)
39}
40
41// askBaseOn is askBaseWith on a screen of view's size, set before anything
42// loads (a phone: taps then land where they are drawn); nil is 1280x800,
43// set after signing in.
44func askBaseOn(t *testing.T, tweak func(*config.Config), view chromedp.Action[chromedp.Void]) (*harness.Rig, *equipotest.Fake, *baseApp) {
45 t.Helper()
46 f := equipotest.New(t)
47 f.Reply = func(string) string {
48 return "You can ask me to plan work, check on a project, or start a task. What would you like to do?"
49 }
50 var b *baseApp
51 rig := newRig(t, func(origin string) http.Handler {
52 cfg := baseConfig(origin)
53 cfg.EquipoOrigin = f.URL
54 if tweak != nil {
55 tweak(&cfg)
56 }
57 b = newBase(t, cfg)
58 return b.handler
59 })
60 if view != nil {
61 drive(t, rig, view)
62 }
63 signInByEmail(t, rig, rig.Origin, b.mail)
64 if view == nil {
65 drive(t, rig, chromedp.EmulateViewport(1280, 800))
66 }
67 connect := `form[action="/ask/connect"] button`
68 drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(connect)),
69 chromedp.Click(chromedp.CSS(connect)), chromedp.WaitVisible(chromedp.CSS(`p.code`)))
70 rig.Screen(".card", "Set up Ask Base, waiting for approval")
71 code := harness.Evaluate[string](rig, `document.querySelector("p.code").textContent`)
72 if !regexp.MustCompile(`^[A-Z0-9]{8}$`).MatchString(code) {
73 t.Fatalf("code %q", code)
74 }
75 if err := f.Approve(code); err != nil {
76 t.Fatal(err)
77 }
78 if _, err := b.db.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
79 t.Fatal(err)
80 }
81 drive(t, rig, chromedp.Click(chromedp.CSS(`form[action="/ask/connect/check"] button`)),
82 chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
83 rig.Screen(".sheet", "Settings, Ask Base set up")
84 return rig, f, b
85}
86
87// settledJS is true once the docked chat is open and done moving.
88const settledJS = `(() => { const d = document.querySelector("#ask-panel"), s = getComputedStyle(d);
89 return d.checkVisibility({ visibilityProperty: true }) && s.opacity === "1" && (s.transform === "none" || s.transform === "matrix(1, 0, 0, 1, 0, 0)"); })()`
90
91// readJS is true once the chat has read the conversation afresh (its
92// /ask/state answer is in), so what a test does next is not undone by it.
93const readJS = `performance.getEntriesByType("resource").some((e) => e.name.includes("/ask/state") && e.responseEnd > 0)`
94
95// openPanel goes to Home, where on a wide screen Ask Base is docked open,
96// and waits for the chat to settle and read the conversation.
97func openPanel(t *testing.T, rig *harness.Rig) {
98 t.Helper()
99 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)),
100 chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(5*time.Second)),
101 chromedp.Poll[chromedp.Void](readJS, chromedp.WithPollingTimeout(5*time.Second)), chromedp.Sleep(100*time.Millisecond))
102}
103
104// slash presses "/" as a keyboard does: one keydown carrying the text, so
105// a page that handles the keydown types nothing.
106func slash() chromedp.Action[chromedp.Void] {
107 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
108 for _, typ := range []input.DispatchKeyEventType{input.DispatchKeyEventTypeKeyDown, input.DispatchKeyEventTypeKeyUp} {
109 k := input.DispatchKeyEventParams{Type: typ, Key: "/", Code: "Slash", WindowsVirtualKeyCode: 191, NativeVirtualKeyCode: 191}
110 if typ == input.DispatchKeyEventTypeKeyDown {
111 k.Text, k.UnmodifiedText = "/", "/"
112 }
113 if _, err := cdp.Call(ctx, target, input.DispatchKeyEvent, k); err != nil {
114 return err
115 }
116 }
117 return nil
118 })
119}
120
121// askClosed waits until the member's close of the docked chat is kept (or
122// its reopening, for false): the script posts it by fetch.
123func askClosed(t *testing.T, b *baseApp, want bool) {
124 t.Helper()
125 for i := 0; ; i++ {
126 var closed bool
127 if err := b.db.QueryRow(`SELECT ask_closed FROM members ORDER BY invited_at LIMIT 1`).Scan(&closed); err != nil {
128 t.Fatal(err)
129 }
130 if closed == want {
131 return
132 }
133 if i > 100 {
134 t.Fatalf("ask_closed is %v, want %v", closed, want)
135 }
136 time.Sleep(20 * time.Millisecond)
137 }
138}
139
140// A double press sends once, and sending again after an answer was lost
141// on the way back reuses the key, so Equipo does the work once.
142func TestAskPanelSendsOnce(t *testing.T) {
143 rig, f := askBase(t)
144 openPanel(t, rig)
145 send := `#ask-panel form.composer button.send`
146 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Build me a quick website"),
147 chromedp.Evaluate[chromedp.Void](`(() => { const b = document.querySelector("`+send+`"); b.click(); b.click(); })()`),
148 chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === 1`, chromedp.WithPollingTimeout(5*time.Second)))
149 if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
150 t.Fatalf("a double press sent %d requests", n)
151 }
152
153 f.FailNextSend()
154 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Put a meeting in my calendar with doc@tito.io for 2pm on Tuesday"),
155 chromedp.Click(chromedp.CSS(send)),
156 chromedp.Poll[chromedp.Void](`document.querySelector("#ask-panel .ask-status").textContent.includes("didn't send")`, chromedp.WithPollingTimeout(5*time.Second)),
157 chromedp.Click(chromedp.CSS(send)),
158 // A send that got its answer clears the field.
159 chromedp.Poll[chromedp.Void](`document.querySelector("#ask-text").value === ""`, chromedp.WithPollingTimeout(5*time.Second)))
160 if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 2 {
161 t.Errorf("person messages shown: %d, want 2", got)
162 }
163 calls := f.Calls("/api/v1/assistant/messages")
164 if len(calls) != 3 || calls[1].Header.Get("Idempotency-Key") != calls[2].Header.Get("Idempotency-Key") ||
165 calls[0].Header.Get("Idempotency-Key") == calls[1].Header.Get("Idempotency-Key") {
166 t.Fatalf("keys: %v", keys(calls))
167 }
168}
169
170// Without a runner that can answer, the panel says so with a link to
171// Equipo; a send keeps what the person wrote in the field and shows no
172// message; a runner too old has its own note.
173func TestAskPanelNoRunner(t *testing.T) {
174 rig, f := askBase(t)
175 f.NoRunner()
176 openPanel(t, rig)
177 note := `#ask-panel .ask-runner[data-when="norunner"]`
178 old := `#ask-panel .ask-runner[data-when="oldrunner"]`
179 drive(t, rig, chromedp.WaitVisible(chromedp.CSS(note)))
180 if !harness.Evaluate[bool](rig, `!!document.querySelector(`+strconv.Quote(note+` a[href="`+f.URL+`/"][target="_blank"]`)+`)`) {
181 t.Fatal("the no-runner note has no link to finish setting up")
182 }
183 rig.Screen("#ask-panel", "the panel without a runner")
184 // Each send moves the panel from one note to the other.
185 const text = "Build me a quick website"
186 f.RunnerTooOld()
187 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), text),
188 chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
189 chromedp.WaitVisible(chromedp.CSS(old)), chromedp.WaitNotVisible(chromedp.CSS(note)))
190 f.NoRunner()
191 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
192 chromedp.WaitVisible(chromedp.CSS(note)), chromedp.WaitNotVisible(chromedp.CSS(old)))
193 if n := len(f.Calls("/api/v1/assistant/messages")); n != 2 {
194 t.Fatalf("sends relayed: %d, want 2", n)
195 }
196 if got := harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`); got != text {
197 t.Errorf("the field holds %q, want %q", got, text)
198 }
199 if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); n != 0 {
200 t.Errorf("person messages shown: %d", n)
201 }
202 if got := harness.Evaluate[string](rig, `document.querySelector("#ask-panel .ask-status").textContent`); got != "" {
203 t.Errorf("status line %q", got)
204 }
205}
206
207// Home's panel draws the states it learns from the script: each shows its
208// approved words in the one visible note, and every other note is hidden.
209func TestAskPanelStatesShowApprovedWords(t *testing.T) {
210 const notes = `#ask-panel .ask-note, #ask-panel .ask-runner`
211 visible := func(t *testing.T, rig *harness.Rig) string {
212 return harness.Evaluate[string](rig, `[...document.querySelectorAll(`+strconv.Quote(notes)+`)]
213 .filter(el => el.checkVisibility()).map(el => el.dataset.when + "=" + el.textContent.replace(/\s+/g, " ").trim()).join("|")`)
214 }
215 openOnly := func(rig *harness.Rig, when string) {
216 drive(t, rig, chromedp.Navigate(rig.Origin+"/"),
217 chromedp.WaitVisible(chromedp.CSS(`#ask-panel .ask-note[data-when="`+when+`"], #ask-panel .ask-runner[data-when="`+when+`"]`)))
218 }
219 t.Run("unavailable", func(t *testing.T) {
220 rig, f := askBase(t)
221 f.FailSnapshots(true)
222 openOnly(rig, "unavailable")
223 if got, want := visible(t, rig), "unavailable=Ask Base isn't answering. Try again in a minute."; got != want {
224 t.Errorf("visible notes %q, want %q", got, want)
225 }
226 })
227 t.Run("norunner", func(t *testing.T) {
228 rig, f := askBase(t)
229 f.NoRunner()
230 openOnly(rig, "norunner")
231 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 {
232 t.Errorf("visible notes %q, want %q", got, want)
233 }
234 })
235 t.Run("oldrunner", func(t *testing.T) {
236 rig, f := askBase(t)
237 f.NoRunner()
238 openOnly(rig, "norunner")
239 f.RunnerTooOld()
240 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Build me a quick website"),
241 chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
242 chromedp.WaitVisible(chromedp.CSS(`#ask-panel .ask-runner[data-when="oldrunner"]`)))
243 if got, want := visible(t, rig), "oldrunner=Ask Base needs an update first. Update it, then try again."; got != want {
244 t.Errorf("visible notes %q, want %q", got, want)
245 }
246 })
247}
248
249func keys(calls []equipotest.Call) []string {
250 var out []string
251 for _, c := range calls {
252 out = append(out, c.Header.Get("Idempotency-Key"))
253 }
254 return out
255}
256
257// On a wide screen Home opens with Ask Base docked open on the right, from
258// under the header to the foot of the screen, beside Home; the greeting's
259// field has folded away and the Base button is hidden. The owner asks one
260// thing and sees the reply stream in, and "/" puts focus in the composer
261// from anywhere but a field.
262func TestAskDockedOpenByDefault(t *testing.T) {
263 rig, f := askBase(t)
264 openPanel(t, rig)
265 if got := harness.Evaluate[string](rig, `(() => {
266 const problems = [], vw = document.documentElement.clientWidth, vh = innerHeight;
267 const p = document.querySelector("#ask-panel").getBoundingClientRect(), bar = document.querySelector(".topbar").getBoundingClientRect();
268 const home = document.querySelector("main.home").getBoundingClientRect(), apps = document.querySelector("nav.apps").getBoundingClientRect();
269 const w = Math.min(440, Math.max(360, vw * 0.3));
270 if (Math.abs(p.width - w) > 1) problems.push("width " + p.width + ", want " + w);
271 if (p.top < bar.bottom || p.top > bar.bottom + 24) problems.push("top " + p.top + ", the header ends at " + bar.bottom);
272 if (p.bottom > vh || vh - p.bottom > 24) problems.push("bottom " + p.bottom + " of " + vh);
273 if (p.right > vw || vw - p.right > 24) problems.push("right " + p.right + " of " + vw);
274 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);
275 if (document.documentElement.classList.contains("desk-closed")) problems.push("drawn closed");
276 const field = document.querySelector(".ask-field"), btn = document.querySelector(".base-btn");
277 if (field.checkVisibility({ visibilityProperty: true }) || !field.closest(".ask-slot").inert) problems.push("the greeting's field shows");
278 if (btn.checkVisibility({ visibilityProperty: true })) problems.push("the Base button shows");
279 if (document.documentElement.scrollWidth > vw) problems.push("page overflows");
280 return problems.join("; ");
281 })()`); got != "" {
282 t.Errorf("the docked chat at 1280x800: %s", got)
283 }
284 if here := harness.Read(rig, chromedp.Location()); here != rig.Origin+"/" {
285 t.Fatalf("Home moved to %s", here)
286 }
287 // "/" from anywhere but a field puts focus in the composer.
288 drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`), slash())
289 if got := harness.Evaluate[string](rig, `document.activeElement.id + "|" + document.querySelector("#ask-text").value`); got != "ask-text|" {
290 t.Errorf(`after "/" focus and the field are %q, want the empty message field`, got)
291 }
292 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"), slash())
293 if got := harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`); got != "What can I do/" {
294 t.Errorf(`"/" in the field typed %q`, got)
295 }
296 drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelector("#ask-text").value = "What can I do"`),
297 chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
298 chromedp.Poll[chromedp.Void](`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent.includes("What would you like to do?") && m.dataset.id)`,
299 chromedp.WithPollingTimeout(10*time.Second)))
300 rig.Screen("#ask-panel", "the docked chat with one question answered")
301 if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 1 {
302 t.Errorf("person messages shown: %d", got)
303 }
304 if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
305 t.Errorf("messages sent to Equipo: %d", n)
306 }
307 if dir := os.Getenv("BASE_BROWSER_ARTIFACTS"); dir != "" {
308 var png []byte
309 drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
310 var err error
311 png, err = chromedp.FullScreenshot(100)(ctx, target)
312 return err
313 }))
314 if err := os.MkdirAll(dir, 0o755); err != nil {
315 t.Fatal(err)
316 }
317 if err := os.WriteFile(filepath.Join(dir, "7-ask-panel.png"), png, 0o644); err != nil {
318 t.Fatal(err)
319 }
320 }
321
322 // There is no ⋯ menu: the header holds the title and Close.
323 if harness.Evaluate[bool](rig, `!!document.querySelector("#ask-panel .ask-head summary, #ask-panel .ask-head a")`) {
324 t.Error("the panel's header still has a menu or a link")
325 }
326}
327
328// Home never waits on Equipo: closed, Home reads nothing and the script
329// reads the conversation as the chat opens (an empty one saying so);
330// open, with the read stalled, Home comes up well inside the client's own
331// 20 s with the chat open, and the script reads the conversation in.
332func TestAskHomeDoesNotWaitOnEquipo(t *testing.T) {
333 rig, f, b := askBaseWith(t, nil)
334 openPanel(t, rig)
335 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel [data-ask-close]`)))
336 askClosed(t, b, true)
337 before := len(f.Calls("/api/v1/assistant/snapshot"))
338 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`button.base-btn`)), chromedp.Sleep(300*time.Millisecond))
339 if n := len(f.Calls("/api/v1/assistant/snapshot")) - before; n != 0 {
340 t.Errorf("Home with the chat closed read the conversation %d times", n)
341 }
342 drive(t, rig, chromedp.Click(chromedp.CSS(`button.base-btn`)),
343 chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(5*time.Second)),
344 chromedp.Poll[chromedp.Void](readJS, chromedp.WithPollingTimeout(5*time.Second)), chromedp.Sleep(100*time.Millisecond))
345 if got := harness.Evaluate[string](rig, `(() => { const e = document.querySelector("#ask-panel [data-empty]");
346 return e.hidden + " " + document.querySelectorAll("#ask-panel .thread > li").length; })()`); got != "false 0" {
347 t.Errorf("opened on an empty conversation, the empty line hidden and lines: %s", got)
348 }
349 askClosed(t, b, false)
350
351 f.Say("Your week is clear.")
352 entered, hold := f.HoldNextSnapshot()
353 release := sync.OnceFunc(hold)
354 defer release()
355 start := time.Now()
356 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)))
357 if took := time.Since(start); took > 5*time.Second {
358 t.Errorf("Home took %v with the conversation's read stalled", took)
359 }
360 select {
361 case <-entered:
362 default:
363 t.Fatal("Home never read the conversation")
364 }
365 drive(t, rig, chromedp.Poll[chromedp.Void](`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent === "Your week is clear.")`,
366 chromedp.WithPollingTimeout(10*time.Second)))
367 if !harness.Evaluate[bool](rig, settledJS) || harness.Evaluate[bool](rig, `!document.querySelector("#ask-panel [data-empty]").hidden`) {
368 t.Error("the chat is not open with its conversation")
369 }
370 release()
371}
372
373// The X slides the docked chat out and Home takes the width (the apps grid
374// gains a column); the Base button shows, with focus. A reload keeps it
375// closed. The Base button, or "/", brings it back, and a reload keeps it
376// open. With reduced motion it opens and closes without moving.
377func TestAskDockClosePersists(t *testing.T) {
378 apps := teamApps(t)
379 rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
380 installAll(t, b)
381 drive(t, rig, chromedp.EmulateViewport(900, 800))
382 openPanel(t, rig)
383 appsRight := func() float64 {
384 return harness.Evaluate[float64](rig, `document.querySelector("nav.apps").getBoundingClientRect().right`)
385 }
386 gone := `(() => { const d = document.querySelector("#ask-panel"); return document.documentElement.classList.contains("desk-closed") && !d.checkVisibility({ visibilityProperty: true }) })()`
387 closedJS := `(() => { const problems = [], vw = document.documentElement.clientWidth;
388 if (!document.documentElement.classList.contains("desk-closed")) problems.push("not desk-closed");
389 if (document.querySelector("#ask-panel").checkVisibility({ visibilityProperty: true })) problems.push("the chat shows");
390 if (!document.querySelector("#ask-panel").inert) problems.push("the chat is not inert");
391 if (!document.querySelector(".base-btn").checkVisibility({ visibilityProperty: true })) problems.push("no Base button");
392 if (!document.querySelector(".ask-field").checkVisibility({ visibilityProperty: true })) problems.push("no field under the greeting");
393 const home = document.querySelector("main.home").getBoundingClientRect();
394 if (vw - home.right > 1) problems.push("Home ends at " + home.right + " of " + vw);
395 return problems.join("; "); })()`
396 open := appsRight()
397
398 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)),
399 chromedp.Poll[chromedp.Void](gone, chromedp.WithPollingTimeout(3*time.Second)))
400 if got := harness.Evaluate[string](rig, closedJS); got != "" {
401 t.Errorf("closed: %s", got)
402 }
403 if got := appsRight(); got <= open+48 {
404 t.Errorf("closed, the apps end at %v, open at %v: Home did not take the width", got, open)
405 }
406 if got := harness.Evaluate[string](rig, `document.activeElement.className`); got != "base-btn" {
407 t.Errorf("after X focus is on %q, want the Base button", got)
408 }
409 askClosed(t, b, true)
410 layoutShot(t, rig, "desktop-chat-closed-dark")
411
412 // Reloaded, it is closed from the first paint.
413 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(".base-btn")))
414 if got := harness.Evaluate[string](rig, closedJS); got != "" {
415 t.Errorf("reloaded: %s", got)
416 }
417
418 // The Base button reopens it, focus in the composer; a reload keeps it.
419 drive(t, rig, chromedp.Click(chromedp.CSS(".base-btn")), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)))
420 if got := harness.Evaluate[string](rig, `document.activeElement.id`); got != "ask-text" {
421 t.Errorf("reopened, focus is on %q, want the message field", got)
422 }
423 askClosed(t, b, false)
424 openPanel(t, rig)
425 if harness.Evaluate[bool](rig, `document.documentElement.classList.contains("desk-closed")`) {
426 t.Error("reopened and reloaded, it is closed")
427 }
428
429 // Closed again, "/" reopens it.
430 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)),
431 chromedp.Poll[chromedp.Void](gone, chromedp.WithPollingTimeout(3*time.Second)))
432 askClosed(t, b, true)
433 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(".base-btn")),
434 slash(), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)))
435 if got := harness.Evaluate[string](rig, `document.activeElement.id`); got != "ask-text" {
436 t.Errorf(`opened by "/", focus is on %q`, got)
437 }
438 askClosed(t, b, false)
439 openPanel(t, rig)
440
441 // With reduced motion nothing moves: it just goes, and just comes back.
442 drive(t, rig, reducedMotion("dark", true))
443 if got := harness.Evaluate[string](rig, `getComputedStyle(document.querySelector("#ask-panel")).transitionDuration`); got != "0s" {
444 t.Errorf("with reduced motion the chat's transition-duration is %q, want 0s", got)
445 }
446 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)))
447 if !harness.Evaluate[bool](rig, gone) {
448 t.Error("with reduced motion the chat did not close at once")
449 }
450 drive(t, rig, chromedp.Click(chromedp.CSS(".base-btn")))
451 if !harness.Evaluate[bool](rig, settledJS) {
452 t.Error("with reduced motion the chat did not open at once")
453 }
454 drive(t, rig, reducedMotion("dark", false))
455 askClosed(t, b, false)
456}
457
458// The composer is the familiar one: no Send until something is typed, then
459// a round arrow inside the field's end that sends on a click or on Enter;
460// while Equipo answers, a square Stop takes its place and cancels the turn.
461func TestAskComposerSendAndStop(t *testing.T) {
462 rig, f := askBase(t)
463 openPanel(t, rig)
464 const send, stop = `#ask-panel form.composer button.send`, `#ask-panel form.composer button.stop`
465 shown := func(sel string) string {
466 return `(() => { const b = document.querySelector(` + strconv.Quote(sel) + `);
467 return !!b && b.checkVisibility({ visibilityProperty: true }) && b.getBoundingClientRect().width > 0 })()`
468 }
469 buttons := func() string {
470 return harness.Evaluate[string](rig, `"send " + `+shown(send)+` + ", stop " + `+shown(stop))
471 }
472 wait := func(js string) {
473 t.Helper()
474 drive(t, rig, chromedp.Poll[chromedp.Void](js, chromedp.WithPollingTimeout(10*time.Second)))
475 }
476 // Once the panel has finished opening.
477 wait(`(() => { const s = getComputedStyle(document.querySelector("#ask-panel")); return s.opacity === "1" && s.transform === "none" })()`)
478 if got := buttons(); got != "send false, stop false" {
479 t.Fatalf("empty field: %s", got)
480 }
481 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), " "), chromedp.Sleep(200*time.Millisecond))
482 if got := buttons(); got != "send false, stop false" {
483 t.Fatalf("only spaces typed: %s", got)
484 }
485 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"))
486 wait(shown(send))
487 // The arrow sits inside the field's right end, named Send.
488 if got := harness.Evaluate[string](rig, `(() => {
489 const b = document.querySelector(`+strconv.Quote(send)+`), f = document.querySelector("#ask-text");
490 for (const a of b.getAnimations()) a.finish(); // measured once it has grown in
491 const r = b.getBoundingClientRect(), x = f.getBoundingClientRect(), p = [];
492 if (b.getAttribute("aria-label") !== "Send" || b.title !== "Send") p.push("named " + b.getAttribute("aria-label") + "/" + b.title);
493 if (b.textContent.trim() !== "") p.push("has text " + b.textContent.trim());
494 if (!b.querySelector("svg")) p.push("no icon");
495 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");
496 if (x.right - r.right > 8) p.push(Math.round(x.right - r.right) + "px from the field's end");
497 return p.join("; ");
498 })()`); got != "" {
499 t.Errorf("the Send button: %s", got)
500 }
501
502 // Sent by a click; while Equipo answers, Stop is where Send was, the
503 // thinking bubble says so (the status line above the field is empty),
504 // and no other Stop shows.
505 f.Hold = true
506 drive(t, rig, chromedp.Click(chromedp.CSS(send)))
507 // (The turn's events can come before the send's answer, which clears
508 // the field.)
509 wait(`document.querySelectorAll("#ask-panel .msg.person").length === 1 && document.querySelector("#ask-text").value === "" && ` + shown(stop))
510 if got := harness.Evaluate[string](rig, `(() => {
511 const b = document.querySelector(`+strconv.Quote(stop)+`), p = [];
512 if (b.getAttribute("aria-label") !== "Stop" || b.title !== "Stop") p.push("named " + b.getAttribute("aria-label") + "/" + b.title);
513 if (!b.querySelector("svg")) p.push("no icon");
514 if (`+shown(send)+`) p.push("Send shows too");
515 if (document.querySelector("#ask-text").value !== "") p.push("the field still holds text");
516 const others = [...document.querySelectorAll("#ask-panel button")].filter(x => x !== b && /Stop/.test(x.textContent) && x.checkVisibility());
517 if (others.length) p.push(others.length + " other Stop buttons");
518 const st = document.querySelector("#ask-panel .ask-status");
519 if (st.textContent !== "") p.push("status " + st.textContent);
520 const bubble = document.querySelector("#ask-panel .thread > li:last-child.thinking");
521 if (!bubble || bubble.textContent !== "" || bubble.querySelectorAll(".dots > i").length !== 3) p.push("bubble " + (bubble && bubble.innerHTML));
522 return p.join("; ");
523 })()`); got != "" {
524 t.Errorf("while answering: %s", got)
525 }
526 action := harness.Evaluate[string](rig, `document.querySelector("#ask-panel form.cancel").getAttribute("action")`)
527 m := regexp.MustCompile(`^/ask/turns/([^/]+)/cancel$`).FindStringSubmatch(action)
528 if m == nil {
529 t.Fatalf("cancel form posts to %q", action)
530 }
531 rig.Screen("#ask-panel", "the panel while Equipo answers, with Stop in the field")
532 drive(t, rig, chromedp.Click(chromedp.CSS(stop)))
533 wait(`!` + shown(stop) + ` && document.querySelector("#ask-panel .ask-status").textContent === ""`)
534 for i := 0; f.Turn(m[1]) != "cancelled"; i++ {
535 if i > 100 {
536 t.Fatalf("Stop left the turn %q", f.Turn(m[1]))
537 }
538 time.Sleep(20 * time.Millisecond)
539 }
540 if got := buttons(); got != "send false, stop false" {
541 t.Errorf("after Stop, the field empty: %s", got)
542 }
543 f.Hold = false
544
545 // Enter sends too.
546 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "And what else?\r"))
547 wait(`document.querySelectorAll("#ask-panel .msg.person").length === 2`)
548 if n := len(f.Calls("/api/v1/assistant/messages")); n != 2 {
549 t.Errorf("messages sent: %d, want 2", n)
550 }
551}
552
553// The key events' modifier bits.
554const altKey, shiftKey = 1, 8
555
556// enter presses Enter as a keyboard does, with modifiers and the key code
557// an input method's Enter carries (229) or Enter's own (13).
558func enter(modifiers, keyCode int64) chromedp.Action[chromedp.Void] {
559 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
560 for _, typ := range []input.DispatchKeyEventType{input.DispatchKeyEventTypeKeyDown, input.DispatchKeyEventTypeKeyUp} {
561 k := input.DispatchKeyEventParams{Type: typ, Key: "Enter", Code: "Enter", Modifiers: modifiers,
562 WindowsVirtualKeyCode: keyCode, NativeVirtualKeyCode: keyCode}
563 if typ == input.DispatchKeyEventTypeKeyDown && keyCode != 229 { // the input method's own text
564 k.Text, k.UnmodifiedText = "\r", "\r"
565 }
566 if _, err := cdp.Call(ctx, target, input.DispatchKeyEvent, k); err != nil {
567 return err
568 }
569 }
570 return nil
571 })
572}
573
574// Paul's Base Mac bug, checked on the web: Enter sends; Shift Enter and
575// Option (Alt) Enter are a new line where the cursor is; an input
576// method's Enter (Safari's keyCode 229) finishes its word and sends
577// nothing.
578func TestAskComposerNewLines(t *testing.T) {
579 rig, f := askBase(t)
580 openPanel(t, rig)
581 value := func() string { return harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`) }
582 at := func(n int) chromedp.Action[chromedp.Void] {
583 return chromedp.Evaluate[chromedp.Void](`(() => { const f = document.querySelector("#ask-text"); f.focus(); f.setSelectionRange(` + strconv.Itoa(n) + `, ` + strconv.Itoa(n) + `) })()`)
584 }
585 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Flour delivery"), at(5), enter(shiftKey, 13))
586 if got := value(); got != "Flour\n delivery" {
587 t.Errorf("Shift Enter mid-text: %q", got)
588 }
589 drive(t, rig, at(len("Flour\n delivery")), enter(altKey, 13))
590 if got := value(); got != "Flour\n delivery\n" {
591 t.Errorf("Option Enter at the end: %q", got)
592 }
593 drive(t, rig, enter(0, 229), chromedp.Sleep(300*time.Millisecond))
594 if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
595 t.Fatalf("sent %d messages before a plain Enter", n)
596 }
597 drive(t, rig, enter(0, 13), chromedp.Sleep(300*time.Millisecond))
598 drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector("#ask-text").value === ""`, chromedp.WithPollingTimeout(10*time.Second)))
599 if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
600 t.Errorf("messages sent: %d, want 1", n)
601 }
602}
603
604// holdDock wraps the page's fetch so its /ask/dock posts follow plan, one
605// step per post: held for some milliseconds, then sent, or answered 500
606// without reaching Base. window.__dock lists the bodies posted.
607// It first waits for any post already on its way to settle.
608func holdDock(plan string) chromedp.Action[chromedp.Void] {
609 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
610 if _, err := chromedp.Poll[chromedp.Void](`!window.__out`, chromedp.WithPollingTimeout(3*time.Second))(ctx, target); err != nil {
611 return err
612 }
613 _, err := chromedp.Evaluate[chromedp.Void](`(() => {
614 window.__dock = []; window.__plan = `+plan+`; window.__out = 0;
615 const real = window.__fetch = window.__fetch || window.fetch;
616 window.fetch = async (url, opts) => {
617 if (!String(url).includes("/ask/dock")) return real(url, opts);
618 const p = window.__plan.shift() || {};
619 window.__dock.push(String(opts.body));
620 window.__out++;
621 try {
622 if (p.hold) await new Promise((r) => setTimeout(r, p.hold));
623 if (p.fail) return new Response("", { status: 500 });
624 return await real(url, opts);
625 } finally {
626 setTimeout(() => window.__out--);
627 }
628 };
629 })()`)(ctx, target)
630 return err
631 })
632}
633
634// toggles presses the X (0) and the Base button (1) in order, at once.
635func toggles(seq string) chromedp.Action[chromedp.Void] {
636 return chromedp.Evaluate[chromedp.Void](`(() => { for (const c of ` + strconv.Quote(seq) + `)
637 document.querySelector(c === "0" ? "#ask-panel form.dock-close" : "form.base-btn-form").requestSubmit(); })()`)
638}
639
640// The docked chat's saves go one at a time and the last choice wins: a
641// close held on its way, then an open, ends open on the server, and
642// presses made while one is on its way send only the latest.
643func TestAskDockSavesInOrder(t *testing.T) {
644 rig, _, b := askBaseWith(t, nil)
645 openPanel(t, rig)
646 drive(t, rig, holdDock(`[{ hold: 400 }]`), toggles("01"))
647 askClosed(t, b, false)
648 drive(t, rig, chromedp.Sleep(600*time.Millisecond))
649 askClosed(t, b, false)
650 if got := harness.Evaluate[string](rig, `window.__dock.join(" ") + " | " + document.documentElement.classList.contains("desk-closed")`); got != "open=0 open=1 | false" {
651 t.Errorf("close then open: posted and drawn %q, want open=0 open=1 | false", got)
652 }
653
654 // Close (held), open, close, open: two posts, the held close and the
655 // last choice, ending open.
656 drive(t, rig, holdDock(`[{ hold: 400 }]`), toggles("0101"),
657 chromedp.Poll[chromedp.Void](`window.__dock.length === 2`, chromedp.WithPollingTimeout(3*time.Second)), chromedp.Sleep(300*time.Millisecond))
658 askClosed(t, b, false)
659 if got := harness.Evaluate[string](rig, `window.__dock.join(" ")`); got != "open=0 open=1" {
660 t.Errorf("four presses posted %q, want the held close then the last choice", got)
661 }
662 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("#ask-panel textarea")))
663 if harness.Evaluate[bool](rig, `document.documentElement.classList.contains("desk-closed")`) {
664 t.Error("reloaded, the last choice (open) did not hold")
665 }
666}
667
668// A save that fails leaves the screen as the person chose it and is not
669// taken as kept: a choice made while it was on its way is sent once it
670// fails, and with none the next press saves.
671func TestAskDockSaveFails(t *testing.T) {
672 rig, _, b := askBaseWith(t, nil)
673 openPanel(t, rig)
674 // Close fails at once: the chat stays closed on screen, the server
675 // still holds open; the next press (open) saves.
676 drive(t, rig, holdDock(`[{ fail: true }]`), toggles("0"), chromedp.Sleep(300*time.Millisecond))
677 if !harness.Evaluate[bool](rig, `document.documentElement.classList.contains("desk-closed")`) {
678 t.Error("a failed save moved the chat back")
679 }
680 askClosed(t, b, false)
681 drive(t, rig, toggles("1"), chromedp.Poll[chromedp.Void](`window.__dock.length === 2`, chromedp.WithPollingTimeout(3*time.Second)))
682 askClosed(t, b, false)
683 drive(t, rig, toggles("0"))
684 askClosed(t, b, true)
685
686 // Open fails after a while; meanwhile close, then open again: once it
687 // fails, the last choice (open) is sent, though it is what failed.
688 drive(t, rig, holdDock(`[{ hold: 400, fail: true }]`), toggles("101"),
689 chromedp.Poll[chromedp.Void](`window.__dock.length === 2`, chromedp.WithPollingTimeout(3*time.Second)))
690 askClosed(t, b, false)
691 if got := harness.Evaluate[string](rig, `window.__dock.join(" ") + " | " + document.documentElement.classList.contains("desk-closed")`); got != "open=1 open=1 | false" {
692 t.Errorf("posted and drawn %q, want the failed open, then open again, drawn open", got)
693 }
694}
695
696// The Assistant's little Markdown (plan decision D16) is drawn the same by
697// the panel's script, for a line that arrives while it is open, as by the
698// server, for /ask: each message's HTML is the same, unsafe links and raw
699// HTML included. The last few lines are where a script and a server most
700// easily part: carriage returns and NULs (which an HTML page cannot
701// hold), letters beyond ASCII next to an _, and
702// lists of each kind back to back.
703func TestAskMarkdownMatchesServer(t *testing.T) {
704 said := []string{
705 "**Done.** Your site is up",
706 "*soon*",
707 "_soon_",
708 "a_b_c",
709 "**<b>x</b>**",
710 "Three things:\n- Docs\n- Sheets\n- [Calendar](https://cal.test/)",
711 "1. One\n2. Two",
712 "3) Three",
713 "- [x](javascript:alert(1))",
714 "** not bold **",
715 "# Heading",
716 "Line one\r\n- a *b*\r\n- **c**\r\nafter\r\n",
717 "é_x_ ü _ä_ _x_y 日本_語_ *😀* **😀 a** _😀_",
718 "- a\n\nb\n* c\n1. d\n0) e\n- f\n1000. g\n- \n",
719 "See https://a.test/_x_ and [*it*](https://b.test/?q=1&r=2) then *after* <img src=x onerror=alert(1)>",
720 "***x*** __y__ *a**b* **a*b** _a__b_ *\t*",
721 "A\rB\x00C\r\n\r\n- d\re",
722 }
723 rig, f := askBase(t)
724 openPanel(t, rig)
725 for _, s := range said {
726 f.Say(s)
727 }
728 drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.coordinator").length === `+strconv.Itoa(len(said)),
729 chromedp.WithPollingTimeout(10*time.Second)))
730 got := harness.Evaluate[string](rig, `(async () => {
731 const page = new DOMParser().parseFromString(await (await fetch("/ask")).text(), "text/html");
732 const out = [];
733 for (const m of document.querySelectorAll("#ask-panel .msg.coordinator")) {
734 const s = page.querySelector('.msg.coordinator[data-id="' + CSS.escape(m.dataset.id) + '"]');
735 if (!s) out.push(m.dataset.id + ": not on /ask");
736 else if (s.innerHTML !== m.innerHTML) out.push(JSON.stringify(m.textContent) + "\n script " + m.innerHTML + "\n server " + s.innerHTML);
737 }
738 return out.join("\n");
739 })()`, chromedp.EvalAwaitPromise)
740 if got != "" {
741 t.Errorf("the script and the server draw differently:\n%s", got)
742 }
743 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 {
744 t.Errorf("unsafe markup drawn: %d", n)
745 }
746 // The thread is a list without markers; the Assistant's lists have them.
747 if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .msg ul, #ask-panel .msg ol")]
748 .map(l => l.tagName + "=" + getComputedStyle(l).listStyleType).filter(s => s !== "UL=disc" && s !== "OL=decimal").join(" ")`); got != "" {
749 t.Errorf("lists without their markers: %s", got)
750 }
751 rig.Screen("#ask-panel", "the Assistant's simple Markdown")
752}
753
754const focusedJS = `document.activeElement && document.activeElement.id`
755
756// The composer has focus when the page opens on a wide screen with the
757// chat open and ready, and only then.
758func TestAskFocusesFieldOnLoad(t *testing.T) {
759 load := func(t *testing.T, rig *harness.Rig, path string) string {
760 t.Helper()
761 drive(t, rig, chromedp.Navigate(rig.Origin+path), chromedp.WaitVisible(chromedp.CSS(`body`)), chromedp.Sleep(500*time.Millisecond))
762 return harness.Evaluate[string](rig, focusedJS)
763 }
764 t.Run("desktop open", func(t *testing.T) {
765 rig, _ := askBase(t)
766 if got := load(t, rig, "/"); got != "ask-text" {
767 t.Errorf("focus is %q, want the composer", got)
768 }
769 if y := harness.Evaluate[float64](rig, `scrollY`); y != 0 {
770 t.Errorf("the page scrolled to %v", y)
771 }
772 if got := load(t, rig, "/ask"); got != "ask-text" {
773 t.Errorf("/ask focus is %q, want the composer", got)
774 }
775 })
776 t.Run("desktop closed", func(t *testing.T) {
777 rig, _, b := askBaseWith(t, nil)
778 openPanel(t, rig)
779 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)))
780 askClosed(t, b, true)
781 if got := load(t, rig, "/"); got == "ask-text" {
782 t.Error("the closed chat's composer took focus")
783 }
784 })
785 t.Run("phone", func(t *testing.T) {
786 rig, _, _ := askBaseOn(t, nil, chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3)))
787 if got := load(t, rig, "/"); got == "ask-text" {
788 t.Error("the composer took focus on a phone")
789 }
790 if got := load(t, rig, "/ask"); got == "ask-text" {
791 t.Error("/ask's composer took focus on a phone")
792 }
793 })
794 t.Run("not connected", func(t *testing.T) {
795 var b *baseApp
796 rig := newRig(t, func(origin string) http.Handler {
797 b = newBase(t, baseConfig(origin))
798 return b.handler
799 })
800 signInByEmail(t, rig, rig.Origin, b.mail)
801 drive(t, rig, chromedp.EmulateViewport(1280, 800))
802 for _, path := range []string{"/", "/ask"} {
803 if got := load(t, rig, path); got == "ask-text" {
804 t.Errorf("%s: the composer took focus without a connection", path)
805 }
806 }
807 })
808}
809