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 thintest
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "net/http"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/wire"
17 "amadan.net/rastrillo/rastrillo/harness"
18 "github.com/chromedp/cdproto/cdp"
19 "github.com/chromedp/cdproto/emulation"
20 "github.com/chromedp/cdproto/input"
21 "github.com/chromedp/cdproto/network"
22 "github.com/chromedp/chromedp"
23)
24
25// innerPage is a signed-in browser on the gallery's instance.
26type innerPage struct {
27 t *testing.T
28 ctx context.Context
29 stop func()
30 base string
31}
32
33// openInner opens a browser at width x height as the session c: a mouse
34// on a desktop, touch on a phone; scheme and motion are the emulated
35// prefers-color-scheme and prefers-reduced-motion.
36func openInner(t *testing.T, base string, c *http.Cookie, width, height int64, touch bool, scheme, motion string) *innerPage {
37 t.Helper()
38 opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)
39 if touch {
40 opts = append(opts, chromedp.Flag("blink-settings", "primaryHoverType=1,availableHoverTypes=1,primaryPointerType=2,availablePointerTypes=2"))
41 } else {
42 opts = append(opts, chromedp.Flag("blink-settings", "primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"))
43 }
44 alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), opts...)
45 ctx, cancel := chromedp.NewContext(alloc)
46 p := &innerPage{t: t, ctx: ctx, stop: func() { cancel(); cancelAlloc() }, base: base}
47 p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
48 _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: c.Name, Value: c.Value, URL: base})
49 if err != nil {
50 return err
51 }
52 _, err = cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: scheme}, {Name: "prefers-reduced-motion", Value: motion}}})
53 return err
54 }))
55 if touch {
56 // A phone: overlay scrollbars, so the page is 390 wide.
57 p.do(chromedp.EmulateViewport(width, height, chromedp.EmulateMobile, chromedp.EmulateTouch, chromedp.EmulateScale(2)))
58 } else {
59 p.do(chromedp.EmulateViewport(width, height))
60 }
61 return p
62}
63
64func (p *innerPage) do(actions ...chromedp.Action[chromedp.Void]) {
65 p.t.Helper()
66 if err := chromedp.Do(p.ctx, actions...); err != nil {
67 p.t.Fatal(err)
68 }
69}
70
71func eval[T any](p *innerPage, expression string) T {
72 p.t.Helper()
73 var out T
74 p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
75 var err error
76 out, err = chromedp.Evaluate[T](expression)(ctx, target)
77 return err
78 }))
79 return out
80}
81
82func (p *innerPage) check(expression, reason string) {
83 p.t.Helper()
84 if !eval[bool](p, expression) {
85 p.t.Fatal(reason)
86 }
87}
88
89// wait polls expression until it is true, for up to 8 s.
90func (p *innerPage) wait(expression, what string) {
91 p.t.Helper()
92 deadline := time.Now().Add(8 * time.Second)
93 for {
94 if eval[bool](p, `document.readyState==='complete' && !!(`+expression+`)`) {
95 return
96 }
97 if time.Now().After(deadline) {
98 p.t.Fatalf("waiting for %s: %s", what, expression)
99 }
100 time.Sleep(40 * time.Millisecond)
101 }
102}
103
104func (p *innerPage) open(path string) {
105 p.t.Helper()
106 p.do(chromedp.Navigate(p.base + path))
107 p.wait(`document.querySelector('#rail')`, path)
108 p.check(`(()=>{window.__nav=performance.getEntriesByType('navigation').length;window.__href=location.href;return true})()`, "mark")
109}
110
111// stayed: no reload or navigation since open.
112func (p *innerPage) stayed(what string) {
113 p.t.Helper()
114 p.check(`performance.getEntriesByType('navigation').length===window.__nav && location.href===window.__href`, what+": the page reloaded")
115}
116
117func (p *innerPage) shot(name string) {
118 p.t.Helper()
119 dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS")
120 if dir == "" {
121 return
122 }
123 var buf []byte
124 p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
125 var err error
126 buf, err = chromedp.FullScreenshot(90)(ctx, target)
127 return err
128 }))
129 if err := os.MkdirAll(dir, 0700); err != nil {
130 p.t.Fatal(err)
131 }
132 if err := os.WriteFile(filepath.Join(dir, name+".png"), buf, 0600); err != nil {
133 p.t.Fatal(err)
134 }
135}
136
137func jsString(s string) string { raw, _ := json.Marshal(s); return string(raw) }
138
139// Measure the central star path, not the asymmetric satellite sparkles.
140func TestBrowserTrackStarCentre(t *testing.T) {
141 g := newGallery(t)
142 for _, width := range []int64{1280, 390} {
143 for _, motion := range []string{"no-preference", "reduce"} {
144 t.Run(fmt.Sprintf("%d/%s", width, motion), func(t *testing.T) {
145 p := openInner(t, g.a.inst.URL, g.a.inst.Cookie(), width, 900, width == 390, "light", motion)
146 defer p.stop()
147 for _, full := range []bool{true, false} {
148 path, selector := "/tasks", `[equipo-row][data-task="`+g.running+`"] [equipo-track]`
149 if full {
150 path, selector = "/tasks/"+g.running, "[equipo-track-full]"
151 }
152 p.open(path)
153 // Sample while animations are running as well as with reduced motion.
154 for sample := 0; sample < 2; sample++ {
155 offsets := eval[[]float64](p, `(()=>{
156 const track=document.querySelector(`+jsString(selector)+`);
157 const li=track.querySelector('[data-live]');
158 const marker=li.querySelector('[equipo-dot]') || li;
159 const n=marker.getBoundingClientRect(), l=li.getBoundingClientRect();
160 const star=li.querySelector('[equipo-mark] svg path').getBoundingClientRect();
161 const x=(star.left+star.right)/2, y=(star.top+star.bottom)/2;
162 const line=getComputedStyle(li,'::before');
163 const lineY=track.hasAttribute('equipo-track-full')
164 ? l.top+parseFloat(line.top)+parseFloat(line.height)/2
165 : (l.top+l.bottom)/2;
166 return [x-(n.left+n.right)/2,y-(n.top+n.bottom)/2,y-lineY];
167 })()`)
168 for axis, offset := range offsets {
169 // The hairline starts at the marker centre, so its painted
170 // centre is half a CSS pixel lower.
171 if offset < -0.6 || offset > 0.6 {
172 t.Fatalf("full=%v sample=%d axis=%d: star offset %.3fpx", full, sample, axis, offset)
173 }
174 }
175 time.Sleep(100 * time.Millisecond)
176 }
177 }
178 })
179 }
180 }
181}
182
183// fits: nothing wider than the viewport, the screen's own text visible.
184func (p *innerPage) fits(what string) {
185 p.t.Helper()
186 if !eval[bool](p, `document.documentElement.scrollWidth<=innerWidth+1`) {
187 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(' | ')`))
188 }
189}
190
191// innerScreens are the screens, by name and path.
192func innerScreens(g *gallery) [][2]string {
193 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"}}
194}
195
196// TestBrowserInnerGallery draws every inner screen at 1280 and 390, light
197// and dark, and saves each when EQUIPO_BROWSER_ARTIFACTS names a
198// directory (ux1-<screen>-<width>-<scheme>.png). It asserts only what any
199// version of the screens must do (no sideways scrolling), so it also
200// records the screens before this round.
201func TestBrowserInnerGallery(t *testing.T) {
202 g := newGallery(t)
203 for _, size := range []struct {
204 w, h int64
205 touch bool
206 }{{1280, 900, false}, {390, 844, true}} {
207 for _, scheme := range []string{"light", "dark"} {
208 p := openInner(t, g.a.inst.URL, g.a.inst.Cookie(), size.w, size.h, size.touch, scheme, "reduce")
209 for _, s := range innerScreens(g) {
210 if s[0] == "index" && size.w > 800 {
211 continue
212 }
213 p.open(s[1])
214 if s[0] != "index" {
215 p.fits(s[0])
216 }
217 p.shot(fmt.Sprintf("ux1-%s-%d-%s", s[0], size.w, scheme))
218 }
219 p.stop()
220 }
221 }
222}
223
224// TestBrowserInnerScreens: the rich screens at 1280 with a mouse and at
225// 390 with touch. Rows are links as a whole, by mouse and by keyboard;
226// quiet actions show on hover or focus, and always on touch; the
227// sidebar's specialist rows and the stage track follow the stream
228// without a reload; the Needs you card answers in one tap.
229func TestBrowserInnerScreens(t *testing.T) {
230 g := newGallery(t)
231 a := g.a
232 doing := "Editing live.js"
233 for _, size := range []struct {
234 w, h int64
235 touch bool
236 }{{1280, 900, false}, {390, 844, true}} {
237 p := openInner(t, a.inst.URL, a.inst.Cookie(), size.w, size.h, size.touch, "light", "no-preference")
238 row := func(id string) string { return `document.querySelector('[equipo-row][data-task="` + id + `"]')` }
239
240 // Tasks: groups in order; a click anywhere on a row opens it.
241 p.open("/tasks")
242 p.check(`[...document.querySelectorAll('[equipo-group]')].map(e=>e.dataset.group).join()==='needs,progress,ready,done'`, "groups")
243 p.check(`getComputedStyle(`+row(g.noras)+`.querySelector('[equipo-row-link]'),'::after').cursor==='pointer'`, "row cursor")
244 // The row's menu is always in its slot, last in the action column.
245 p.check(`getComputedStyle(`+row(g.stopped)+`.querySelector('[equipo-menu]')).opacity==='1'`, "⋯ hidden")
246 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]})()`)
247 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)))
248 p.wait(`location.pathname==='/tasks/`+g.noras+`'`, "the row's click")
249
250 // Keyboard: Tab from the last filter reaches the first row; the row
251 // shows the focus ring; Enter opens it.
252 p.open("/tasks")
253 p.check(`(()=>{const f=[...document.querySelectorAll('[equipo-filter] > summary')].pop();f.focus();return document.activeElement===f})()`, "focus filter")
254 p.do(chromedp.KeyEvent("\t"))
255 p.check(`document.activeElement===document.querySelector('[equipo-group] [equipo-trow-proj] summary')`, "Tab did not reach the first row's project")
256 p.do(chromedp.KeyEvent("\t"))
257 first := `document.querySelector('[equipo-group] [equipo-row-link]')`
258 p.check(`document.activeElement===`+first, "Tab did not reach the first row")
259 p.check(`getComputedStyle(`+first+`.closest('[equipo-row]')).boxShadow.includes('inset')`, "no focus ring on the row")
260 want := eval[string](p, first+`.getAttribute('href')`)
261 p.do(chromedp.KeyEvent("\r"))
262 p.wait(`location.pathname===`+jsString(want), "Enter on the row")
263
264 // The sidebar's specialist row follows the step's activity live, in
265 // plain words (on a phone, the sidebar is the index page).
266 rail := "/tasks"
267 if size.touch {
268 rail = "/work"
269 }
270 p.open(rail)
271 eng := `document.querySelector('#rail [data-specialist="engineering"]')`
272 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")
273 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")
274 line, plain := "go test ./internal/equipo -run Live", "Running the tests"
275 if size.touch {
276 line, plain = `/bin/bash -lc "go build ./cmd/equipo"`, "Building the project"
277 }
278 a.activity("live-"+fmt.Sprint(size.w), wire.StepActivityReport{TaskID: g.running, StepID: g.runningStep.StepID, Attempt: 1, Kind: wire.ActivityRun, Subject: line})
279 p.wait(eng+`.querySelector('[equipo-spec-doing]').textContent===`+jsString(plain), "the new activity line")
280 doing = plain
281 p.stayed("row")
282 if size.touch {
283 p.shot(fmt.Sprintf("ux1-index-open-%d", size.w))
284 }
285
286 // Needs you: one card per decision, the prominent answer in reach.
287 p.open("/tasks?needs=you")
288 p.check(`document.querySelectorAll('[equipo-decision][data-decision]').length===2`, "two decisions")
289 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")
290 p.fits("needs")
291
292 if size.touch {
293 // The phone's bars: on the conversation the back link, the title
294 // and the notebook button share one centre line (Paul, f2eac36);
295 // on the task and project pages the back link sits on its bar's
296 // centre.
297 mid := `(e=>{const r=e.getBoundingClientRect();return (r.top+r.bottom)/2})`
298 p.open("/conversation")
299 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")
300 for _, path := range []string{"/tasks/" + g.unchecked, "/projects/" + a.conv.Tasks[g.unchecked].ProjectID} {
301 p.open(path)
302 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")
303 }
304 }
305
306 // Under production's policy (no inline styles): avatars and
307 // monograms carry their hue and the spread bars their widths. The
308 // one exception is the living mark's motes, which Stardust places
309 // through the CSSOM (not markup; the policy allows it).
310 p.open("/projects")
311 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")
312
313 // Timeline entries: one plain line each, the rest behind Details,
314 // closed by default; Details opens by keyboard and by click.
315 p.open("/tasks/" + g.unchecked)
316 more := `[...document.querySelectorAll('[equipo-tl-more]')]`
317 p.check(more+`.length>=3 && `+more+`.every(d=>!d.open) && document.querySelectorAll('[equipo-headline]').length>=4`, "timeline entries not collapsed with headlines")
318 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")
319 p.do(chromedp.KeyEvent("\r"))
320 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")
321 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")
322 p.shot(fmt.Sprintf("ux1-task-details-open-%d", size.w))
323
324 // Relative times keep current on their own (the minute tick).
325 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")
326
327 // "From your conversation" opens the conversation at that message,
328 // in view and highlighted.
329 p.open("/tasks/" + g.unchecked)
330 src := a.conv.Tasks[g.unchecked].SourceMessageID
331 p.check(`(()=>{const l=document.querySelector('#task-head a[equipo-source]');l.click();return true})()`, "source link")
332 p.wait(`location.pathname==='/conversation' && document.querySelector('[data-message="`+src+`"]')?.hasAttribute('data-highlight')`, "the highlighted source message")
333 p.check(`(()=>{const r=document.querySelector('[data-message="`+src+`"]').getBoundingClientRect();return r.top>=0 && r.bottom<=innerHeight})()`, "source message out of view")
334 p.stop()
335 }
336
337 // The stage track follows the step live, on the Tasks page and the
338 // task page, with no reload. Reduced motion keeps the mark still and
339 // the clock counting.
340 p := openInner(t, a.inst.URL, a.inst.Cookie(), 1280, 900, false, "dark", "reduce")
341 defer p.stop()
342 p.open("/tasks/" + g.running)
343 cur := `document.querySelector('[equipo-track-full] [data-s="current"]')`
344 p.check(cur+`?.hasAttribute('data-live') && `+cur+`.textContent.startsWith('In progress')`, "running track")
345 p.check(`getComputedStyle(document.querySelector('[equipo-t-summary] [equipo-mark] path')).animationName==='none'`, "the mark moves under reduced motion")
346 clock := `document.querySelector('#task-main [equipo-clock]').textContent`
347 before := eval[string](p, clock)
348 time.Sleep(1200 * time.Millisecond)
349 p.check(clock+`!==`+jsString(before), "the clock stopped under reduced motion")
350 a.activity("live-task", wire.StepActivityReport{TaskID: g.running, StepID: g.runningStep.StepID, Attempt: 1, Kind: wire.ActivityRun, Subject: "go test ./internal/equipo"})
351 p.wait(`[...document.querySelectorAll('#task-main [data-step-lines] li')].pop()?.textContent==='Running go test ./internal/equipo'`, "the timeline's activity line")
352 cand := "a7c41e2" + strings.Repeat("c", 33)
353 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."})
354 p.wait(cur+`?.textContent.startsWith('In review')`, "the track moved to In review")
355 p.wait(`[...document.querySelectorAll('#task-main [equipo-tl] > li')].some(l=>l.textContent.includes('Pushed a7c41e2'))`, "the pushed step in the timeline")
356 p.stayed("task page")
357 p.open("/tasks")
358 c := a.dispatched(wire.SpecialistChecks, strings.Repeat("8", 40), cand, 0)
359 a.step("live-checks-run", wire.StepReport{TaskID: g.running, StepID: c.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: c.BaseSHA, CandidateSHA: cand})
360 r := `document.querySelector('[equipo-row][data-task="` + g.running + `"]')`
361 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")
362 a.checks("live-checks", c, wire.ChecksPassed, exit(0), "", "ok")
363 p.wait(r+`?.querySelector('[equipo-badge2][data-kind="checks"][data-tone="positive"]')`, "checks passed on the row")
364 p.stayed("tasks page")
365}
366
367// timezone makes the page's clock a zone (Intl, and so zone.js, which
368// tells Equipo the person's zone on the next page it opens).
369func (p *innerPage) timezone(zone string) {
370 p.t.Helper()
371 p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
372 _, err := cdp.Call(ctx, target, emulation.SetTimezoneOverride, emulation.SetTimezoneOverrideParams{TimezoneID: zone})
373 return err
374 }))
375}
376