oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package headless
4
5import (
6 "context"
7 "os"
8 "sort"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/browsertest"
13 "amadan.net/rastrillo/rastrillo/harness"
14 "github.com/chromedp/cdproto/cdp"
15 "github.com/chromedp/cdproto/emulation"
16 "github.com/chromedp/cdproto/network"
17 "github.com/chromedp/chromedp"
18)
19
20// A formatted reply is formatted as it streams: its bullets are list
21// items on their own lines, no asterisks show, the new words fade in
22// inside the formatting, and the committed reply is the last streamed
23// render plus at most its last characters (normalised HTML; the same
24// height when equal). A long reply is drawn within light.js's frame
25// budget (about 4 ms).
26//
27// Everything is judged from what the page records as it happens: each
28// draw is read the moment it lands (a MutationObserver, not a sampled
29// frame, so a commit straight after the last draw cannot hide it), and
30// the commit records its time beside the deadline the page set for it
31// (settleBy). The page commits an undrawn draft only at that 2 s cap; a
32// commit at the cap is logged, and anything earlier must be the last
33// render plus its last characters. The frame budget is a time on this
34// machine, so like the CI timing budgets it is enforced only where
35// EQUIPO_CI_DEDICATED=1 and reported elsewhere.
36func TestBrowserDraftStreamsFormatted(t *testing.T) {
37 _, inst, r := localEnv(t)
38 r.start(t)
39 alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...)
40 defer cancelAlloc()
41 ctx, cancel := chromedp.NewContext(alloc)
42 defer cancel()
43 run := func(actions ...chromedp.Action[chromedp.Void]) {
44 t.Helper()
45 if err := chromedp.Do(ctx, actions...); err != nil {
46 t.Fatal(err)
47 }
48 }
49 check := func(expression, reason string) {
50 t.Helper()
51 if !evaluateIn[bool](t, ctx, expression) {
52 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)`))
53 }
54 }
55 cookie := inst.Cookie()
56 open := func(motion string) {
57 t.Helper()
58 run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
59 if _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}); err != nil {
60 return err
61 }
62 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: motion}}})
63 return err
64 }), chromedp.EmulateViewport(1280, 800), chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`))
65 }
66 // record follows the next reply until it is committed: its last
67 // render (the fade spans unwrapped) and height, markup shown outside
68 // code, the fade inside a list item, where two list items sit, each
69 // draw's time, and when it was committed against the page's deadline
70 // for it (settleBy).
71 record := `(()=>{const s=window.__s={el:null,last:null,h:0,stray:null,fade:null,lines:null,frames:[],done:false,at:0,by:0};
72new PerformanceObserver(l=>{for(const e of l.getEntries())if(e.name==='equipo-draft')s.frames.push(e.duration)}).observe({type:'measure'});
73window.__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};
74const f=()=>{if(s.done)return;if(!s.el)s.el=document.querySelector('[equipo-thinking][data-streaming]');const x=s.el;if(!x)return;
75if(!x.hasAttribute('equipo-thinking')){s.done=true;s.at=Date.now();s.by=x.settleBy||0;return}
76const b=x.querySelector('[data-stream-text]');if(b&&b.firstChild){s.last=window.__norm(b);s.h=b.getBoundingClientRect().height;
77const 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;
78const n=b.querySelector('li [data-new]');if(n&&!s.fade){const st=getComputedStyle(n);s.fade=st.animationName+' '+st.animationDuration}
79const 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]}};
80new MutationObserver(f).observe(document.body,{childList:true,subtree:true,characterData:true,attributes:true});f();return true})()`
81 send := func(text string) {
82 t.Helper()
83 check(record, "record")
84 check(`(()=>{document.querySelector('#chat-body').value=`+jsString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`, "send")
85 }
86 committed := func(reason string) {
87 t.Helper()
88 run(browsertest.WaitWithin(`window.__s.done && !!window.__s.el.dataset.message`, 60*time.Second))
89 if evaluateIn[bool](t, ctx, `window.__s.by>0 && window.__s.at>=window.__s.by`) {
90 // The draft was still drawing when the page's 2 s wait ran
91 // out: the page commits then by design, so how far the last
92 // render was behind is this machine's speed, not the page.
93 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`))
94 check(`window.__s.stray===null`, reason+": markup characters showed while streaming")
95 return
96 }
97 // Past what the two share, the last render has only the closing
98 // tags of the text it ends in.
99 check(`(()=>{const f=window.__norm(window.__s.el.querySelector('[equipo-message-body]')),l=window.__s.last;let k=0;while(k<l.length&&l[k]===f[k])k++;window.__s.same=l===f;return l===f||/^(<\/[a-z]+>\s*)+$/.test(l.slice(k))&&f.length-k<80})()`, reason+": the committed reply is not the last streamed render plus its last characters")
100 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")
101 t.Logf("%s: last streamed render equal to the committed reply: %v", reason, evaluateIn[bool](t, ctx, `window.__s.same`))
102 check(`window.__s.stray===null`, reason+": markup characters showed while streaming")
103 }
104 for _, m := range []struct{ motion, fade string }{{"no-preference", "equipo-fade 0.32s"}, {"reduce", "equipo-fade 0.2s"}} {
105 open(m.motion)
106 send("replymd chunks:80 sleep:40 slowstream")
107 // While streaming the bullets are list items on their own lines.
108 run(browsertest.WaitWithin(`!!window.__s.lines`, 30*time.Second))
109 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")
110 committed(m.motion)
111 check(`window.__s.fade===`+jsString(m.fade), "the words in a list item did not fade in as "+m.fade)
112 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")
113 }
114 // A long reply: about 14 KB in 400 deltas.
115 open("no-preference")
116 send("replymd:long chunks:400 sleep:12 slowstream")
117 committed("long reply")
118 // The runner sends the deltas it has about ten times a second.
119 frames := evaluateIn[[]float64](t, ctx, `window.__s.frames`)
120 sort.Float64s(frames)
121 n := len(frames)
122 if n < 2 {
123 t.Fatalf("long reply: %d draws: it was not drawn as it streamed", n)
124 }
125 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])
126 if os.Getenv("EQUIPO_CI_DEDICATED") != "1" {
127 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)")
128 } else if n < 30 || frames[n*95/100] > 4 {
129 t.Fatalf("long reply: %d draws (want 30 or more), 95th percentile %.2f ms (budget 4 ms)", n, frames[n*95/100])
130 }
131}
132
133// evaluateIn is the value of a page expression in the browser of ctx.
134func evaluateIn[T any](t *testing.T, ctx context.Context, expression string) T {
135 t.Helper()
136 var out T
137 if err := chromedp.Do(ctx, chromedp.Func(func(ctx context.Context, target *chromedp.Target) (err error) {
138 out, err = chromedp.Evaluate[T](expression)(ctx, target)
139 return
140 })); err != nil {
141 t.Fatal(err)
142 }
143 return out
144}
145