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 "context"
7 "strconv"
8 "strings"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/browsertest"
13 "github.com/chromedp/cdproto/cdp"
14 "github.com/chromedp/cdproto/emulation"
15 cdppage "github.com/chromedp/cdproto/page"
16 "github.com/chromedp/chromedp"
17)
18
19// Paul, 2026-11-11: Copy on a prompt block in a coordinator reply put
20// nothing on his clipboard. Two replies arrive through the live stream
21// and commit, each with a command box and a prompt box, a paragraph
22// between them; no committed Copy is left aria-disabled. Each box is
23// given its own text, so every copy can only be that box's. Every Copy is
24// clicked with the mouse:
25// - on every run, the clipboard API records what paste.js gives it,
26// and with the API refused, the execCommand fallback records the
27// hidden field it copies from: each is exactly that box's text;
28// - where the browser grants the real clipboard (the grant does not
29// take in every Chromium, so it is logged and left out where it does
30// not), the clipboard is read back after each click.
31func TestBrowserPasteCopiesItsBox(t *testing.T) {
32 _, inst, r := localEnv(t)
33 r.start(t)
34 c := inst.Cookie()
35 p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true)
36 defer p.stop()
37 // The first reply streams slowly, so its boxes are drawn as a draft
38 // first (Copy disabled), then the committed reply takes the draft over.
39 p.send("replymd:paste chunks:120 sleep:40 slowstream")
40 p.run(browsertest.WaitWithin(pasteBoxesCommitted(2), 60*time.Second))
41 p.send("replymd:paste chunks:40 slowstream")
42 p.run(browsertest.WaitWithin(pasteBoxesCommitted(4), 60*time.Second))
43 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')`))
44 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")
45 var want []string
46 for i, text := range []string{pastedCommand, pastedPrompt, pastedCommand, pastedPrompt} {
47 want = append(want, text+" [box "+strconv.Itoa(i)+"]")
48 }
49 click := func(i int) {
50 t.Helper()
51 id := "#copy-" + strconv.Itoa(i)
52 p.run(chromedp.Evaluate[chromedp.Void](`document.querySelector('` + id + `').scrollIntoView({block:'center'})`))
53 p.run(chromedp.Click(chromedp.CSS(id)))
54 }
55
56 // The real clipboard, where the browser grants it.
57 if read, why := grantClipboard(t, p, inst.URL); read == nil {
58 t.Logf("real clipboard left out: this Chromium refuses it (%s); the recorded cases below cover paste.js on every run", why)
59 } else {
60 for _, i := range []int{3, 2, 1, 0} {
61 click(i)
62 p.run(browsertest.Wait(`document.querySelector('#copy-` + strconv.Itoa(i) + `').textContent.trim()==='Copied'`))
63 if got := read(); got != want[i] {
64 t.Fatalf("real clipboard: Copy %d put %q there, want %q", i, got, want[i])
65 }
66 }
67 }
68
69 // Every run: what paste.js hands the clipboard API, then the fallback.
70 p.check(recordCopies, "recorder")
71 for n, i := range []int{3, 2, 1, 0} {
72 click(i)
73 p.run(browsertest.Wait(`window.__copied.length===` + strconv.Itoa(n+1)))
74 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)`))
75 }
76 p.check(`(()=>{window.__refuse=true;return true})()`, "refuse")
77 for n, i := range []int{1, 0, 3, 2} {
78 click(i)
79 p.run(browsertest.Wait(`window.__exec.length===` + strconv.Itoa(n+1)))
80 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)`))
81 p.run(browsertest.Wait(`document.querySelector('#copy-` + strconv.Itoa(i) + `').textContent.trim()==='Copied'`))
82 }
83 p.check(`window.__copied.length===4`, "the refused clipboard API recorded a copy")
84}
85
86// recordCopies makes paste.js's copies observable in any browser: the
87// clipboard API records what it is given (window.__copied) or, with
88// window.__refuse set, refuses as a browser does; execCommand records
89// the hidden field paste.js copies from (window.__exec) and succeeds.
90const recordCopies = `(()=>{window.__copied=[];window.__exec=[];window.__refuse=false;
91navigator.clipboard.writeText=t=>{if(window.__refuse)return Promise.reject(new DOMException('refused','NotAllowedError'));window.__copied.push(t);return Promise.resolve()};
92document.execCommand=c=>{const f=document.querySelector('textarea[readonly][equipo-visually-hidden]');window.__exec.push(c+':'+(f?f.value:''));return c==='copy'&&!!f};return true})()`
93
94// pasteBoxesCommitted: n paste boxes in committed replies, none streaming.
95func pasteBoxesCommitted(n int) string {
96 return `document.querySelectorAll('[equipo-message="incoming"][data-message]:not([equipo-thinking]) [equipo-paste]').length===` + strconv.Itoa(n) + ` && !document.querySelector('[equipo-thinking]')`
97}
98
99// grantPermissions is Browser.grantPermissions, which this cdproto does
100// not carry.
101var grantPermissions = cdp.Command[grantParams, cdp.Empty]{Method: "Browser.grantPermissions"}
102
103type grantParams struct {
104 Permissions []string `json:"permissions"`
105 Origin string `json:"origin,omitempty"`
106}
107
108// grantClipboard gives the page the browser's own clipboard: the page
109// in front and focused (headless Chrome has no focused window), clipboard
110// read and write granted for its origin. It returns a reader, or nil and
111// why when the browser still refuses to read it. The test itself never
112// writes: a write without a click is refused in some Chromiums.
113func grantClipboard(t *testing.T, p *page, origin string) (read func() string, why string) {
114 t.Helper()
115 origin = strings.TrimSuffix(origin, "/")
116 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
117 if _, err := cdp.Call(ctx, target, cdppage.BringToFront, cdp.Empty{}); err != nil {
118 return err
119 }
120 if _, err := cdp.Call(ctx, target, emulation.SetFocusEmulationEnabled, emulation.SetFocusEmulationEnabledParams{Enabled: true}); err != nil {
121 return err
122 }
123 if _, err := cdp.Call(ctx, target, grantPermissions, grantParams{Permissions: []string{"clipboardReadWrite", "clipboardSanitizedWrite"}, Origin: origin}); err != nil {
124 why = "grantPermissions: " + err.Error()
125 }
126 return nil
127 }))
128 if why != "" {
129 return nil, why
130 }
131 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
132 var err error
133 why, err = chromedp.Evaluate[string](`navigator.clipboard.readText().then(()=>'',e=>e.name+': '+e.message)`, chromedp.EvalAwaitPromise)(ctx, target)
134 return err
135 }))
136 if why != "" {
137 return nil, why
138 }
139 return func() string {
140 t.Helper()
141 var s string
142 p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
143 var err error
144 s, err = chromedp.Evaluate[string](`navigator.clipboard.readText()`, chromedp.EvalAwaitPromise)(ctx, target)
145 return err
146 }))
147 return s
148 }, ""
149}
150
151// Why Paul's Copy did nothing (2026-11-11): his conversation page was
152// loaded before the deploy that added the paste box. The live feed puts
153// replies rendered by the new build into the open page, whose scripts and
154// stylesheet were the old build's: no paste.js, so Copy did nothing, and
155// no paste styles, so the prompt did not wrap. A page that finds the
156// server's assets differ from its own reloads at the first quiet moment,
157// keeping its place; not while something is typed in the composer; and
158// only once for a server build, so a cache that keeps serving the old
159// page does not loop.
160func TestBrowserStalePageReloads(t *testing.T) {
161 _, inst, r := localEnv(t)
162 r.start(t)
163 c := inst.Cookie()
164 p := openPage(t, inst.URL, c.Name, c.Value, 1280, 520, true)
165 defer p.stop()
166 p.check(`(()=>{sessionStorage.clear();return true})()`, "storage")
167 p.send("replymd:paste chunks:3")
168 p.run(browsertest.WaitWithin(pasteBoxesCommitted(2), 60*time.Second))
169
170 // An older page: its stylesheet is another build's. Something is
171 // typed in the composer while the next reply streams.
172 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})()`
173 p.check(older, "older stylesheet")
174 p.send("replymd:paste chunks:12 slowstream")
175 p.check(`(()=>{const c=document.querySelector('#chat-body');c.value='half a thought';c.dispatchEvent(new Event('input',{bubbles:true}));return true})()`, "type")
176 p.run(browsertest.WaitWithin(pasteBoxesCommitted(4), 60*time.Second))
177 time.Sleep(2500 * time.Millisecond)
178 p.check(`window.__older===true && document.querySelector('#chat-body').value==='half a thought'`, "the page reloaded with words in the composer")
179
180 // The words go; the page reloads, where it was in the feed.
181 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")
182 p.run(browsertest.WaitWithin(`!window.__older && !!document.querySelector('[data-chat-stream]') && document.querySelectorAll('[equipo-paste]').length===4`, 10*time.Second))
183 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)`))
184 p.check(`document.documentElement.hasAttribute('data-paste') && !!sessionStorage.getItem('equipo.reloaded-for')`, "after the reload")
185
186 // Copy works on the reloaded page.
187 p.check(recordCopies, "recorder")
188 p.check(`(()=>{const b=document.querySelectorAll('[equipo-paste-copy]');b[3].id='copy-last';b[3].scrollIntoView({block:'center'});return true})()`, "id")
189 p.run(chromedp.Click(chromedp.CSS(`#copy-last`)))
190 p.run(browsertest.Wait(`document.querySelector('#copy-last').textContent.trim()==='Copied'`))
191 p.check(`window.__copied.length===1 && window.__copied[0]===`+jsonString(pastedPrompt), "after the reload Copy copied other text")
192
193 // No loop: the page still differs after reloading for the same server
194 // build (a cache serving the old page), so it stays.
195 p.check(older, "older stylesheet again")
196 p.send("replymd:paste chunks:3")
197 p.run(browsertest.WaitWithin(pasteBoxesCommitted(6), 60*time.Second))
198 time.Sleep(2500 * time.Millisecond)
199 p.check(`window.__older===true`, "the page reloaded again for the same build")
200}
201