//go:build browser package headless import ( "context" "testing" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" ) // The conversation page follows the stream: a scriptless send, the // streamed draft, the committed markdown reply and the offline line. It // sets up nothing a person could not. func TestBrowserChat(t *testing.T) { _, inst, r := localEnv(t) r.start(t) alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...) defer cancelAlloc() ctx, cancel := chromedp.NewContext(alloc) defer cancel() cookie := inst.Cookie() run := func(actions ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, actions...); err != nil { t.Fatal(err) } } run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}) return err })) run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`)) send := func(text string) { t.Helper() run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := chromedp.Evaluate[bool](`(()=>{document.querySelector('#chat-body').value=`+jsString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`)(ctx, target) return err })) } send("hello from the browser") run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator'))`)) // The draft streams into the waiting bubble before the reply lands. send("think about it sleep:2500") run(browsertest.Wait(`[...document.querySelectorAll('[data-stream-text]')].some(e=>e.textContent.length>0)`)) run(browsertest.Wait(`document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])').length===2 && !document.querySelector('[equipo-thinking]')`)) // Multibyte text: every delta lands in the draft, which reaches the // full reply before the committed message replaces it. send("accents slowstream sleep:700") run(browsertest.Wait(`[...document.querySelectorAll('[data-stream-text]')].some(e=>e.textContent.trim()==="Café con ñandú, señor. ☕ Ünïcödé 🎉 works.")`)) run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("🎉 works")) && !document.querySelector('[equipo-thinking]')`)) r.stop(t) run(browsertest.Wait(`!document.querySelector('[equipo-offline]').hidden`)) } func jsString(s string) string { out := []byte{'"'} for _, c := range []byte(s) { if c == '"' || c == '\\' { out = append(out, '\\') } out = append(out, c) } return string(append(out, '"')) } // On a phone, sending stays on the page: no navigation and so no page // transition, the message shows at once and is reconciled with the // committed one, focus stays in the composer, Enter sends and Shift+Enter // does not, and a failed post offers Retry. func TestBrowserChatSendStaysOnPage(t *testing.T) { _, inst, r := localEnv(t) r.start(t) alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...) defer cancelAlloc() ctx, cancel := chromedp.NewContext(alloc) defer cancel() cookie := inst.Cookie() run := func(actions ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, actions...); err != nil { t.Fatal(err) } } check := func(expression, reason string) { t.Helper() var ok bool run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error ok, err = chromedp.Evaluate[bool](expression)(ctx, target) return err })) if !ok { t.Fatal(reason) } } run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}) return err }), chromedp.EmulateViewport(390, 844)) run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]')`)) check(`(()=>{window.__page=1;window.__revealed=false;addEventListener('pagereveal',()=>{window.__revealed=true});addEventListener('pageswap',()=>{window.__revealed=true});return true})()`, "setup") 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") run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator'))`)) check(`window.__page===1 && !window.__revealed && performance.getEntriesByType('navigation').length===1 && location.pathname==='/conversation'`, "sending navigated") check(`document.activeElement && document.activeElement.id==='chat-body'`, "focus left the composer") 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") // Shift+Enter keeps writing; Enter sends. 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") 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") run(browsertest.Wait(`document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])').length===2`)) // A failed post keeps the message and offers Retry, which sends it. 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") run(browsertest.Wait(`!!document.querySelector('[equipo-message="own"][data-send-failed] [data-retry-send]')`)) check(`(()=>{document.querySelector('[data-retry-send]').click();return true})()`, "retry") run(browsertest.Wait(`document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])').length===3 && !document.querySelector('[data-send-failed]')`)) check(`window.__page===1 && performance.getEntriesByType('navigation').length===1`, "retry navigated") } // A fresh coordinator moves in on the page: the line says "Moving in…" // and what it reads; a message sent meanwhile is answered first, with no // cancelled note for the move-in that gave way; then the one // introduction lands. func TestBrowserMoveIn(t *testing.T) { _, inst, r := localEnv(t) r.opts.NoMoveIn = false r.opts.Claude.MoveInNote = "\nmovein-pause:600" alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...) defer cancelAlloc() ctx, cancel := chromedp.NewContext(alloc) defer cancel() cookie := inst.Cookie() run := func(actions ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, actions...); err != nil { t.Fatal(err) } } run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}) return err }), chromedp.EmulateViewport(390, 844)) run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]')`)) // Any ended note, even one a later re-render removes, is counted. run(browsertest.Wait(`(()=>{window.__ended=0;setInterval(()=>{if(document.querySelector('[data-ended]'))window.__ended++},10);return true})()`)) r.start(t) run(browsertest.Wait(`[...document.querySelectorAll('[equipo-thinking] [equipo-activity]')].some(e=>e.textContent.startsWith('Moving in… reading '))`)) run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := chromedp.Evaluate[bool](`(()=>{document.querySelector('#chat-body').value='hello while you move in';document.querySelector('#composer').requestSubmit();return true})()`)(ctx, target) return err })) run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator'))`)) run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")) && !document.querySelector('[equipo-thinking]')`)) var notes int run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error notes, err = chromedp.Evaluate[int](`window.__ended+document.querySelectorAll('[data-ended]').length`)(ctx, target) return err })) if notes != 0 { t.Fatalf("%d ended notes; a move-in that gave way says nothing", notes) } // After a reload, the server-rendered page agrees. 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`)) }