| 1 | //go:build browser |
| 2 | |
| 3 | package headless |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strconv" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/browsertest" |
| 14 | "github.com/chromedp/cdproto/cdp" |
| 15 | "github.com/chromedp/cdproto/emulation" |
| 16 | "github.com/chromedp/chromedp" |
| 17 | ) |
| 18 | |
| 19 | // pasted are the two blocks of fakeclaude's pasteSample, as written |
| 20 | // between their fences: a command with <, &, quotes, a tab and trailing |
| 21 | // spaces, and a prompt. |
| 22 | const ( |
| 23 | pastedCommand = "go test ./internal/checkout/... -run 'TestTotal' > out.txt && echo \"a < b\"\t " |
| 24 | pastedPrompt = "Check that the invoice total counts delivery once, & say which test shows it. Keep the receipt as it is." |
| 25 | ) |
| 26 | |
| 27 | // Every fenced block in a reply is a paste box. While its fence is still |
| 28 | // streaming the box shows and Copy is there but disabled (a click copies |
| 29 | // nothing); when the fence closes Copy turns on in the same box, which |
| 30 | // does not move. In the committed reply a click copies the block's exact |
| 31 | // text, "Copied" shows and is announced, then Copy comes back; from the |
| 32 | // keyboard, Tab reaches the next Copy with a visible focus ring, and |
| 33 | // Enter and Space copy. Set EQUIPO_SCREENSHOTS to a directory to save |
| 34 | // paste-*.png. |
| 35 | func TestBrowserPasteBox(t *testing.T) { |
| 36 | _, inst, r := localEnv(t) |
| 37 | r.start(t) |
| 38 | c := inst.Cookie() |
| 39 | p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) |
| 40 | defer p.stop() |
| 41 | // The clipboard records what it is given. |
| 42 | p.check(`(()=>{window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard stub") |
| 43 | // record follows the streaming reply frame by frame: the first box |
| 44 | // while its Copy is disabled (its text, its place in the message, a |
| 45 | // click on it) and the first frame Copy is on. Its place is its top in |
| 46 | // the message, its bar's height and Copy's distance from its right edge: |
| 47 | // the bubble may still widen as the last line grows. |
| 48 | 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}; |
| 49 | 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]; |
| 50 | const f=()=>{if(!s.el)s.el=document.querySelector('[equipo-thinking][data-streaming]');const x=s.el; |
| 51 | 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; |
| 52 | 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()}} |
| 53 | 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}}} |
| 54 | if(!x||x.hasAttribute('equipo-thinking'))requestAnimationFrame(f);else s.done=true};f();return true})()` |
| 55 | p.check(record, "record") |
| 56 | p.send("replymd:paste chunks:120 sleep:40 slowstream") |
| 57 | p.run(browsertest.WaitWithin(`window.__p.done && !!window.__p.el.dataset.message`, 60*time.Second)) |
| 58 | state := func() string { return evaluateIn[string](t, p.ctx, `JSON.stringify(window.__p)`) } |
| 59 | p.check(`window.__p.open>0 && window.__p.box!==null`, "the box did not show while its fence was open: "+state()) |
| 60 | p.check(`parseFloat(window.__p.dim)<0.7`, "the disabled Copy is not visibly dimmed: "+state()) |
| 61 | p.check(`window.__copied.length===0`, "a click on an open fence's Copy copied: "+state()) |
| 62 | // An open block's last line is still arriving; the renderer ends it |
| 63 | // with a newline, as it ends every line. |
| 64 | p.check(`(`+jsonString(pastedCommand)+`).startsWith(window.__p.openText.replace(/\n$/,''))`, "the open box showed other text: "+state()) |
| 65 | p.check(`window.__p.on!==null && window.__p.same`, "Copy did not turn on in the same box while streaming: "+state()) |
| 66 | p.check(`window.__p.on===`+jsonString(pastedCommand+"\n"), "Copy turned on before the fence closed: "+state()) |
| 67 | 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()) |
| 68 | p.check(`window.__p.icon>0`, "the streaming box's Copy icon does not draw: "+state()) |
| 69 | |
| 70 | // The committed reply: two boxes, a command and a prompt. |
| 71 | 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; |
| 72 | if(b[0].querySelector('[equipo-paste-lang]').textContent!=='Command'||b[1].querySelector('[equipo-paste-lang]').textContent!=='Prompt'||m.querySelector('[aria-disabled]'))return false; |
| 73 | 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; |
| 74 | 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") |
| 75 | shot := func(name string) { |
| 76 | dir := os.Getenv("EQUIPO_SCREENSHOTS") |
| 77 | if dir == "" { |
| 78 | return |
| 79 | } |
| 80 | var raw []byte |
| 81 | p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 82 | var err error |
| 83 | raw, err = chromedp.CaptureScreenshot()(ctx, target) |
| 84 | return err |
| 85 | })) |
| 86 | if err := os.WriteFile(filepath.Join(dir, "paste-"+name+".png"), raw, 0o644); err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | } |
| 90 | shot("light") |
| 91 | |
| 92 | // A click copies the command exactly; "Copied" shows, is announced, |
| 93 | // then Copy comes back. |
| 94 | p.run(chromedp.Click(chromedp.CSS(`#paste-a`))) |
| 95 | p.run(browsertest.Wait(`window.__copied.length===1`)) |
| 96 | p.check(`window.__copied[0]===`+jsonString(pastedCommand), "the copied text is not the block's: "+evaluateIn[string](t, p.ctx, `JSON.stringify(window.__copied)`)) |
| 97 | p.check(`document.querySelector('#paste-a').textContent.trim()==='Copied'`, "the button did not say Copied") |
| 98 | p.run(browsertest.Wait(`[...document.querySelectorAll('[role="status"]')].some(e=>e.textContent==='Copied')`)) |
| 99 | shot("copied") |
| 100 | p.run(browsertest.WaitWithin(`document.querySelector('#paste-a').textContent.trim()==='Copy'`, 5*time.Second)) |
| 101 | |
| 102 | // The keyboard: Tab from the first Copy reaches the second, with a |
| 103 | // visible focus ring; Enter copies the prompt, Space the command. |
| 104 | p.check(`(()=>{document.querySelector('#paste-a').focus();return true})()`, "focus") |
| 105 | p.run(chromedp.KeyEvent("\t")) |
| 106 | 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") |
| 107 | shot("focus") |
| 108 | p.run(chromedp.KeyEvent("\r")) |
| 109 | p.run(browsertest.Wait(`window.__copied.length===2 && document.querySelector('#paste-b').textContent.trim()==='Copied'`)) |
| 110 | p.check(`window.__copied[1]===`+jsonString(pastedPrompt), "Enter copied other text") |
| 111 | p.check(`(()=>{document.querySelector('#paste-a').focus();return true})()`, "focus") |
| 112 | p.run(chromedp.KeyEvent(" ")) |
| 113 | p.run(browsertest.Wait(`window.__copied.length===3`)) |
| 114 | p.check(`window.__copied[2]===`+jsonString(pastedCommand), "Space copied other text") |
| 115 | |
| 116 | // Dark theme, for the screenshots. |
| 117 | p.check(`(()=>{document.documentElement.dataset.theme='dark';return true})()`, "theme") |
| 118 | shot("dark") |
| 119 | |
| 120 | // Without script the box is still there and its text can be |
| 121 | // selected; Copy is hidden, never a button that does nothing. |
| 122 | p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 123 | _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}) |
| 124 | return err |
| 125 | }), chromedp.Navigate(inst.URL+"/conversation")) |
| 126 | p.run(browsertest.Wait(`document.querySelectorAll('[equipo-paste]').length>=2`)) |
| 127 | t.Logf("scripting: none matches: %v", evaluateIn[bool](t, p.ctx, `matchMedia('(scripting: none)').matches`)) |
| 128 | p.check(`!document.documentElement.hasAttribute('data-paste')`, "paste.js ran with scripts off") |
| 129 | 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") |
| 130 | shot("noscript") |
| 131 | } |
| 132 | |
| 133 | // The paste box's look (Paul, 2026-11-11: "This could be styled much |
| 134 | // nicer"). One unit: the bar is inside the box, its label quiet on the |
| 135 | // left (Command, Prompt) and Copy on the right, an icon and its word, |
| 136 | // a tick and Copied once it has copied, the bar keeping its height. A |
| 137 | // prompt reads as prose: the body font, wrapped, nothing running off at |
| 138 | // 390 wide. A command keeps its lines in monospace and scrolls. Light |
| 139 | // and dark, at 1280 and 390. Set EQUIPO_SCREENSHOTS to a directory to |
| 140 | // save paste-look-<width>-<theme>.png. |
| 141 | func TestBrowserPasteBoxLook(t *testing.T) { |
| 142 | _, inst, r := localEnv(t) |
| 143 | r.start(t) |
| 144 | c := inst.Cookie() |
| 145 | p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) |
| 146 | defer p.stop() |
| 147 | p.check(`(()=>{window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard stub") |
| 148 | p.send("replymd:paste chunks:3") |
| 149 | p.run(browsertest.WaitWithin(pasteBoxesCommitted(2), 60*time.Second)) |
| 150 | boxes := `[...document.querySelectorAll('[equipo-message="incoming"][data-message] [equipo-paste]')].slice(-2)` |
| 151 | for _, width := range []int64{1280, 390} { |
| 152 | p.run(chromedp.EmulateViewport(width, 900)) |
| 153 | for _, theme := range []string{"light", "dark"} { |
| 154 | p.theme(theme) |
| 155 | p.check(`(()=>{`+boxes+`[0].scrollIntoView({block:'center'});return true})()`, "scroll") |
| 156 | if dir := os.Getenv("EQUIPO_SCREENSHOTS"); dir != "" { |
| 157 | var raw []byte |
| 158 | p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 159 | var err error |
| 160 | raw, err = chromedp.CaptureScreenshot()(ctx, target) |
| 161 | return err |
| 162 | })) |
| 163 | if err := os.WriteFile(filepath.Join(dir, "paste-look-"+strconv.FormatInt(width, 10)+"-"+theme+".png"), raw, 0o644); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | p.theme("light") |
| 170 | for _, width := range []int64{1280, 390} { |
| 171 | p.run(chromedp.EmulateViewport(width, 900)) |
| 172 | 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}}))`) |
| 173 | // One unit: the box has its edge, the bar sits inside it, Copy is an |
| 174 | // icon and its word, and the labels are the app's words. |
| 175 | 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'); |
| 176 | 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) |
| 177 | // The command: monospace, its lines kept, scrolling inside the box. |
| 178 | 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) |
| 179 | // The prompt: prose in the body font, wrapped, nothing over its edge. |
| 180 | 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) |
| 181 | p.check(`document.documentElement.scrollWidth<=innerWidth && `+boxes+`.every(b=>b.getBoundingClientRect().right<=innerWidth)`, "the page runs off the screen: "+state) |
| 182 | } |
| 183 | // Copied: the tick replaces the icon, the word says Copied, the bar |
| 184 | // keeps its height and the label stays where it was. |
| 185 | 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") |
| 186 | p.run(chromedp.Click(chromedp.CSS(`#look-copy`))) |
| 187 | p.run(browsertest.Wait(`window.__copied.length===1`)) |
| 188 | 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"]'); |
| 189 | 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") |
| 190 | p.check(`window.__copied[0]===`+jsonString(pastedPrompt), "copied other text") |
| 191 | p.run(browsertest.WaitWithin(`document.querySelector('#look-copy [equipo-paste-word]').textContent==='Copy' && !document.querySelector('#look-copy').hasAttribute('data-done')`, 5*time.Second)) |
| 192 | } |
| 193 | |