| 1 | //go:build browser |
| 2 | |
| 3 | package thintest |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "testing" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/wire" |
| 10 | "github.com/chromedp/cdproto/cdp" |
| 11 | "github.com/chromedp/cdproto/page" |
| 12 | "github.com/chromedp/chromedp" |
| 13 | ) |
| 14 | |
| 15 | // instantPage opens the conversation with a fake clock (window.__skew) and |
| 16 | // a hold on the send: every POST to /conversation waits until |
| 17 | // window.__release() (or fails, with window.__fail set), so what the page |
| 18 | // shows before any answer from the server can be checked. |
| 19 | func instantPage(t *testing.T, r *rig) *innerPage { |
| 20 | t.Helper() |
| 21 | p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", "no-preference") |
| 22 | p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 23 | _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `(()=>{ |
| 24 | window.__beats=0;setInterval(()=>window.__beats++,250);const real=Date.now.bind(Date);window.__skew=0;Date.now=()=>real()+window.__skew; |
| 25 | const fetch0=window.fetch.bind(window);window.__held=[];window.__answered=0; |
| 26 | window.fetch=(url,opts)=>{ |
| 27 | if(!opts||opts.method!=='POST'||!String(url).endsWith('/conversation'))return fetch0(url,opts); |
| 28 | if(window.__fail)return Promise.resolve(new Response('',{status:500})); |
| 29 | return new Promise(go=>window.__held.push(()=>go(fetch0(url,opts).then(r=>{window.__answered++;return r})))); |
| 30 | }; |
| 31 | window.__release=()=>{const h=window.__held.shift();if(h)h();return true}; |
| 32 | })()`}) |
| 33 | return err |
| 34 | })) |
| 35 | p.open("/conversation") |
| 36 | p.wait(`document.querySelector('[data-chat-stream]')`, "the conversation") |
| 37 | // The page's timers are going (the thinking line's clock runs on them). |
| 38 | p.wait(`window.__beats>2`, "page timers running") |
| 39 | return p |
| 40 | } |
| 41 | |
| 42 | // sendNow types text, sends it, and reports in the same task whether the |
| 43 | // coordinator's line is already there, then again at the next frame. |
| 44 | const sendNow = `(text=>{ |
| 45 | const before=window.__answered; |
| 46 | const box=document.querySelector('#composer textarea');box.value=text;box.dispatchEvent(new Event('input')); |
| 47 | document.querySelector('#composer').requestSubmit(); |
| 48 | const lines=[...document.querySelectorAll('[equipo-thinking][data-optimistic]')]; |
| 49 | window.__line=lines[lines.length-1]||null; |
| 50 | window.__sync=!!window.__line && window.__answered===before && window.__line.querySelector('[equipo-elapsed]').textContent==='0s' && !!window.__line.querySelector('[equipo-sparkle]') && !!window.__line.querySelector('[equipo-phrase] [data-in]'); |
| 51 | requestAnimationFrame(()=>{window.__frame=!!window.__line&&window.__line.isConnected&&window.__answered===before}); |
| 52 | return window.__sync; |
| 53 | })` |
| 54 | |
| 55 | const oneLine = `document.querySelectorAll('[equipo-thinking]').length===1` |
| 56 | |
| 57 | // TestBrowserInstantThinking: Paul, "a slight delay before the |
| 58 | // coordinator's loading state appears". The line comes with the send, |
| 59 | // before the server has answered (the POST held back), with its sparkle, a |
| 60 | // phrase and a timer from 0 on the fake clock; the turn then adopts that |
| 61 | // same element, timer and all. A send that fails takes its line away and |
| 62 | // says so; a turn with no connection gives the line up for the quiet |
| 63 | // waiting state; two sends that share a queued turn leave one line. |
| 64 | func TestBrowserInstantThinking(t *testing.T) { |
| 65 | |
| 66 | t.Run("instant_then_adopted", func(t *testing.T) { |
| 67 | r, runner := instantRig(t) |
| 68 | p := instantPage(t, r) |
| 69 | defer p.stop() |
| 70 | p.check(sendNow+`('Can you look at the build?')`, "no line at once, before the server answered") |
| 71 | p.wait(`window.__frame===true`, "the line within one frame of the send") |
| 72 | p.check(`window.__held.length===1 && window.__answered===0`, "the send was not held") |
| 73 | started := eval[string](p, `window.__line.dataset.started`) |
| 74 | // The timer counts on the fake clock while the server has said nothing. |
| 75 | p.check(`(()=>{window.__skew+=2100;return true})()`, "advance the clock") |
| 76 | p.wait(`window.__line.querySelector('[equipo-elapsed]').textContent==='2s'`, "the timer counting from the send") |
| 77 | p.check(`window.__release()`, "release the send") |
| 78 | f := messageFrame(t, r, runner) |
| 79 | p.wait(`window.__line.isConnected && window.__line.dataset.turn!=='' && !window.__line.hasAttribute('data-optimistic')`, "the turn adopted the line") |
| 80 | p.check(oneLine+` && document.querySelector('[equipo-thinking]')===window.__line`, "a second line, or a new element, for the turn") |
| 81 | p.check(`window.__line.dataset.started===`+jsString(started), "the timer restarted") |
| 82 | runner.Send(r.ctx, "a-1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 83 | turn := eval[string](p, `window.__line.dataset.turn`) |
| 84 | r.wait("running", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnRunning }) |
| 85 | p.check(`(()=>{window.__skew+=1000;return true})()`, "advance the clock") |
| 86 | p.wait(`window.__line.isConnected && window.__line.querySelector('[equipo-elapsed]').textContent.match(/^(\d+)s$/)?.[1]>=3 && window.__line.dataset.started===`+jsString(started), "the same line runs on, timed from the send") |
| 87 | p.check(oneLine, "one line while running") |
| 88 | runner.Send(r.ctx, "r-1", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "It builds now."}) |
| 89 | p.wait(`!document.querySelector('[equipo-thinking]') && [...document.querySelectorAll('[data-message]')].some(m=>m.textContent.includes('It builds now.'))`, "the reply took the line's place") |
| 90 | p.stayed("instant send") |
| 91 | }) |
| 92 | |
| 93 | t.Run("attachment_line_before_upload", func(t *testing.T) { |
| 94 | r, runner := instantRig(t) |
| 95 | p := instantPage(t, r) |
| 96 | defer p.stop() |
| 97 | // A pasted file is still uploading when the send goes. |
| 98 | p.check(`(()=>{const dt=new DataTransfer();dt.items.add(new File(['notes'],'notes.txt',{type:'text/plain'}));const box=document.querySelector('#composer textarea');box.dispatchEvent(new ClipboardEvent('paste',{clipboardData:dt,bubbles:true,cancelable:true}));return document.querySelectorAll('[equipo-chip]').length===1})()`, "the pasted file") |
| 99 | p.check(sendNow+`('Here are the notes.')`, "no line at once with an attachment") |
| 100 | p.wait(`window.__held.length===1`, "the send waits for the upload, then is held") |
| 101 | p.check(`window.__line.isConnected && window.__line.hasAttribute('data-optimistic')`, "the line went while the upload ran") |
| 102 | p.check(`window.__release()`, "release the send") |
| 103 | f := messageFrame(t, r, runner) |
| 104 | p.wait(`window.__line.isConnected && !window.__line.hasAttribute('data-optimistic')`, "the turn adopted the line") |
| 105 | p.check(oneLine, "one line") |
| 106 | turn := eval[string](p, `window.__line.dataset.turn`) |
| 107 | runner.Send(r.ctx, "a-2", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 108 | runner.Send(r.ctx, "r-2", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Read them."}) |
| 109 | p.wait(`!document.querySelector('[equipo-thinking]')`, "the reply") |
| 110 | }) |
| 111 | |
| 112 | t.Run("send_failed", func(t *testing.T) { |
| 113 | r, runner := instantRig(t) |
| 114 | p := instantPage(t, r) |
| 115 | defer p.stop() |
| 116 | p.check(`(()=>{window.__fail=true;return true})()`, "fail the next send") |
| 117 | p.check(sendNow+`('This one will not go.')`, "no line at once") |
| 118 | p.wait(`!document.querySelector('[equipo-thinking]') && document.querySelector('[data-send-failed] [data-retry-send]')`, "the line gone and the send error shown") |
| 119 | // Trying again shows the line again, at once. |
| 120 | p.check(`(()=>{window.__fail=false;document.querySelector('[data-retry-send]').click();return !!document.querySelector('[equipo-thinking][data-optimistic]')})()`, "no line on retry") |
| 121 | p.check(`window.__release()`, "release the retry") |
| 122 | f := messageFrame(t, r, runner) |
| 123 | p.wait(`document.querySelector('[equipo-thinking]:not([data-optimistic])') && `+oneLine, "the retry's turn adopted its line") |
| 124 | turn := eval[string](p, `document.querySelector('[equipo-thinking]').dataset.turn`) |
| 125 | runner.Send(r.ctx, "a-3", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 126 | runner.Send(r.ctx, "r-3", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Got it."}) |
| 127 | p.wait(`!document.querySelector('[equipo-thinking]')`, "the reply") |
| 128 | }) |
| 129 | |
| 130 | t.Run("no_connection", func(t *testing.T) { |
| 131 | r, runner := instantRig(t) |
| 132 | p := instantPage(t, r) |
| 133 | defer p.stop() |
| 134 | p.check(sendNow+`('Are you there?')`, "no line at once") |
| 135 | p.check(`window.__release()`, "release the send") |
| 136 | f := messageFrame(t, r, runner) |
| 137 | runner.Send(r.ctx, "a-4", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 138 | var turn string |
| 139 | r.wait("queued or running", func(c *Conversation) bool { |
| 140 | for id, v := range c.Turns { |
| 141 | if v.State == wire.TurnQueued || v.State == wire.TurnRunning { |
| 142 | turn = id |
| 143 | return true |
| 144 | } |
| 145 | } |
| 146 | return false |
| 147 | }) |
| 148 | runner.Send(r.ctx, "r-hold", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: wire.ReasonNoConnection}) |
| 149 | p.wait(`!document.querySelector('[equipo-thinking]') && document.querySelector('[data-waiting-connection]')`, "the quiet waiting state in place of the line") |
| 150 | // It goes on, on a connection: the thinking line again. |
| 151 | runner.Send(r.ctx, "r-go", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnRunning}) |
| 152 | p.wait(oneLine+` && document.querySelector('[equipo-thinking]').dataset.turn===`+jsString(turn), "the line back when it runs") |
| 153 | runner.Send(r.ctx, "r-4", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Here now."}) |
| 154 | p.wait(`!document.querySelector('[equipo-thinking]')`, "the reply") |
| 155 | }) |
| 156 | } |
| 157 | |
| 158 | // instantRig is an instance with a scripted runner online. |
| 159 | func instantRig(t *testing.T) (*rig, *FakeRunner) { |
| 160 | t.Helper() |
| 161 | r := newRig(t) |
| 162 | runner := r.dial(0) |
| 163 | if err := runner.Send(r.ctx, "h1", wire.FrameHello, toolHello(runner.Welcome.Generation)); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) |
| 167 | return r, runner |
| 168 | } |
| 169 | |
| 170 | // messageFrame is the next message frame, attachment chunks acked on the way. |
| 171 | func messageFrame(t *testing.T, r *rig, runner *FakeRunner) wire.Frame { |
| 172 | t.Helper() |
| 173 | for { |
| 174 | f, _, err := runner.Next(r.ctx) |
| 175 | if err != nil { |
| 176 | t.Fatal(err) |
| 177 | } |
| 178 | switch f.Type { |
| 179 | case wire.FrameMessage: |
| 180 | return f |
| 181 | case wire.FrameAttachment: |
| 182 | runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 183 | case wire.FrameAck: |
| 184 | default: |
| 185 | t.Fatalf("unexpected frame %s", f.Type) |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | // TestBrowserInstantThinkingQueued: while one turn runs, a second message |
| 191 | // queues a turn behind it and a third joins that queued turn (the server |
| 192 | // says so in its answer). The first send shows its line at once; the |
| 193 | // queued ones show no line or timer of their own, only a quiet note under |
| 194 | // the latest (Paul, 2026-11-11: ten stacked lines, "Did I push it too |
| 195 | // hard?"). When the server has answered there is one line, the element |
| 196 | // shown at the first send, and nothing is orphaned. |
| 197 | func TestBrowserInstantThinkingQueued(t *testing.T) { |
| 198 | r, runner := instantRig(t) |
| 199 | p := instantPage(t, r) |
| 200 | defer p.stop() |
| 201 | p.check(sendNow+`('First thing.')`, "no line for the first send") |
| 202 | p.check(`(()=>{window.__first=window.__line;return window.__release()})()`, "release the first") |
| 203 | f := messageFrame(t, r, runner) |
| 204 | runner.Send(r.ctx, "a-q1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 205 | p.wait(`!window.__first.hasAttribute('data-optimistic')`, "the first turn adopted its line") |
| 206 | first := eval[string](p, `window.__first.dataset.turn`) |
| 207 | r.wait("first running", func(c *Conversation) bool { return c.Turns[first].State == wire.TurnRunning }) |
| 208 | // queuedNow sends text and reports in the same task that the only line |
| 209 | // is still the first's and the note is under this message. |
| 210 | queuedNow := `(text=>{ |
| 211 | const box=document.querySelector('#composer textarea');box.value=text;box.dispatchEvent(new Event('input')); |
| 212 | document.querySelector('#composer').requestSubmit(); |
| 213 | const lines=[...document.querySelectorAll('[equipo-thinking]')], notes=[...document.querySelectorAll('[data-queued]')]; |
| 214 | return lines.length===1 && lines[0]===window.__first && notes.length===1 && notes[0].closest('[equipo-message="own"]').querySelector('[equipo-message-body]').textContent===text; |
| 215 | })` |
| 216 | p.check(queuedNow+`('And a second.')`, "a line of its own, or no note, for the second send") |
| 217 | p.check(queuedNow+`('And a third.')`, "a line of its own, or no note, for the third send") |
| 218 | p.check(`window.__held.length===2`, "both sends held") |
| 219 | p.check(`window.__release()`, "release the second") |
| 220 | p.wait(`window.__answered===2`, "the second answered") |
| 221 | p.check(`window.__release()`, "release the third") |
| 222 | p.wait(`window.__answered===3`, "the third answered") |
| 223 | p.wait(`document.querySelectorAll('[data-queued]').length===1 && [...document.querySelectorAll('[equipo-message="own"]')].find(m=>m.querySelector('[data-queued]')).querySelector('[equipo-message-body]').textContent==='And a third.'`, "one note, under the third") |
| 224 | lines := `[...document.querySelectorAll('[equipo-thinking]')].map(l=>(l===window.__first?'first:':'')+l.dataset.turn).join(' ')` |
| 225 | if got := eval[string](p, lines); got != "first:"+first { |
| 226 | t.Fatalf("lines %q, want only the first's for turn %s", got, first) |
| 227 | } |
| 228 | snap, err := r.client.Snapshot(r.ctx) |
| 229 | if err != nil { |
| 230 | t.Fatal(err) |
| 231 | } |
| 232 | if len(snap.Turns) != 2 { |
| 233 | t.Fatalf("the third message did not join the queued turn: %+v", snap.Turns) |
| 234 | } |
| 235 | var second string |
| 236 | for _, v := range snap.Turns { |
| 237 | if v.ID != first { |
| 238 | second = v.ID |
| 239 | } |
| 240 | } |
| 241 | // The first replies: the queued turn's line comes, the note goes. |
| 242 | runner.Send(r.ctx, "r-q1", wire.FrameReply, wire.Reply{TurnID: first, Attempt: 1, Text: "First done."}) |
| 243 | p.wait(`document.querySelectorAll('[equipo-thinking]').length===1 && document.querySelector('[equipo-thinking]').dataset.turn===`+jsString(second)+` && !document.querySelector('[data-queued]')`, "the second turn's line, no note") |
| 244 | // The batch of two fails for no reason given: its note says these |
| 245 | // messages, from the event and then the server. |
| 246 | bf := messageFrame(t, r, runner) |
| 247 | runner.Send(r.ctx, "a-q2", wire.FrameAck, wire.Ack{ID: bf.ID}) |
| 248 | runner.Send(r.ctx, "f-q2", wire.FrameTurn, wire.TurnReport{TurnID: second, Attempt: 1, State: wire.TurnFailed, Reason: ""}) |
| 249 | p.wait(`(document.querySelector('[data-ended=`+jsString(second)+`] p')||{}).textContent===`+jsString("The coordinator could not answer these messages."), "the failed batch's note") |
| 250 | p.stayed("queued sends") |
| 251 | } |
| 252 | |