//go:build browser package headless import ( "context" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" cdppage "github.com/chromedp/cdproto/page" "github.com/chromedp/chromedp" ) // Paul, 2026-11-11: Copy on a prompt block in a coordinator reply put // nothing on his clipboard. Two replies arrive through the live stream // and commit, each with a command box and a prompt box, a paragraph // between them; no committed Copy is left aria-disabled. Each box is // given its own text, so every copy can only be that box's. Every Copy is // clicked with the mouse: // - on every run, the clipboard API records what paste.js gives it, // and with the API refused, the execCommand fallback records the // hidden field it copies from: each is exactly that box's text; // - where the browser grants the real clipboard (the grant does not // take in every Chromium, so it is logged and left out where it does // not), the clipboard is read back after each click. func TestBrowserPasteCopiesItsBox(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 first reply streams slowly, so its boxes are drawn as a draft // first (Copy disabled), then the committed reply takes the draft over. p.send("replymd:paste chunks:120 sleep:40 slowstream") p.run(browsertest.WaitWithin(pasteBoxesCommitted(2), 60*time.Second)) p.send("replymd:paste chunks:40 slowstream") p.run(browsertest.WaitWithin(pasteBoxesCommitted(4), 60*time.Second)) p.check(`!document.querySelector('[equipo-paste-copy][aria-disabled]')`, "a committed Copy is still aria-disabled: "+evaluateIn[string](t, p.ctx, `[...document.querySelectorAll('[equipo-paste-copy][aria-disabled]')].map(b=>b.closest('[equipo-message]').outerHTML.slice(0,300)).join('\n')`)) p.check(`(()=>{const b=[...document.querySelectorAll('[equipo-paste]')];b.forEach((x,i)=>{x.querySelector('[equipo-paste-copy]').id='copy-'+i;const c=x.querySelector('pre > code');c.textContent=c.textContent.replace(/\n$/,'')+' [box '+i+']\n'});return b.length===4})()`, "ids") var want []string for i, text := range []string{pastedCommand, pastedPrompt, pastedCommand, pastedPrompt} { want = append(want, text+" [box "+strconv.Itoa(i)+"]") } click := func(i int) { t.Helper() id := "#copy-" + strconv.Itoa(i) p.run(chromedp.Evaluate[chromedp.Void](`document.querySelector('` + id + `').scrollIntoView({block:'center'})`)) p.run(chromedp.Click(chromedp.CSS(id))) } // The real clipboard, where the browser grants it. if read, why := grantClipboard(t, p, inst.URL); read == nil { t.Logf("real clipboard left out: this Chromium refuses it (%s); the recorded cases below cover paste.js on every run", why) } else { for _, i := range []int{3, 2, 1, 0} { click(i) p.run(browsertest.Wait(`document.querySelector('#copy-` + strconv.Itoa(i) + `').textContent.trim()==='Copied'`)) if got := read(); got != want[i] { t.Fatalf("real clipboard: Copy %d put %q there, want %q", i, got, want[i]) } } } // Every run: what paste.js hands the clipboard API, then the fallback. p.check(recordCopies, "recorder") for n, i := range []int{3, 2, 1, 0} { click(i) p.run(browsertest.Wait(`window.__copied.length===` + strconv.Itoa(n+1))) p.check(`window.__copied[`+strconv.Itoa(n)+`]===`+jsonString(want[i]), "Copy "+strconv.Itoa(i)+" copied other text: "+evaluateIn[string](t, p.ctx, `JSON.stringify(window.__copied)`)) } p.check(`(()=>{window.__refuse=true;return true})()`, "refuse") for n, i := range []int{1, 0, 3, 2} { click(i) p.run(browsertest.Wait(`window.__exec.length===` + strconv.Itoa(n+1))) p.check(`window.__exec[`+strconv.Itoa(n)+`]===`+jsonString("copy:"+want[i]), "the fallback for Copy "+strconv.Itoa(i)+" copied other text: "+evaluateIn[string](t, p.ctx, `JSON.stringify(window.__exec)`)) p.run(browsertest.Wait(`document.querySelector('#copy-` + strconv.Itoa(i) + `').textContent.trim()==='Copied'`)) } p.check(`window.__copied.length===4`, "the refused clipboard API recorded a copy") } // recordCopies makes paste.js's copies observable in any browser: the // clipboard API records what it is given (window.__copied) or, with // window.__refuse set, refuses as a browser does; execCommand records // the hidden field paste.js copies from (window.__exec) and succeeds. const recordCopies = `(()=>{window.__copied=[];window.__exec=[];window.__refuse=false; navigator.clipboard.writeText=t=>{if(window.__refuse)return Promise.reject(new DOMException('refused','NotAllowedError'));window.__copied.push(t);return Promise.resolve()}; document.execCommand=c=>{const f=document.querySelector('textarea[readonly][equipo-visually-hidden]');window.__exec.push(c+':'+(f?f.value:''));return c==='copy'&&!!f};return true})()` // pasteBoxesCommitted: n paste boxes in committed replies, none streaming. func pasteBoxesCommitted(n int) string { return `document.querySelectorAll('[equipo-message="incoming"][data-message]:not([equipo-thinking]) [equipo-paste]').length===` + strconv.Itoa(n) + ` && !document.querySelector('[equipo-thinking]')` } // grantPermissions is Browser.grantPermissions, which this cdproto does // not carry. var grantPermissions = cdp.Command[grantParams, cdp.Empty]{Method: "Browser.grantPermissions"} type grantParams struct { Permissions []string `json:"permissions"` Origin string `json:"origin,omitempty"` } // grantClipboard gives the page the browser's own clipboard: the page // in front and focused (headless Chrome has no focused window), clipboard // read and write granted for its origin. It returns a reader, or nil and // why when the browser still refuses to read it. The test itself never // writes: a write without a click is refused in some Chromiums. func grantClipboard(t *testing.T, p *page, origin string) (read func() string, why string) { t.Helper() origin = strings.TrimSuffix(origin, "/") p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { if _, err := cdp.Call(ctx, target, cdppage.BringToFront, cdp.Empty{}); err != nil { return err } if _, err := cdp.Call(ctx, target, emulation.SetFocusEmulationEnabled, emulation.SetFocusEmulationEnabledParams{Enabled: true}); err != nil { return err } if _, err := cdp.Call(ctx, target, grantPermissions, grantParams{Permissions: []string{"clipboardReadWrite", "clipboardSanitizedWrite"}, Origin: origin}); err != nil { why = "grantPermissions: " + err.Error() } return nil })) if why != "" { return nil, why } p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error why, err = chromedp.Evaluate[string](`navigator.clipboard.readText().then(()=>'',e=>e.name+': '+e.message)`, chromedp.EvalAwaitPromise)(ctx, target) return err })) if why != "" { return nil, why } return func() string { t.Helper() var s string p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error s, err = chromedp.Evaluate[string](`navigator.clipboard.readText()`, chromedp.EvalAwaitPromise)(ctx, target) return err })) return s }, "" } // Why Paul's Copy did nothing (2026-11-11): his conversation page was // loaded before the deploy that added the paste box. The live feed puts // replies rendered by the new build into the open page, whose scripts and // stylesheet were the old build's: no paste.js, so Copy did nothing, and // no paste styles, so the prompt did not wrap. A page that finds the // server's assets differ from its own reloads at the first quiet moment, // keeping its place; not while something is typed in the composer; and // only once for a server build, so a cache that keeps serving the old // page does not loop. func TestBrowserStalePageReloads(t *testing.T) { _, inst, r := localEnv(t) r.start(t) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, 1280, 520, true) defer p.stop() p.check(`(()=>{sessionStorage.clear();return true})()`, "storage") p.send("replymd:paste chunks:3") p.run(browsertest.WaitWithin(pasteBoxesCommitted(2), 60*time.Second)) // An older page: its stylesheet is another build's. Something is // typed in the composer while the next reply streams. older := `(()=>{const l=document.querySelector('link[rel~="stylesheet"][href*="/equipo."]');l.setAttribute('href',l.getAttribute('href').replace(/\.[0-9a-f]{16}\.css$/,'.0000000000000000.css'));window.__older=true;return true})()` p.check(older, "older stylesheet") p.send("replymd:paste chunks:12 slowstream") p.check(`(()=>{const c=document.querySelector('#chat-body');c.value='half a thought';c.dispatchEvent(new Event('input',{bubbles:true}));return true})()`, "type") p.run(browsertest.WaitWithin(pasteBoxesCommitted(4), 60*time.Second)) time.Sleep(2500 * time.Millisecond) p.check(`window.__older===true && document.querySelector('#chat-body').value==='half a thought'`, "the page reloaded with words in the composer") // The words go; the page reloads, where it was in the feed. p.check(`(()=>{const b=document.querySelector('[equipo-scroll]');if(b.scrollHeight-b.clientHeight<120)return false;b.scrollTop=60;b.dispatchEvent(new Event('scroll'));const c=document.querySelector('#chat-body');c.value='';c.dispatchEvent(new Event('input',{bubbles:true}));return true})()`, "the feed does not scroll, or clearing failed") p.run(browsertest.WaitWithin(`!window.__older && !!document.querySelector('[data-chat-stream]') && document.querySelectorAll('[equipo-paste]').length===4`, 10*time.Second)) p.check(`Math.abs(document.querySelector('[equipo-scroll]').scrollTop-60)<2`, "the reload lost the place in the feed: "+evaluateIn[string](t, p.ctx, `String(document.querySelector('[equipo-scroll]').scrollTop)`)) p.check(`document.documentElement.hasAttribute('data-paste') && !!sessionStorage.getItem('equipo.reloaded-for')`, "after the reload") // Copy works on the reloaded page. p.check(recordCopies, "recorder") p.check(`(()=>{const b=document.querySelectorAll('[equipo-paste-copy]');b[3].id='copy-last';b[3].scrollIntoView({block:'center'});return true})()`, "id") p.run(chromedp.Click(chromedp.CSS(`#copy-last`))) p.run(browsertest.Wait(`document.querySelector('#copy-last').textContent.trim()==='Copied'`)) p.check(`window.__copied.length===1 && window.__copied[0]===`+jsonString(pastedPrompt), "after the reload Copy copied other text") // No loop: the page still differs after reloading for the same server // build (a cache serving the old page), so it stays. p.check(older, "older stylesheet again") p.send("replymd:paste chunks:3") p.run(browsertest.WaitWithin(pasteBoxesCommitted(6), 60*time.Second)) time.Sleep(2500 * time.Millisecond) p.check(`window.__older===true`, "the page reloaded again for the same build") }