| 1 | //go:build browser |
| 2 | |
| 3 | package thintest |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "strconv" |
| 8 | "strings" |
| 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 | // TestBrowserThinkingLinesClear: Paul on staging, 2026-11-11, "Did I push |
| 19 | // it too hard?": ten Coordinator lines stacked, timers 22 s to 139 s, for |
| 20 | // a conversation where every turn had replied. A specialist was at work |
| 21 | // on a task meanwhile, and each of its step activity events (no turn) |
| 22 | // drew a new thinking line that nothing took away. |
| 23 | // |
| 24 | // Messages go quickly, some while a turn runs (one joins the queued |
| 25 | // turn), one reply lands while a refresh is in flight, and the task's |
| 26 | // step reports activity throughout. While a turn runs there is one |
| 27 | // thinking line (the running turn's) and the waiting message has a quiet |
| 28 | // queued note instead of a line and timer of its own. Once every turn has |
| 29 | // replied there is no thinking line, live and after a reload, and each |
| 30 | // reply shows once. |
| 31 | func TestBrowserThinkingLinesClear(t *testing.T) { |
| 32 | r := newToolRig(t) |
| 33 | // A task whose step keeps running: its activity reaches the stream. |
| 34 | task := taskID(t, r.call("k1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back from the edge does nothing", "brief": "x"})) |
| 35 | r.call("k2", wire.ToolStartTask, map[string]string{"task": task, "brief": "go"}) |
| 36 | _, body := r.expect(wire.FrameDispatch) |
| 37 | d := body.(*wire.DispatchCommand) |
| 38 | r.step("r-s1", wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)}) |
| 39 | acts := 0 |
| 40 | activity := func() { |
| 41 | t.Helper() |
| 42 | acts++ |
| 43 | r.activity("act-"+strconv.Itoa(acts), wire.StepActivityReport{TaskID: task, StepID: d.StepID, Attempt: 1, Kind: wire.ActivityRead, Subject: "panes/swipe.go"}) |
| 44 | r.wait("step activity", func(c *Conversation) bool { return len(c.StepActivity[d.StepID]) == acts }) |
| 45 | } |
| 46 | reply := func(turn, text string) { |
| 47 | t.Helper() |
| 48 | if err := r.runner.Send(r.ctx, "r-"+turn, wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: text}); err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | r.wait("replied", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnReplied }) |
| 52 | } |
| 53 | // next is the turn the instance dispatches next, acked: running. |
| 54 | next := func() string { |
| 55 | t.Helper() |
| 56 | _, body := r.expect(wire.FrameMessage) |
| 57 | turn := body.(*wire.MessageCommand).TurnID |
| 58 | r.wait("running", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnRunning }) |
| 59 | return turn |
| 60 | } |
| 61 | reply(r.turn, "Started on the swipe.") |
| 62 | |
| 63 | p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", "no-preference") |
| 64 | defer p.stop() |
| 65 | // Count the events the page has applied, and hold the page's refresh |
| 66 | // answers on demand (the request goes; its answer waits). |
| 67 | p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 68 | _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `(()=>{ |
| 69 | const ES=window.EventSource;window.__seen={}; |
| 70 | window.EventSource=function(u,o){const s=new ES(u,o);const add=s.addEventListener.bind(s);s.addEventListener=function(t,f,x){return add(t,function(e){f.call(this,e);window.__seen[t]=(window.__seen[t]||0)+1},x)};return s}; |
| 71 | window.EventSource.prototype=ES.prototype; |
| 72 | const fetch0=window.fetch.bind(window);window.__hold=false;window.__held=[]; |
| 73 | window.fetch=(url,opts)=>{const f=fetch0(url,opts);if(!window.__hold||opts&&opts.method==='POST'||!String(url).endsWith('/conversation'))return f;return new Promise(go=>window.__held.push(()=>go(f)))}; |
| 74 | window.__release=()=>{window.__hold=false;const h=window.__held.splice(0);h.forEach(f=>f());return h.length}; |
| 75 | })()`}) |
| 76 | return err |
| 77 | })) |
| 78 | p.open("/conversation") |
| 79 | p.wait(`document.querySelector('[data-chat-stream]') && window.__seen`, "the conversation") |
| 80 | turns := func() string { |
| 81 | var out []string |
| 82 | r.conv.Locked(func(c *Conversation) { |
| 83 | for id, v := range c.Turns { |
| 84 | out = append(out, id+" "+v.State+" "+strings.Join(v.MessageIDs, ",")) |
| 85 | } |
| 86 | }) |
| 87 | return strings.Join(out, "; ") |
| 88 | } |
| 89 | // What the feed shows, for a failure: lines by turn, messages by turn. |
| 90 | state := `[...document.querySelectorAll('[equipo-feed] > *')].map(l=>l.hasAttribute('equipo-thinking')?'line:'+l.dataset.turn+(l.hasAttribute('data-optimistic')?'(optimistic)':''):l.matches('[equipo-message]')?l.getAttribute('equipo-message')+':'+(l.dataset.turnId||'-')+':'+l.querySelector('[equipo-message-body]').textContent.slice(0,24)+(l.querySelector('[data-queued]')?' (queued)':''):l.tagName).join('\n')` |
| 91 | wait := func(expression, what string) { |
| 92 | t.Helper() |
| 93 | for deadline := time.Now().Add(8 * time.Second); !eval[bool](p, `!!(`+expression+`)`); time.Sleep(40 * time.Millisecond) { |
| 94 | if time.Now().After(deadline) { |
| 95 | t.Fatalf("waiting for %s; the feed:\n%s\nturns: %s", what, eval[string](p, state), turns()) |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | check := func(expression, what string) { |
| 100 | t.Helper() |
| 101 | if !eval[bool](p, `!!(`+expression+`)`) { |
| 102 | t.Fatalf("%s; the feed:\n%s\nturns: %s", what, eval[string](p, state), turns()) |
| 103 | } |
| 104 | } |
| 105 | // send types text and sends it; behind a running turn, nothing but |
| 106 | // that turn's line shows, from the moment of sending. |
| 107 | send := func(text string, behind bool) { |
| 108 | t.Helper() |
| 109 | check(`(()=>{const box=document.querySelector('#composer textarea');box.value=`+jsString(text)+`;box.dispatchEvent(new Event('input'));document.querySelector('#composer').requestSubmit();return `+strconv.FormatBool(!behind)+` || document.querySelectorAll('[equipo-thinking]').length===1})()`, "a second line at the send of "+text) |
| 110 | } |
| 111 | lines := `document.querySelectorAll('[equipo-thinking]').length` |
| 112 | lineFor := func(turn string) string { |
| 113 | return `document.querySelectorAll('[equipo-thinking]').length===1 && document.querySelector('[equipo-thinking]').dataset.turn===` + jsString(turn) |
| 114 | } |
| 115 | seen := func(n int) string { return `(window.__seen.activity||0)>=` + strconv.Itoa(n) } |
| 116 | own := func(text string) string { |
| 117 | return `[...document.querySelectorAll('[equipo-message="own"]')].find(m=>m.querySelector('[equipo-message-body]').textContent===` + jsString(text) + `)` |
| 118 | } |
| 119 | queued := func(text string) string { return `!!` + own(text) + `?.querySelector('[data-queued]')` } |
| 120 | notes := `document.querySelectorAll('[data-queued]').length` |
| 121 | count := func(text string) string { |
| 122 | return `[...document.querySelectorAll('[equipo-message="incoming"][data-message]')].filter(m=>m.textContent.includes(` + text + `)).length===1` |
| 123 | } |
| 124 | once := func(text string) string { return count(jsString(text)) } |
| 125 | wait(once("Started on the swipe.")+` && `+lines+`===0`, "the opening reply, no line") |
| 126 | activity() |
| 127 | wait(seen(1), "the first step activity") |
| 128 | check(lines+`===0`, "a step's activity drew a coordinator line") |
| 129 | |
| 130 | // M1 runs; the specialist goes on meanwhile. |
| 131 | send("First thing.", false) |
| 132 | t1 := next() |
| 133 | wait(lineFor(t1), "one line, for the first turn") |
| 134 | activity() |
| 135 | wait(seen(2), "step activity while a turn runs") |
| 136 | check(lineFor(t1), "a second line beside the running turn's") |
| 137 | |
| 138 | // M2 while T1 runs: queued, a quiet note and no line of its own; M3 |
| 139 | // joins the queued turn. |
| 140 | send("And a second.", true) |
| 141 | wait(queued("And a second."), "the queued note under the second message") |
| 142 | check(lineFor(t1), "a line and timer for the queued turn") |
| 143 | wait(own("And a second.")+`?.dataset.message`, "the second message sent") |
| 144 | send("And a third.", true) |
| 145 | wait(queued("And a third.")+` && `+notes+`===1`, "one queued note, under the latest message") |
| 146 | check(lineFor(t1), "a line and timer for the joined turn") |
| 147 | wait(own("And a third.")+`?.dataset.turnId===`+own("And a second.")+`.dataset.turnId`, "the third message joined the queued turn") |
| 148 | |
| 149 | // T1 replies: the queued turn runs, its note goes, its line comes. |
| 150 | reply(t1, "Done with the first.") |
| 151 | t2 := next() |
| 152 | wait(once("Done with the first.")+` && `+lineFor(t2)+` && `+notes+`===0`, "the first reply once, one line for the second turn, no note") |
| 153 | activity() |
| 154 | wait(seen(3), "step activity") |
| 155 | check(lineFor(t2), "a second line beside the running turn's") |
| 156 | |
| 157 | // A refresh in flight (a task recorded during T2) when T2's reply |
| 158 | // lands and T3 starts running. |
| 159 | check(`(()=>{window.__hold=true;return true})()`, "hold refreshes") |
| 160 | r.turn = t2 |
| 161 | r.call("k3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Pull to refresh stalls", "brief": "y"}) |
| 162 | wait(`window.__held.length>=1`, "a refresh in flight") |
| 163 | send("A fourth.", true) |
| 164 | wait(queued("A fourth."), "the queued note under the fourth message") |
| 165 | reply(t2, "Second done.") |
| 166 | t3 := next() |
| 167 | activity() |
| 168 | wait(seen(4), "step activity during the refresh") |
| 169 | wait(`document.querySelector('[equipo-thinking][data-turn=`+jsString(t3)+`]')`, "the third turn's line") |
| 170 | // The answer from before T3 started never takes its line away. |
| 171 | check(`(()=>{window.__t3=document.querySelector('[equipo-thinking][data-turn=`+jsString(t3)+`]');return window.__release()>=1})()`, "release the refresh") |
| 172 | wait(once("Second done.")+` && `+lineFor(t3)+` && `+notes+`===0`, "the second reply once, one line for the third turn") |
| 173 | check(`document.querySelector('[equipo-thinking]')===window.__t3 && window.__t3.isConnected`, "the third turn's line went and came back") |
| 174 | |
| 175 | reply(t3, "Fourth handled.") |
| 176 | wait(once("Fourth handled.")+` && `+lines+`===0`, "the last reply, no line") |
| 177 | // The specialist is still at work after the chat goes quiet. |
| 178 | activity() |
| 179 | activity() |
| 180 | wait(seen(6), "step activity after every turn replied") |
| 181 | check(lines+`===0`, "stale thinking lines once every turn replied") |
| 182 | replies := `["Started on the swipe.","Done with the first.","Second done.","Fourth handled."].every(t=>` + count("t") + `)` |
| 183 | check(replies, "a reply missing or shown twice") |
| 184 | p.stayed("quick sends") |
| 185 | |
| 186 | p.open("/conversation") |
| 187 | wait(`document.querySelector('[data-chat-stream]')`, "the conversation again") |
| 188 | check(lines+`===0 && `+notes+`===0`, "a thinking line or queued note after a reload") |
| 189 | check(replies, "a reply missing or shown twice after a reload") |
| 190 | } |
| 191 | |