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 headless
4
5import (
6 "bytes"
7 "context"
8 "encoding/base64"
9 "os"
10 "path/filepath"
11 "strconv"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/attach/attachtest"
16 "amadan.net/oficina/equipo/internal/browsertest"
17 "github.com/chromedp/cdproto/cdp"
18 "github.com/chromedp/cdproto/emulation"
19 "github.com/chromedp/cdproto/fetch"
20 "github.com/chromedp/chromedp"
21)
22
23// The send arrow, by its computed style.
24const (
25 sendShown = `(()=>{const c=getComputedStyle(document.querySelector('[equipo-send]'));return c.visibility==='visible'&&c.opacity==='1'})()`
26 sendHidden = `(()=>{const c=getComputedStyle(document.querySelector('[equipo-send]'));return c.visibility==='hidden'&&c.opacity==='0'})()`
27)
28
29func typeText(text string) string {
30 return `(()=>{const b=document.querySelector('#chat-body');b.focus();b.value=` + jsonString(text) + `;b.dispatchEvent(new Event('input',{bubbles:true}));return true})()`
31}
32
33// TestBrowserComposer: Paul, 2026-11-08, after Eleven's composer. At 1280
34// with a mouse and 390 on touch, light and dark: the send arrow shows only
35// with words or an attachment; Enter and Shift+Enter on a keyboard, Return
36// a new line on touch; the + menu (by click and by keyboard); a picked
37// image becomes a chip, then a thumbnail in the feed that reaches the
38// coordinator and opens full size; Remove; a size error and a type error
39// in words; paste and drop on a desktop; 44 px targets; reduced motion.
40// Set EQUIPO_SCREENSHOTS to a directory to save composer-after-*.png.
41func TestBrowserComposer(t *testing.T) {
42 _, inst, r := localEnv(t)
43 r.start(t)
44 c := inst.Cookie()
45 dir := t.TempDir()
46 write := func(name string, data []byte) string {
47 path := filepath.Join(dir, name)
48 if err := os.WriteFile(path, data, 0600); err != nil {
49 t.Fatal(err)
50 }
51 return path
52 }
53 screen := write("screen.png", attachtest.PNG(120, 80))
54 notes := write("notes.md", []byte("# Notes\n\nStep three fails.\n"))
55 big := write("big.log", bytes.Repeat([]byte("x"), 10<<20+1))
56 binary := write("tool.bin", []byte{0x4d, 0x5a, 0, 1, 2, 3})
57 small := base64.StdEncoding.EncodeToString(attachtest.PNG(8, 8))
58 huge := write("huge.png", attachtest.PNG(3000, 1500))
59 shots := os.Getenv("EQUIPO_SCREENSHOTS")
60 for _, tc := range []struct {
61 width, height int64
62 touch bool
63 }{{1280, 900, false}, {390, 844, true}} {
64 p := openPage(t, inst.URL, c.Name, c.Value, tc.width, tc.height, !tc.touch)
65 at := strconv.FormatInt(tc.width, 10)
66 if tc.touch {
67 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
68 _, err := cdp.Call(ctx, target, emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5})
69 return err
70 }))
71 }
72 shot := func(name string) {
73 t.Helper()
74 if shots == "" {
75 return
76 }
77 var raw []byte
78 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
79 var err error
80 raw, err = chromedp.CaptureScreenshot()(ctx, target)
81 return err
82 }))
83 if err := os.WriteFile(filepath.Join(shots, "composer-after-"+name+"-"+at+".png"), raw, 0644); err != nil {
84 t.Fatal(err)
85 }
86 }
87 pick := func(which, path string) {
88 t.Helper()
89 p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="`+which+`"]`), []string{path}))
90 }
91 chip := func(state string) string {
92 return `document.querySelector('[equipo-chip][data-state="` + state + `"]')`
93 }
94 own := `document.querySelectorAll('[equipo-message="own"]').length`
95
96 // The deferred scripts have run: the + is shown, the arrow managed.
97 p.run(browsertest.Wait(`!!document.querySelector('#composer[data-enhanced]') && !document.querySelector('[equipo-adder]').hidden && !!window.EquipoAttach`))
98 // Targets: the + and the arrow are 44 px (by layout: the hidden arrow
99 // is scaled down); the placeholder is short.
100 var sizes string
101 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
102 var err error
103 sizes, err = chromedp.Evaluate[string](`(()=>{const a=document.querySelector('[equipo-plus]'),b=document.querySelector('[equipo-send]');return [a.offsetWidth,a.offsetHeight,b.offsetWidth,b.offsetHeight,document.querySelector('#chat-body').placeholder].join(' ')})()`)(ctx, target)
104 return err
105 }))
106 if sizes != "44 44 44 44 Message" {
107 t.Fatalf("%s: targets and placeholder %q, want 44 px each and Message", at, sizes)
108 }
109 // Baselines: the +, the words and the arrow share a centre line.
110 p.check(`(()=>{const c=e=>{const r=document.querySelector(e).getBoundingClientRect();return r.y+r.height/2};return Math.abs(c('[equipo-plus]')-c('#chat-body'))<=1.5&&Math.abs(c('[equipo-send]')-c('#chat-body'))<=1.5})()`, at+": the +, the words and the arrow are not on one line")
111
112 // The arrow shows only with something to send.
113 p.run(browsertest.Wait(sendHidden))
114 p.check(typeText(" "), "spaces")
115 p.run(browsertest.Wait(sendHidden))
116 p.check(typeText("hello"), "type")
117 p.run(browsertest.Wait(sendShown))
118 p.check(typeText(""), "clear")
119 p.run(browsertest.Wait(sendHidden))
120
121 // Keys: Enter sends on a keyboard, Shift+Enter starts a line; on touch
122 // Return starts a line and nothing goes.
123 before := 0
124 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
125 var err error
126 before, err = chromedp.Evaluate[int](own)(ctx, target)
127 return err
128 }))
129 p.check(typeText("keys "+at), "type")
130 p.check(`(()=>{const e=new KeyboardEvent('keydown',{key:'Enter',shiftKey:true,bubbles:true,cancelable:true});document.querySelector('#chat-body').dispatchEvent(e);return !e.defaultPrevented})()`, at+": Shift+Enter did not start a line")
131 enter := `(()=>{const e=new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true});document.querySelector('#chat-body').dispatchEvent(e);return e.defaultPrevented})()`
132 if tc.touch {
133 p.check(`!`+enter, "390: Return sent on touch")
134 p.check(`document.querySelector('#chat-body').value==='keys 390' && `+own+`===`+strconv.Itoa(before), "390: Return sent on touch")
135 p.check(typeText(""), "clear")
136 } else {
137 p.check(enter, "1280: Enter did not send")
138 p.run(browsertest.Wait(own + `===` + strconv.Itoa(before+1) + ` && document.querySelector('#chat-body').value===''`))
139 p.run(browsertest.Wait(sendHidden))
140 }
141
142 // The + menu: Photo or image (the library or camera on a phone)
143 // and File; it closes on a pick, outside, and Escape.
144 p.run(chromedp.Click(chromedp.CSS(`[equipo-plus]`)))
145 p.run(browsertest.Wait(`!document.querySelector('[equipo-add-menu]').hidden && document.querySelector('[equipo-plus]').getAttribute('aria-expanded')==='true'`))
146 p.check(`(()=>{const i=[...document.querySelectorAll('[equipo-add-menu] [role=menuitem]')].map(e=>e.textContent.trim());return i.join('|')==='Photo or image|File'&&document.querySelector('[data-picker=image]').accept==='image/*'})()`, at+": menu items")
147 p.check(`(()=>{const m=document.querySelector('[equipo-add-menu]').getBoundingClientRect(),c=document.querySelector('#chat-composer').getBoundingClientRect();return m.bottom<=c.top+c.height&&m.left>=0&&m.right<=innerWidth&&[...document.querySelectorAll('[equipo-add-menu] [role=menuitem]')].every(e=>e.getBoundingClientRect().height>=44)})()`, at+": the menu is off screen or its items are small")
148 shot("menu")
149 p.run(chromedp.Click(chromedp.CSS(`[equipo-scroll]`)))
150 p.run(browsertest.Wait(`document.querySelector('[equipo-add-menu]').hidden`))
151 if !tc.touch {
152 // By keyboard: Enter on the + opens it at its first item, arrows
153 // move, Escape closes and returns to the +.
154 p.check(`(()=>{document.querySelector('[equipo-plus]').focus();return true})()`, "focus")
155 p.run(chromedp.KeyEvent("\r"))
156 p.run(browsertest.Wait(`document.activeElement===document.querySelector('[data-pick=image]')`))
157 p.check(`(()=>{document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true,cancelable:true}));return document.activeElement===document.querySelector('[data-pick=file]')})()`, "ArrowDown")
158 p.check(`(()=>{document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true}));return document.querySelector('[equipo-add-menu]').hidden&&document.activeElement===document.querySelector('[equipo-plus]')})()`, "Escape")
159 }
160
161 // A picked image: a chip that uploads, then the arrow.
162 pick("image", screen)
163 p.run(browsertest.Wait(chip("ready") + ` && ` + chip("ready") + `.dataset.kind==='image' && !document.querySelector('[equipo-chips]').hidden`))
164 // The preview has loaded under the page's policy (data:, not blob:),
165 // fills a 56 to 64 px square, and the x sits over the corner.
166 p.check(`(()=>{const c=`+chip("ready")+`,i=c.querySelector('[equipo-chip-thumb] img'),r=c.getBoundingClientRect(),x=c.querySelector('[equipo-chip-remove]').getBoundingClientRect();return !!i&&i.src.startsWith('data:image/')&&i.complete&&i.naturalWidth>0&&getComputedStyle(i).objectFit==='cover'&&r.width>=56&&r.width<=64&&Math.abs(r.width-r.height)<1&&x.width>=19&&x.width<=25&&x.right>r.right&&x.top<r.top&&x.left>r.left+r.width/2})()`, at+": the chip's preview did not load, or its size or x is wrong")
167 p.run(browsertest.Wait(sendShown))
168 p.check(`(()=>{const c=document.querySelector('[equipo-chips]').getBoundingClientRect(),i=document.querySelector('#chat-body').getBoundingClientRect(),p=document.querySelector('[equipo-pill]').getBoundingClientRect();return c.bottom<=i.top+1&&c.top>=p.top&&c.left>=p.left})()`, at+": the chip is not above the words inside the pill")
169 // A file beside it, then removed with its x.
170 pick("file", notes)
171 p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`))
172 p.check(`(()=>{const f=document.querySelector('[equipo-chip][data-kind="file"]');return f.querySelector('[equipo-chip-name]').textContent==='notes.md'&&/B$/.test(f.querySelector('[equipo-chip-note]').textContent)&&f.querySelector('[equipo-chip-remove]').getAttribute('aria-label')==='Remove notes.md'})()`, at+": the file chip")
173 shot("chips")
174 p.check(`(()=>{document.querySelector('[equipo-chip][data-kind="file"] [equipo-chip-remove]').click();return document.querySelectorAll('[equipo-chip]').length===1})()`, at+": remove")
175 // Remove deleted the upload, so it no longer counts as unsent.
176 for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(100 * time.Millisecond) {
177 var held int
178 if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_attachments WHERE name = 'notes.md' AND message_id = ''").Scan(&held); err != nil {
179 t.Fatal(err)
180 }
181 if held == 0 {
182 break
183 }
184 if time.Now().After(deadline) {
185 t.Fatalf("%s: the removed upload is still held", at)
186 }
187 }
188 // Errors in words: too large (refused here), a type (refused by the
189 // server); they stay out of a send and do not show the arrow alone.
190 pick("file", big)
191 p.run(browsertest.Wait(chip("error") + ` && ` + chip("error") + `.querySelector('[equipo-chip-note]').textContent==='That file is over 10 MB.'`))
192 pick("file", binary)
193 p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-chip][data-state="error"] [equipo-chip-note]')].some(e=>e.textContent.startsWith('Equipo takes images'))`))
194 shot("errors")
195 p.check(`(()=>{document.querySelectorAll('[equipo-chip][data-state="error"] [equipo-chip-remove]').forEach(b=>b.click());return document.querySelectorAll('[equipo-chip]').length===1})()`, at+": remove errors")
196
197 // Sent with no words: the thumbnail in the person's message, no empty
198 // bubble; it reaches the coordinator as an image.
199 p.run(chromedp.Click(chromedp.CSS(`[equipo-send]`)))
200 p.run(browsertest.Wait(`document.querySelector('[equipo-chips]').hidden && document.querySelectorAll('[equipo-chip]').length===0`))
201 p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('[image image/png 120x80'))`))
202 thumb := `[...document.querySelectorAll('[equipo-message="own"] [equipo-file-thumb] img')].pop()`
203 p.run(browsertest.Wait(`(()=>{const i=` + thumb + `;return !!i&&/\/conversation\/attachments\/at_[a-z0-9]+\/preview$/.test(new URL(i.src).pathname)&&i.complete&&i.naturalWidth===120})()`))
204 p.check(`(()=>{`+thumb+`.scrollIntoView({block:'center'});return true})()`, "scroll")
205 shot("feed")
206 p.check(`(()=>{const li=`+thumb+`.closest('[equipo-message]');const b=li.querySelector('[equipo-bubble]');return li.getAttribute('equipo-message')==='own'&&getComputedStyle(b).display==='none'})()`, at+": an empty bubble shows under the image")
207 // Tap for full size, in the page; tap again to close.
208 p.check(`(()=>{`+thumb+`.scrollIntoView({block:'center'});return true})()`, "scroll")
209 var spot []float64
210 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
211 var err error
212 spot, err = chromedp.Evaluate[[]float64](`(()=>{const r=`+thumb+`.getBoundingClientRect();return [r.x+r.width/2,r.y+r.height/2]})()`)(ctx, target)
213 return err
214 }))
215 p.run(chromedp.MouseClickXY(spot[0], spot[1]))
216 p.run(browsertest.Wait(`!!document.querySelector('[equipo-lightbox][open] img') && document.querySelector('[equipo-lightbox] img').src.endsWith(` + thumb + `.closest('a').getAttribute('href'))`))
217 shot("full-size")
218 p.check(`(()=>{document.querySelector('[equipo-lightbox]').click();return !document.querySelector('[equipo-lightbox]').open})()`, at+": full size did not close")
219
220 if !tc.touch {
221 // Paste and drop on a desktop.
222 file := `new File([Uint8Array.from(atob('` + small + `'),c=>c.charCodeAt(0))],'pasted.png',{type:'image/png'})`
223 p.check(`(()=>{const d=new DataTransfer();d.items.add(`+file+`);const e=new ClipboardEvent('paste',{clipboardData:d,bubbles:true,cancelable:true});document.querySelector('#chat-body').dispatchEvent(e);return e.defaultPrevented})()`, "paste was not taken")
224 p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===1`))
225 p.check(`(()=>{const d=new DataTransfer();d.items.add(new File(['a,b\n1,2\n'],'rows.csv',{type:'text/csv'}));const area=document.querySelector('[equipo-conversation]');area.dispatchEvent(new DragEvent('dragover',{dataTransfer:d,bubbles:true,cancelable:true}));const lit=document.querySelector('#composer').hasAttribute('data-dropping');area.dispatchEvent(new DragEvent('drop',{dataTransfer:d,bubbles:true,cancelable:true}));return lit&&!document.querySelector('#composer').hasAttribute('data-dropping')})()`, "drop was not shown or taken")
226 p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`))
227 p.check(typeText("pasted and dropped"), "type")
228 p.check(enter, "send")
229 p.run(browsertest.Wait(`(()=>{const li=[...document.querySelectorAll('[equipo-message="own"]')].find(e=>e.textContent.includes('pasted and dropped'));return !!li&&li.querySelectorAll('[equipo-file-thumb]').length===1&&li.querySelector('[equipo-file-chip] [equipo-file-name]').textContent==='rows.csv'&&getComputedStyle(li.querySelector('[equipo-bubble]')).display!=='none'})()`))
230 }
231
232 if !tc.touch {
233 // A large image goes up scaled to 2560 px, as a JPEG.
234 pick("image", huge)
235 p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===1`))
236 var w int
237 var media, name string
238 if err := inst.DB.Writer().QueryRow("SELECT width, media_type, name FROM chat_attachments ORDER BY created_at DESC, rowid DESC LIMIT 1").Scan(&w, &media, &name); err != nil {
239 t.Fatal(err)
240 }
241 if w != 2560 || media != "image/jpeg" || name != "huge.jpg" {
242 t.Fatalf("the large image went up as %s %s %d px wide", name, media, w)
243 }
244 p.check(`(()=>{document.querySelector('[equipo-chip] [equipo-chip-remove]').click();return document.querySelectorAll('[equipo-chip]').length===0})()`, "remove huge")
245 }
246 // Light and dark: the composer as it rests, and growing to six lines.
247 for _, theme := range []string{"light", "dark"} {
248 p.theme(theme)
249 p.check(`(()=>{const s=document.querySelector('[equipo-scroll]');s.scrollTop=s.scrollHeight;return true})()`, "scroll")
250 p.check(`(()=>{const b=getComputedStyle(document.querySelector('[equipo-pill]'));return parseFloat(b.borderTopWidth)>=1&&b.backgroundColor!=='rgba(0, 0, 0, 0)'})()`, theme+": the pill lost its field")
251 shot("rest-" + theme)
252 p.check(typeText("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine"), "lines")
253 p.check(`(()=>{const i=document.querySelector('#chat-body'),c=getComputedStyle(i),l=parseFloat(c.lineHeight),h=i.clientHeight-parseFloat(c.paddingTop)-parseFloat(c.paddingBottom);return h>=l*5.5&&h<=l*6.5&&i.scrollHeight>i.clientHeight})()`, theme+": the message does not grow to six lines and scroll")
254 p.run(browsertest.Wait(sendShown + ` && ['none','matrix(1, 0, 0, 1, 0, 0)'].includes(getComputedStyle(document.querySelector('[equipo-send]')).transform)`))
255 p.check(`(()=>{const c=e=>document.querySelector(e).getBoundingClientRect().bottom;return Math.abs(c('[equipo-plus]')-c('[equipo-send]'))<=1.5})()`, theme+": the + and the arrow left the last line")
256 shot("lines-" + theme)
257 p.check(typeText(""), "clear")
258 }
259 p.theme("light")
260 // Reduced motion: the arrow appears without moving.
261 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
262 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: "reduce"}}})
263 return err
264 }))
265 p.check(`getComputedStyle(document.querySelector('[equipo-send]')).transitionDuration.split(',').every(d=>parseFloat(d)===0)`, at+": the arrow moves under reduced motion")
266 p.stop()
267 }
268}
269
270// TestBrowserComposerReconcile: Astra round 1: when the send's POST lands
271// before its message event, the message kept this device's provisional
272// attachments (a file chip linking to "#"). With the event stream held
273// back, the sent message's attachments become the server's at once: the
274// image from its preview, the file linking to its download.
275func TestBrowserComposerReconcile(t *testing.T) {
276 _, inst, r := localEnv(t)
277 r.start(t)
278 c := inst.Cookie()
279 dir := t.TempDir()
280 img := filepath.Join(dir, "screen.png")
281 notes := filepath.Join(dir, "notes.md")
282 os.WriteFile(img, attachtest.PNG(120, 80), 0600)
283 os.WriteFile(notes, []byte("# Notes\n"), 0600)
284 p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true)
285 defer p.stop()
286 // Hold every event stream request: none ever reaches the page.
287 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
288 _, err := cdp.Call(ctx, target, fetch.Enable, fetch.EnableParams{Patterns: []*fetch.RequestPattern{{URLPattern: "*/api/v1/events*"}}})
289 return err
290 }))
291 p.run(chromedp.Reload(), browsertest.Wait(`!!document.querySelector('#composer[data-enhanced]') && !!window.EquipoAttach`))
292 p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="image"]`), []string{img}))
293 p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="file"]`), []string{notes}))
294 p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`))
295 p.check(typeText("held back"), "type")
296 p.run(chromedp.Click(chromedp.CSS(`[equipo-send]`)))
297 own := `[...document.querySelectorAll('[equipo-message="own"]')].find(e=>e.textContent.includes('held back'))`
298 p.run(browsertest.Wait(`(()=>{const li=` + own + `;return !!li&&!!li.dataset.message&&!li.hasAttribute('data-pending')})()`))
299 p.check(`(()=>{const li=`+own+`,f=li.querySelector('[equipo-file-chip]'),i=li.querySelector('[equipo-file-thumb] img');return li.querySelectorAll('[equipo-message-files] > a').length===2&&!!f&&/^\/conversation\/attachments\/at_[a-z0-9]+$/.test(new URL(f.href).pathname)&&!!i&&/^\/conversation\/attachments\/at_[a-z0-9]+\/preview$/.test(new URL(i.src).pathname)})()`, "the sent message kept its provisional attachments")
300}
301