//go:build browser package headless import ( "context" "os" "path/filepath" "strconv" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp" ) // pasted are the two blocks of fakeclaude's pasteSample, as written // between their fences: a command with <, &, quotes, a tab and trailing // spaces, and a prompt. const ( pastedCommand = "go test ./internal/checkout/... -run 'TestTotal' > out.txt && echo \"a < b\"\t " pastedPrompt = "Check that the invoice total counts delivery once, & say which test shows it. Keep the receipt as it is." ) // Every fenced block in a reply is a paste box. While its fence is still // streaming the box shows and Copy is there but disabled (a click copies // nothing); when the fence closes Copy turns on in the same box, which // does not move. In the committed reply a click copies the block's exact // text, "Copied" shows and is announced, then Copy comes back; from the // keyboard, Tab reaches the next Copy with a visible focus ring, and // Enter and Space copy. Set EQUIPO_SCREENSHOTS to a directory to save // paste-*.png. func TestBrowserPasteBox(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() // The clipboard records what it is given. p.check(`(()=>{window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard stub") // record follows the streaming reply frame by frame: the first box // while its Copy is disabled (its text, its place in the message, a // click on it) and the first frame Copy is on. Its place is its top in // the message, its bar's height and Copy's distance from its right edge: // the bubble may still widen as the last line grows. record := `(()=>{const s=window.__p={el:null,box:null,open:0,openText:null,openAt:null,dim:null,clicked:false,on:null,onAt:null,same:null,done:false}; const at=(b,x)=>[b.getBoundingClientRect().top-x.getBoundingClientRect().top,b.querySelector('[equipo-paste-bar]').getBoundingClientRect().height,b.getBoundingClientRect().right-b.querySelector('[equipo-paste-copy]').getBoundingClientRect().right]; const f=()=>{if(!s.el)s.el=document.querySelector('[equipo-thinking][data-streaming]');const x=s.el; if(x&&x.hasAttribute('equipo-thinking')){const b=x.querySelector('[equipo-paste]');if(b){const btn=b.querySelector('[equipo-paste-copy]'),code=b.querySelector('pre > code').textContent; if(btn.getAttribute('aria-disabled')==='true'){if(!s.box)s.box=b;s.open++;s.openText=code;s.openAt=at(b,x);s.dim=getComputedStyle(btn).opacity;if(!s.clicked){s.clicked=true;btn.click()}} else if(s.on===null){s.on=code;s.onAt=at(b,x);s.same=s.box===b;const i=btn.querySelector('[equipo-paste-icon="copy"] svg');s.icon=i?i.getBoundingClientRect().width:0}}} if(!x||x.hasAttribute('equipo-thinking'))requestAnimationFrame(f);else s.done=true};f();return true})()` p.check(record, "record") p.send("replymd:paste chunks:120 sleep:40 slowstream") p.run(browsertest.WaitWithin(`window.__p.done && !!window.__p.el.dataset.message`, 60*time.Second)) state := func() string { return evaluateIn[string](t, p.ctx, `JSON.stringify(window.__p)`) } p.check(`window.__p.open>0 && window.__p.box!==null`, "the box did not show while its fence was open: "+state()) p.check(`parseFloat(window.__p.dim)<0.7`, "the disabled Copy is not visibly dimmed: "+state()) p.check(`window.__copied.length===0`, "a click on an open fence's Copy copied: "+state()) // An open block's last line is still arriving; the renderer ends it // with a newline, as it ends every line. p.check(`(`+jsonString(pastedCommand)+`).startsWith(window.__p.openText.replace(/\n$/,''))`, "the open box showed other text: "+state()) p.check(`window.__p.on!==null && window.__p.same`, "Copy did not turn on in the same box while streaming: "+state()) p.check(`window.__p.on===`+jsonString(pastedCommand+"\n"), "Copy turned on before the fence closed: "+state()) p.check(`window.__p.openAt.every((v,i)=>Math.abs(v-window.__p.onAt[i])<0.5)`, "the box moved when its fence closed: "+state()) p.check(`window.__p.icon>0`, "the streaming box's Copy icon does not draw: "+state()) // The committed reply: two boxes, a command and a prompt. p.check(`(()=>{const m=window.__p.el,b=m.querySelectorAll('[equipo-paste]');if(b.length!==2||b[0].getAttribute('equipo-paste')!=='code'||b[1].getAttribute('equipo-paste')!=='prose')return false; if(b[0].querySelector('[equipo-paste-lang]').textContent!=='Command'||b[1].querySelector('[equipo-paste-lang]').textContent!=='Prompt'||m.querySelector('[aria-disabled]'))return false; const cs=getComputedStyle(b[0].querySelector('pre')),ps=getComputedStyle(b[1].querySelector('pre'));if(cs.whiteSpace!=='pre'||ps.whiteSpace!=='pre-wrap'||!/mono/i.test(cs.fontFamily))return false; b[0].querySelector('[equipo-paste-copy]').id='paste-a';b[1].querySelector('[equipo-paste-copy]').id='paste-b';b[0].scrollIntoView({block:'center'});return true})()`, "the committed reply's boxes") shot := func(name string) { dir := os.Getenv("EQUIPO_SCREENSHOTS") if dir == "" { 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(dir, "paste-"+name+".png"), raw, 0o644); err != nil { t.Fatal(err) } } shot("light") // A click copies the command exactly; "Copied" shows, is announced, // then Copy comes back. p.run(chromedp.Click(chromedp.CSS(`#paste-a`))) p.run(browsertest.Wait(`window.__copied.length===1`)) p.check(`window.__copied[0]===`+jsonString(pastedCommand), "the copied text is not the block's: "+evaluateIn[string](t, p.ctx, `JSON.stringify(window.__copied)`)) p.check(`document.querySelector('#paste-a').textContent.trim()==='Copied'`, "the button did not say Copied") p.run(browsertest.Wait(`[...document.querySelectorAll('[role="status"]')].some(e=>e.textContent==='Copied')`)) shot("copied") p.run(browsertest.WaitWithin(`document.querySelector('#paste-a').textContent.trim()==='Copy'`, 5*time.Second)) // The keyboard: Tab from the first Copy reaches the second, with a // visible focus ring; Enter copies the prompt, Space the command. p.check(`(()=>{document.querySelector('#paste-a').focus();return true})()`, "focus") p.run(chromedp.KeyEvent("\t")) p.check(`(()=>{const a=document.activeElement;return a.id==='paste-b'&&a.matches(':focus-visible')&&getComputedStyle(a).outlineStyle==='solid'&&parseFloat(getComputedStyle(a).outlineWidth)>=2})()`, "Tab did not reach the second Copy with a focus ring") shot("focus") p.run(chromedp.KeyEvent("\r")) p.run(browsertest.Wait(`window.__copied.length===2 && document.querySelector('#paste-b').textContent.trim()==='Copied'`)) p.check(`window.__copied[1]===`+jsonString(pastedPrompt), "Enter copied other text") p.check(`(()=>{document.querySelector('#paste-a').focus();return true})()`, "focus") p.run(chromedp.KeyEvent(" ")) p.run(browsertest.Wait(`window.__copied.length===3`)) p.check(`window.__copied[2]===`+jsonString(pastedCommand), "Space copied other text") // Dark theme, for the screenshots. p.check(`(()=>{document.documentElement.dataset.theme='dark';return true})()`, "theme") shot("dark") // Without script the box is still there and its text can be // selected; Copy is hidden, never a button that does nothing. p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}) return err }), chromedp.Navigate(inst.URL+"/conversation")) p.run(browsertest.Wait(`document.querySelectorAll('[equipo-paste]').length>=2`)) t.Logf("scripting: none matches: %v", evaluateIn[bool](t, p.ctx, `matchMedia('(scripting: none)').matches`)) p.check(`!document.documentElement.hasAttribute('data-paste')`, "paste.js ran with scripts off") p.check(`(()=>{const b=[...document.querySelectorAll('[equipo-paste]')].slice(-2);return b.every(x=>{const st=getComputedStyle(x.querySelector('[equipo-paste-copy]'));return (st.display==='none'||st.visibility==='hidden')&&getComputedStyle(x.querySelector('pre > code')).userSelect!=='none'})&&b[0].querySelector('pre > code').textContent===`+jsonString(pastedCommand+"\n")+`})()`, "without script Copy shows, or the text is not there to select") shot("noscript") } // The paste box's look (Paul, 2026-11-11: "This could be styled much // nicer"). One unit: the bar is inside the box, its label quiet on the // left (Command, Prompt) and Copy on the right, an icon and its word, // a tick and Copied once it has copied, the bar keeping its height. A // prompt reads as prose: the body font, wrapped, nothing running off at // 390 wide. A command keeps its lines in monospace and scrolls. Light // and dark, at 1280 and 390. Set EQUIPO_SCREENSHOTS to a directory to // save paste-look--.png. func TestBrowserPasteBoxLook(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.check(`(()=>{window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard stub") p.send("replymd:paste chunks:3") p.run(browsertest.WaitWithin(pasteBoxesCommitted(2), 60*time.Second)) boxes := `[...document.querySelectorAll('[equipo-message="incoming"][data-message] [equipo-paste]')].slice(-2)` for _, width := range []int64{1280, 390} { p.run(chromedp.EmulateViewport(width, 900)) for _, theme := range []string{"light", "dark"} { p.theme(theme) p.check(`(()=>{`+boxes+`[0].scrollIntoView({block:'center'});return true})()`, "scroll") if dir := os.Getenv("EQUIPO_SCREENSHOTS"); dir != "" { 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(dir, "paste-look-"+strconv.FormatInt(width, 10)+"-"+theme+".png"), raw, 0o644); err != nil { t.Fatal(err) } } } } p.theme("light") for _, width := range []int64{1280, 390} { p.run(chromedp.EmulateViewport(width, 900)) state := evaluateIn[string](t, p.ctx, `JSON.stringify(`+boxes+`.map(b=>{const r=b.getBoundingClientRect(),bar=b.querySelector('[equipo-paste-bar]').getBoundingClientRect(),pre=getComputedStyle(b.querySelector('pre'));return {box:[r.left,r.top,r.right,r.bottom],bar:[bar.left,bar.top,bar.right,bar.bottom],ws:pre.whiteSpace,ox:pre.overflowX,font:pre.fontFamily}}))`) // One unit: the box has its edge, the bar sits inside it, Copy is an // icon and its word, and the labels are the app's words. p.check(`(()=>{const b=`+boxes+`;return b.every(x=>{const r=x.getBoundingClientRect(),bar=x.querySelector('[equipo-paste-bar]'),q=bar.getBoundingClientRect(),c=x.querySelector('[equipo-paste-copy]'),i=c.querySelector('[equipo-paste-icon="copy"] svg'); return getComputedStyle(x).borderTopStyle==='solid'&&q.top>=r.top&&q.bottom<=r.bottom&&q.left>=r.left&&q.right<=r.right&&getComputedStyle(bar).backgroundColor!==getComputedStyle(x).backgroundColor&&i&&i.getBoundingClientRect().width>0&&c.querySelector('[equipo-paste-word]').textContent==='Copy'&&c.getBoundingClientRect().right<=r.right})&&b[0].querySelector('[equipo-paste-lang]').textContent==='Command'&&b[1].querySelector('[equipo-paste-lang]').textContent==='Prompt'})()`, "the box is not one unit at "+strconv.FormatInt(width, 10)+": "+state) // The command: monospace, its lines kept, scrolling inside the box. p.check(`(()=>{const pre=`+boxes+`[0].querySelector('pre'),s=getComputedStyle(pre);return s.whiteSpace==='pre'&&s.overflowX==='auto'&&/mono/i.test(s.fontFamily)})()`, "the command box does not keep its lines and scroll: "+state) // The prompt: prose in the body font, wrapped, nothing over its edge. p.check(`(()=>{const pre=`+boxes+`[1].querySelector('pre'),s=getComputedStyle(pre);return s.whiteSpace==='pre-wrap'&&s.overflowWrap==='anywhere'&&!/mono/i.test(s.fontFamily)&&pre.scrollWidth<=pre.clientWidth+1})()`, "the prompt box is not wrapped prose: "+state) p.check(`document.documentElement.scrollWidth<=innerWidth && `+boxes+`.every(b=>b.getBoundingClientRect().right<=innerWidth)`, "the page runs off the screen: "+state) } // Copied: the tick replaces the icon, the word says Copied, the bar // keeps its height and the label stays where it was. p.check(`(()=>{const b=`+boxes+`[1];window.__bar=[b.querySelector('[equipo-paste-bar]').getBoundingClientRect().height,b.querySelector('[equipo-paste-lang]').getBoundingClientRect().left];b.querySelector('[equipo-paste-copy]').id='look-copy';return true})()`, "id") p.run(chromedp.Click(chromedp.CSS(`#look-copy`))) p.run(browsertest.Wait(`window.__copied.length===1`)) p.check(`(()=>{const c=document.querySelector('#look-copy'),b=c.closest('[equipo-paste]'),tick=c.querySelector('[equipo-paste-icon="copied"]'),icon=c.querySelector('[equipo-paste-icon="copy"]'); return c.querySelector('[equipo-paste-word]').textContent==='Copied'&&tick.getBoundingClientRect().width>0&&icon.getBoundingClientRect().width===0&&Math.abs(b.querySelector('[equipo-paste-bar]').getBoundingClientRect().height-window.__bar[0])<0.5&&Math.abs(b.querySelector('[equipo-paste-lang]').getBoundingClientRect().left-window.__bar[1])<0.5})()`, "Copied does not show its tick, or the bar moved") p.check(`window.__copied[0]===`+jsonString(pastedPrompt), "copied other text") p.run(browsertest.WaitWithin(`document.querySelector('#look-copy [equipo-paste-word]').textContent==='Copy' && !document.querySelector('#look-copy').hasAttribute('data-done')`, 5*time.Second)) }