//go:build browser package headless import ( "context" "os" "sort" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" ) // A formatted reply is formatted as it streams: its bullets are list // items on their own lines, no asterisks show, the new words fade in // inside the formatting, and the committed reply is the last streamed // render plus at most its last characters (normalised HTML; the same // height when equal). A long reply is drawn within light.js's frame // budget (about 4 ms). // // Everything is judged from what the page records as it happens: each // draw is read the moment it lands (a MutationObserver, not a sampled // frame, so a commit straight after the last draw cannot hide it), and // the commit records its time beside the deadline the page set for it // (settleBy). The page commits an undrawn draft only at that 2 s cap; a // commit at the cap is logged, and anything earlier must be the last // render plus its last characters. The frame budget is a time on this // machine, so like the CI timing budgets it is enforced only where // EQUIPO_CI_DEDICATED=1 and reported elsewhere. func TestBrowserDraftStreamsFormatted(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() 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() if !evaluateIn[bool](t, ctx, expression) { t.Fatalf("%s (recorded: %s)", reason, evaluateIn[string](t, ctx, `JSON.stringify(window.__s ? {last: window.__s.last, stray: window.__s.stray, fade: window.__s.fade, lines: window.__s.lines} : null)`)) } } cookie := inst.Cookie() open := func(motion string) { t.Helper() run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { if _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}); err != nil { return err } _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: motion}}}) return err }), chromedp.EmulateViewport(1280, 800), chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`)) } // record follows the next reply until it is committed: its last // render (the fade spans unwrapped) and height, markup shown outside // code, the fade inside a list item, where two list items sit, each // draw's time, and when it was committed against the page's deadline // for it (settleBy). record := `(()=>{const s=window.__s={el:null,last:null,h:0,stray:null,fade:null,lines:null,frames:[],done:false,at:0,by:0}; new PerformanceObserver(l=>{for(const e of l.getEntries())if(e.name==='equipo-draft')s.frames.push(e.duration)}).observe({type:'measure'}); window.__norm=b=>{const c=document.createElement('div');c.innerHTML=b.innerHTML;c.querySelectorAll('[equipo-stream-caret]').forEach(e=>e.remove());c.querySelectorAll('span[data-new]').forEach(e=>e.replaceWith(new Text(e.textContent)));c.normalize();return c.innerHTML}; const f=()=>{if(s.done)return;if(!s.el)s.el=document.querySelector('[equipo-thinking][data-streaming]');const x=s.el;if(!x)return; if(!x.hasAttribute('equipo-thinking')){s.done=true;s.at=Date.now();s.by=x.settleBy||0;return} const b=x.querySelector('[data-stream-text]');if(b&&b.firstChild){s.last=window.__norm(b);s.h=b.getBoundingClientRect().height; const c=document.createElement('div');c.innerHTML=b.innerHTML;c.querySelectorAll('pre, code').forEach(e=>e.remove());if(/[*\x60]|\]\(/.test(c.textContent))s.stray=c.textContent; const n=b.querySelector('li [data-new]');if(n&&!s.fade){const st=getComputedStyle(n);s.fade=st.animationName+' '+st.animationDuration} const li=b.querySelectorAll('ul > li');if(li.length>=2&&!s.lines)s.lines=[li[0].getBoundingClientRect().top,li[1].getBoundingClientRect().top,li[0].textContent,li[1].textContent]}}; new MutationObserver(f).observe(document.body,{childList:true,subtree:true,characterData:true,attributes:true});f();return true})()` send := func(text string) { t.Helper() check(record, "record") check(`(()=>{document.querySelector('#chat-body').value=`+jsString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`, "send") } committed := func(reason string) { t.Helper() run(browsertest.WaitWithin(`window.__s.done && !!window.__s.el.dataset.message`, 60*time.Second)) if evaluateIn[bool](t, ctx, `window.__s.by>0 && window.__s.at>=window.__s.by`) { // The draft was still drawing when the page's 2 s wait ran // out: the page commits then by design, so how far the last // render was behind is this machine's speed, not the page. t.Logf("%s: committed at the 2 s cap, %d ms past the deadline; the last render is not compared", reason, evaluateIn[int](t, ctx, `window.__s.at-window.__s.by`)) check(`window.__s.stray===null`, reason+": markup characters showed while streaming") return } // Past what the two share, the last render has only the closing // tags of the text it ends in. check(`(()=>{const f=window.__norm(window.__s.el.querySelector('[equipo-message-body]')),l=window.__s.last;let k=0;while(k\s*)+$/.test(l.slice(k))&&f.length-k<80})()`, reason+": the committed reply is not the last streamed render plus its last characters") check(`!window.__s.same || Math.abs(window.__s.el.querySelector('[equipo-message-body]').getBoundingClientRect().height-window.__s.h)<1`, reason+": the reply changed height when committed") t.Logf("%s: last streamed render equal to the committed reply: %v", reason, evaluateIn[bool](t, ctx, `window.__s.same`)) check(`window.__s.stray===null`, reason+": markup characters showed while streaming") } for _, m := range []struct{ motion, fade string }{{"no-preference", "equipo-fade 0.32s"}, {"reduce", "equipo-fade 0.2s"}} { open(m.motion) send("replymd chunks:80 sleep:40 slowstream") // While streaming the bullets are list items on their own lines. run(browsertest.WaitWithin(`!!window.__s.lines`, 30*time.Second)) check(`window.__s.lines[1]-window.__s.lines[0]>8 && window.__s.lines[2].startsWith('Guest:') && (window.__s.lines[3].startsWith('Customer:') || 'Customer:'.startsWith(window.__s.lines[3]))`, "the bullets did not stream as list items on their own lines") committed(m.motion) check(`window.__s.fade===`+jsString(m.fade), "the words in a list item did not fade in as "+m.fade) check(`(()=>{const b=window.__s.el.querySelector('[equipo-message-body]');return b.querySelectorAll('ol > li').length===3 && b.querySelectorAll('strong').length===6 && !!b.querySelector('a[href="/tasks/tks6kwzzdngr"]') && !!b.querySelector('li code')})()`, "the committed reply lost its formatting") } // A long reply: about 14 KB in 400 deltas. open("no-preference") send("replymd:long chunks:400 sleep:12 slowstream") committed("long reply") // The runner sends the deltas it has about ten times a second. frames := evaluateIn[[]float64](t, ctx, `window.__s.frames`) sort.Float64s(frames) n := len(frames) if n < 2 { t.Fatalf("long reply: %d draws: it was not drawn as it streamed", n) } t.Logf("long reply: %d draws, median %.2f ms, 95th %.2f ms, worst %.2f ms", n, frames[n/2], frames[n*95/100], frames[n-1]) if os.Getenv("EQUIPO_CI_DEDICATED") != "1" { t.Logf("long reply: frame budget (30 or more draws, 95th percentile 4 ms) reported, not enforced: a shared machine's load is not the page's time (EQUIPO_CI_DEDICATED=1 enforces it)") } else if n < 30 || frames[n*95/100] > 4 { t.Fatalf("long reply: %d draws (want 30 or more), 95th percentile %.2f ms (budget 4 ms)", n, frames[n*95/100]) } } // evaluateIn is the value of a page expression in the browser of ctx. func evaluateIn[T any](t *testing.T, ctx context.Context, expression string) T { t.Helper() var out T if err := chromedp.Do(ctx, chromedp.Func(func(ctx context.Context, target *chromedp.Target) (err error) { out, err = chromedp.Evaluate[T](expression)(ctx, target) return })); err != nil { t.Fatal(err) } return out }