//go:build browser package thintest import ( "context" "encoding/json" "fmt" "net/http" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/cdproto/input" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" ) // innerPage is a signed-in browser on the gallery's instance. type innerPage struct { t *testing.T ctx context.Context stop func() base string } // openInner opens a browser at width x height as the session c: a mouse // on a desktop, touch on a phone; scheme and motion are the emulated // prefers-color-scheme and prefers-reduced-motion. func openInner(t *testing.T, base string, c *http.Cookie, width, height int64, touch bool, scheme, motion string) *innerPage { t.Helper() opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox) if touch { opts = append(opts, chromedp.Flag("blink-settings", "primaryHoverType=1,availableHoverTypes=1,primaryPointerType=2,availablePointerTypes=2")) } else { opts = append(opts, chromedp.Flag("blink-settings", "primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4")) } alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), opts...) ctx, cancel := chromedp.NewContext(alloc) p := &innerPage{t: t, ctx: ctx, stop: func() { cancel(); cancelAlloc() }, base: base} p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: c.Name, Value: c.Value, URL: base}) if err != nil { return err } _, 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 })) if touch { // A phone: overlay scrollbars, so the page is 390 wide. p.do(chromedp.EmulateViewport(width, height, chromedp.EmulateMobile, chromedp.EmulateTouch, chromedp.EmulateScale(2))) } else { p.do(chromedp.EmulateViewport(width, height)) } return p } func (p *innerPage) do(actions ...chromedp.Action[chromedp.Void]) { p.t.Helper() if err := chromedp.Do(p.ctx, actions...); err != nil { p.t.Fatal(err) } } func eval[T any](p *innerPage, expression string) T { p.t.Helper() var out T p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error out, err = chromedp.Evaluate[T](expression)(ctx, target) return err })) return out } func (p *innerPage) check(expression, reason string) { p.t.Helper() if !eval[bool](p, expression) { p.t.Fatal(reason) } } // wait polls expression until it is true, for up to 8 s. func (p *innerPage) wait(expression, what string) { p.t.Helper() deadline := time.Now().Add(8 * time.Second) for { if eval[bool](p, `document.readyState==='complete' && !!(`+expression+`)`) { return } if time.Now().After(deadline) { p.t.Fatalf("waiting for %s: %s", what, expression) } time.Sleep(40 * time.Millisecond) } } func (p *innerPage) open(path string) { p.t.Helper() p.do(chromedp.Navigate(p.base + path)) p.wait(`document.querySelector('#rail')`, path) p.check(`(()=>{window.__nav=performance.getEntriesByType('navigation').length;window.__href=location.href;return true})()`, "mark") } // stayed: no reload or navigation since open. func (p *innerPage) stayed(what string) { p.t.Helper() p.check(`performance.getEntriesByType('navigation').length===window.__nav && location.href===window.__href`, what+": the page reloaded") } func (p *innerPage) shot(name string) { p.t.Helper() dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS") if dir == "" { return } var buf []byte p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error buf, err = chromedp.FullScreenshot(90)(ctx, target) return err })) if err := os.MkdirAll(dir, 0700); err != nil { p.t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, name+".png"), buf, 0600); err != nil { p.t.Fatal(err) } } func jsString(s string) string { raw, _ := json.Marshal(s); return string(raw) } // Measure the central star path, not the asymmetric satellite sparkles. func TestBrowserTrackStarCentre(t *testing.T) { g := newGallery(t) for _, width := range []int64{1280, 390} { for _, motion := range []string{"no-preference", "reduce"} { t.Run(fmt.Sprintf("%d/%s", width, motion), func(t *testing.T) { p := openInner(t, g.a.inst.URL, g.a.inst.Cookie(), width, 900, width == 390, "light", motion) defer p.stop() for _, full := range []bool{true, false} { path, selector := "/tasks", `[equipo-row][data-task="`+g.running+`"] [equipo-track]` if full { path, selector = "/tasks/"+g.running, "[equipo-track-full]" } p.open(path) // Sample while animations are running as well as with reduced motion. for sample := 0; sample < 2; sample++ { offsets := eval[[]float64](p, `(()=>{ const track=document.querySelector(`+jsString(selector)+`); const li=track.querySelector('[data-live]'); const marker=li.querySelector('[equipo-dot]') || li; const n=marker.getBoundingClientRect(), l=li.getBoundingClientRect(); const star=li.querySelector('[equipo-mark] svg path').getBoundingClientRect(); const x=(star.left+star.right)/2, y=(star.top+star.bottom)/2; const line=getComputedStyle(li,'::before'); const lineY=track.hasAttribute('equipo-track-full') ? l.top+parseFloat(line.top)+parseFloat(line.height)/2 : (l.top+l.bottom)/2; return [x-(n.left+n.right)/2,y-(n.top+n.bottom)/2,y-lineY]; })()`) for axis, offset := range offsets { // The hairline starts at the marker centre, so its painted // centre is half a CSS pixel lower. if offset < -0.6 || offset > 0.6 { t.Fatalf("full=%v sample=%d axis=%d: star offset %.3fpx", full, sample, axis, offset) } } time.Sleep(100 * time.Millisecond) } } }) } } } // fits: nothing wider than the viewport, the screen's own text visible. func (p *innerPage) fits(what string) { p.t.Helper() if !eval[bool](p, `document.documentElement.scrollWidth<=innerWidth+1`) { p.t.Fatal(what+" scrolls sideways: ", eval[string](p, `[...document.querySelectorAll('main *')].filter(e=>e.getBoundingClientRect().right>innerWidth+1).slice(-4).map(e=>e.tagName+' '+[...e.attributes].map(a=>a.name).join(' ')+' '+Math.round(e.getBoundingClientRect().right)).join(' | ')`)) } } // innerScreens are the screens, by name and path. func innerScreens(g *gallery) [][2]string { return [][2]string{{"tasks", "/tasks"}, {"task", "/tasks/" + g.unchecked}, {"task-live", "/tasks/" + g.running}, {"needs", "/tasks?needs=you"}, {"projects", "/projects"}, {"project", "/projects/" + g.a.conv.Tasks[g.unchecked].ProjectID}, {"index", "/work"}} } // TestBrowserInnerGallery draws every inner screen at 1280 and 390, light // and dark, and saves each when EQUIPO_BROWSER_ARTIFACTS names a // directory (ux1---.png). It asserts only what any // version of the screens must do (no sideways scrolling), so it also // records the screens before this round. func TestBrowserInnerGallery(t *testing.T) { g := newGallery(t) for _, size := range []struct { w, h int64 touch bool }{{1280, 900, false}, {390, 844, true}} { for _, scheme := range []string{"light", "dark"} { p := openInner(t, g.a.inst.URL, g.a.inst.Cookie(), size.w, size.h, size.touch, scheme, "reduce") for _, s := range innerScreens(g) { if s[0] == "index" && size.w > 800 { continue } p.open(s[1]) if s[0] != "index" { p.fits(s[0]) } p.shot(fmt.Sprintf("ux1-%s-%d-%s", s[0], size.w, scheme)) } p.stop() } } } // TestBrowserInnerScreens: the rich screens at 1280 with a mouse and at // 390 with touch. Rows are links as a whole, by mouse and by keyboard; // quiet actions show on hover or focus, and always on touch; the // sidebar's specialist rows and the stage track follow the stream // without a reload; the Needs you card answers in one tap. func TestBrowserInnerScreens(t *testing.T) { g := newGallery(t) a := g.a doing := "Editing live.js" for _, size := range []struct { w, h int64 touch bool }{{1280, 900, false}, {390, 844, true}} { p := openInner(t, a.inst.URL, a.inst.Cookie(), size.w, size.h, size.touch, "light", "no-preference") row := func(id string) string { return `document.querySelector('[equipo-row][data-task="` + id + `"]')` } // Tasks: groups in order; a click anywhere on a row opens it. p.open("/tasks") p.check(`[...document.querySelectorAll('[equipo-group]')].map(e=>e.dataset.group).join()==='needs,progress,ready,done'`, "groups") p.check(`getComputedStyle(`+row(g.noras)+`.querySelector('[equipo-row-link]'),'::after').cursor==='pointer'`, "row cursor") // The row's menu is always in its slot, last in the action column. p.check(`getComputedStyle(`+row(g.stopped)+`.querySelector('[equipo-menu]')).opacity==='1'`, "⋯ hidden") box := eval[[]float64](p, `(()=>{`+row(g.noras)+`.scrollIntoView({block:'center'});const r=`+row(g.noras)+`.getBoundingClientRect();return [r.x+r.width*0.45,r.y+r.height-6]})()`) p.do(chromedp.MouseEvent(input.DispatchMouseEventTypeMousePressed, box[0], box[1], chromedp.ButtonLeft, chromedp.ClickCount(1)), chromedp.MouseEvent(input.DispatchMouseEventTypeMouseReleased, box[0], box[1], chromedp.ButtonLeft, chromedp.ClickCount(1))) p.wait(`location.pathname==='/tasks/`+g.noras+`'`, "the row's click") // Keyboard: Tab from the last filter reaches the first row; the row // shows the focus ring; Enter opens it. p.open("/tasks") p.check(`(()=>{const f=[...document.querySelectorAll('[equipo-filter] > summary')].pop();f.focus();return document.activeElement===f})()`, "focus filter") p.do(chromedp.KeyEvent("\t")) p.check(`document.activeElement===document.querySelector('[equipo-group] [equipo-trow-proj] summary')`, "Tab did not reach the first row's project") p.do(chromedp.KeyEvent("\t")) first := `document.querySelector('[equipo-group] [equipo-row-link]')` p.check(`document.activeElement===`+first, "Tab did not reach the first row") p.check(`getComputedStyle(`+first+`.closest('[equipo-row]')).boxShadow.includes('inset')`, "no focus ring on the row") want := eval[string](p, first+`.getAttribute('href')`) p.do(chromedp.KeyEvent("\r")) p.wait(`location.pathname===`+jsString(want), "Enter on the row") // The sidebar's specialist row follows the step's activity live, in // plain words (on a phone, the sidebar is the index page). rail := "/tasks" if size.touch { rail = "/work" } p.open(rail) eng := `document.querySelector('#rail [data-specialist="engineering"]')` p.check(eng+`.dataset.state==='working' && !!`+eng+`.querySelector('[equipo-sparkle]') && /^\d+:\d\d$/.test(`+eng+`.querySelector('[equipo-clock]').textContent)`, "Engineering is not shown working with its mark and clock") p.check(eng+`.querySelector('[equipo-nav-task]').textContent==='Task list loses its scroll position after a refresh' && `+eng+`.querySelector('[equipo-spec-doing]').textContent===`+jsString(doing), "row content") line, plain := "go test ./internal/equipo -run Live", "Running the tests" if size.touch { line, plain = `/bin/bash -lc "go build ./cmd/equipo"`, "Building the project" } a.activity("live-"+fmt.Sprint(size.w), wire.StepActivityReport{TaskID: g.running, StepID: g.runningStep.StepID, Attempt: 1, Kind: wire.ActivityRun, Subject: line}) p.wait(eng+`.querySelector('[equipo-spec-doing]').textContent===`+jsString(plain), "the new activity line") doing = plain p.stayed("row") if size.touch { p.shot(fmt.Sprintf("ux1-index-open-%d", size.w)) } // Needs you: one card per decision, the prominent answer in reach. p.open("/tasks?needs=you") p.check(`document.querySelectorAll('[equipo-decision][data-decision]').length===2`, "two decisions") p.check(`(()=>{const b=document.querySelector('[data-decision="`+g.unchecked+`"] [data-merge-choice="merge"]').getBoundingClientRect();return b.width>0 && b.height>=`+map[bool]string{true: "44", false: "30"}[size.touch]+`})()`, "Merge out of reach") p.fits("needs") if size.touch { // The phone's bars: on the conversation the back link, the title // and the notebook button share one centre line (Paul, f2eac36); // on the task and project pages the back link sits on its bar's // centre. mid := `(e=>{const r=e.getBoundingClientRect();return (r.top+r.bottom)/2})` p.open("/conversation") p.check(`(()=>{const m=`+mid+`;const a=m(document.querySelector('[rst-shell-back] > a')),h=m(document.querySelector('[equipo-chat-header] h1')),b=m(document.querySelector('[equipo-chat-header] [equipo-needs-pill]'));return Math.abs(a-h)<=1 && Math.abs(h-b)<=1})()`, "conversation bar not on one centre line") for _, path := range []string{"/tasks/" + g.unchecked, "/projects/" + a.conv.Tasks[g.unchecked].ProjectID} { p.open(path) p.check(`(()=>{const m=`+mid+`;const bar=document.querySelector('[rst-shell-back]'),l=bar.querySelector('a');const pad=parseFloat(getComputedStyle(bar).paddingTop);const r=bar.getBoundingClientRect();return Math.abs(m(l)-(r.top+pad+r.bottom)/2)<=1})()`, path+" back link off its bar's centre") } } // Under production's policy (no inline styles): avatars and // monograms carry their hue and the spread bars their widths. The // one exception is the living mark's motes, which Stardust places // through the CSSOM (not markup; the policy allows it). p.open("/projects") p.check(`(()=>{const h=e=>getComputedStyle(e).getPropertyValue('--h').trim();const av=document.querySelector('[equipo-av]'),mono=document.querySelector('[equipo-mono]'),bar=document.querySelector('[equipo-bar] i');return !!av&&h(av)!==''&&!!mono&&h(mono)!==''&&!!bar&&bar.getBoundingClientRect().width>0&&!document.querySelector('[style]:not([equipo-sparkle] [data-mote])')})()`, "a hue or a bar width is missing under the policy") // Timeline entries: one plain line each, the rest behind Details, // closed by default; Details opens by keyboard and by click. p.open("/tasks/" + g.unchecked) more := `[...document.querySelectorAll('[equipo-tl-more]')]` p.check(more+`.length>=3 && `+more+`.every(d=>!d.open) && document.querySelectorAll('[equipo-headline]').length>=4`, "timeline entries not collapsed with headlines") p.check(`(()=>{const s=document.querySelector('[equipo-tl] > li[data-kind="step"] [equipo-tl-more] > summary');s.focus();return document.activeElement===s})()`, "Details not focusable") p.do(chromedp.KeyEvent("\r")) p.wait(`document.querySelector('[equipo-tl] > li[data-kind="step"] [equipo-tl-more]').open && document.querySelector('[equipo-tl] > li[data-kind="step"] [equipo-tl-body]').getBoundingClientRect().height>0`, "Details opened by keyboard") p.check(`(()=>{const s=document.querySelector('[equipo-tl] > li[data-kind="finding"] [equipo-tl-more] > summary');s.click();return s.parentElement.open && s.parentElement.textContent.includes('AccountNavigationHost.swift')})()`, "Details opened by click with the path") p.shot(fmt.Sprintf("ux1-task-details-open-%d", size.w)) // Relative times keep current on their own (the minute tick). p.check(`(()=>{const e=document.querySelector('[equipo-ago][data-at]');e.dataset.at=String(Date.now()-5*60000-1000);window.equipoAges();return e.textContent.endsWith('5 min ago')})()`, "relative time did not tick") // "From your conversation" opens the conversation at that message, // in view and highlighted. p.open("/tasks/" + g.unchecked) src := a.conv.Tasks[g.unchecked].SourceMessageID p.check(`(()=>{const l=document.querySelector('#task-head a[equipo-source]');l.click();return true})()`, "source link") p.wait(`location.pathname==='/conversation' && document.querySelector('[data-message="`+src+`"]')?.hasAttribute('data-highlight')`, "the highlighted source message") p.check(`(()=>{const r=document.querySelector('[data-message="`+src+`"]').getBoundingClientRect();return r.top>=0 && r.bottom<=innerHeight})()`, "source message out of view") p.stop() } // The stage track follows the step live, on the Tasks page and the // task page, with no reload. Reduced motion keeps the mark still and // the clock counting. p := openInner(t, a.inst.URL, a.inst.Cookie(), 1280, 900, false, "dark", "reduce") defer p.stop() p.open("/tasks/" + g.running) cur := `document.querySelector('[equipo-track-full] [data-s="current"]')` p.check(cur+`?.hasAttribute('data-live') && `+cur+`.textContent.startsWith('In progress')`, "running track") p.check(`getComputedStyle(document.querySelector('[equipo-t-summary] [equipo-mark] path')).animationName==='none'`, "the mark moves under reduced motion") clock := `document.querySelector('#task-main [equipo-clock]').textContent` before := eval[string](p, clock) time.Sleep(1200 * time.Millisecond) p.check(clock+`!==`+jsString(before), "the clock stopped under reduced motion") a.activity("live-task", wire.StepActivityReport{TaskID: g.running, StepID: g.runningStep.StepID, Attempt: 1, Kind: wire.ActivityRun, Subject: "go test ./internal/equipo"}) p.wait(`[...document.querySelectorAll('#task-main [data-step-lines] li')].pop()?.textContent==='Running go test ./internal/equipo'`, "the timeline's activity line") cand := "a7c41e2" + strings.Repeat("c", 33) a.step("live-done", wire.StepReport{TaskID: g.running, StepID: g.runningStep.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: strings.Repeat("8", 40), CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a", Summary: "Keep the scroll position across a live swap."}) p.wait(cur+`?.textContent.startsWith('In review')`, "the track moved to In review") p.wait(`[...document.querySelectorAll('#task-main [equipo-tl] > li')].some(l=>l.textContent.includes('Pushed a7c41e2'))`, "the pushed step in the timeline") p.stayed("task page") p.open("/tasks") c := a.dispatched(wire.SpecialistChecks, strings.Repeat("8", 40), cand, 0) a.step("live-checks-run", wire.StepReport{TaskID: g.running, StepID: c.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: c.BaseSHA, CandidateSHA: cand}) r := `document.querySelector('[equipo-row][data-task="` + g.running + `"]')` p.wait(r+`?.querySelector('[equipo-badge2][data-kind="checks"][data-tone="live"]') && `+r+`.querySelector('[equipo-track] [data-s="current"]').title==='In review'`, "the row's track and live checks badge") a.checks("live-checks", c, wire.ChecksPassed, exit(0), "", "ok") p.wait(r+`?.querySelector('[equipo-badge2][data-kind="checks"][data-tone="positive"]')`, "checks passed on the row") p.stayed("tasks page") } // timezone makes the page's clock a zone (Intl, and so zone.js, which // tells Equipo the person's zone on the next page it opens). func (p *innerPage) timezone(zone string) { p.t.Helper() p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetTimezoneOverride, emulation.SetTimezoneOverrideParams{TimezoneID: zone}) return err })) }