//go:build browser package thintest import ( "context" "testing" "amadan.net/oficina/equipo/internal/wire" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/page" "github.com/chromedp/chromedp" ) // instantPage opens the conversation with a fake clock (window.__skew) and // a hold on the send: every POST to /conversation waits until // window.__release() (or fails, with window.__fail set), so what the page // shows before any answer from the server can be checked. func instantPage(t *testing.T, r *rig) *innerPage { t.Helper() p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", "no-preference") p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `(()=>{ window.__beats=0;setInterval(()=>window.__beats++,250);const real=Date.now.bind(Date);window.__skew=0;Date.now=()=>real()+window.__skew; const fetch0=window.fetch.bind(window);window.__held=[];window.__answered=0; window.fetch=(url,opts)=>{ if(!opts||opts.method!=='POST'||!String(url).endsWith('/conversation'))return fetch0(url,opts); if(window.__fail)return Promise.resolve(new Response('',{status:500})); return new Promise(go=>window.__held.push(()=>go(fetch0(url,opts).then(r=>{window.__answered++;return r})))); }; window.__release=()=>{const h=window.__held.shift();if(h)h();return true}; })()`}) return err })) p.open("/conversation") p.wait(`document.querySelector('[data-chat-stream]')`, "the conversation") // The page's timers are going (the thinking line's clock runs on them). p.wait(`window.__beats>2`, "page timers running") return p } // sendNow types text, sends it, and reports in the same task whether the // coordinator's line is already there, then again at the next frame. const sendNow = `(text=>{ const before=window.__answered; const box=document.querySelector('#composer textarea');box.value=text;box.dispatchEvent(new Event('input')); document.querySelector('#composer').requestSubmit(); const lines=[...document.querySelectorAll('[equipo-thinking][data-optimistic]')]; window.__line=lines[lines.length-1]||null; 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]'); requestAnimationFrame(()=>{window.__frame=!!window.__line&&window.__line.isConnected&&window.__answered===before}); return window.__sync; })` const oneLine = `document.querySelectorAll('[equipo-thinking]').length===1` // TestBrowserInstantThinking: Paul, "a slight delay before the // coordinator's loading state appears". The line comes with the send, // before the server has answered (the POST held back), with its sparkle, a // phrase and a timer from 0 on the fake clock; the turn then adopts that // same element, timer and all. A send that fails takes its line away and // says so; a turn with no connection gives the line up for the quiet // waiting state; two sends that share a queued turn leave one line. func TestBrowserInstantThinking(t *testing.T) { t.Run("instant_then_adopted", func(t *testing.T) { r, runner := instantRig(t) p := instantPage(t, r) defer p.stop() p.check(sendNow+`('Can you look at the build?')`, "no line at once, before the server answered") p.wait(`window.__frame===true`, "the line within one frame of the send") p.check(`window.__held.length===1 && window.__answered===0`, "the send was not held") started := eval[string](p, `window.__line.dataset.started`) // The timer counts on the fake clock while the server has said nothing. p.check(`(()=>{window.__skew+=2100;return true})()`, "advance the clock") p.wait(`window.__line.querySelector('[equipo-elapsed]').textContent==='2s'`, "the timer counting from the send") p.check(`window.__release()`, "release the send") f := messageFrame(t, r, runner) p.wait(`window.__line.isConnected && window.__line.dataset.turn!=='' && !window.__line.hasAttribute('data-optimistic')`, "the turn adopted the line") p.check(oneLine+` && document.querySelector('[equipo-thinking]')===window.__line`, "a second line, or a new element, for the turn") p.check(`window.__line.dataset.started===`+jsString(started), "the timer restarted") runner.Send(r.ctx, "a-1", wire.FrameAck, wire.Ack{ID: f.ID}) turn := eval[string](p, `window.__line.dataset.turn`) r.wait("running", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnRunning }) p.check(`(()=>{window.__skew+=1000;return true})()`, "advance the clock") 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") p.check(oneLine, "one line while running") runner.Send(r.ctx, "r-1", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "It builds now."}) 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") p.stayed("instant send") }) t.Run("attachment_line_before_upload", func(t *testing.T) { r, runner := instantRig(t) p := instantPage(t, r) defer p.stop() // A pasted file is still uploading when the send goes. 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") p.check(sendNow+`('Here are the notes.')`, "no line at once with an attachment") p.wait(`window.__held.length===1`, "the send waits for the upload, then is held") p.check(`window.__line.isConnected && window.__line.hasAttribute('data-optimistic')`, "the line went while the upload ran") p.check(`window.__release()`, "release the send") f := messageFrame(t, r, runner) p.wait(`window.__line.isConnected && !window.__line.hasAttribute('data-optimistic')`, "the turn adopted the line") p.check(oneLine, "one line") turn := eval[string](p, `window.__line.dataset.turn`) runner.Send(r.ctx, "a-2", wire.FrameAck, wire.Ack{ID: f.ID}) runner.Send(r.ctx, "r-2", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Read them."}) p.wait(`!document.querySelector('[equipo-thinking]')`, "the reply") }) t.Run("send_failed", func(t *testing.T) { r, runner := instantRig(t) p := instantPage(t, r) defer p.stop() p.check(`(()=>{window.__fail=true;return true})()`, "fail the next send") p.check(sendNow+`('This one will not go.')`, "no line at once") p.wait(`!document.querySelector('[equipo-thinking]') && document.querySelector('[data-send-failed] [data-retry-send]')`, "the line gone and the send error shown") // Trying again shows the line again, at once. p.check(`(()=>{window.__fail=false;document.querySelector('[data-retry-send]').click();return !!document.querySelector('[equipo-thinking][data-optimistic]')})()`, "no line on retry") p.check(`window.__release()`, "release the retry") f := messageFrame(t, r, runner) p.wait(`document.querySelector('[equipo-thinking]:not([data-optimistic])') && `+oneLine, "the retry's turn adopted its line") turn := eval[string](p, `document.querySelector('[equipo-thinking]').dataset.turn`) runner.Send(r.ctx, "a-3", wire.FrameAck, wire.Ack{ID: f.ID}) runner.Send(r.ctx, "r-3", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Got it."}) p.wait(`!document.querySelector('[equipo-thinking]')`, "the reply") }) t.Run("no_connection", func(t *testing.T) { r, runner := instantRig(t) p := instantPage(t, r) defer p.stop() p.check(sendNow+`('Are you there?')`, "no line at once") p.check(`window.__release()`, "release the send") f := messageFrame(t, r, runner) runner.Send(r.ctx, "a-4", wire.FrameAck, wire.Ack{ID: f.ID}) var turn string r.wait("queued or running", func(c *Conversation) bool { for id, v := range c.Turns { if v.State == wire.TurnQueued || v.State == wire.TurnRunning { turn = id return true } } return false }) runner.Send(r.ctx, "r-hold", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: wire.ReasonNoConnection}) p.wait(`!document.querySelector('[equipo-thinking]') && document.querySelector('[data-waiting-connection]')`, "the quiet waiting state in place of the line") // It goes on, on a connection: the thinking line again. runner.Send(r.ctx, "r-go", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnRunning}) p.wait(oneLine+` && document.querySelector('[equipo-thinking]').dataset.turn===`+jsString(turn), "the line back when it runs") runner.Send(r.ctx, "r-4", wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Here now."}) p.wait(`!document.querySelector('[equipo-thinking]')`, "the reply") }) } // instantRig is an instance with a scripted runner online. func instantRig(t *testing.T) (*rig, *FakeRunner) { t.Helper() r := newRig(t) runner := r.dial(0) if err := runner.Send(r.ctx, "h1", wire.FrameHello, toolHello(runner.Welcome.Generation)); err != nil { t.Fatal(err) } r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) return r, runner } // messageFrame is the next message frame, attachment chunks acked on the way. func messageFrame(t *testing.T, r *rig, runner *FakeRunner) wire.Frame { t.Helper() for { f, _, err := runner.Next(r.ctx) if err != nil { t.Fatal(err) } switch f.Type { case wire.FrameMessage: return f case wire.FrameAttachment: runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) case wire.FrameAck: default: t.Fatalf("unexpected frame %s", f.Type) } } } // TestBrowserInstantThinkingQueued: while one turn runs, a second message // queues a turn behind it and a third joins that queued turn (the server // says so in its answer). The first send shows its line at once; the // queued ones show no line or timer of their own, only a quiet note under // the latest (Paul, 2026-11-11: ten stacked lines, "Did I push it too // hard?"). When the server has answered there is one line, the element // shown at the first send, and nothing is orphaned. func TestBrowserInstantThinkingQueued(t *testing.T) { r, runner := instantRig(t) p := instantPage(t, r) defer p.stop() p.check(sendNow+`('First thing.')`, "no line for the first send") p.check(`(()=>{window.__first=window.__line;return window.__release()})()`, "release the first") f := messageFrame(t, r, runner) runner.Send(r.ctx, "a-q1", wire.FrameAck, wire.Ack{ID: f.ID}) p.wait(`!window.__first.hasAttribute('data-optimistic')`, "the first turn adopted its line") first := eval[string](p, `window.__first.dataset.turn`) r.wait("first running", func(c *Conversation) bool { return c.Turns[first].State == wire.TurnRunning }) // queuedNow sends text and reports in the same task that the only line // is still the first's and the note is under this message. queuedNow := `(text=>{ const box=document.querySelector('#composer textarea');box.value=text;box.dispatchEvent(new Event('input')); document.querySelector('#composer').requestSubmit(); const lines=[...document.querySelectorAll('[equipo-thinking]')], notes=[...document.querySelectorAll('[data-queued]')]; return lines.length===1 && lines[0]===window.__first && notes.length===1 && notes[0].closest('[equipo-message="own"]').querySelector('[equipo-message-body]').textContent===text; })` p.check(queuedNow+`('And a second.')`, "a line of its own, or no note, for the second send") p.check(queuedNow+`('And a third.')`, "a line of its own, or no note, for the third send") p.check(`window.__held.length===2`, "both sends held") p.check(`window.__release()`, "release the second") p.wait(`window.__answered===2`, "the second answered") p.check(`window.__release()`, "release the third") p.wait(`window.__answered===3`, "the third answered") 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") lines := `[...document.querySelectorAll('[equipo-thinking]')].map(l=>(l===window.__first?'first:':'')+l.dataset.turn).join(' ')` if got := eval[string](p, lines); got != "first:"+first { t.Fatalf("lines %q, want only the first's for turn %s", got, first) } snap, err := r.client.Snapshot(r.ctx) if err != nil { t.Fatal(err) } if len(snap.Turns) != 2 { t.Fatalf("the third message did not join the queued turn: %+v", snap.Turns) } var second string for _, v := range snap.Turns { if v.ID != first { second = v.ID } } // The first replies: the queued turn's line comes, the note goes. runner.Send(r.ctx, "r-q1", wire.FrameReply, wire.Reply{TurnID: first, Attempt: 1, Text: "First done."}) 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") // The batch of two fails for no reason given: its note says these // messages, from the event and then the server. bf := messageFrame(t, r, runner) runner.Send(r.ctx, "a-q2", wire.FrameAck, wire.Ack{ID: bf.ID}) runner.Send(r.ctx, "f-q2", wire.FrameTurn, wire.TurnReport{TurnID: second, Attempt: 1, State: wire.TurnFailed, Reason: ""}) p.wait(`(document.querySelector('[data-ended=`+jsString(second)+`] p')||{}).textContent===`+jsString("The coordinator could not answer these messages."), "the failed batch's note") p.stayed("queued sends") }