//go:build browser package headless import ( "context" "fmt" "os" "path/filepath" "strconv" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" "github.com/chromedp/chromedp" ) // Connections slice 1, gate 1d: the pages a person uses, in a browser. // waitLong is browsertest.Wait with room for a turn that moves // connection (two cold starts) to arrive. func waitLong(expression string) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { deadline := time.Now().Add(45 * time.Second) for { ok, err := chromedp.Evaluate[bool]("document.readyState === 'complete' && ("+expression+")")(ctx, target) if err == nil && ok { return nil } if time.Now().After(deadline) { return fmt.Errorf("waiting for %s (last evaluation: %v)", expression, err) } time.Sleep(50 * time.Millisecond) } }) } func connectionsPage(t *testing.T, inst *thintest.Instance) *page { t.Helper() cookie := inst.Cookie() p := openPage(t, inst.URL, cookie.Name, cookie.Value, 390, 844, false) t.Cleanup(p.stop) return p } // connShot writes docs/mockups/built/2026-11-08/conn--.png // when EQUIPO_CONN_SHOTS is set. func connShot(t *testing.T, p *page, name string, width int64) { t.Helper() connShotOn(t, p, "2026-11-08", name, width) } // connShotOn is connShot into docs/mockups/built//. func connShotOn(t *testing.T, p *page, day, name string, width int64) { t.Helper() if os.Getenv("EQUIPO_CONN_SHOTS") == "" { return } dir := filepath.Join("..", "..", "docs", "mockups", "built", day) if err := os.MkdirAll(dir, 0755); err != nil { t.Fatal(err) } var shot []byte p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { var err error shot, err = chromedp.FullScreenshot(90)(ctx, target) return err })) if err := os.WriteFile(filepath.Join(dir, "conn-"+name+"-"+strconv.FormatInt(width, 10)+".png"), shot, 0644); err != nil { t.Fatal(err) } } // stayed is true while the page is the one first loaded: a reload or a // navigation loses the mark. const stayed = `window.__equipoStayed === true && performance.getEntriesByType('navigation').length === 1` // A1 and A4: Add Codex shows its card at once (a loading line, then the // three steps with the code once), Copy copies, and the approval lands in // place, with no reload; Add Claude shows the link the runner's own // setup-token printed, and the code field. func TestBrowserConnectionsAdd(t *testing.T) { for _, width := range []int64{390, 1280} { t.Run(strconv.FormatInt(width, 10), func(t *testing.T) { _, inst, r := localEnv(t) r.start(t) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600) t.Cleanup(p.stop) p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]')`)) p.check(`(()=>{window.__equipoStayed=true;return true})()`, "mark") p.check(`!document.querySelector('meta[http-equiv="refresh"]')`, "the page refreshes itself") // The chooser: Claude, Codex and TensorX live, two more greyed. p.check(`(()=>{const c=document.querySelector('[equipo-conn-chooser]');return !!c && c.checkVisibility() && !document.querySelector('[data-add="codex"]').disabled && !document.querySelector('[data-add="claude"]').disabled && c.querySelectorAll('[equipo-conn-opt][disabled]').length===2 && !!c.querySelector('[data-add-metered="tensorx"]')})()`, "the chooser is not Claude, Codex and TensorX with two greyed") p.check(`(()=>{document.querySelector('[data-add="codex"]').click();return !!document.querySelector('[data-connecting][data-provider="codex"]')})()`, "no card the instant Codex is chosen") p.run(browsertest.Wait(`!!document.querySelector('[data-device-code]')`)) p.check(`(()=>{const card=document.querySelector('[data-connecting][data-provider="codex"]');const code=card.querySelector('[data-code]').textContent;const open=card.querySelector('[data-open-provider]');return /^FAKE-/.test(code) && card.textContent.split(code).length===2 && open.getAttribute('href')==='https://auth.openai.com/codex/device' && open.target==='_blank' && !card.textContent.includes('auth.openai.com') && card.querySelectorAll('ol > li').length===3 && card.querySelector('h3').textContent==='Connect Codex'})()`, "the device code card is not the three steps with the code once") connShot(t, p, "codex-code", width) p.check(`(()=>{document.querySelector('[data-device-code] [data-copy]:not([data-copy-link])').click();return true})()`, "Copy") p.run(browsertest.Wait(`document.querySelector('[data-device-code] [data-copy]:not([data-copy-link])').textContent==='Copied'`)) // The approval lands with the success card, then Connections // with the new row. p.check(stayed, "the page reloaded or navigated while the code was shown") writeJSON(t, filepath.Join(r.root, "accounts", ".fake-device.json"), map[string]any{"email": second, "plan": "pro"}) p.run(waitLong(`location.pathname==='/conversation/settings/connections' && [...document.querySelectorAll('[equipo-conn-row][data-provider="codex"]')].some(e=>!e.hidden && e.querySelector('[data-connection-state]').textContent==='Ready' && e.textContent.includes('` + second + `'))`)) connShot(t, p, "codex-connected", width) // Prefer Codex: pressed at once, and still after the stream's refresh. p.check(`(()=>{document.querySelector('[data-prefer="codex"]').click();return document.querySelector('[data-prefer="codex"]').getAttribute('aria-pressed')==='true'})()`, "Prefer Codex") p.run(waitLong(`document.querySelector('[data-prefer="codex"]').getAttribute('aria-pressed')==='true' && !!document.querySelector('[equipo-conn-row][data-provider="codex"] [equipo-conn-pref]')`)) // Claude: the real runner starts its own sign-in (the fake // setup-token) and the card shows the link it printed. p.check(`(()=>{document.querySelector('[data-add-link]').click();return true})()`, "Add a connection") p.run(waitLong(`location.pathname==='/conversation/settings/connections/add' && !!document.querySelector('[equipo-conn-chooser] [data-add="claude"]')`)) p.check(`(()=>{window.__equipoStayed=true;document.querySelector('[data-add="claude"]').click();return !!document.querySelector('[data-connecting][data-provider="claude"]')})()`, "no card the instant Claude is chosen") p.run(waitLong(`!!document.querySelector('[data-code-steps]')`)) p.check(`(()=>{const open=document.querySelector('[data-code-steps] [data-open-anthropic]');const u=new URL(open.href);return u.host==='claude.com' && u.searchParams.get('redirect_uri')==='`+wire.EndpointClaudeCode+`' && open.target==='_blank' && !!document.querySelector('[data-code-field]') && !document.querySelector('[data-finish-on],[data-same-machine]')})()`, "the sign-in card is not the runner's link with the code field") connShot(t, p, "claude-sign-in", width) p.check(`(()=>{document.querySelector('[data-connecting][data-provider="claude"] [data-connection-cancel]').click();return true})()`, "Cancel") p.run(waitLong(`!document.querySelector('[data-connecting]') && !!document.querySelector('[equipo-conn-chooser]')`)) p.check(stayed, "the page reloaded or navigated") p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections"), browsertest.Wait(`!!document.querySelector('[equipo-conn-row]')`)) p.check(`(()=>{window.__equipoStayed=true;return true})()`, "mark") // Signed out: one clear Connect again in the row's action column, // full width under the state line at 390, the usage under it. p.check(`(()=>{document.querySelector('[equipo-conn-row][data-provider="codex"] [data-sign-out]').click();return true})()`, "Sign out") p.run(waitLong(`!!document.querySelector('[equipo-conn-row][data-provider="codex"][data-state="signed_out"] [data-recover]')`)) p.check(`(()=>{const row=document.querySelector('[equipo-conn-row][data-state="signed_out"]');const b=row.querySelector('[data-recover]').getBoundingClientRect(),u=row.querySelector('[equipo-conn-usage]').getBoundingClientRect(),r=row.getBoundingClientRect();const visible=getComputedStyle(row.querySelector('[data-recover]')).opacity==='1';return visible && b.bottom<=u.top+1 && (`+strconv.FormatBool(width < 600)+` ? b.width>r.width*0.7 : Math.abs(b.right-u.right)<2)})()`, "the recovery button is not in the action column with the usage under it") connShot(t, p, "signed-out", width) p.check(stayed, "the page reloaded or navigated") }) } } // Paul, 2026-11-08: turns that wait for a connection show no thinking // line and no timer, live or after a reload: a quiet status under each // waiting message and one card for the conversation; once a connection // is added they run, in order. func TestBrowserWaitingTurns(t *testing.T) { env, inst, r := localEnv(t) r.start(t) c := inst.Cookie() const quiet = `document.querySelectorAll('[equipo-thinking]').length===0 && document.querySelectorAll('[data-no-connection]').length===1 && document.querySelectorAll('[data-waiting-connection]').length===%d && [...document.querySelectorAll('[data-waiting-connection]')].every(e=>e.textContent==='Waiting for a connection') && !document.body.textContent.includes('Thinking')` p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) t.Cleanup(p.stop) p.send("Can we work on the shop? limit:" + thintest.Owner) p.run(waitLong(fmt.Sprintf(quiet, 1))) p.send("And the docs after that.") p.run(waitLong(fmt.Sprintf(quiet, 2))) // The card stands after the last waiting message. p.check(`(()=>{const own=[...document.querySelectorAll('[equipo-message="own"]')];return !!(own[own.length-1].compareDocumentPosition(document.querySelector('[data-no-connection]'))&4)})()`, "the card is not after the last waiting message") time.Sleep(1500 * time.Millisecond) p.check(fmt.Sprintf(quiet, 2), "a thinking line or a timer came back") p.run(chromedp.Reload(), browsertest.Wait(`!!document.querySelector('[data-chat-stream]')`)) p.check(fmt.Sprintf(quiet, 2), "after a reload, a waiting turn shows a thinking line, or not one card") connShot(t, p, "waiting", 1280) small := openPage(t, inst.URL, c.Name, c.Value, 390, 844, false) t.Cleanup(small.stop) small.check(fmt.Sprintf(quiet, 2), "at 390, a waiting turn shows a thinking line, or not one card") connShot(t, small, "waiting", 390) // A connection arrives: both turns start on their own, in order. writeJSON(t, filepath.Join(r.root, "accounts", ".fake-device.json"), map[string]any{"email": "third@example.com", "plan": "pro"}) if _, err := env.Client.Connect(t.Context(), wire.Connect{Provider: "codex"}); err != nil { t.Fatal(err) } p.run(waitLong(`!document.querySelector('[data-no-connection]') && !document.querySelector('[data-waiting-connection]') && document.querySelectorAll('[equipo-message="incoming"]:not([equipo-thinking])').length>=2 && document.querySelectorAll('[equipo-thinking]').length===0`)) p.check(`(()=>{const own=[...document.querySelectorAll('[equipo-message="own"]')].map(e=>e.dataset.turnId);const replies=[...document.querySelectorAll('[equipo-message="incoming"]:not([equipo-thinking])')].map(e=>e.dataset.turnId).filter(id=>own.includes(id));return replies.length===2 && replies[0]===own[0] && replies[1]===own[1]})()`, "the waiting turns did not answer in order") } // F1 and F7 on the conversation page: the switched line under a reply // that moved connection, and the waiting card that turns into the reply // once a connection is added, without a reload. func TestBrowserConnectionsConversation(t *testing.T) { env, inst, r := localEnv(t) r.addAccount(t, "claude", "claude-2", second) r.start(t) p := connectionsPage(t, inst) p.send("Hello. limit:" + thintest.Owner) p.run(waitLong(`!!document.querySelector('[data-switched]') && document.querySelector('[data-switched]').textContent.startsWith('Switched to Claude')`)) // F7: claude-2 limited too; nothing can answer. p.send("Again. limit:" + second) p.run(waitLong(`!!document.querySelector('[data-no-connection]') && document.querySelector('[data-no-connection]').textContent.includes('Nothing can answer right now.') && !!document.querySelector('[data-add-connection]')`)) p.check(`!document.body.textContent.includes('Send your message again')`, "the old retry line is shown") writeJSON(t, filepath.Join(r.root, "accounts", ".fake-device.json"), map[string]any{"email": "third@example.com", "plan": "pro"}) ctx := t.Context() c, err := env.Client.Connect(ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } _ = c p.run(waitLong(`!document.querySelector('[data-no-connection]') && [...document.querySelectorAll('[data-switched]')].some(e=>e.textContent.startsWith('Switched to Codex'))`)) var _ = time.Second }