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 thintest
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13 "github.com/chromedp/cdproto/cdp"
14 "github.com/chromedp/cdproto/page"
15 "github.com/chromedp/chromedp"
16)
17
18// TestBrowserThinkingWords: the Thinking words page previews the chosen
19// set on the Stardust line, at 1280 and 390; a set chosen elsewhere
20// reaches an open conversation's thinking line with no reload, while the
21// tool labels stay plain; Random takes one of
22// the sets for the turn.
23func TestBrowserThinkingWords(t *testing.T) {
24 r := newToolRig(t)
25 words, err := r.client.Thinking(r.ctx)
26 if err != nil {
27 t.Fatal(err)
28 }
29 phrases := map[string]map[string][]string{}
30 for _, s := range words.Sets {
31 phrases[s.ID] = s.Phrases
32 }
33 in := func(set, sit string) string {
34 raw, _ := json.Marshal(phrases[set][sit])
35 return string(raw)
36 }
37
38 for _, size := range []struct {
39 w, h int64
40 touch bool
41 }{{1280, 900, false}, {390, 844, true}} {
42 p := openInner(t, r.inst.URL, r.inst.Cookie(), size.w, size.h, size.touch, "light", "no-preference")
43 p.open("/settings/thinking")
44 preview := `document.querySelector('[data-preview-phrase]').textContent`
45 p.wait(in("professional", "think")+`.includes(`+preview+`)`, "the preview shows Professional")
46 // Picking a set saves it at once (Paul, iPhone: the button below was
47 // easy to miss, and the line kept the default).
48 p.check(`(()=>{document.querySelector('[data-set="pirate"] label').click();return document.querySelector('input[value="pirate"]').checked})()`, "pick Pirate adventure")
49 p.wait(`document.querySelector('input[value="pirate"]').checked && document.querySelector('[equipo-saved-tick][data-shown]')`, "picking saved the set")
50 p.stayed("picking a set")
51 p.wait(in("pirate", "think")+`.includes(`+preview+`)`, "the preview shows Pirate adventure")
52 p.check(`document.querySelector('[data-preview-line]').dataset.set==='pirate'`, "preview set")
53 if got, _ := r.client.Thinking(r.ctx); got.Set != "pirate" {
54 t.Fatalf("saved %s", got.Set)
55 }
56 p.shot(fmt.Sprintf("ux1-thinking-words-%d", size.w))
57 cur, _ := r.client.Thinking(r.ctx)
58 if _, err := r.client.SetThinking(r.ctx, "professional", cur.Revision); err != nil {
59 t.Fatal(err)
60 }
61 p.stop()
62 }
63
64 // The conversation follows a choice made elsewhere, from the next phrase.
65 p := openInner(t, r.inst.URL, r.inst.Cookie(), 1280, 900, false, "light", "no-preference")
66 defer p.stop()
67 p.open("/conversation")
68 line := `document.querySelector('[equipo-thinking][data-turn="` + r.turn + `"]')`
69 phrase := line + `?.querySelector('[equipo-phrase] [data-in]')?.textContent`
70 p.wait(in("professional", "think")+`.includes(`+phrase+`)`, "Professional while thinking")
71 _ = p
72 cur, _ := r.client.Thinking(r.ctx)
73 if _, err := r.client.SetThinking(r.ctx, "galaxy", cur.Revision); err != nil {
74 t.Fatal(err)
75 }
76 p.wait(`document.querySelector('[data-chat-stream]').dataset.thinkingSet==='galaxy'`, "the choice reached the page")
77 if err := r.runner.Send(r.ctx, "act-read", wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile}); err != nil {
78 t.Fatal(err)
79 }
80 p.wait(phrase+`==='Reading the code…'`, "plain label while reading")
81 p.check(line+`.querySelector('[equipo-activity]').textContent==='Reading the code…' && `+line+`.querySelector('[equipo-activity-line]').title==='Reading the code…'`, "the plain activity is not the label and tooltip")
82 cur, _ = r.client.Thinking(r.ctx)
83 if _, err := r.client.SetThinking(r.ctx, "random", cur.Revision); err != nil {
84 t.Fatal(err)
85 }
86 p.wait(`document.querySelector('[data-chat-stream]').dataset.thinkingSet==='random'`, "Random reached the page")
87 if err := r.runner.Send(r.ctx, "act-search", wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityThink}); err != nil {
88 t.Fatal(err)
89 }
90 p.wait(`(()=>{const l=`+line+`;const s=l?.dataset.thinkingWords;const all={professional:`+in("professional", "think")+`,playful:`+in("playful", "think")+`,galaxy:`+in("galaxy", "think")+`,bridge:`+in("bridge", "think")+`,pirate:`+in("pirate", "think")+`,terminal:`+in("terminal", "think")+`};return !!s && s!=='random' && (all[s]||[]).includes(`+phrase+`)})()`, "Random took one set for the turn")
91 p.stayed("conversation")
92}
93
94// TestBrowserThinkingCycles: Paul, 2026-11-09: "They could swap a touch
95// less frequently, they're a bit frantic. There needs to be many more per
96// category so it takes a while before I see the same ones again." A
97// situation's first phrase holds 5 s, then a new one every 6 to 8 s; the
98// phrases come from a shuffled deck, none again until all have shown,
99// across two turns (a reload keeps only localStorage); after the deck runs
100// out the next is none of the last three; a tool shows its plain label
101// once the phrase before has had its 1.5 s; under reduced motion the
102// thinking words still change.
103//
104// The page's clock stands still but for the test (clock below): each
105// phrase is held to just under its minimum while the phrase timer looks,
106// then to its maximum. The page records each phrase it draws with its
107// clock, and the dwell rule is judged from that record, never from how
108// long the test waited, so a slow machine cannot make a phrase go early.
109func TestBrowserThinkingCycles(t *testing.T) {
110 r := newToolRig(t)
111 words, _ := r.client.Thinking(r.ctx)
112 var think []string
113 for _, s := range words.Sets {
114 if s.ID == wire.DefaultThinking {
115 think = s.Phrases["think"]
116 }
117 }
118 js := func(v any) string { raw, _ := json.Marshal(v); return string(raw) }
119 // The runner keeps reading, so it answers the instance's pings (a
120 // websocket answers only while it reads) and its stream outlives the
121 // ping deadline however slow the machine is; nothing it is sent
122 // matters here.
123 go func() {
124 for {
125 if _, _, err := r.runner.Conn.Read(r.ctx); err != nil {
126 return
127 }
128 }
129 }()
130 // clock: Date.now is base + skew, both kept in sessionStorage so a
131 // reload goes on from the same time; it moves only when the test
132 // moves it. The phrase timer (chat-stream.js turns phrases from a
133 // 250 ms interval) looks every 50 ms here, which changes no dwell (the
134 // dwell is read from the clock), and __ticks counts its runs, so the
135 // test knows the timer has looked at the clock it set. __drawn is each
136 // phrase drawn: its turn, its text and the clock when it came in.
137 const clock = `(()=>{const real=Date.now.bind(Date);window.__base=Number(sessionStorage.getItem('base'))||real();sessionStorage.setItem('base',window.__base);window.__skew=Number(sessionStorage.getItem('skew')||0);Date.now=()=>window.__base+window.__skew;` +
138 `window.__ticks=0;const every=window.setInterval;window.setInterval=function(fn,ms,...rest){if(ms===250&&typeof fn==='function'){const f=fn;fn=function(){try{return f.apply(this,arguments)}finally{window.__ticks++}};ms=50}return every.call(window,fn,ms,...rest)};` +
139 `window.__drawn=[];const once=new WeakSet();new MutationObserver(ms=>{for(const m of ms)for(const e of m.target.querySelectorAll('[equipo-phrase] > [data-in]'))if(!once.has(e)&&once.add(e))window.__drawn.push({turn:e.closest('[equipo-thinking]')?.dataset.turn,text:e.textContent,at:Date.now()})}).observe(document,{childList:true,subtree:true});})()`
140 for _, motion := range []string{"no-preference", "reduce"} {
141 p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", motion)
142 p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
143 _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: clock})
144 return err
145 }))
146 p.open("/conversation")
147 line := `document.querySelector('[equipo-thinking][data-turn="` + r.turn + `"]')`
148 phrase := line + `?.querySelector('[equipo-phrase] [data-in]')?.textContent`
149 drawn := `window.__drawn.filter(d=>d.turn===` + js(r.turn) + `)`
150 // age: the page's clock to ms after the shown phrase came in, by
151 // the page's record.
152 age := func(ms int) {
153 t.Helper()
154 p.check(fmt.Sprintf(`(()=>{const d=%s;window.__skew=d[d.length-1].at-window.__base+%d;sessionStorage.setItem('skew',window.__skew);window.__looked=window.__ticks;return true})()`, drawn, ms), "set the clock")
155 }
156 var seen []string
157 first := func(what string) {
158 t.Helper()
159 p.wait(js(think)+`.includes(`+phrase+`) && `+drawn+`.length>0`, what)
160 seen = append(seen, eval[string](p, phrase))
161 }
162 // holds: at ms, once the phrase timer has looked, the same phrase.
163 holds := func(ms int, what string) {
164 t.Helper()
165 age(ms)
166 p.wait(`window.__ticks>window.__looked`, "the phrase timer looked")
167 p.check(phrase+`===`+js(seen[len(seen)-1]), what)
168 }
169 next := func(ms int) {
170 t.Helper()
171 age(ms)
172 p.wait(phrase+`!==`+js(seen[len(seen)-1])+` && `+js(think)+`.includes(`+phrase+`)`, fmt.Sprintf("phrase %d", len(seen)+1))
173 seen = append(seen, eval[string](p, phrase))
174 }
175 // cycle: the next phrase, held past just under 6 s, gone by 8 s.
176 cycle := func() {
177 t.Helper()
178 holds(5999, motion+": a phrase went before 6 s")
179 next(8000)
180 }
181 // dwelt: the page's record of this page's phrases is seen[from:],
182 // in order; the first came in 5 s after the one before it, each
183 // later one 6 to 8 s after.
184 dwelt := func(from int) {
185 t.Helper()
186 if bad := eval[string](p, `(()=>{const d=`+drawn+`,want=`+js(seen[from:])+`;if(JSON.stringify(d.map(x=>x.text))!==JSON.stringify(want))return 'drawn '+JSON.stringify(d.map(x=>x.text));for(let i=1;i<d.length;i++){const g=d[i].at-d[i-1].at,min=i===1?5000:6000,max=i===1?5000:8000;if(g<min||g>max)return 'phrase '+(i+1)+' came '+g+' ms after the one before'}return ''})()`); bad != "" {
187 t.Fatalf("%s: %s", motion, bad)
188 }
189 }
190 first("the first thinking phrase")
191 holds(4999, motion+": the first phrase went before 5 s")
192 next(5000)
193 for len(seen) < 20 {
194 cycle()
195 }
196 dwelt(0)
197 // A new turn: the page again, nothing kept but localStorage.
198 p.do(chromedp.Reload())
199 from := len(seen)
200 first("the thinking phrase after the reload")
201 holds(4999, motion+": the first phrase after the reload went before 5 s")
202 next(5000)
203 for len(seen) < len(think) {
204 cycle()
205 }
206 distinct := map[string]bool{}
207 for _, s := range seen {
208 if distinct[s] {
209 t.Fatalf("%s: %q came again before the deck of %d ran out: %v", motion, s, len(think), seen)
210 }
211 distinct[s] = true
212 }
213 // The deck ran out: the next is none of the last three.
214 last := seen[len(seen)-3:]
215 cycle()
216 for _, l := range last {
217 if seen[len(seen)-1] == l {
218 t.Fatalf("%s: %q again straight after the deck ran out", motion, l)
219 }
220 }
221 dwelt(from)
222 // A tool activity: its plain label, after the phrase's dwell.
223 if err := r.runner.Send(r.ctx, "cyc-read-"+motion, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile}); err != nil {
224 t.Fatal(err)
225 }
226 p.wait(phrase+`==='Reading the code…'`, "a plain reading label after the dwell")
227 if motion == "reduce" {
228 p.check(`getComputedStyle(document.querySelector('[equipo-sparkle] path')).animationName==='none'`, "the mark moves under reduced motion")
229 }
230 p.stop()
231 if err := r.runner.Send(r.ctx, "cyc-think-"+motion, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityThink}); err != nil {
232 t.Fatal(err)
233 }
234 }
235}
236
237// TestBrowserThinkingSteady: Paul on staging, 2026-11-20: "When it was
238// responding, the thinking kept flashing quite quickly." A turn's first
239// moments bring a burst: thinking, the runner's tool label and then the
240// instance's named one, and cards whose refreshes re-rendered the feed.
241// Every activity drew a phrase at once over the ones still fading, and
242// each refresh took the line out and put it back, so every fading phrase
243// started its animation again on top of the new one. Now each phrase
244// stays at least 1.5 s and the latest waiting one follows, one phrase
245// shows at a time, a refresh leaves the line where it is, and the timer
246// counts the whole turn.
247func TestBrowserThinkingSteady(t *testing.T) {
248 r := newToolRig(t)
249 if err := r.runner.Send(r.ctx, "r-first", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "First."}); err != nil {
250 t.Fatal(err)
251 }
252 r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
253 // The page's record: each phrase drawn, the most phrases visible at
254 // once (letters a new phrase keeps from the old one are the old
255 // ones'), how often a phrase's animation started again, and the timer
256 // each frame.
257 const watch = `(()=>{window.__drawn=[];window.__most=0;window.__again=0;window.__timer=[];const once=new WeakSet(),began=new WeakMap();` +
258 `new MutationObserver(()=>{for(const e of document.querySelectorAll('[equipo-phrase] > [data-in]'))if(!once.has(e)&&once.add(e))__drawn.push({text:e.textContent,at:performance.now()})}).observe(document,{childList:true,subtree:true});` +
259 `const frame=()=>{const layers=[...document.querySelectorAll('[equipo-phrase] > [data-in], [equipo-phrase] > [data-out]')];__most=Math.max(__most,layers.filter(l=>[...l.children].some(c=>{const s=getComputedStyle(c);return !c.hasAttribute('data-keep')&&s.visibility!=='hidden'&&Number(s.opacity)>.1})).length);` +
260 `for(const l of layers){const w=l.firstElementChild?.getAnimations().find(a=>a.animationName==='equipo-wave');if(!w||w.startTime===null)continue;if(!began.has(l))began.set(l,w.startTime);else if(began.get(l)!==w.startTime){began.set(l,w.startTime);__again++}}` +
261 `const e=document.querySelector('[equipo-elapsed]');if(e&&e.textContent)__timer.push(parseInt(e.textContent));requestAnimationFrame(frame)};requestAnimationFrame(frame)})()`
262 p := openInner(t, r.inst.URL, r.inst.Cookie(), 1280, 900, false, "light", "no-preference")
263 defer p.stop()
264 p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
265 _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: watch})
266 return err
267 }))
268 p.open("/conversation")
269 p.wait(`document.querySelector('#composer textarea')`, "the composer")
270 sent := time.Now()
271 p.check(`(()=>{const box=document.querySelector('#composer textarea');box.value='Fix the swipe';box.dispatchEvent(new Event('input'));document.querySelector('#composer').requestSubmit();return true})()`, "send")
272 f, body, err := r.runner.Expect(r.ctx, wire.FrameMessage)
273 if err != nil {
274 t.Fatal(err)
275 }
276 if err := r.runner.Send(r.ctx, "a-fix", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
277 t.Fatal(err)
278 }
279 r.turn = body.(*wire.MessageCommand).TurnID
280 p.wait(`document.querySelector('[equipo-thinking][data-turn=`+jsString(r.turn)+`]')`, "the turn's line")
281 act := func(id, kind, tool string) {
282 t.Helper()
283 if err := r.runner.Send(r.ctx, id, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: kind, Tool: tool}); err != nil {
284 t.Fatal(err)
285 }
286 }
287 from := eval[int](p, `__drawn.length`)
288 burst := time.Now()
289 act("s1", wire.ActivityThink, "")
290 act("s2", wire.ActivityTool, wire.ToolRecordTask)
291 task := taskID(t, r.call("s-rec", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back", "brief": "x"}))
292 act("s3", wire.ActivityThink, "")
293 act("s4", wire.ActivityTool, wire.ToolStartTask)
294 r.call("s-start", wire.ToolStartTask, map[string]string{"task": task, "brief": "go"})
295 r.expect(wire.FrameDispatch)
296 act("s5", wire.ActivityThink, "")
297 took := time.Since(burst)
298 words, _ := r.client.Thinking(r.ctx)
299 var think []string
300 for _, s := range words.Sets {
301 if s.ID == wire.DefaultThinking {
302 think = s.Phrases["think"]
303 }
304 }
305 thinks, _ := json.Marshal(think)
306 line := `document.querySelector('[equipo-thinking][data-turn=` + jsString(r.turn) + `]')`
307 p.wait(line+`?.querySelector('[equipo-activity]').textContent==='Thinking' && document.querySelector('[data-card]')`, "the latest activity for screen readers, and the task's card")
308 // The latest waiting phrase comes once the one before has had its time.
309 p.wait(`(()=>{const d=__drawn.slice(`+fmt.Sprint(from)+`);return d.length>0 && performance.now()-d[d.length-1].at>1700 && `+string(thinks)+`.includes(d[d.length-1].text)})()`, "the burst settles on a thinking phrase")
310 drawn := eval[[]map[string]any](p, `__drawn.slice(`+fmt.Sprint(from)+`)`)
311 if most := 2 + int(took/(1500*time.Millisecond)); len(drawn) > most {
312 t.Fatalf("%d phrases for a burst of %s, want at most %d: %v", len(drawn), took, most, drawn)
313 }
314 all := eval[[]map[string]any](p, `__drawn`)
315 for i := 1; i < len(all); i++ {
316 if gap := all[i]["at"].(float64) - all[i-1]["at"].(float64); gap < 1450 {
317 t.Fatalf("%q came %.0f ms after %q: %v", all[i]["text"], gap, all[i-1]["text"], all)
318 }
319 }
320 if most := eval[int](p, `__most`); most > 1 {
321 t.Fatalf("%d phrases visible at once", most)
322 }
323 if again := eval[int](p, `__again`); again > 0 {
324 t.Fatalf("a phrase's animation started again %d times while the turn ran", again)
325 }
326 timer := eval[[]int](p, `__timer`)
327 for i := 1; i < len(timer); i++ {
328 if timer[i] < timer[i-1] {
329 t.Fatalf("the timer went from %ds to %ds", timer[i-1], timer[i])
330 }
331 }
332 // It shows whole seconds, a tick a second: up to two behind.
333 if got, since := timer[len(timer)-1], time.Since(sent); got < int(since.Seconds())-2 {
334 t.Fatalf("the timer shows %ds, %s after the send", got, since)
335 }
336 p.stayed("the burst")
337}
338