//go:build browser package headless import ( "context" "os" "path/filepath" "strconv" "testing" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/oficina/equipo/internal/runner/thin" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/input" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" ) type page struct { t *testing.T ctx context.Context stop func() check func(expression, reason string) run func(actions ...chromedp.Action[chromedp.Void]) } // openPage signs a browser in and opens /conversation at width x height. func openPage(t *testing.T, url, cookieName, cookieValue string, width, height int64, pointer bool) *page { opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox) if pointer { // Headless Chrome reports no hover; a desktop has a mouse (Blink's // hover type 2 is hover, pointer type 4 is fine). opts = append(opts, chromedp.Flag("blink-settings", "primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4")) } else { opts = append(opts, chromedp.Flag("blink-settings", "primaryHoverType=1,availableHoverTypes=1,primaryPointerType=2,availablePointerTypes=2")) } alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), opts...) ctx, cancel := chromedp.NewContext(alloc) p := &page{t: t, ctx: ctx, stop: func() { cancel(); cancelAlloc() }} p.run = func(actions ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, actions...); err != nil { t.Fatal(err) } } p.check = func(expression, reason string) { t.Helper() var ok bool p.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) } } p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookieName, Value: cookieValue, URL: url}) return err }), chromedp.EmulateViewport(width, height)) p.run(chromedp.Navigate(url+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`)) return p } func (p *page) send(text string) { p.t.Helper() p.check(`(()=>{document.querySelector('#chat-body').value=`+jsonString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`, "send") } // receiptAboveReply: the receipt of a turn sits before that turn's reply // (compareDocumentPosition 4: the reply follows). const receiptAboveReply = `(()=>{const r=document.querySelector('[equipo-receipt][data-state="added"]');if(!r)return false;const m=[...document.querySelectorAll('[equipo-message="incoming"][data-turn-id="'+r.dataset.turnId+'"]')][0];return !!m && !!(r.compareDocumentPosition(m)&4)})()` const actionsShown = `getComputedStyle(document.querySelector('[equipo-receipt] [equipo-receipt-actions]')).opacity==='1'` // Paul, 2b: a receipt (Added, Working in, New projects go to) is a quiet // line placed where its action happened, before the reply; its actions // show only on hover or keyboard focus, without moving anything. func TestBrowserReceiptsDesktop(t *testing.T) { _, inst, r := localEnv(t) r.start(t) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) defer p.stop() p.send("Fix the README typo in sample.\ntool:add_project:oficina/sample") p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('Added oficina/sample'))`)) p.run(browsertest.Wait(receiptAboveReply)) p.check(`(()=>{const r=document.querySelector('[equipo-receipt]');return !r.querySelector('[rst-btn]:not(details [rst-btn])') && getComputedStyle(r).borderTopColor==='rgba(0, 0, 0, 0)' || getComputedStyle(r).backgroundColor==='rgba(0, 0, 0, 0)'})()`, "a receipt has button chrome") p.check(`!(`+actionsShown+`) && getComputedStyle(document.querySelector('[equipo-receipt-more]')).display==='none'`, "actions shown before hover") var box struct{ X, Y, H float64 } p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { v, err := chromedp.Evaluate[[]float64](`(()=>{const b=document.querySelector('[equipo-receipt]').getBoundingClientRect();return [b.x+8,b.y+b.height/2,b.height]})()`)(ctx, target) box.X, box.Y, box.H = v[0], v[1], v[2] return err })) p.run(chromedp.MouseEvent(input.DispatchMouseEventTypeMouseMoved, box.X, box.Y)) p.run(browsertest.Wait(actionsShown)) p.check(`Math.abs(document.querySelector('[equipo-receipt]').getBoundingClientRect().height-`+jsonNumber(box.H)+`)<0.5`, "showing the actions moved the line") // Keyboard: focus reaches the actions and shows them. p.run(chromedp.MouseEvent(input.DispatchMouseEventTypeMouseMoved, 5, 5)) p.run(browsertest.Wait(`!(` + actionsShown + `)`)) p.check(`(()=>{const b=document.querySelector('[equipo-receipt] [equipo-receipt-actions] button[equipo-link]');b.focus();return document.activeElement===b && b.textContent.trim()!==''})()`, "Remove not focusable") p.run(browsertest.Wait(actionsShown)) // The order holds in the server render too. p.run(chromedp.Reload(), browsertest.Wait(`!!document.querySelector('[data-chat-stream]')`), browsertest.Wait(receiptAboveReply)) // An unclear home request asks with a prominent one-tap card; the tap // turns it into a quiet receipt with Undo. 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"] [rst-btn="primary"][value="confirm"]')`)) p.check(`!document.querySelector('[equipo-card="home"][data-state="ask"]').hasAttribute('equipo-receipt')`, "a question rendered as a receipt") 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"] [equipo-link][value="undo"]')`)) } // On touch (no hover) a small ⋯ at the end of the line shows the actions. func TestBrowserReceiptsTouch(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() p.send("Fix the README typo in sample.\ntool:add_project:oficina/sample") p.run(browsertest.Wait(receiptAboveReply)) p.check(`getComputedStyle(document.querySelector('[equipo-receipt-more]')).display!=='none' && !(`+actionsShown+`)`, "no ⋯ on touch, or actions already shown") p.check(`(()=>{const m=document.querySelector('[equipo-receipt-more]');return m.getAttribute('aria-label')!=='' && m.getAttribute('aria-expanded')==='false'})()`, "⋯ has no accessible name or state") p.check(`(()=>{window.__h=document.querySelector('[equipo-receipt]').getBoundingClientRect().height;document.querySelector('[equipo-receipt-more]').click();return true})()`, "tap ⋯") p.run(browsertest.Wait(actionsShown)) p.check(`document.querySelector('[equipo-receipt-more]').getAttribute('aria-expanded')==='true' && Math.abs(document.querySelector('[equipo-receipt]').getBoundingClientRect().height-window.__h)<0.5`, "⋯ moved the line or kept its state") } // Astra 2b review 1: the owner opens Notebook from the conversation // header, sees each entry and where it came from, and Reset starts the // coordinator afresh: it moves in again and introduces itself. func TestBrowserNotebook(t *testing.T) { _, inst, r := localEnv(t) r.opts.NoMoveIn = false r.start(t) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) defer p.stop() p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator"))`)) p.check(`(()=>{const a=document.querySelector('[equipo-chat-header] a[href="/conversation/settings/notebook"]');if(!a)return false;a.click();return true})()`, "no Notebook link in the header") p.run(browsertest.Wait(`location.pathname==='/conversation/settings/notebook' && [...document.querySelectorAll('[equipo-note]')].some(e=>e.textContent.includes('From oficina/equipo/README.md'))`)) // Reset saves in place, as every Settings change does: the notebook // empties, "Saved", no navigation; the conversation then has the new // coordinator's introduction. p.check(`(()=>{window.__stay=1;document.querySelector('[data-notebook-reset]').click();return true})()`, "reset") p.run(browsertest.Wait(`window.__stay===1 && location.pathname==='/conversation/settings/notebook' && !document.querySelector('[equipo-note]') && !!document.querySelector('#notebook [equipo-saved-tick][data-shown]')`)) p.run(chromedp.Navigate(inst.URL + "/conversation")) p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].filter(e=>e.textContent.includes("I'm your coordinator")).length===2`)) } func jsonNumber(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) } // Astra 2b minor: an explore turn that ends with nothing to say leaves no // thinking bubble behind. func TestBrowserEmptyExplore(t *testing.T) { _, inst, r := localEnv(t) r.opts.NoMoveIn = false r.opts.Claude.MoveInNote = "\nmovein-pause:400" r.start(t) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) defer p.stop() p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator"))`)) // The runner lost its record of moving in but explored this access // already: the instance makes it an explore, which has nothing to say. r.stop(t) desk, err := thin.OpenDesk(thin.SessionRoot(r.cfg), thintest.Owner) if err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(filepath.Dir(desk.Dir), "desk.json"), []byte(`{"moved_in":false,"namespaces":["oficina"],"next_id":50}`), 0600); err != nil { t.Fatal(err) } p.check(`(()=>{window.__bubble=false;setInterval(()=>{if(document.querySelector('[equipo-thinking]'))window.__bubble=true},10);return true})()`, "watch") r.start(t) p.run(browsertest.Wait(`window.__bubble===true`)) p.run(browsertest.Wait(`!document.querySelector('[equipo-thinking]') && !document.querySelector('[data-ended]')`)) p.check(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].filter(e=>e.textContent.includes("I'm your coordinator")).length===1`, "a second introduction") }