//go:build browser package headless import ( "context" "fmt" "os" "path/filepath" "testing" "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" ) // The reply streams into the message it becomes. The draft has no box or // border; when the reply is committed the same element stays, takes its // id and time, and keeps its size. At 1280 and 390 px, light and dark, // and once with reduced motion. EQUIPO_BROWSER_ARTIFACTS, when set, // receives thinking-*.png of the line, the stream and the settled reply. func TestBrowserDraftIsTheMessage(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) } } shot := func(name string) { t.Helper() dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS") if dir == "" { return } run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { png, err := chromedp.CaptureScreenshot()(ctx, target) if err != nil { return err } if err := os.MkdirAll(dir, 0o755); err != nil { return err } return os.WriteFile(filepath.Join(dir, "thinking-"+name+".png"), png, 0o644) })) } media := func(scheme, motion string) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: scheme}, {Name: "prefers-reduced-motion", Value: motion}}}) return 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 })) for _, c := range []struct { width, height int scheme, motion string }{ {1280, 800, "light", "no-preference"}, {1280, 800, "dark", "no-preference"}, {390, 844, "light", "no-preference"}, {390, 844, "dark", "no-preference"}, {390, 844, "light", "reduce"}, } { name := fmt.Sprintf("%d-%s", c.width, c.scheme) if c.motion == "reduce" { name += "-reduced" } run(chromedp.EmulateViewport(int64(c.width), int64(c.height)), media(c.scheme, c.motion)) run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`)) run(browsertest.Wait(`true`)) check(`(()=>{document.querySelector('#chat-body').value='draft check pause:2200 sleep:1200 slowstream';document.querySelector('#composer').requestSubmit();return true})()`, "send") // The line: sparkle, words and timer, above the composer. run(browsertest.Wait(`(()=>{const e=document.querySelector('[equipo-thinking] [equipo-elapsed]');return !!document.querySelector('[equipo-thinking] [equipo-sparkle]') && !!e && /^[1-9]/.test(e.textContent)})()`)) check(`(()=>{const b=document.querySelector('[equipo-thinking]').getBoundingClientRect();const c=document.querySelector('#chat-composer').getBoundingClientRect();return b.bottom<=c.top+1 && b.top>=0})()`, "the thinking line is not fully above the composer") shot(name + "-line") // Record the draft as it streams, frame by frame, until it is // committed. check(`(()=>{window.__d=null;window.__m=null;const f=()=>{const d=document.querySelector('[equipo-thinking][data-streaming]');if(d&&!window.__d)window.__d=d;const x=window.__d;if(x&&x.hasAttribute('equipo-thinking')&&x.querySelector('[data-stream-text] p')){const b=x.querySelector('[equipo-bubble]'),s=getComputedStyle(b),r=x.getBoundingClientRect(),q=x.querySelector('[equipo-message-body]').getBoundingClientRect();window.__m={w:r.width,h:r.height,bw:q.width,bh:q.height,border:s.borderTopWidth+' '+s.borderLeftWidth,bg:s.backgroundColor,pad:s.paddingTop+' '+s.paddingLeft}}if(!x||x.hasAttribute('equipo-thinking'))requestAnimationFrame(f)};f();return true})()`, "record") run(browsertest.Wait(`!!window.__m`)) check(`window.__m.border==='0px 0px' && window.__m.bg==='rgba(0, 0, 0, 0)' && window.__m.pad==='0px 0px'`, "the streaming draft has a box") check(`!!window.__d.querySelector('[equipo-message-meta] strong') && !!window.__d.querySelector('[equipo-message-meta] time') && window.__d.querySelector('[equipo-message-body]').hasAttribute('equipo-markdown')`, "the draft is not marked up as a message") shot(name + "-streaming") // Committed: the same element, its id and time filled, the same size. run(browsertest.Wait(`!!window.__d && !window.__d.hasAttribute('equipo-thinking') && !!window.__d.dataset.message`)) check(`window.__d.isConnected && document.querySelector('[data-message="'+CSS.escape(window.__d.dataset.message)+'"]')===window.__d`, "the committed reply replaced its draft") check(`/^[0-9]{2}:[0-9]{2}$/.test(window.__d.querySelector('[equipo-message-meta] time').textContent)`, "no time on the committed reply") check(`(()=>{const r=window.__d.getBoundingClientRect(),q=window.__d.querySelector('[equipo-message-body]').getBoundingClientRect(),m=window.__m;return Math.abs(r.width-m.w)<1 && Math.abs(r.height-m.h)<1 && Math.abs(q.width-m.bw)<1 && Math.abs(q.height-m.bh)<1})()`, "the reply changed size when committed") run(browsertest.Wait(`!window.__d.querySelector('[equipo-activity-line]') && !document.querySelector('[equipo-thinking]')`)) shot(name + "-reply") } }