//go:build browser package headless import ( "bytes" "context" "encoding/base64" "os" "path/filepath" "strconv" "testing" "time" "amadan.net/oficina/equipo/internal/attach/attachtest" "amadan.net/oficina/equipo/internal/browsertest" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/cdproto/fetch" "github.com/chromedp/chromedp" ) // The send arrow, by its computed style. const ( sendShown = `(()=>{const c=getComputedStyle(document.querySelector('[equipo-send]'));return c.visibility==='visible'&&c.opacity==='1'})()` sendHidden = `(()=>{const c=getComputedStyle(document.querySelector('[equipo-send]'));return c.visibility==='hidden'&&c.opacity==='0'})()` ) func typeText(text string) string { return `(()=>{const b=document.querySelector('#chat-body');b.focus();b.value=` + jsonString(text) + `;b.dispatchEvent(new Event('input',{bubbles:true}));return true})()` } // TestBrowserComposer: Paul, 2026-11-08, after Eleven's composer. At 1280 // with a mouse and 390 on touch, light and dark: the send arrow shows only // with words or an attachment; Enter and Shift+Enter on a keyboard, Return // a new line on touch; the + menu (by click and by keyboard); a picked // image becomes a chip, then a thumbnail in the feed that reaches the // coordinator and opens full size; Remove; a size error and a type error // in words; paste and drop on a desktop; 44 px targets; reduced motion. // Set EQUIPO_SCREENSHOTS to a directory to save composer-after-*.png. func TestBrowserComposer(t *testing.T) { _, inst, r := localEnv(t) r.start(t) c := inst.Cookie() dir := t.TempDir() write := func(name string, data []byte) string { path := filepath.Join(dir, name) if err := os.WriteFile(path, data, 0600); err != nil { t.Fatal(err) } return path } screen := write("screen.png", attachtest.PNG(120, 80)) notes := write("notes.md", []byte("# Notes\n\nStep three fails.\n")) big := write("big.log", bytes.Repeat([]byte("x"), 10<<20+1)) binary := write("tool.bin", []byte{0x4d, 0x5a, 0, 1, 2, 3}) small := base64.StdEncoding.EncodeToString(attachtest.PNG(8, 8)) huge := write("huge.png", attachtest.PNG(3000, 1500)) shots := os.Getenv("EQUIPO_SCREENSHOTS") for _, tc := range []struct { width, height int64 touch bool }{{1280, 900, false}, {390, 844, true}} { p := openPage(t, inst.URL, c.Name, c.Value, tc.width, tc.height, !tc.touch) at := strconv.FormatInt(tc.width, 10) if tc.touch { p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}) return err })) } shot := func(name string) { t.Helper() if shots == "" { return } var raw []byte p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error raw, err = chromedp.CaptureScreenshot()(ctx, target) return err })) if err := os.WriteFile(filepath.Join(shots, "composer-after-"+name+"-"+at+".png"), raw, 0644); err != nil { t.Fatal(err) } } pick := func(which, path string) { t.Helper() p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="`+which+`"]`), []string{path})) } chip := func(state string) string { return `document.querySelector('[equipo-chip][data-state="` + state + `"]')` } own := `document.querySelectorAll('[equipo-message="own"]').length` // The deferred scripts have run: the + is shown, the arrow managed. p.run(browsertest.Wait(`!!document.querySelector('#composer[data-enhanced]') && !document.querySelector('[equipo-adder]').hidden && !!window.EquipoAttach`)) // Targets: the + and the arrow are 44 px (by layout: the hidden arrow // is scaled down); the placeholder is short. var sizes string p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error 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) return err })) if sizes != "44 44 44 44 Message" { t.Fatalf("%s: targets and placeholder %q, want 44 px each and Message", at, sizes) } // Baselines: the +, the words and the arrow share a centre line. 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") // The arrow shows only with something to send. p.run(browsertest.Wait(sendHidden)) p.check(typeText(" "), "spaces") p.run(browsertest.Wait(sendHidden)) p.check(typeText("hello"), "type") p.run(browsertest.Wait(sendShown)) p.check(typeText(""), "clear") p.run(browsertest.Wait(sendHidden)) // Keys: Enter sends on a keyboard, Shift+Enter starts a line; on touch // Return starts a line and nothing goes. before := 0 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error before, err = chromedp.Evaluate[int](own)(ctx, target) return err })) p.check(typeText("keys "+at), "type") 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") enter := `(()=>{const e=new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true});document.querySelector('#chat-body').dispatchEvent(e);return e.defaultPrevented})()` if tc.touch { p.check(`!`+enter, "390: Return sent on touch") p.check(`document.querySelector('#chat-body').value==='keys 390' && `+own+`===`+strconv.Itoa(before), "390: Return sent on touch") p.check(typeText(""), "clear") } else { p.check(enter, "1280: Enter did not send") p.run(browsertest.Wait(own + `===` + strconv.Itoa(before+1) + ` && document.querySelector('#chat-body').value===''`)) p.run(browsertest.Wait(sendHidden)) } // The + menu: Photo or image (the library or camera on a phone) // and File; it closes on a pick, outside, and Escape. p.run(chromedp.Click(chromedp.CSS(`[equipo-plus]`))) p.run(browsertest.Wait(`!document.querySelector('[equipo-add-menu]').hidden && document.querySelector('[equipo-plus]').getAttribute('aria-expanded')==='true'`)) 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") 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") shot("menu") p.run(chromedp.Click(chromedp.CSS(`[equipo-scroll]`))) p.run(browsertest.Wait(`document.querySelector('[equipo-add-menu]').hidden`)) if !tc.touch { // By keyboard: Enter on the + opens it at its first item, arrows // move, Escape closes and returns to the +. p.check(`(()=>{document.querySelector('[equipo-plus]').focus();return true})()`, "focus") p.run(chromedp.KeyEvent("\r")) p.run(browsertest.Wait(`document.activeElement===document.querySelector('[data-pick=image]')`)) p.check(`(()=>{document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true,cancelable:true}));return document.activeElement===document.querySelector('[data-pick=file]')})()`, "ArrowDown") 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") } // A picked image: a chip that uploads, then the arrow. pick("image", screen) p.run(browsertest.Wait(chip("ready") + ` && ` + chip("ready") + `.dataset.kind==='image' && !document.querySelector('[equipo-chips]').hidden`)) // The preview has loaded under the page's policy (data:, not blob:), // fills a 56 to 64 px square, and the x sits over the corner. 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.topr.left+r.width/2})()`, at+": the chip's preview did not load, or its size or x is wrong") p.run(browsertest.Wait(sendShown)) 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") // A file beside it, then removed with its x. pick("file", notes) p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`)) 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") shot("chips") p.check(`(()=>{document.querySelector('[equipo-chip][data-kind="file"] [equipo-chip-remove]').click();return document.querySelectorAll('[equipo-chip]').length===1})()`, at+": remove") // Remove deleted the upload, so it no longer counts as unsent. for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(100 * time.Millisecond) { var held int if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_attachments WHERE name = 'notes.md' AND message_id = ''").Scan(&held); err != nil { t.Fatal(err) } if held == 0 { break } if time.Now().After(deadline) { t.Fatalf("%s: the removed upload is still held", at) } } // Errors in words: too large (refused here), a type (refused by the // server); they stay out of a send and do not show the arrow alone. pick("file", big) p.run(browsertest.Wait(chip("error") + ` && ` + chip("error") + `.querySelector('[equipo-chip-note]').textContent==='That file is over 10 MB.'`)) pick("file", binary) p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-chip][data-state="error"] [equipo-chip-note]')].some(e=>e.textContent.startsWith('Equipo takes images'))`)) shot("errors") 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") // Sent with no words: the thumbnail in the person's message, no empty // bubble; it reaches the coordinator as an image. p.run(chromedp.Click(chromedp.CSS(`[equipo-send]`))) p.run(browsertest.Wait(`document.querySelector('[equipo-chips]').hidden && document.querySelectorAll('[equipo-chip]').length===0`)) p.run(browsertest.Wait(`[...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('[image image/png 120x80'))`)) thumb := `[...document.querySelectorAll('[equipo-message="own"] [equipo-file-thumb] img')].pop()` 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})()`)) p.check(`(()=>{`+thumb+`.scrollIntoView({block:'center'});return true})()`, "scroll") shot("feed") 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") // Tap for full size, in the page; tap again to close. p.check(`(()=>{`+thumb+`.scrollIntoView({block:'center'});return true})()`, "scroll") var spot []float64 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error spot, err = chromedp.Evaluate[[]float64](`(()=>{const r=`+thumb+`.getBoundingClientRect();return [r.x+r.width/2,r.y+r.height/2]})()`)(ctx, target) return err })) p.run(chromedp.MouseClickXY(spot[0], spot[1])) p.run(browsertest.Wait(`!!document.querySelector('[equipo-lightbox][open] img') && document.querySelector('[equipo-lightbox] img').src.endsWith(` + thumb + `.closest('a').getAttribute('href'))`)) shot("full-size") p.check(`(()=>{document.querySelector('[equipo-lightbox]').click();return !document.querySelector('[equipo-lightbox]').open})()`, at+": full size did not close") if !tc.touch { // Paste and drop on a desktop. file := `new File([Uint8Array.from(atob('` + small + `'),c=>c.charCodeAt(0))],'pasted.png',{type:'image/png'})` 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") p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===1`)) 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") p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`)) p.check(typeText("pasted and dropped"), "type") p.check(enter, "send") 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'})()`)) } if !tc.touch { // A large image goes up scaled to 2560 px, as a JPEG. pick("image", huge) p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===1`)) var w int var media, name string 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 { t.Fatal(err) } if w != 2560 || media != "image/jpeg" || name != "huge.jpg" { t.Fatalf("the large image went up as %s %s %d px wide", name, media, w) } p.check(`(()=>{document.querySelector('[equipo-chip] [equipo-chip-remove]').click();return document.querySelectorAll('[equipo-chip]').length===0})()`, "remove huge") } // Light and dark: the composer as it rests, and growing to six lines. for _, theme := range []string{"light", "dark"} { p.theme(theme) p.check(`(()=>{const s=document.querySelector('[equipo-scroll]');s.scrollTop=s.scrollHeight;return true})()`, "scroll") 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") shot("rest-" + theme) p.check(typeText("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine"), "lines") 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") p.run(browsertest.Wait(sendShown + ` && ['none','matrix(1, 0, 0, 1, 0, 0)'].includes(getComputedStyle(document.querySelector('[equipo-send]')).transform)`)) 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") shot("lines-" + theme) p.check(typeText(""), "clear") } p.theme("light") // Reduced motion: the arrow appears without moving. p.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 })) p.check(`getComputedStyle(document.querySelector('[equipo-send]')).transitionDuration.split(',').every(d=>parseFloat(d)===0)`, at+": the arrow moves under reduced motion") p.stop() } } // TestBrowserComposerReconcile: Astra round 1: when the send's POST lands // before its message event, the message kept this device's provisional // attachments (a file chip linking to "#"). With the event stream held // back, the sent message's attachments become the server's at once: the // image from its preview, the file linking to its download. func TestBrowserComposerReconcile(t *testing.T) { _, inst, r := localEnv(t) r.start(t) c := inst.Cookie() dir := t.TempDir() img := filepath.Join(dir, "screen.png") notes := filepath.Join(dir, "notes.md") os.WriteFile(img, attachtest.PNG(120, 80), 0600) os.WriteFile(notes, []byte("# Notes\n"), 0600) p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) defer p.stop() // Hold every event stream request: none ever reaches the page. p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, fetch.Enable, fetch.EnableParams{Patterns: []*fetch.RequestPattern{{URLPattern: "*/api/v1/events*"}}}) return err })) p.run(chromedp.Reload(), browsertest.Wait(`!!document.querySelector('#composer[data-enhanced]') && !!window.EquipoAttach`)) p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="image"]`), []string{img})) p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="file"]`), []string{notes})) p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`)) p.check(typeText("held back"), "type") p.run(chromedp.Click(chromedp.CSS(`[equipo-send]`))) own := `[...document.querySelectorAll('[equipo-message="own"]')].find(e=>e.textContent.includes('held back'))` p.run(browsertest.Wait(`(()=>{const li=` + own + `;return !!li&&!!li.dataset.message&&!li.hasAttribute('data-pending')})()`)) 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") }