package thintest import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "math/big" "net/http" "net/http/httptest" "net/netip" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/chat" "amadan.net/oficina/equipo/internal/websearch" "amadan.net/oficina/equipo/internal/websearch/websearchtest" "amadan.net/oficina/equipo/internal/websource/guard" "amadan.net/oficina/equipo/internal/wire" ) // Lookups end to end (spec 2026-11-26-assistant-abilities ยง10.1): a fake // search backend, fake pages behind the guard's TestDial, and the // person's model on the fake runner answering the two steps. type confirmedNet struct{} func (confirmedNet) Ready(context.Context) error { return nil } func (confirmedNet) Inside(netip.Addr) bool { return false } // lookupWeb is the public web: one TLS server for every page host. type lookupWeb struct { srv *httptest.Server roots *x509.CertPool mu sync.Mutex got []string } func startLookupWeb(t *testing.T) *lookupWeb { t.Helper() key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) tmpl := &x509.Certificate{SerialNumber: big.NewInt(3), Subject: pkix.Name{CommonName: "web"}, DNSNames: []string{"www.met.ie", "www.museum.ie"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true} der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) cert, _ := x509.ParseCertificate(der) w := &lookupWeb{roots: x509.NewCertPool()} w.roots.AddCert(cert) w.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { w.mu.Lock() w.got = append(w.got, r.Host+r.URL.Path) w.mu.Unlock() rw.Header().Set("Content-Type", "text/html") _, _ = rw.Write([]byte("" + r.Host + "

Rain at first, then sun. Highs of 11 degrees. Open 10:00 to 17:00.

