//go:build browser package headless import ( "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" ) // canaryKey is an obviously fake TensorX key. const canaryKey = "tx-CANARY-not-a-real-key-CANARY-0123456789" // quiet says the runner received no frame of kind for a while. func (r *fakeRunner) quiet(t *testing.T, kind string, d time.Duration) { t.Helper() deadline := time.After(d) for { select { case in, ok := <-r.frames: if !ok { return } if in.frame.Type == kind { t.Fatalf("a %s frame reached the runner", kind) } case <-deadline: return } } } // Connectors spec §2.1 (S1, the browser test S2 adds): a TensorX key is // saved only once the person confirms "This key has a spending limit at // TensorX". Without it, the browser does not send the form; sent anyway // (the check stripped), the server refuses it; either way nothing is // stored and nothing is queued for the runner. With it, the connection // is made, the key card opens, and the key goes to the runner sealed in // the page, bound to TensorX's origin. func TestBrowserConnectionsMeteredLimitRequired(t *testing.T) { for _, width := range []int64{1280, 390} { t.Run(strconv.FormatInt(width, 10), func(t *testing.T) { inst := thintest.StartInstance(t) runner := dialFakeAt(t, inst, wire.ProtocolMetered) client := thintest.NewClient(inst.URL, inst.DeviceToken(t)) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600) t.Cleanup(p.stop) none := func(what string) { t.Helper() runner.quiet(t, wire.FrameConnect, 1500*time.Millisecond) list, err := client.Connections(t.Context()) if err != nil || len(list.Items) != 0 { t.Fatalf("%s: stored %+v %v", what, list.Items, err) } } p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-add-metered="tensorx"]') && !!window.EquipoSeal`)) p.check(`(()=>{window.__equipoStayed=true;document.querySelector('[data-add-metered="tensorx"] summary').click();return document.querySelector('[data-add-metered="tensorx"]').open})()`, "TensorX did not open") p.check(`(()=>{const box=document.querySelector('[data-limit-confirmed]');return box.required && !box.checked && box.closest('label').textContent.includes('This key has a spending limit at TensorX')})()`, "the confirmation is not there, required and unticked") connShotOn(t, p, "2026-11-12", "metered-confirm", width) // Unticked: the browser does not send it. p.check(`(()=>{document.querySelector('[data-metered-continue]').click();return !document.querySelector('[data-limit-confirmed]').checkValidity() && location.pathname==='/conversation/settings/connections/add'})()`, "Continue went on without the confirmation") none("unticked") p.check(stayed, "the page reloaded or navigated") // Sent anyway, the browser's check stripped: the server refuses. p.check(`(()=>{const box=document.querySelector('[data-limit-confirmed]');box.required=false;document.querySelector('[data-metered-continue]').click();return true})()`, "submit") p.run(waitLong(`!!document.querySelector('[data-metered-refused]') && document.querySelector('[data-metered-refused]').textContent.length>0 && !document.querySelector('[data-key-form]')`)) none("the check stripped") // Ticked: the connection is made and the key card opens. p.check(`(()=>{const d=document.querySelector('[data-add-metered="tensorx"]');d.open=true;const box=document.querySelector('[data-limit-confirmed]');box.checked=true;document.querySelector('[data-metered-continue]').click();return true})()`, "ticked") cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) if cmd.Kind != wire.KindAPIKey || cmd.Provider != wire.ProviderTensorX || cmd.Budget == nil { t.Fatalf("connect %+v", cmd) } list, err := client.Connections(t.Context()) if err != nil || len(list.Items) != 1 || list.Items[0].LimitConfirmedAt == nil { t.Fatalf("stored %+v %v", list.Items, err) } p.run(waitLong(`!!document.querySelector('[data-connecting][data-kind="api_key"] [data-key-form]')`)) p.check(recordPosts, "record posts") p.check(`(()=>{const f=document.querySelector('[data-key-field]');f.value=`+jsonString(canaryKey)+`;f.form.requestSubmit();return f.value===''})()`, "the key field was not cleared at once") p.run(waitLong(`window.__posts.length===1`)) p.check(`(()=>{const post=window.__posts[0];return post.url.endsWith('/secret') && !post.body.includes('CANARY') && !document.documentElement.outerHTML.includes('CANARY')})()`, "the request or the page holds the key") secret := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand) opened := runner.open(t, secret.Sealed) if opened.Secret != canaryKey || opened.Provider != wire.ProviderTensorX || opened.Endpoint != wire.APIKeyProviders[wire.ProviderTensorX].Endpoint || opened.ConnectionID != cmd.Connection || opened.Attempt != 1 { t.Fatalf("the opened payload: provider %q endpoint %q", opened.Provider, opened.Endpoint) } }) } } // goCanaryKey is an obviously fake OpenCode Go key. const goCanaryKey = "sk-go-CANARY-not-a-real-key-CANARY-0123456789" // Connectors spec §2.1's Go row and §4.2 (S5, as S2 did for TensorX): an // OpenCode Go key is saved only once the person confirms "This key has a // spending limit at OpenCode Go", and there is no pay-as-you-go // confirmation to give (Go stays metered, §0 decision 7). Without the // confirmation the browser does not send the form; sent anyway, the // server refuses it; either way nothing is stored or queued. With it the // connection is made on a protocol 17 runner, and the key goes to the // runner sealed in the page, bound to opencode.ai. func TestBrowserConnectionsOpenCodeGoLimitRequired(t *testing.T) { for _, width := range []int64{1280, 390} { t.Run(strconv.FormatInt(width, 10), func(t *testing.T) { inst := thintest.StartInstance(t) runner := dialFakeAt(t, inst, wire.ProtocolOpenCode) client := thintest.NewClient(inst.URL, inst.DeviceToken(t)) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600) t.Cleanup(p.stop) none := func(what string) { t.Helper() runner.quiet(t, wire.FrameConnect, 1500*time.Millisecond) list, err := client.Connections(t.Context()) if err != nil || len(list.Items) != 0 { t.Fatalf("%s: stored %+v %v", what, list.Items, err) } } const form = `document.querySelector('[data-add-metered="opencode-go"]')` p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!`+form+` && !!window.EquipoSeal`)) p.check(`(()=>{window.__equipoStayed=true;`+form+`.querySelector('summary').click();return `+form+`.open})()`, "OpenCode Go did not open") p.check(`(()=>{const box=`+form+`.querySelector('[data-limit-confirmed]');return box.required && !box.checked && box.closest('label').textContent.includes('This key has a spending limit at OpenCode Go') && !`+form+`.querySelector('[name="payg_off_confirmed"]')})()`, "the confirmation is not there, required and unticked, or a pay-as-you-go one is") connShotOn(t, p, "2026-11-12", "opencode-go-confirm", width) // Unticked: the browser does not send it. p.check(`(()=>{`+form+`.querySelector('[data-metered-continue]').click();return !`+form+`.querySelector('[data-limit-confirmed]').checkValidity() && location.pathname==='/conversation/settings/connections/add'})()`, "Continue went on without the confirmation") none("unticked") p.check(stayed, "the page reloaded or navigated") // Sent anyway, the browser's check stripped: the server refuses. p.check(`(()=>{const box=`+form+`.querySelector('[data-limit-confirmed]');box.required=false;`+form+`.querySelector('[data-metered-continue]').click();return true})()`, "submit") p.run(waitLong(`!!document.querySelector('[data-add-metered="opencode-go"] [data-metered-refused]') && !document.querySelector('[data-key-form]')`)) none("the check stripped") // Ticked: the connection is made and the key card opens. p.check(`(()=>{const d=`+form+`;d.open=true;d.querySelector('[data-limit-confirmed]').checked=true;d.querySelector('[data-metered-continue]').click();return true})()`, "ticked") cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) if cmd.Kind != wire.KindAPIKey || cmd.Provider != wire.ProviderOpenCodeGo || cmd.Billing != wire.BillingMetered || cmd.Budget == nil { t.Fatalf("connect %+v", cmd) } list, err := client.Connections(t.Context()) if err != nil || len(list.Items) != 1 || list.Items[0].LimitConfirmedAt == nil || list.Items[0].PaygOffConfirmedAt != nil || list.Items[0].Harness != wire.HarnessOpenCode { t.Fatalf("stored %+v %v", list.Items, err) } p.run(waitLong(`!!document.querySelector('[data-connecting][data-kind="api_key"] [data-key-form]')`)) p.check(recordPosts, "record posts") p.check(`(()=>{const f=document.querySelector('[data-key-field]');f.value=`+jsonString(goCanaryKey)+`;f.form.requestSubmit();return f.value===''})()`, "the key field was not cleared at once") p.run(waitLong(`window.__posts.length===1`)) p.check(`(()=>{const post=window.__posts[0];return post.url.endsWith('/secret') && !post.body.includes('CANARY') && !document.documentElement.outerHTML.includes('CANARY')})()`, "the request or the page holds the key") secret := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand) opened := runner.open(t, secret.Sealed) if opened.Secret != goCanaryKey || opened.Provider != wire.ProviderOpenCodeGo || opened.Endpoint != "https://opencode.ai:443" || opened.ConnectionID != cmd.Connection || opened.Attempt != 1 { t.Fatalf("the opened payload: provider %q endpoint %q", opened.Provider, opened.Endpoint) } }) } }