//go:build browser package headless import ( "context" "encoding/json" "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" ) // At 390 px: the thinking line counts up and shows what the coordinator // is doing beside a sparkle, a cobalt wave running through its letters // unless reduced motion is asked for; the Added card // removes its project, a question card takes a tap; and with a smaller // visual viewport (a phone keyboard) the newest bubble stays above the // composer. func TestBrowserThinkingAndCards(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) } } send := func(text string) { t.Helper() check(`(()=>{document.querySelector('#chat-body').value=`+jsonString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`, "send") } 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]') && document.querySelector('[equipo-offline]').hidden`)) // The allowlist arrives with the runner's hello. run(browsertest.Wait(`true`)) // The timer counts in seconds from the send; the line shows the // latest activity, then gives way to the streamed reply. send("think pause:2600 sleep:1500 tool:status\ntool:add_project:oficina/sample") run(browsertest.Wait(`(()=>{const l=document.querySelector('[equipo-thinking] [equipo-activity]');return !!l && l.textContent==='Adding oficina/sample…'})()`)) run(browsertest.Wait(`(()=>{const e=document.querySelector('[equipo-thinking] [equipo-elapsed]');return !!e && /^[1-9][0-9]*s$/.test(e.textContent)})()`)) check(`!!document.querySelector('[equipo-thinking] [equipo-sparkle] svg') && [...document.querySelectorAll('[equipo-thinking] [equipo-phrase] [data-in] > span')].some(s=>getComputedStyle(s).animationName.includes('equipo-wave'))`, "no sparkle or wave") check(`!document.querySelector('[equipo-thinking-dots]')`, "dots still shown") run(browsertest.Wait(`!!document.querySelector('[equipo-thinking][data-streaming]') && getComputedStyle(document.querySelector('[equipo-thinking] [equipo-activity-line]')).visibility==='hidden'`)) run(browsertest.Wait(`!document.querySelector('[equipo-thinking]')`)) run(browsertest.Wait(`[...document.querySelectorAll('[equipo-card="project"][data-state="added"]')].some(e=>e.textContent.includes('Added oficina/sample'))`)) // Reduced motion: the line is still. run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: "reduce"}}}) return err })) send("think pause:2000") run(browsertest.Wait(`!!document.querySelector('[equipo-thinking] [equipo-phrase] [data-in] > span')`)) check(`getComputedStyle(document.querySelector('[equipo-thinking] [equipo-sparkle] path')).animationName==='none' && ![...document.querySelectorAll('[equipo-thinking] [equipo-phrase] span')].some(s=>getComputedStyle(s).animationName.includes('equipo-wave'))`, "reduced motion still animates") run(browsertest.Wait(`!document.querySelector('[equipo-thinking]')`)) // Remove on the Added card takes the project out, without navigating. check(`(()=>{window.__page=1;document.querySelector('[equipo-card="project"][data-state="added"] form[action$="/remove"] button').click();return true})()`, "remove") run(browsertest.Wait(`[...document.querySelectorAll('[equipo-card="project"][data-state="removed"]')].some(e=>e.textContent.includes('Removed oficina/sample'))`)) check(`window.__page===1 && performance.getEntriesByType('navigation').length===1`, "remove navigated") // A question card takes one tap; the answer is the person's message. send("tool:ask_person:Should the panes slide on iPad too?|Yes|No") run(browsertest.Wait(`!!document.querySelector('[equipo-card="question"][data-state="open"] button[value="Yes"]')`)) check(`(()=>{document.querySelector('[equipo-card="question"][data-state="open"] button[value="Yes"]').click();return true})()`, "answer") run(browsertest.Wait(`[...document.querySelectorAll('[equipo-card="question"][data-state="answered"] [equipo-thread-turn][data-own] [equipo-thread-text]')].some(e=>e.textContent.trim()==='Yes')`)) run(browsertest.Wait(`!document.querySelector('[equipo-thinking]')`)) // A keyboard shrinks the visual viewport: after a send the newest // bubble sits fully above the composer. for range 6 { send("filler") run(browsertest.Wait(`!document.querySelector('[equipo-thinking]') && !document.querySelector('[data-pending]')`)) } run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { // Only the visual viewport shrinks, as with the iOS keyboard: the // layout viewport keeps its height. _, err := cdp.Call(ctx, target, emulation.SetPageScaleFactor, emulation.SetPageScaleFactorParams{PageScaleFactor: 1.6}) return err })) run(browsertest.Wait(`window.visualViewport.height{const b=document.querySelector('[equipo-thinking]').getBoundingClientRect();const c=document.querySelector('#chat-composer').getBoundingClientRect();return b.bottom<=c.top+1 && b.top>=0 && c.bottom<=window.visualViewport.height+1})()`)) // Reading back up is not yanked down by new text. check(`(()=>{const s=document.querySelector('[equipo-scroll]');s.scrollTop=0;s.dispatchEvent(new Event('scroll'));return true})()`, "scroll up") run(browsertest.Wait(`!document.querySelector('[equipo-thinking]')`)) check(`document.querySelector('[equipo-scroll]').scrollTop<50`, "a reply yanked the reader to the bottom") } func jsonString(s string) string { raw, _ := json.Marshal(s); return string(raw) } // Review fix 4: refreshes overlap when a card and the reply land close // together. A slow first refresh carrying an older page must not undo the // newer one: refreshes are serialised and an older page is never applied. func TestBrowserRefreshRace(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]') && document.querySelector('[equipo-offline]').hidden`)) // The first refresh answers late with the page as it was at load. check(`(()=>{const x=new XMLHttpRequest();x.open('GET',location.pathname,false);x.send();const stale=x.responseText;window.__fetch=window.fetch;let first=true;window.fetch=function(u,o){if(first&&(!o||!o.method||o.method==='GET')&&String(u).endsWith('/conversation')){first=false;return new Promise(res=>setTimeout(()=>res(new Response(stale,{status:200,headers:{'Content-Type':'text/html'}})),1500))}return window.__fetch(u,o)};return true})()`, "setup") check(`(()=>{document.querySelector('#chat-body').value='tool:add_project:oficina/sample';document.querySelector('#composer').requestSubmit();return true})()`, "send") run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('Added oficina/sample'))`)) // After the slow stale page has come and gone, the newest state stays. run(chromedp.Sleep(2500 * time.Millisecond)) check(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('Added oficina/sample')) && !!document.querySelector('[equipo-card="project"][data-state="added"]')`, "a stale refresh undid the newer page") } // Paul, 2026-11-27: a tap on a card's choice, read from above the bottom // of the conversation, left the view where it was while the follow-up // came in below. The answer settles the view at the bottom, where the // follow-up shows, as a send does; without script the answer's redirect // lands there too. func TestBrowserCardAnswerSettlesAtBottom(t *testing.T) { _, inst, r := localEnv(t) r.start(t) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, 390, 844, false) defer p.stop() const quiet = `!document.querySelector('[equipo-thinking]') && !document.querySelector('[data-pending]')` const atBottom = `(()=>{const s=document.querySelector('[equipo-scroll]');return s.scrollHeight-s.clientHeight>400 && s.scrollHeight-s.scrollTop-s.clientHeight<2})()` const readUp = `(()=>{const s=document.querySelector('[equipo-scroll]');s.scrollTop=s.scrollHeight-s.clientHeight-400;s.dispatchEvent(new Event('scroll'));return s.scrollHeight-s.scrollTop-s.clientHeight>300})()` for range 6 { p.send("filler") p.run(browsertest.Wait(quiet)) } p.send("What about oficina for new projects\ntool:set_project_home:oficina") p.run(browsertest.Wait(`!!document.querySelector('[equipo-card="home"][data-state="ask"] [value="confirm"]')`), browsertest.Wait(quiet)) // With script: read back up, tap the choice; the view settles at the bottom. p.check(readUp, "could not read back up") p.check(`(()=>{document.querySelector('[equipo-card="home"][data-state="ask"] [value="confirm"]').click();return true})()`, "tap") p.run(browsertest.Wait(`!!document.querySelector('[equipo-receipt][equipo-card="home"][data-state="set"]')`), browsertest.Wait(quiet)) p.run(browsertest.Wait(atBottom)) // Without script the page opens at the top of the feed; the answer's // redirect (Undo on the receipt) lands at the bottom. p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}) return err }), chromedp.Navigate(inst.URL+"/conversation")) p.run(browsertest.Wait(`!!document.querySelector('[equipo-receipt][equipo-card="home"][data-state="set"] [value="undo"]')`)) p.check(`!`+atBottom, "the page opened at the bottom without script") p.check(`(()=>{document.querySelector('[equipo-receipt][equipo-card="home"][data-state="set"] [value="undo"]').closest('form').requestSubmit(document.querySelector('[equipo-receipt][equipo-card="home"][data-state="set"] [value="undo"]'));return true})()`, "undo") p.run(browsertest.Wait(`location.pathname==='/conversation' && location.hash==='#conversation-end'`), browsertest.Wait(atBottom)) }