")) })) w.srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} w.srv.StartTLS() t.Cleanup(w.srv.Close) return w } // lookupRig is a team rig at protocol 36 whose Base draws answers, with // lookups configured on the instance. type lookupE2E struct { *teamRig search *websearchtest.Fake web *lookupWeb mu sync.Mutex steps []wire.LookupStep } func newLookupE2E(t *testing.T, protocol int, draws bool) *lookupE2E { t.Helper() o := &lookupE2E{teamRig: newTeamRigAt(t, protocol), search: &websearchtest.Fake{Backend: "kagi", Results: map[string][]websearch.Result{ "dublin weather": {{Title: "Dublin forecast", URL: "https://www.met.ie/dublin"}}, "dublin weather tomorrow": {{Title: "Dublin tomorrow", URL: "https://www.met.ie/dublin/tomorrow"}}, "national museum dublin": {{Title: "National Museum", URL: "https://www.museum.ie/visit"}}, }}, web: startLookupWeb(t)} if draws { o.client.Capabilities = wire.CapLookupAnswers } if _, err := o.a.PutTimeZone(o.ctx, "Europe/Dublin"); err != nil { t.Fatal(err) } if _, err := o.a.Snapshot(o.ctx); err != nil { t.Fatal(err) } g := guard.Config{Inventory: confirmedNet{}, Resolve: func(context.Context, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil }, TestDial: func(string) (string, *x509.CertPool) { return o.web.srv.Listener.Addr().String(), o.web.roots }} pageCfg := g pageCfg.Policy, pageCfg.Redirects = guard.PolicyLookupPage, guard.MaxRedirects pages, err := guard.New(pageCfg) if err != nil { t.Fatal(err) } o.inst.Store.Chat().SetLookups(&chat.LookupConfig{Search: websearch.Chain{Primary: o.search, Usage: &websearchtest.MemUsage{Caps: map[string]int{"kagi": 100}, Month: "2026-11"}}, Pages: pages, Inventory: confirmedNet{}}) o.lookupAnswer = func(s wire.LookupStep) wire.LookupResult { o.mu.Lock() o.steps = append(o.steps, s) o.mu.Unlock() q := strings.ToLower(s.Pack.Question) if s.Stage == wire.LookupStageQuery { switch { case strings.Contains(q, "museum"): return wire.LookupResult{Queries: []string{"national museum dublin"}} case strings.Contains(q, "tomorrow"): return wire.LookupResult{Queries: []string{"dublin weather tomorrow"}} } return wire.LookupResult{Queries: []string{"dublin weather"}} } if strings.Contains(q, "museum") { return wire.LookupResult{Answer: "It's open 10:00 to 17:00.", Used: []int{0}} } return wire.LookupResult{Answer: "Rain at first, then sun. Highs of 11 degrees.", Used: []int{0}} } return o } // look asks and runs web_lookup in the turn, ending it with a reply; // it returns the lookup's tool result and the reply as read now. func (o *lookupE2E) lookUp(words string) (wire.ToolResult, wire.Message) { o.t.Helper() o.ask(words) res := o.use("wl-"+itoa(len(o.runner.Sent)), "web_lookup", map[string]any{}) o.reply(o.turn) return res, o.replyOf(o.turn) } func (o *lookupE2E) replyOf(turn string) wire.Message { o.t.Helper() var reply wire.Message o.wait("the reply", func(*Conversation) bool { snap, err := o.a.Snapshot(o.ctx) if err != nil { o.t.Fatal(err) } for _, m := range snap.Messages { if m.TurnID == turn && m.Role == wire.RoleAssistant { reply = m } } return reply.ID != "" }) return reply } // "What's the weather in Dublin?": a forecast under the reply, with its // source, and the Assistant told only that it was shown. func TestWeatherDublinGetsForecast(t *testing.T) { o := newLookupE2E(t, wire.ProtocolLookup, true) res, reply := o.lookUp("What's the weather in Dublin?") if res.IsError || res.Code != "used" || !strings.Contains(res.Text, `"code":"shown"`) || strings.Contains(res.Text, "Rain") { t.Fatalf("result %+v", res) } if len(reply.Lookups) != 1 || !strings.Contains(reply.Lookups[0].Answer, "11 degrees") || reply.Lookups[0].Sources[0].URL != "https://www.met.ie/dublin" { t.Errorf("reply %+v", reply) } o.mu.Lock() defer o.mu.Unlock() if len(o.steps) != 2 || o.steps[0].Pack.City != "Dublin" || o.steps[0].Pack.Earlier != nil || len(o.steps[1].Pages) != 1 { t.Errorf("steps %+v", o.steps) } } // "And tomorrow?" after it: the query writer sees the earlier question. func TestAndTomorrowUsesEarlierQuestion(t *testing.T) { o := newLookupE2E(t, wire.ProtocolLookup, true) o.lookUp("What's the weather in Dublin?") _, reply := o.lookUp("And tomorrow?") o.mu.Lock() query := o.steps[2] o.mu.Unlock() if query.Stage != wire.LookupStageQuery || len(query.Pack.Earlier) != 1 || query.Pack.Earlier[0] != "What's the weather in Dublin?" { t.Errorf("pack %+v", query.Pack) } if len(reply.Lookups) != 1 || reply.Lookups[0].Sources[0].URL != "https://www.met.ie/dublin/tomorrow" { t.Errorf("reply %+v", reply.Lookups) } } // With web off: refused in one line naming who can turn it on, and not // offered. func TestWebOffOneLineNamesOwner(t *testing.T) { o := newLookupE2E(t, wire.ProtocolLookup, true) o.setBoard(wire.AbilityWeb) o.ask("What's the weather in Dublin?") res := o.use("wo", "web_lookup", map[string]any{}) if !res.IsError || res.Code != wire.CodeAbilityOff || !strings.Contains(res.Text, "Paul") { t.Errorf("result %+v", res) } if look := o.tool("wo-look", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(look.Text, "web_lookup") { t.Errorf("offered with web off: %s", look.Text) } if len(o.web.got) != 0 || o.search.Asked() != 0 { t.Error("something went out") } } // A museum's opening hours, then "put it in my calendar": the Assistant // never saw the answer, so it is told to ask for what it needs. func TestMuseumThenCalendarAsksForTime(t *testing.T) { o := newLookupE2E(t, wire.ProtocolLookup, true) res, reply := o.lookUp("When is the National Museum in Dublin open?") if len(reply.Lookups) != 1 || !strings.Contains(reply.Lookups[0].Answer, "10:00") { t.Fatalf("reply %+v", reply) } if strings.Contains(res.Text, "10:00") || !strings.Contains(res.Text, "Tell me the day and time") { t.Errorf("the Assistant's result %s", res.Text) } } // A runner below 36: web_lookup isn't offered, and the reply is as today. func TestStep3WithOldRunner(t *testing.T) { o := newLookupE2E(t, wire.ProtocolChangeDiffs, true) o.ask("What's the weather in Dublin?") if look := o.tool("or-look", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(look.Text, "web_lookup") { t.Errorf("offered at 35: %s", look.Text) } if res := o.use("or", "web_lookup", map[string]any{}); !res.IsError { t.Errorf("ran at 35: %+v", res) } } // A Base that can't draw answers: web_lookup isn't offered; an answer // already in the history reads as plain text for it. func TestStep3WithOldNative(t *testing.T) { o := newLookupE2E(t, wire.ProtocolLookup, true) o.lookUp("What's the weather in Dublin?") o.client.Capabilities = "" if _, err := o.a.Snapshot(o.ctx); err != nil { t.Fatal(err) } reply := o.replyOf(o.turn) if reply.Lookups != nil || !strings.Contains(reply.Text, "11 degrees") || !strings.Contains(reply.Text, "https://www.met.ie/dublin") { t.Errorf("history for an older client %+v", reply) } o.ask("And tomorrow?") if look := o.tool("on-look", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(look.Text, "web_lookup") { t.Errorf("offered to a Base that can't draw it: %s", look.Text) } }