//go:build browser package thintest import ( "context" "encoding/json" "fmt" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/page" "github.com/chromedp/chromedp" ) // TestBrowserThinkingWords: the Thinking words page previews the chosen // set on the Stardust line, at 1280 and 390; a set chosen elsewhere // reaches an open conversation's thinking line with no reload, while the // tool labels stay plain; Random takes one of // the sets for the turn. func TestBrowserThinkingWords(t *testing.T) { r := newToolRig(t) words, err := r.client.Thinking(r.ctx) if err != nil { t.Fatal(err) } phrases := map[string]map[string][]string{} for _, s := range words.Sets { phrases[s.ID] = s.Phrases } in := func(set, sit string) string { raw, _ := json.Marshal(phrases[set][sit]) return string(raw) } for _, size := range []struct { w, h int64 touch bool }{{1280, 900, false}, {390, 844, true}} { p := openInner(t, r.inst.URL, r.inst.Cookie(), size.w, size.h, size.touch, "light", "no-preference") p.open("/settings/thinking") preview := `document.querySelector('[data-preview-phrase]').textContent` p.wait(in("professional", "think")+`.includes(`+preview+`)`, "the preview shows Professional") // Picking a set saves it at once (Paul, iPhone: the button below was // easy to miss, and the line kept the default). p.check(`(()=>{document.querySelector('[data-set="pirate"] label').click();return document.querySelector('input[value="pirate"]').checked})()`, "pick Pirate adventure") p.wait(`document.querySelector('input[value="pirate"]').checked && document.querySelector('[equipo-saved-tick][data-shown]')`, "picking saved the set") p.stayed("picking a set") p.wait(in("pirate", "think")+`.includes(`+preview+`)`, "the preview shows Pirate adventure") p.check(`document.querySelector('[data-preview-line]').dataset.set==='pirate'`, "preview set") if got, _ := r.client.Thinking(r.ctx); got.Set != "pirate" { t.Fatalf("saved %s", got.Set) } p.shot(fmt.Sprintf("ux1-thinking-words-%d", size.w)) cur, _ := r.client.Thinking(r.ctx) if _, err := r.client.SetThinking(r.ctx, "professional", cur.Revision); err != nil { t.Fatal(err) } p.stop() } // The conversation follows a choice made elsewhere, from the next phrase. p := openInner(t, r.inst.URL, r.inst.Cookie(), 1280, 900, false, "light", "no-preference") defer p.stop() p.open("/conversation") line := `document.querySelector('[equipo-thinking][data-turn="` + r.turn + `"]')` phrase := line + `?.querySelector('[equipo-phrase] [data-in]')?.textContent` p.wait(in("professional", "think")+`.includes(`+phrase+`)`, "Professional while thinking") _ = p cur, _ := r.client.Thinking(r.ctx) if _, err := r.client.SetThinking(r.ctx, "galaxy", cur.Revision); err != nil { t.Fatal(err) } p.wait(`document.querySelector('[data-chat-stream]').dataset.thinkingSet==='galaxy'`, "the choice reached the page") 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 { t.Fatal(err) } p.wait(phrase+`==='Reading the code…'`, "plain label while reading") 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") cur, _ = r.client.Thinking(r.ctx) if _, err := r.client.SetThinking(r.ctx, "random", cur.Revision); err != nil { t.Fatal(err) } p.wait(`document.querySelector('[data-chat-stream]').dataset.thinkingSet==='random'`, "Random reached the page") if err := r.runner.Send(r.ctx, "act-search", wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityThink}); err != nil { t.Fatal(err) } 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") p.stayed("conversation") } // TestBrowserThinkingCycles: Paul, 2026-11-09: "They could swap a touch // less frequently, they're a bit frantic. There needs to be many more per // category so it takes a while before I see the same ones again." A // situation's first phrase holds 5 s, then a new one every 6 to 8 s; the // phrases come from a shuffled deck, none again until all have shown, // across two turns (a reload keeps only localStorage); after the deck runs // out the next is none of the last three; a tool shows its plain label // once the phrase before has had its 1.5 s; under reduced motion the // thinking words still change. // // The page's clock stands still but for the test (clock below): each // phrase is held to just under its minimum while the phrase timer looks, // then to its maximum. The page records each phrase it draws with its // clock, and the dwell rule is judged from that record, never from how // long the test waited, so a slow machine cannot make a phrase go early. func TestBrowserThinkingCycles(t *testing.T) { r := newToolRig(t) words, _ := r.client.Thinking(r.ctx) var think []string for _, s := range words.Sets { if s.ID == wire.DefaultThinking { think = s.Phrases["think"] } } js := func(v any) string { raw, _ := json.Marshal(v); return string(raw) } // The runner keeps reading, so it answers the instance's pings (a // websocket answers only while it reads) and its stream outlives the // ping deadline however slow the machine is; nothing it is sent // matters here. go func() { for { if _, _, err := r.runner.Conn.Read(r.ctx); err != nil { return } } }() // clock: Date.now is base + skew, both kept in sessionStorage so a // reload goes on from the same time; it moves only when the test // moves it. The phrase timer (chat-stream.js turns phrases from a // 250 ms interval) looks every 50 ms here, which changes no dwell (the // dwell is read from the clock), and __ticks counts its runs, so the // test knows the timer has looked at the clock it set. __drawn is each // phrase drawn: its turn, its text and the clock when it came in. 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;` + `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)};` + `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});})()` for _, motion := range []string{"no-preference", "reduce"} { p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", motion) p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: clock}) return err })) p.open("/conversation") line := `document.querySelector('[equipo-thinking][data-turn="` + r.turn + `"]')` phrase := line + `?.querySelector('[equipo-phrase] [data-in]')?.textContent` drawn := `window.__drawn.filter(d=>d.turn===` + js(r.turn) + `)` // age: the page's clock to ms after the shown phrase came in, by // the page's record. age := func(ms int) { t.Helper() 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") } var seen []string first := func(what string) { t.Helper() p.wait(js(think)+`.includes(`+phrase+`) && `+drawn+`.length>0`, what) seen = append(seen, eval[string](p, phrase)) } // holds: at ms, once the phrase timer has looked, the same phrase. holds := func(ms int, what string) { t.Helper() age(ms) p.wait(`window.__ticks>window.__looked`, "the phrase timer looked") p.check(phrase+`===`+js(seen[len(seen)-1]), what) } next := func(ms int) { t.Helper() age(ms) p.wait(phrase+`!==`+js(seen[len(seen)-1])+` && `+js(think)+`.includes(`+phrase+`)`, fmt.Sprintf("phrase %d", len(seen)+1)) seen = append(seen, eval[string](p, phrase)) } // cycle: the next phrase, held past just under 6 s, gone by 8 s. cycle := func() { t.Helper() holds(5999, motion+": a phrase went before 6 s") next(8000) } // dwelt: the page's record of this page's phrases is seen[from:], // in order; the first came in 5 s after the one before it, each // later one 6 to 8 s after. dwelt := func(from int) { t.Helper() 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;imax)return 'phrase '+(i+1)+' came '+g+' ms after the one before'}return ''})()`); bad != "" { t.Fatalf("%s: %s", motion, bad) } } first("the first thinking phrase") holds(4999, motion+": the first phrase went before 5 s") next(5000) for len(seen) < 20 { cycle() } dwelt(0) // A new turn: the page again, nothing kept but localStorage. p.do(chromedp.Reload()) from := len(seen) first("the thinking phrase after the reload") holds(4999, motion+": the first phrase after the reload went before 5 s") next(5000) for len(seen) < len(think) { cycle() } distinct := map[string]bool{} for _, s := range seen { if distinct[s] { t.Fatalf("%s: %q came again before the deck of %d ran out: %v", motion, s, len(think), seen) } distinct[s] = true } // The deck ran out: the next is none of the last three. last := seen[len(seen)-3:] cycle() for _, l := range last { if seen[len(seen)-1] == l { t.Fatalf("%s: %q again straight after the deck ran out", motion, l) } } dwelt(from) // A tool activity: its plain label, after the phrase's dwell. 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 { t.Fatal(err) } p.wait(phrase+`==='Reading the code…'`, "a plain reading label after the dwell") if motion == "reduce" { p.check(`getComputedStyle(document.querySelector('[equipo-sparkle] path')).animationName==='none'`, "the mark moves under reduced motion") } p.stop() if err := r.runner.Send(r.ctx, "cyc-think-"+motion, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityThink}); err != nil { t.Fatal(err) } } } // TestBrowserThinkingSteady: Paul on staging, 2026-11-20: "When it was // responding, the thinking kept flashing quite quickly." A turn's first // moments bring a burst: thinking, the runner's tool label and then the // instance's named one, and cards whose refreshes re-rendered the feed. // Every activity drew a phrase at once over the ones still fading, and // each refresh took the line out and put it back, so every fading phrase // started its animation again on top of the new one. Now each phrase // stays at least 1.5 s and the latest waiting one follows, one phrase // shows at a time, a refresh leaves the line where it is, and the timer // counts the whole turn. func TestBrowserThinkingSteady(t *testing.T) { r := newToolRig(t) if err := r.runner.Send(r.ctx, "r-first", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "First."}); err != nil { t.Fatal(err) } r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied }) // The page's record: each phrase drawn, the most phrases visible at // once (letters a new phrase keeps from the old one are the old // ones'), how often a phrase's animation started again, and the timer // each frame. const watch = `(()=>{window.__drawn=[];window.__most=0;window.__again=0;window.__timer=[];const once=new WeakSet(),began=new WeakMap();` + `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});` + `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);` + `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++}}` + `const e=document.querySelector('[equipo-elapsed]');if(e&&e.textContent)__timer.push(parseInt(e.textContent));requestAnimationFrame(frame)};requestAnimationFrame(frame)})()` p := openInner(t, r.inst.URL, r.inst.Cookie(), 1280, 900, false, "light", "no-preference") defer p.stop() p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: watch}) return err })) p.open("/conversation") p.wait(`document.querySelector('#composer textarea')`, "the composer") sent := time.Now() 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") f, body, err := r.runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } if err := r.runner.Send(r.ctx, "a-fix", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { t.Fatal(err) } r.turn = body.(*wire.MessageCommand).TurnID p.wait(`document.querySelector('[equipo-thinking][data-turn=`+jsString(r.turn)+`]')`, "the turn's line") act := func(id, kind, tool string) { t.Helper() if err := r.runner.Send(r.ctx, id, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: kind, Tool: tool}); err != nil { t.Fatal(err) } } from := eval[int](p, `__drawn.length`) burst := time.Now() act("s1", wire.ActivityThink, "") act("s2", wire.ActivityTool, wire.ToolRecordTask) task := taskID(t, r.call("s-rec", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back", "brief": "x"})) act("s3", wire.ActivityThink, "") act("s4", wire.ActivityTool, wire.ToolStartTask) r.call("s-start", wire.ToolStartTask, map[string]string{"task": task, "brief": "go"}) r.expect(wire.FrameDispatch) act("s5", wire.ActivityThink, "") took := time.Since(burst) words, _ := r.client.Thinking(r.ctx) var think []string for _, s := range words.Sets { if s.ID == wire.DefaultThinking { think = s.Phrases["think"] } } thinks, _ := json.Marshal(think) line := `document.querySelector('[equipo-thinking][data-turn=` + jsString(r.turn) + `]')` p.wait(line+`?.querySelector('[equipo-activity]').textContent==='Thinking' && document.querySelector('[data-card]')`, "the latest activity for screen readers, and the task's card") // The latest waiting phrase comes once the one before has had its time. 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") drawn := eval[[]map[string]any](p, `__drawn.slice(`+fmt.Sprint(from)+`)`) if most := 2 + int(took/(1500*time.Millisecond)); len(drawn) > most { t.Fatalf("%d phrases for a burst of %s, want at most %d: %v", len(drawn), took, most, drawn) } all := eval[[]map[string]any](p, `__drawn`) for i := 1; i < len(all); i++ { if gap := all[i]["at"].(float64) - all[i-1]["at"].(float64); gap < 1450 { t.Fatalf("%q came %.0f ms after %q: %v", all[i]["text"], gap, all[i-1]["text"], all) } } if most := eval[int](p, `__most`); most > 1 { t.Fatalf("%d phrases visible at once", most) } if again := eval[int](p, `__again`); again > 0 { t.Fatalf("a phrase's animation started again %d times while the turn ran", again) } timer := eval[[]int](p, `__timer`) for i := 1; i < len(timer); i++ { if timer[i] < timer[i-1] { t.Fatalf("the timer went from %ds to %ds", timer[i-1], timer[i]) } } // It shows whole seconds, a tick a second: up to two behind. if got, since := timer[len(timer)-1], time.Since(sent); got < int(since.Seconds())-2 { t.Fatalf("the timer shows %ds, %s after the send", got, since) } p.stayed("the burst") }