| 1 | //go:build browser |
| 2 | |
| 3 | package headless |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "testing" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/browsertest" |
| 10 | "amadan.net/rastrillo/rastrillo/harness" |
| 11 | "github.com/chromedp/cdproto/cdp" |
| 12 | "github.com/chromedp/cdproto/network" |
| 13 | "github.com/chromedp/chromedp" |
| 14 | ) |
| 15 | |
| 16 | // The conversation page follows the stream: a scriptless send, the |
| 17 | // streamed draft, the committed markdown reply and the offline line. It |
| 18 | // sets up nothing a person could not. |
| 19 | func TestBrowserChat(t *testing.T) { |
| 20 | _, inst, r := localEnv(t) |
| 21 | r.start(t) |
| 22 | alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...) |
| 23 | defer cancelAlloc() |
| 24 | ctx, cancel := chromedp.NewContext(alloc) |
| 25 | defer cancel() |
| 26 | cookie := inst.Cookie() |
| 27 | run := func(actions ...chromedp.Action[chromedp.Void]) { |
| 28 | t.Helper() |
| 29 | if err := chromedp.Do(ctx, actions...); err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | } |
| 33 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 34 | _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}) |
| 35 | return err |
| 36 | })) |
| 37 | run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`)) |
| 38 | send := func(text string) { |
| 39 | t.Helper() |
| 40 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 41 | _, err := chromedp.Evaluate[bool](`(()=>{document.querySelector('#chat-body').value=`+jsString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`)(ctx, target) |
| 42 | return err |
| 43 | })) |
| 44 | } |
| 45 | send("hello from the browser") |
| 46 | run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator'))`)) |
| 47 | // The draft streams into the waiting bubble before the reply lands. |
| 48 | send("think about it sleep:2500") |
| 49 | run(browsertest.Wait(`[...document.querySelectorAll('[data-stream-text]')].some(e=>e.textContent.length>0)`)) |
| 50 | run(browsertest.Wait(`document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])').length===2 && !document.querySelector('[equipo-thinking]')`)) |
| 51 | // Multibyte text: every delta lands in the draft, which reaches the |
| 52 | // full reply before the committed message replaces it. |
| 53 | send("accents slowstream sleep:700") |
| 54 | run(browsertest.Wait(`[...document.querySelectorAll('[data-stream-text]')].some(e=>e.textContent.trim()==="Café con ñandú, señor. ☕ Ünïcödé 🎉 works.")`)) |
| 55 | run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("🎉 works")) && !document.querySelector('[equipo-thinking]')`)) |
| 56 | r.stop(t) |
| 57 | run(browsertest.Wait(`!document.querySelector('[equipo-offline]').hidden`)) |
| 58 | } |
| 59 | |
| 60 | func jsString(s string) string { |
| 61 | out := []byte{'"'} |
| 62 | for _, c := range []byte(s) { |
| 63 | if c == '"' || c == '\\' { |
| 64 | out = append(out, '\\') |
| 65 | } |
| 66 | out = append(out, c) |
| 67 | } |
| 68 | return string(append(out, '"')) |
| 69 | } |
| 70 | |
| 71 | // On a phone, sending stays on the page: no navigation and so no page |
| 72 | // transition, the message shows at once and is reconciled with the |
| 73 | // committed one, focus stays in the composer, Enter sends and Shift+Enter |
| 74 | // does not, and a failed post offers Retry. |
| 75 | func TestBrowserChatSendStaysOnPage(t *testing.T) { |
| 76 | _, inst, r := localEnv(t) |
| 77 | r.start(t) |
| 78 | alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...) |
| 79 | defer cancelAlloc() |
| 80 | ctx, cancel := chromedp.NewContext(alloc) |
| 81 | defer cancel() |
| 82 | cookie := inst.Cookie() |
| 83 | run := func(actions ...chromedp.Action[chromedp.Void]) { |
| 84 | t.Helper() |
| 85 | if err := chromedp.Do(ctx, actions...); err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | } |
| 89 | check := func(expression, reason string) { |
| 90 | t.Helper() |
| 91 | var ok bool |
| 92 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 93 | var err error |
| 94 | ok, err = chromedp.Evaluate[bool](expression)(ctx, target) |
| 95 | return err |
| 96 | })) |
| 97 | if !ok { |
| 98 | t.Fatal(reason) |
| 99 | } |
| 100 | } |
| 101 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 102 | _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}) |
| 103 | return err |
| 104 | }), chromedp.EmulateViewport(390, 844)) |
| 105 | run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]')`)) |
| 106 | check(`(()=>{window.__page=1;window.__revealed=false;addEventListener('pagereveal',()=>{window.__revealed=true});addEventListener('pageswap',()=>{window.__revealed=true});return true})()`, "setup") |
| 107 | check(`(()=>{const b=document.querySelector('#chat-body');b.focus();b.value='hello from a phone';document.querySelector('#composer').requestSubmit();return [...document.querySelectorAll('[equipo-message="own"] [equipo-message-body]')].some(e=>e.textContent==='hello from a phone')})()`, "the message did not show at once") |
| 108 | run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator'))`)) |
| 109 | check(`window.__page===1 && !window.__revealed && performance.getEntriesByType('navigation').length===1 && location.pathname==='/conversation'`, "sending navigated") |
| 110 | check(`document.activeElement && document.activeElement.id==='chat-body'`, "focus left the composer") |
| 111 | check(`(()=>{const own=[...document.querySelectorAll('[equipo-message="own"]')].filter(e=>e.textContent.includes('hello from a phone'));return own.length===1 && own[0].dataset.message!==''})()`, "optimistic message not reconciled once") |
| 112 | // Shift+Enter keeps writing; Enter sends. |
| 113 | check(`(()=>{const b=document.querySelector('#chat-body');b.value='line one';b.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',shiftKey:true,bubbles:true,cancelable:true}));return b.value==='line one'})()`, "Shift+Enter sent") |
| 114 | check(`(()=>{const b=document.querySelector('#chat-body');b.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true}));return b.value===''&&[...document.querySelectorAll('[equipo-message="own"] [equipo-message-body]')].some(e=>e.textContent==='line one')})()`, "Enter did not send") |
| 115 | run(browsertest.Wait(`document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])').length===2`)) |
| 116 | // A failed post keeps the message and offers Retry, which sends it. |
| 117 | check(`(()=>{window.__fetch=window.fetch;let once=true;window.fetch=function(u,o){if(once&&o&&o.method==='POST'){once=false;return Promise.reject(new Error('offline'))}return window.__fetch(u,o)};const b=document.querySelector('#chat-body');b.value='try again';document.querySelector('#composer').requestSubmit();return true})()`, "setup failure") |
| 118 | run(browsertest.Wait(`!!document.querySelector('[equipo-message="own"][data-send-failed] [data-retry-send]')`)) |
| 119 | check(`(()=>{document.querySelector('[data-retry-send]').click();return true})()`, "retry") |
| 120 | run(browsertest.Wait(`document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])').length===3 && !document.querySelector('[data-send-failed]')`)) |
| 121 | check(`window.__page===1 && performance.getEntriesByType('navigation').length===1`, "retry navigated") |
| 122 | } |
| 123 | |
| 124 | // A fresh coordinator moves in on the page: the line says "Moving in…" |
| 125 | // and what it reads; a message sent meanwhile is answered first, with no |
| 126 | // cancelled note for the move-in that gave way; then the one |
| 127 | // introduction lands. |
| 128 | func TestBrowserMoveIn(t *testing.T) { |
| 129 | _, inst, r := localEnv(t) |
| 130 | r.opts.NoMoveIn = false |
| 131 | r.opts.Claude.MoveInNote = "\nmovein-pause:600" |
| 132 | alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...) |
| 133 | defer cancelAlloc() |
| 134 | ctx, cancel := chromedp.NewContext(alloc) |
| 135 | defer cancel() |
| 136 | cookie := inst.Cookie() |
| 137 | run := func(actions ...chromedp.Action[chromedp.Void]) { |
| 138 | t.Helper() |
| 139 | if err := chromedp.Do(ctx, actions...); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | } |
| 143 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 144 | _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}) |
| 145 | return err |
| 146 | }), chromedp.EmulateViewport(390, 844)) |
| 147 | run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]')`)) |
| 148 | // Any ended note, even one a later re-render removes, is counted. |
| 149 | run(browsertest.Wait(`(()=>{window.__ended=0;setInterval(()=>{if(document.querySelector('[data-ended]'))window.__ended++},10);return true})()`)) |
| 150 | r.start(t) |
| 151 | run(browsertest.Wait(`[...document.querySelectorAll('[equipo-thinking] [equipo-activity]')].some(e=>e.textContent.startsWith('Moving in… reading '))`)) |
| 152 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 153 | _, err := chromedp.Evaluate[bool](`(()=>{document.querySelector('#chat-body').value='hello while you move in';document.querySelector('#composer').requestSubmit();return true})()`)(ctx, target) |
| 154 | return err |
| 155 | })) |
| 156 | run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator'))`)) |
| 157 | run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")) && !document.querySelector('[equipo-thinking]')`)) |
| 158 | var notes int |
| 159 | run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 160 | var err error |
| 161 | notes, err = chromedp.Evaluate[int](`window.__ended+document.querySelectorAll('[data-ended]').length`)(ctx, target) |
| 162 | return err |
| 163 | })) |
| 164 | if notes != 0 { |
| 165 | t.Fatalf("%d ended notes; a move-in that gave way says nothing", notes) |
| 166 | } |
| 167 | // After a reload, the server-rendered page agrees. |
| 168 | run(chromedp.Reload(), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && [...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")) && document.querySelectorAll('[data-ended]').length===0`)) |
| 169 | } |
| 170 | |