oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "context"
5 "crypto/ecdsa"
6 "crypto/elliptic"
7 "crypto/rand"
8 "crypto/tls"
9 "crypto/x509"
10 "crypto/x509/pkix"
11 "math/big"
12 "net/http"
13 "net/http/httptest"
14 "net/netip"
15 "strings"
16 "sync"
17 "testing"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/equipo/chat"
21 "amadan.net/oficina/equipo/internal/websearch"
22 "amadan.net/oficina/equipo/internal/websearch/websearchtest"
23 "amadan.net/oficina/equipo/internal/websource/guard"
24 "amadan.net/oficina/equipo/internal/wire"
25)
26
27// Lookups end to end (spec 2026-11-26-assistant-abilities §10.1): a fake
28// search backend, fake pages behind the guard's TestDial, and the
29// person's model on the fake runner answering the two steps.
30
31type confirmedNet struct{}
32
33func (confirmedNet) Ready(context.Context) error { return nil }
34func (confirmedNet) Inside(netip.Addr) bool { return false }
35
36// lookupWeb is the public web: one TLS server for every page host.
37type lookupWeb struct {
38 srv *httptest.Server
39 roots *x509.CertPool
40 mu sync.Mutex
41 got []string
42}
43
44func startLookupWeb(t *testing.T) *lookupWeb {
45 t.Helper()
46 key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
47 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),
48 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true}
49 der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
50 cert, _ := x509.ParseCertificate(der)
51 w := &lookupWeb{roots: x509.NewCertPool()}
52 w.roots.AddCert(cert)
53 w.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
54 w.mu.Lock()
55 w.got = append(w.got, r.Host+r.URL.Path)
56 w.mu.Unlock()
57 rw.Header().Set("Content-Type", "text/html")
58 _, _ = rw.Write([]byte("<html><title>" + r.Host + "</title><body><p>Rain at first, then sun. Highs of 11 degrees. Open 10:00 to 17:00.</p></body></html>"))
59 }))
60 w.srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}
61 w.srv.StartTLS()
62 t.Cleanup(w.srv.Close)
63 return w
64}
65
66// lookupRig is a team rig at protocol 36 whose Base draws answers, with
67// lookups configured on the instance.
68type lookupE2E struct {
69 *teamRig
70 search *websearchtest.Fake
71 web *lookupWeb
72 mu sync.Mutex
73 steps []wire.LookupStep
74}
75
76func newLookupE2E(t *testing.T, protocol int, draws bool) *lookupE2E {
77 t.Helper()
78 o := &lookupE2E{teamRig: newTeamRigAt(t, protocol), search: &websearchtest.Fake{Backend: "kagi", Results: map[string][]websearch.Result{
79 "dublin weather": {{Title: "Dublin forecast", URL: "https://www.met.ie/dublin"}},
80 "dublin weather tomorrow": {{Title: "Dublin tomorrow", URL: "https://www.met.ie/dublin/tomorrow"}},
81 "national museum dublin": {{Title: "National Museum", URL: "https://www.museum.ie/visit"}},
82 }}, web: startLookupWeb(t)}
83 if draws {
84 o.client.Capabilities = wire.CapLookupAnswers
85 }
86 if _, err := o.a.PutTimeZone(o.ctx, "Europe/Dublin"); err != nil {
87 t.Fatal(err)
88 }
89 if _, err := o.a.Snapshot(o.ctx); err != nil {
90 t.Fatal(err)
91 }
92 g := guard.Config{Inventory: confirmedNet{}, Resolve: func(context.Context, string) ([]netip.Addr, error) {
93 return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
94 }, TestDial: func(string) (string, *x509.CertPool) { return o.web.srv.Listener.Addr().String(), o.web.roots }}
95 pageCfg := g
96 pageCfg.Policy, pageCfg.Redirects = guard.PolicyLookupPage, guard.MaxRedirects
97 pages, err := guard.New(pageCfg)
98 if err != nil {
99 t.Fatal(err)
100 }
101 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{}})
102 o.lookupAnswer = func(s wire.LookupStep) wire.LookupResult {
103 o.mu.Lock()
104 o.steps = append(o.steps, s)
105 o.mu.Unlock()
106 q := strings.ToLower(s.Pack.Question)
107 if s.Stage == wire.LookupStageQuery {
108 switch {
109 case strings.Contains(q, "museum"):
110 return wire.LookupResult{Queries: []string{"national museum dublin"}}
111 case strings.Contains(q, "tomorrow"):
112 return wire.LookupResult{Queries: []string{"dublin weather tomorrow"}}
113 }
114 return wire.LookupResult{Queries: []string{"dublin weather"}}
115 }
116 if strings.Contains(q, "museum") {
117 return wire.LookupResult{Answer: "It's open 10:00 to 17:00.", Used: []int{0}}
118 }
119 return wire.LookupResult{Answer: "Rain at first, then sun. Highs of 11 degrees.", Used: []int{0}}
120 }
121 return o
122}
123
124// look asks and runs web_lookup in the turn, ending it with a reply;
125// it returns the lookup's tool result and the reply as read now.
126func (o *lookupE2E) lookUp(words string) (wire.ToolResult, wire.Message) {
127 o.t.Helper()
128 o.ask(words)
129 res := o.use("wl-"+itoa(len(o.runner.Sent)), "web_lookup", map[string]any{})
130 o.reply(o.turn)
131 return res, o.replyOf(o.turn)
132}
133
134func (o *lookupE2E) replyOf(turn string) wire.Message {
135 o.t.Helper()
136 var reply wire.Message
137 o.wait("the reply", func(*Conversation) bool {
138 snap, err := o.a.Snapshot(o.ctx)
139 if err != nil {
140 o.t.Fatal(err)
141 }
142 for _, m := range snap.Messages {
143 if m.TurnID == turn && m.Role == wire.RoleAssistant {
144 reply = m
145 }
146 }
147 return reply.ID != ""
148 })
149 return reply
150}
151
152// "What's the weather in Dublin?": a forecast under the reply, with its
153// source, and the Assistant told only that it was shown.
154func TestWeatherDublinGetsForecast(t *testing.T) {
155 o := newLookupE2E(t, wire.ProtocolLookup, true)
156 res, reply := o.lookUp("What's the weather in Dublin?")
157 if res.IsError || res.Code != "used" || !strings.Contains(res.Text, `"code":"shown"`) || strings.Contains(res.Text, "Rain") {
158 t.Fatalf("result %+v", res)
159 }
160 if len(reply.Lookups) != 1 || !strings.Contains(reply.Lookups[0].Answer, "11 degrees") || reply.Lookups[0].Sources[0].URL != "https://www.met.ie/dublin" {
161 t.Errorf("reply %+v", reply)
162 }
163 o.mu.Lock()
164 defer o.mu.Unlock()
165 if len(o.steps) != 2 || o.steps[0].Pack.City != "Dublin" || o.steps[0].Pack.Earlier != nil || len(o.steps[1].Pages) != 1 {
166 t.Errorf("steps %+v", o.steps)
167 }
168}
169
170// "And tomorrow?" after it: the query writer sees the earlier question.
171func TestAndTomorrowUsesEarlierQuestion(t *testing.T) {
172 o := newLookupE2E(t, wire.ProtocolLookup, true)
173 o.lookUp("What's the weather in Dublin?")
174 _, reply := o.lookUp("And tomorrow?")
175 o.mu.Lock()
176 query := o.steps[2]
177 o.mu.Unlock()
178 if query.Stage != wire.LookupStageQuery || len(query.Pack.Earlier) != 1 || query.Pack.Earlier[0] != "What's the weather in Dublin?" {
179 t.Errorf("pack %+v", query.Pack)
180 }
181 if len(reply.Lookups) != 1 || reply.Lookups[0].Sources[0].URL != "https://www.met.ie/dublin/tomorrow" {
182 t.Errorf("reply %+v", reply.Lookups)
183 }
184}
185
186// With web off: refused in one line naming who can turn it on, and not
187// offered.
188func TestWebOffOneLineNamesOwner(t *testing.T) {
189 o := newLookupE2E(t, wire.ProtocolLookup, true)
190 o.setBoard(wire.AbilityWeb)
191 o.ask("What's the weather in Dublin?")
192 res := o.use("wo", "web_lookup", map[string]any{})
193 if !res.IsError || res.Code != wire.CodeAbilityOff || !strings.Contains(res.Text, "Paul") {
194 t.Errorf("result %+v", res)
195 }
196 if look := o.tool("wo-look", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(look.Text, "web_lookup") {
197 t.Errorf("offered with web off: %s", look.Text)
198 }
199 if len(o.web.got) != 0 || o.search.Asked() != 0 {
200 t.Error("something went out")
201 }
202}
203
204// A museum's opening hours, then "put it in my calendar": the Assistant
205// never saw the answer, so it is told to ask for what it needs.
206func TestMuseumThenCalendarAsksForTime(t *testing.T) {
207 o := newLookupE2E(t, wire.ProtocolLookup, true)
208 res, reply := o.lookUp("When is the National Museum in Dublin open?")
209 if len(reply.Lookups) != 1 || !strings.Contains(reply.Lookups[0].Answer, "10:00") {
210 t.Fatalf("reply %+v", reply)
211 }
212 if strings.Contains(res.Text, "10:00") || !strings.Contains(res.Text, "Tell me the day and time") {
213 t.Errorf("the Assistant's result %s", res.Text)
214 }
215}
216
217// A runner below 36: web_lookup isn't offered, and the reply is as today.
218func TestStep3WithOldRunner(t *testing.T) {
219 o := newLookupE2E(t, wire.ProtocolChangeDiffs, true)
220 o.ask("What's the weather in Dublin?")
221 if look := o.tool("or-look", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(look.Text, "web_lookup") {
222 t.Errorf("offered at 35: %s", look.Text)
223 }
224 if res := o.use("or", "web_lookup", map[string]any{}); !res.IsError {
225 t.Errorf("ran at 35: %+v", res)
226 }
227}
228
229// A Base that can't draw answers: web_lookup isn't offered; an answer
230// already in the history reads as plain text for it.
231func TestStep3WithOldNative(t *testing.T) {
232 o := newLookupE2E(t, wire.ProtocolLookup, true)
233 o.lookUp("What's the weather in Dublin?")
234 o.client.Capabilities = ""
235 if _, err := o.a.Snapshot(o.ctx); err != nil {
236 t.Fatal(err)
237 }
238 reply := o.replyOf(o.turn)
239 if reply.Lookups != nil || !strings.Contains(reply.Text, "11 degrees") || !strings.Contains(reply.Text, "https://www.met.ie/dublin") {
240 t.Errorf("history for an older client %+v", reply)
241 }
242 o.ask("And tomorrow?")
243 if look := o.tool("on-look", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(look.Text, "web_lookup") {
244 t.Errorf("offered to a Base that can't draw it: %s", look.Text)
245 }
246}
247