gateway: a search API's or plan service's ask is routed and archived (axelburks)

axelburks on Discord: when magpie searches for a model through a search
API, the Routing page doesn't say which API answered, and Usage →
Requests lists the row but has no request archive, so the request and
response sent to the API can't be seen.

A model's search (searchWith) was already routed and archived. A search
API's ask (askSearchAPIKeys, a plugin's search hook, a signed-in search
API) and a plan's own search service (Kimi Code, GLM Coding Plan,
WorkBuddy, Codex's searchBy, and searchBy's Kimi branch, which wrote no
row at all before) only wrote a usage row.

Now every ask that writes a row goes through keepSearch
(search_archive.go): a done web_search route, agent magpie, For the
agent searched for, the API's name as model and its host as provider,
seated on the masked key or account; a Recent call with ring-cut
bodies; and with the request archive on, archiveOwn of the exchange as
sent. The row gets RouteID and Archive, which the Requests tab already
opens. Each ask has a searchWire in its context, filled where it is sent
(tapSearch tees the answer as read; the last exchange stands, so GLM's
MCP tools/call is the one kept). A plugin's search is noted as what
magpie handed the hook (key masked) and what came back (PLUGIN method).
The key is replaced by MaskSearchKey in path, query, headers and both
bodies before anything is kept; the archive's own scrub runs on top.
Bodies are kept up to RequestArchiveMaxMB (longer marked cut); archive
off keeps nothing on disk, the route and Recent call stay.

Run (mote's disk filled mid-work, see below; the rest on WSL
magpie-desktop via wsl-run):
- mote-run: go test -run 'Search|Archive' ./internal/gateway ok; GUI
  usage-ledger-search, routing-side-calls, request-archive-usage in
  chromium+webkit, every language and width: 38 pass.
- wsl-run: go test -run 'Search|Archive' ./internal/gateway ok; go vet
  ./internal/gateway ok; GOOS=windows go vet ./internal/gateway
  ./internal/gui ok; GOOS=darwin CGO_ENABLED=0 go vet ./internal/gateway
  ok; GUI usage-ledger-search, routing-side-calls, request-archive-usage,
  search-instead, search-mcp in both engines: 68 pass, 0 fail.
- gofmt -l clean.

Broken by hand: keepSearch's call commented out turns all five new
gateway tests red; taken()'s key masking turned off turns
TestSearchAPIAskIsRoutedAndArchived and TestSearchAPIKeyInQueryNotArchived
red. TestSearchRowKeepsRouteAndArchive (internal/gui) is a guard that the
row's RouteID and Archive reach /api/usage/requests; it passed on the
old code too.

Not tried: real Tavily/Brave/Kimi/GLM/WorkBuddy/Codex accounts (httptest
stubs only); Linux go vet of internal/gui (WSL lacks gtk4/webkitgtk);
web_fetch (search_fetch.go) and a vendor's own search (search_native.go),
which magpie doesn't send, are unchanged. Full suite runs after the push.
No GUI asset, API call or i18n string changed.
This commit is contained in:
yetone
2026-11-05 12:40:35 +08:00
parent 1826c4bd99
commit 73c98ebc20
12 changed files with 648 additions and 34 deletions
+31 -2
View File
@@ -1648,8 +1648,37 @@ page's Requests tab badges one "Search API" with the host and masked key
where the provider goes. A searcher model's request is a model row of its
own, as before. A plan's own search service (Kimi Code's, a GLM Coding Plan's, WorkBuddy's:
`ownSearch`, through `logOwnSearch`) is a row the same way, under the
plan's provider id and name, badged "Web search". Not covered: the
Routing page, which lists only requests through `serve`.
plan's provider id and name, badged "Web search".
Each such ask is on the Routing page and in Recent calls too, with its
exchange in the request archive when that is on (axelburks on Discord:
the Routing page didn't say which API answered, and the row had no
archive). `logSearch` calls `keepSearch` in
[`search_archive.go`](../../internal/gateway/search_archive.go) before
the row is written: a done route, agent `magpie` with `For` the agent
the search was for, `Kind` `web_search`, the API's or service's name as
the model and its host (a plan's provider id) as the provider, its seat
the masked key or the account. The row gets the route's id (`RouteID`)
and the archive's name (`Archive`), which the Requests tab opens. Each
ask runs with a `searchWire` in its context (`withSearchWire`, one per
key or account); the place that sends it fills it (`tapSearch`: the
request as signed, its body, and the answer as it is read, the last
exchange standing, so GLM's MCP search keeps its `tools/call`). A
plugin's search API is noted as magpie handed it to the plugin
(`notePluginSearch`, method `PLUGIN`, the key masked) and what came
back. The key an ask went with is replaced with its masked form in the
path, query, headers and both bodies before anything is kept (`taken`),
and the archive's own scrub takes Authorization and the like out as for
every call. Bodies are kept up to `RequestArchiveMaxMB` (a longer answer
is marked cut) and Recent calls keep their own 256 KiB; with the
archive off nothing is archived, but the route and Recent call are
still there. Covered by `TestSearchAPIAskIsRoutedAndArchived`,
`TestSearchAPIKeyInQueryNotArchived`, `TestPluginSearchAPIRoutedAndArchived`,
`TestKimiPlanSearchRoutedAndArchived`, `TestGLMPlanSearchArchivesItsToolsCall`,
`TestSearchRowKeepsRouteAndArchive` (internal/gui),
`usage-ledger-search.test.cjs` and `routing-side-calls.test.cjs`. Not
covered: `web_fetch` (`search_fetch.go`) and a vendor's own search
(`search_native.go`), which magpie doesn't send.
A search a provider's model runs with its provider's own tool is a row
the same way when its reply shows it (cybercaius on Discord: DeepSeek
+13 -5
View File
@@ -148,11 +148,12 @@ func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, que
for _, i := range searchKeyOrder(a, keys, time.Now()) {
one := a
one.Key = keys[i]
ctx, _ := withSearchWire(ctx, one.Key)
ctx, cancel := context.WithTimeout(ctx, searchTimeout/4)
start := time.Now()
pages, err := s.askSearchAPI(ctx, one, query)
cancel()
logSearchAPI(ctx, one, query, start, len(pages), err)
s.logSearchAPI(ctx, one, query, start, len(pages), err)
if err == nil {
wakeSearchKey(a.Vendor, keys[i])
return pages, nil
@@ -178,20 +179,22 @@ func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, que
// with one key (usage.SourceSearch; cybercaius on Discord: which search
// API each search used, and how much, couldn't be seen): the API by name,
// where it was asked, the key masked, how long it took and how it ended.
func logSearchAPI(ctx context.Context, a provider.SearchAPI, query string, start time.Time, found int, err error) {
func (s *Server) logSearchAPI(ctx context.Context, a provider.SearchAPI, query string, start time.Time, found int, err error) {
rec := usage.Record{Requested: a.Name(), Host: provider.HostOf(a.Base())}
if a.Key != "" {
rec.ProviderKeyID, rec.ProviderKeyName = searchKeyID(a.Vendor, a.Key), provider.MaskSearchKey(a.Key)
}
logSearch(ctx, rec, query, start, found, err)
s.logSearch(ctx, rec, query, start, found, err)
}
// logSearch writes rec, a search magpie ran with a search API or a plan's
// own search service, as the request log's row of it: the agent it was
// for, how long it took and how it ended (200, the API's refusal, the
// error, "found nothing"). The query is never kept, nor said in the
// error: the row may go to another computer the usage syncs with.
func logSearch(ctx context.Context, rec usage.Record, query string, start time.Time, found int, err error) {
// error: the row may go to another computer the usage syncs with. The
// ask is a request of the Routing page's and Recent calls', its exchange
// kept by the request archive when it is on (keepSearch).
func (s *Server) logSearch(ctx context.Context, rec usage.Record, query string, start time.Time, found int, err error) {
rec.Time, rec.Agent, rec.Kind, rec.Source = start, "magpie", "web_search", usage.SourceSearch
rec.Millis = time.Since(start).Milliseconds()
if f := searchFor(ctx); f != nil && f.Agent != "" {
@@ -223,6 +226,7 @@ func logSearch(ctx context.Context, rec usage.Record, query string, start time.T
default:
rec.Status = http.StatusOK
}
s.keepSearch(ctx, &rec, start)
budget.Append(rec)
}
@@ -270,8 +274,10 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s
}
var r *http.Request
var err error
var sent []byte
post := func(path string, body any) {
b, _ := json.Marshal(body)
sent = b
if r, err = http.NewRequestWithContext(ctx, http.MethodPost, a.Base()+path, bytes.NewReader(b)); err == nil {
r.Header.Set("Content-Type", "application/json")
}
@@ -358,6 +364,7 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s
return nil
}
res, err := c.Do(r)
res = tapSearch(ctx, r, sent, res)
if err != nil {
if ctx.Err() != nil {
return nil, errors.New("no answer in time")
@@ -424,6 +431,7 @@ var runPluginSearch = plugin.RunSearch
// found is cut and cleaned as a built-in's pages are.
func (s *Server) askPluginSearch(ctx context.Context, a provider.SearchAPI, v provider.SearchVendor, query string) ([]foundPage, error) {
got, err := runPluginSearch(ctx, v.Plugin, v.PluginID, query, searchHits, a.Key, a.Base())
notePluginSearch(ctx, v.Plugin, pluginSearchAsked(v, query, a.Base(), a.Key, ""), got, err)
if err != nil {
var r plugin.SearchRefused
if errors.As(err, &r) {
+222
View File
@@ -0,0 +1,222 @@
package gateway
import (
"cmp"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// A search magpie runs with a search API or a plan's own search service
// is a request of magpie's own, as a model's search is (searchWith): the
// Routing page lists it, naming the API or service and the key or account
// it went with, Recent calls keeps its request and response, and with the
// request archive on they are kept as a client's are, its usage row naming
// them (axelburks on Discord: 搜索API代搜时 路由页面不显示是请求了哪个API…
// 用量-请求 页面 能看到请求记录 但是无请求存档). Every ask that writes a usage
// row (logSearch) has its exchange in a searchWire, put in its context
// before it is sent, which the place that sends it fills (tapSearch).
type searchWireKey struct{}
// searchWire is one ask's exchange as it went: the request with the
// headers it was signed with and its body, and the answer's status,
// headers and body, as much of it as was read. secret is the key it was
// asked with, which is never kept: it is masked out of all of it.
type searchWire struct {
mu sync.Mutex
sent *http.Request
body []byte
status int
head http.Header
answer []byte
cut bool // more of the answer came than was kept
limit int
secret string
}
// withSearchWire is ctx for one ask of a search, with key the key it is
// asked with ("" for none or an account's sign-in, which goes in headers
// alone). A body is kept up to the archive's size (RequestArchiveMaxMB),
// and at least what Recent calls keeps.
func withSearchWire(ctx context.Context, key string) (context.Context, *searchWire) {
w := &searchWire{limit: int(max(archiveLimit(), callBodyLimit)) + 1, secret: key}
return context.WithValue(ctx, searchWireKey{}, w), w
}
func searchWireOf(ctx context.Context) *searchWire {
w, _ := ctx.Value(searchWireKey{}).(*searchWire)
return w
}
// tapSearch notes r, sent with body, and res, its answer (nil when none
// came), as ctx's ask's exchange, the last one it sent standing (GLM's
// MCP search sends three: its tools/call is the search); res's body is
// kept as it is read. Without a wire in ctx it does nothing.
func tapSearch(ctx context.Context, r *http.Request, body []byte, res *http.Response) *http.Response {
w := searchWireOf(ctx)
if w == nil || r == nil {
return res
}
w.mu.Lock()
defer w.mu.Unlock()
w.sent, w.body = r, body[:min(len(body), w.limit)]
w.status, w.head, w.answer, w.cut = 0, nil, nil, false
if res != nil {
w.status, w.head = res.StatusCode, res.Header.Clone()
res.Body = &searchTee{ReadCloser: res.Body, w: w}
}
return res
}
// searchTee keeps what is read of a search's answer in its wire.
type searchTee struct {
io.ReadCloser
w *searchWire
}
func (t *searchTee) Read(p []byte) (int, error) {
n, err := t.ReadCloser.Read(p)
if n > 0 {
w := t.w
w.mu.Lock()
room := w.limit - len(w.answer)
w.answer = append(w.answer, p[:min(n, max(room, 0))]...)
w.cut = w.cut || n > room
w.mu.Unlock()
}
return n, err
}
// notePluginSearch notes, as ctx's ask's exchange, an ask of a plugin's
// search API, which the plugin host sends: what magpie handed the plugin
// (asked, pluginSearchAsked) and what it gave back, the pages it found or
// the error it threw, with the status of a refusal. The request the
// plugin itself made goes from the host, out of magpie's sight.
func notePluginSearch(ctx context.Context, spec string, asked map[string]any, got []plugin.SearchPage, err error) {
w := searchWireOf(ctx)
if w == nil {
return
}
status, answer := http.StatusOK, any(map[string]any{"results": got})
if err != nil {
status = 0
var r plugin.SearchRefused
if errors.As(err, &r) {
status = r.Status
}
answer = map[string]any{"error": err.Error(), "status": status}
}
body, _ := json.Marshal(asked)
b, _ := json.Marshal(answer)
r := &http.Request{Method: "PLUGIN", URL: &url.URL{Path: spec}, Header: http.Header{}}
w.mu.Lock()
defer w.mu.Unlock()
w.sent, w.body, w.status, w.head, w.answer, w.cut = r, body, status, http.Header{"Content-Type": {"application/json"}}, b, false
}
// pluginSearchAsked is what magpie hands a plugin's search hook, as its
// archive says it: the provider, the query, how many pages, the address
// set (when one is) and the key masked or the account it signs in as.
func pluginSearchAsked(v provider.SearchVendor, query, at, key, account string) map[string]any {
m := map[string]any{"hook": "search", "provider": v.PluginID, "query": query, "count": searchHits}
if at != "" {
m["url"] = at
}
if key != "" {
m["key"] = provider.MaskSearchKey(key)
}
if account != "" {
m["account"] = account
}
return m
}
// taken is the exchange with the key masked out of everything: the path
// and query, every header (Authorization and the like are scrubbed on
// the way to the archive anyway), and both bodies. ok is false when
// nothing was sent.
func (w *searchWire) taken() (sent *http.Request, body []byte, status int, head http.Header, answer []byte, cut bool, ok bool) {
if w == nil {
return
}
w.mu.Lock()
defer w.mu.Unlock()
if w.sent == nil {
return
}
mask := func(b []byte) []byte { return b }
if k := w.secret; len(k) >= 4 {
hidden := provider.MaskSearchKey(k)
mask = func(b []byte) []byte { return []byte(strings.ReplaceAll(string(b), k, hidden)) }
}
u := *w.sent.URL
u.Path, u.RawPath = string(mask([]byte(u.Path))), ""
u.RawQuery = string(mask([]byte(u.RawQuery)))
sent = &http.Request{Method: w.sent.Method, URL: &u, Header: http.Header{}}
for k, vs := range w.sent.Header {
for _, v := range vs {
sent.Header.Add(k, string(mask([]byte(v))))
}
}
head = http.Header{}
for k, vs := range w.head {
for _, v := range vs {
head.Add(k, string(mask([]byte(v))))
}
}
return sent, mask(w.body), w.status, head, mask(w.answer), w.cut, true
}
// keepSearch puts a search's ask, rec its usage row as logSearch made
// it, on the Routing page and in Recent calls, and with the request
// archive on keeps its exchange there, and gives the row the route and
// the archive's name.
func (s *Server) keepSearch(ctx context.Context, rec *usage.Record, start time.Time) {
if s == nil {
return
}
// who it went to, as the Routing page names a key or an account: the
// API or service, and the key, the account or, with neither, where it
// was asked
seat := Weighed{ID: cmp.Or(rec.ProviderKeyID, rec.Provider, rec.Requested), Provider: cmp.Or(rec.Provider, rec.Requested),
Name: rec.Requested, Who: cmp.Or(rec.ProviderKeyName, rec.ProviderAccount, rec.Host), Kind: "key", Model: rec.Requested}
if rec.ProviderAccount != "" {
seat.Kind = "account"
}
where := cmp.Or(rec.Provider, rec.Host, rec.Requested)
err := rec.Error
// magpie asked, as for a model's search; whose search it was is For
rt := Route{callerKey: access.Caller(ctx).KeyID, Time: start, Agent: "magpie", Kind: "web_search", For: searchFor(ctx),
Model: rec.Requested, Provider: where, Order: []Weighed{seat},
Tries: []Try{{ID: seat.ID, Model: seat.Model, Start: start, Done: true, Status: rec.Status, Millis: rec.Millis, Error: err}}}
tr := s.trace.begin(rt)
rec.RouteID = tr.ID
c := Call{Route: tr.ID, Time: start, Agent: rt.Agent, Kind: "web_search", For: rt.For, Model: rec.Requested,
Provider: where, Status: rec.Status, Millis: rec.Millis, Error: err}
if sent, body, status, head, answer, cut, ok := searchWireOf(ctx).taken(); ok {
if c.Status == 0 {
c.Status = status
}
rec.Archive = archiveOwn(c, sent, body, status, head, answer)
c.Archive = rec.Archive
c.RequestBody, c.RequestTruncated = captureRequestBody(body)
c.ResponseBody, c.ResponseTruncated = captureRequestBody(answer)
c.ResponseTruncated = c.ResponseTruncated || cut
s.record(c)
}
s.trace.update(tr, func(r *Route) {
r.Done, r.Status, r.Error, r.Millis, r.Archive = true, rec.Status, err, rec.Millis, rec.Archive
})
}
+271
View File
@@ -0,0 +1,271 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// searchRoute is the newest web_search route the Routing page lists.
func searchRoute(t *testing.T, s *Server) Route {
t.Helper()
routes := s.Trace(context.Background(), 0, 0).Routes
for i := len(routes) - 1; i >= 0; i-- {
if routes[i].Kind == "web_search" {
return routes[i]
}
}
t.Fatalf("no web_search route in %d", len(routes))
return Route{}
}
// noSecret fails when any archived object holds one of the secrets.
func noSecret(t *testing.T, b *memBucket, secrets ...string) {
t.Helper()
b.mu.Lock()
defer b.mu.Unlock()
for name, data := range b.objs {
for _, k := range secrets {
if strings.Contains(string(data), k) {
t.Errorf("%q in %s:\n%s", k, name, data)
}
}
}
}
// axelburks on Discord: 搜索API代搜时 路由页面不显示是请求了哪个API … 用量-请求
// 页面 能看到请求记录 但是无请求存档. A search magpie asks a search API for
// is a route of the Routing page naming the API and the key (masked), a
// Recent call with its request and answer, and, with the request archive
// on, an archive its usage row names, the key nowhere in it, even where
// the API says it back. Off, nothing is archived, and the route is still listed.
func TestSearchAPIAskIsRoutedAndArchived(t *testing.T) {
fresh(t)
const key = "tvly-dev-secret0123456789"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Echo-Key", key) // an API that says the key back
if !strings.Contains(string(b)+r.Header.Get("Authorization"), key) {
w.WriteHeader(401)
io.WriteString(w, `{"detail":{"error":"no key"}}`)
return
}
io.WriteString(w, `{"query":"x","results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"go1.27.1, key `+key+`","score":0.9}]}`)
}))
defer srv.Close()
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: key, URL: srv.URL}); err != nil {
t.Fatal(err)
}
b := &memBucket{objs: map[string][]byte{}}
archiveTo(t, b)
s := New()
ctx := context.WithValue(context.Background(), searchForKey{}, &CallFor{Agent: "claude"})
search := func() Route {
t.Helper()
if _, hits, err := s.apiSearch(ctx, "latest go"); err != nil || len(hits) != 1 {
t.Fatalf("%+v %v", hits, err)
}
archivePending.Wait()
return searchRoute(t, s)
}
r := search()
if len(b.objs) != 0 || r.Archive != "" {
t.Fatalf("archived while off: %v %q", keys(b.objs), r.Archive)
}
// the API by name, and where it was asked, as the usage row says them
host := provider.HostOf(srv.URL)
if r.Model != "Tavily" || r.Provider != host || r.Agent != "magpie" || r.For == nil || r.For.Agent != "claude" || !r.Done || r.Status != 200 ||
len(r.Order) != 1 || r.Order[0].Who != provider.MaskSearchKey(key) || r.Order[0].Kind != "key" {
t.Fatalf("route %+v", r)
}
c := s.Recent()[0]
if c.Route != r.ID || c.Kind != "web_search" || c.Provider != host || !strings.Contains(c.RequestBody, "latest go") ||
!strings.Contains(c.ResponseBody, "go.dev/dl") || strings.Contains(c.RequestBody+c.ResponseBody, key) {
t.Fatalf("recent %+v", c)
}
settings.Save(settings.Settings{RequestArchive: true})
r = search()
got := archivedOf(t, b)[host]
if len(got) != 1 || len(b.objs) != 1 {
t.Fatalf("uploaded %v", keys(b.objs))
}
noSecret(t, b, key)
a := got[0]
if r.Archive != a.ID || s.Recent()[0].Archive != a.ID || a.Request.Method != "POST" || a.Request.Path != "/search" ||
!strings.Contains(a.Request.Body, "latest go") ||
a.Response.Status != 200 || !strings.Contains(a.Response.Body, "go.dev/dl") || a.Call.Kind != "web_search" {
t.Errorf("archived %+v", a)
}
// the usage row names the route, and the archive once it is on
rows, _ := searchRows(t)
if len(rows) != 2 || rows[0].RouteID == 0 || rows[0].Archive != "" || rows[1].Archive != a.ID || rows[1].RouteID != r.ID {
t.Errorf("rows %+v", rows)
}
}
// An API asked by GET with its key in the address (and its answer cut
// at the archive's size) keeps neither the key nor more than the size.
func TestSearchAPIKeyInQueryNotArchived(t *testing.T) {
fresh(t)
const key = "BSAsecretkey0123456789"
big := strings.Repeat("x", 2<<20)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"web":{"results":[{"title":"Go","url":"https://go.dev/dl/","description":"`+big+`"}]}}`)
}))
defer srv.Close()
b := &memBucket{objs: map[string][]byte{}}
archiveTo(t, b)
st := settings.Settings{RequestArchive: true, RequestArchiveMaxMB: 1}
settings.Save(st)
ctx, w := withSearchWire(context.Background(), key)
r, _ := http.NewRequestWithContext(ctx, "GET", srv.URL+"/res/v1/web/search?q=go&key="+key, nil)
r.Header.Set("X-Subscription-Token", key)
res, err := http.DefaultClient.Do(r)
if err != nil {
t.Fatal(err)
}
res = tapSearch(ctx, r, nil, res)
io.Copy(io.Discard, res.Body)
res.Body.Close()
sent, _, _, _, answer, cut, ok := w.taken()
if !ok || strings.Contains(sent.URL.RawQuery, key) || strings.Contains(sent.Header.Get("X-Subscription-Token"), key) ||
!cut || len(answer) > 1<<20+1 {
t.Fatalf("taken %v %q %q cut %v %d", ok, sent.URL.RawQuery, sent.Header, cut, len(answer))
}
s := New()
s.logSearch(ctx, usage.Record{Requested: "Brave", Host: "api.search.brave.com"}, "go", time.Now(), 1, nil)
archivePending.Wait()
got := archivedOf(t, b)["api.search.brave.com"]
if len(got) != 1 || !got[0].Response.Truncated || !strings.HasPrefix(got[0].Request.Path, "/res/v1/web/search?") {
t.Fatalf("archived %v %+v", keys(b.objs), got)
}
noSecret(t, b, key)
}
// A plugin's search API is a route and an archive too: what magpie
// handed the plugin, its key masked, and the pages it gave back, or the
// refusal it threw.
func TestPluginSearchAPIRoutedAndArchived(t *testing.T) {
fresh(t)
const spec = "@acme/opencode-mojeek-search@1.0.0"
const id = "mojeek-search:mojeek"
plugged(t, spec, false)
t.Cleanup(forgetSearchKeys) // the refused key rests past the test otherwise
old := runPluginSearch
t.Cleanup(func() { runPluginSearch = old })
runPluginSearch = func(_ context.Context, _, _, _ string, _ int, key, _ string) ([]plugin.SearchPage, error) {
if key == "spent-key-0001" {
return nil, plugin.SearchRefused{Status: 429, Msg: "slow down"}
}
return []plugin.SearchPage{{Title: "Go downloads", URL: "https://go.dev/dl/", Text: "go1.27.1"}}, nil
}
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: id, Key: "spent-key-0001,good-key-0003"}); err != nil {
t.Fatal(err)
}
b := &memBucket{objs: map[string][]byte{}}
archiveTo(t, b)
settings.Save(settings.Settings{RequestArchive: true})
s := New()
if _, _, err := s.apiSearch(context.Background(), "latest go"); err != nil {
t.Fatal(err)
}
archivePending.Wait()
got := archivedOf(t, b)["Mojeek"]
if len(got) != 2 {
t.Fatalf("uploaded %v", keys(b.objs))
}
noSecret(t, b, "spent-key-0001", "good-key-0003")
var refused, found bool
for _, a := range got {
var asked map[string]any
json.Unmarshal([]byte(a.Request.Body), &asked)
if a.Request.Method != "PLUGIN" || a.Request.Path != spec || asked["query"] != "latest go" || asked["provider"] != "mojeek" {
t.Errorf("asked %+v", a.Request)
}
refused = refused || a.Response.Status == 429 && strings.Contains(a.Response.Body, "slow down")
found = found || a.Response.Status == 200 && strings.Contains(a.Response.Body, "go.dev/dl")
}
if !refused || !found {
t.Errorf("archived %+v", got)
}
if r := searchRoute(t, s); r.Model != "Mojeek" || r.Status != 200 || r.Archive == "" {
t.Errorf("route %+v", r)
}
}
// A Kimi Code plan named to search searches with its own search service
// (searchBy): the ask is a usage row, a route and an archive, the plan's
// key in none of them. Before, it wrote no row at all.
func TestKimiPlanSearchRoutedAndArchived(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
setHome(t, t.TempDir())
kimi := newKimiPlan(t)
if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi Code", Preset: "kimi-code-cn", Key: "sk-kimi",
Chat: kimi.URL + "/coding/v1", Models: []string{"kimi-for-coding"}}); err != nil {
t.Fatal(err)
}
b := &memBucket{objs: map[string][]byte{}}
archiveTo(t, b)
settings.Save(settings.Settings{Searcher: "kimi", RequestArchive: true})
s := New()
if _, hits, err := s.webSearch(context.Background(), "latest go"); err != nil || len(hits) != 1 {
t.Fatalf("%+v %v", hits, err)
}
archivePending.Wait()
got := archivedOf(t, b)["kimi"]
if len(got) != 1 || got[0].Request.Path != "/coding/v1/search" || !strings.Contains(got[0].Request.Body, "latest go") ||
got[0].Request.Headers["Authorization"][0] != "[REDACTED]" || !strings.Contains(got[0].Response.Body, "go.dev/dl") {
t.Fatalf("archived %v %+v", keys(b.objs), got)
}
noSecret(t, b, "sk-kimi")
r := searchRoute(t, s)
if r.Provider != "kimi" || r.Model != "Kimi Code" || r.Archive != got[0].ID || r.Status != 200 {
t.Errorf("route %+v", r)
}
rows, _ := searchRows(t)
if len(rows) != 1 || rows[0].Provider != "kimi" || rows[0].Archive != got[0].ID || rows[0].RouteID != r.ID {
t.Errorf("rows %+v", rows)
}
}
// GLM Coding Plan's search goes as an MCP session; the archive keeps its
// tools/call, the search itself.
func TestGLMPlanSearchArchivesItsToolsCall(t *testing.T) {
fresh(t)
g := newGLMSearchPlan(t)
glm := provider.Provider{ID: "glm", Name: "GLM Coding Plan", Preset: "zhipu", Key: "sk-glm", Chat: g.URL + "/api/coding/paas/v4", Models: []string{"glm-4.6"}}
if err := provider.Save(glm); err != nil {
t.Fatal(err)
}
b := &memBucket{objs: map[string][]byte{}}
archiveTo(t, b)
settings.Save(settings.Settings{RequestArchive: true})
s := New()
if _, hits, err := s.glmSearch(context.Background(), glm, "latest go"); err != nil || len(hits) != 1 {
t.Fatalf("%+v %v", hits, err)
}
archivePending.Wait()
got := archivedOf(t, b)["glm"]
if len(got) != 1 || !strings.Contains(got[0].Request.Body, "tools/call") || !strings.Contains(got[0].Response.Body, "go.dev/dl") {
t.Fatalf("archived %v %+v", keys(b.objs), got)
}
noSecret(t, b, "sk-glm")
if r := searchRoute(t, s); r.Provider != "glm" || r.Archive != got[0].ID {
t.Errorf("route %+v", r)
}
}
+2 -4
View File
@@ -11,7 +11,6 @@ import (
"log"
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
)
@@ -86,9 +85,7 @@ var codexSearchRule = "\n" + strings.Repeat("-", 80) + "\n"
// codexSearchBy searches with a ChatGPT account: by the backend's search,
// then, when it fails, by the account's small model.
func (s *Server) codexSearchBy(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
start := time.Now()
said, hits, err := s.codexSearch(ctx, p, query)
logOwnSearch(ctx, p, provider.CodexBase, query, start, len(hits), err)
said, hits, err := s.askOwnSearch(ctx, p, provider.CodexBase, query, s.codexSearch)
if err == nil || ctx.Err() != nil {
return said, hits, err
}
@@ -142,6 +139,7 @@ func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query str
return "", nil, errors.New(who + why)
}
res, err := s.client.Do(r)
res = tapSearch(ctx, r, body, res)
if err != nil {
if ctx.Err() != nil {
return "", nil, fmt.Errorf("%sno answer in time", who)
+4 -2
View File
@@ -61,9 +61,10 @@ func (s *Server) glmSearch(ctx context.Context, p provider.Provider, query strin
}
var errs []error
for _, k := range keys {
ctx, _ := withSearchWire(ctx, k.Key)
start := time.Now()
pages, err := s.glmSearchKey(ctx, k, query)
logOwnSearch(ctx, k, provider.ZhipuCodingSearch(k), query, start, len(pages), err)
s.logOwnSearch(ctx, k, provider.ZhipuCodingSearch(k), query, start, len(pages), err)
if err == nil {
said, hits := pagesSaid(pages)
return said, hits, nil
@@ -215,7 +216,8 @@ func (c *glmMCP) post(ctx context.Context, body []byte) (*http.Response, error)
r.Header.Set("Mcp-Session-Id", c.session)
r.Header.Set("MCP-Protocol-Version", glmSearchProtocol)
}
return c.s.client.Do(r)
res, err := c.s.client.Do(r)
return tapSearch(ctx, r, body, res), err
}
// call asks the server method and gives its result.
+19 -11
View File
@@ -81,19 +81,13 @@ func ownSearcher(ctx context.Context) (provider.Provider, bool) {
// ownSearch searches with the conversation's own provider (ownSearcher).
func (s *Server) ownSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
if provider.KimiCodeSearch(p) != "" {
start := time.Now()
said, hits, err := s.kimiSearch(ctx, p, query)
logOwnSearch(ctx, p, provider.KimiCodeSearch(p), query, start, len(hits), err)
return said, hits, err
return s.askOwnSearch(ctx, p, provider.KimiCodeSearch(p), query, s.kimiSearch)
}
if glmSearches(p) {
return s.glmSearch(ctx, p, query)
}
if wbSearches(p) {
start := time.Now()
said, hits, err := s.wbSearch(ctx, p, query)
logOwnSearch(ctx, p, p.Origin(ctx), query, start, len(hits), err)
return said, hits, err
return s.askOwnSearch(ctx, p, p.Origin(ctx), query, s.wbSearch)
}
ctx, cancel := context.WithTimeout(context.WithValue(ctx, searchingKey{}, true), searchTimeout)
defer cancel()
@@ -104,8 +98,10 @@ func (s *Server) ownSearch(ctx context.Context, p provider.Provider, query strin
// service, a ChatGPT account named with codexSearchModel by the backend's
// search, any other by its model.
func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query, effort string) (string, []Hit, error) {
// a Kimi Code plan picked to search for another's model is its
// search service's ask, logged as one for its own model is
if provider.KimiCodeSearch(p) != "" {
return s.kimiSearch(ctx, p, query)
return s.askOwnSearch(ctx, p, provider.KimiCodeSearch(p), query, s.kimiSearch)
}
if model == codexSearchModel && codexSearches(p) {
return s.codexSearchBy(ctx, p, query)
@@ -116,8 +112,19 @@ func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query
// logOwnSearch writes the request log's row of a search a plan's own
// search service (Kimi Code's, WorkBuddy's) ran, at where (#3528): the
// plan's provider by name, and how it ended.
func logOwnSearch(ctx context.Context, p provider.Provider, where, query string, start time.Time, found int, err error) {
logSearch(ctx, usage.Record{Provider: p.ID, Requested: p.Name, Host: provider.HostOf(where)}, query, start, found, err)
func (s *Server) logOwnSearch(ctx context.Context, p provider.Provider, where, query string, start time.Time, found int, err error) {
s.logSearch(ctx, usage.Record{Provider: p.ID, Requested: p.Name, Host: provider.HostOf(where)}, query, start, found, err)
}
// askOwnSearch asks p's plan's search service at where with ask, and
// logs it (logOwnSearch), its exchange kept as ask sends it (tapSearch).
func (s *Server) askOwnSearch(ctx context.Context, p provider.Provider, where, query string,
ask func(context.Context, provider.Provider, string) (string, []Hit, error)) (string, []Hit, error) {
ctx, _ = withSearchWire(ctx, p.Key)
start := time.Now()
said, hits, err := ask(ctx, p, query)
s.logOwnSearch(ctx, p, where, query, start, len(hits), err)
return said, hits, err
}
// kimiSearch asks a Kimi Code plan's search service.
@@ -143,6 +150,7 @@ func (s *Server) kimiSearch(ctx context.Context, p provider.Provider, query stri
r.Header.Set("X-Msh-Tool-Call-Id", id)
}
res, err := s.client.Do(r)
res = tapSearch(ctx, r, body, res)
if err != nil {
if ctx.Err() != nil {
return "", nil, fmt.Errorf("%s: no answer in time", p.Name)
+5 -3
View File
@@ -40,7 +40,7 @@ func (s *Server) askSearchSignedIn(ctx context.Context, a provider.SearchAPI, v
if p != nil {
err = fmt.Errorf("no account of %s is on", name)
}
logSearch(ctx, usage.Record{Requested: a.Name()}, query, time.Now(), 0, err)
s.logSearch(ctx, usage.Record{Requested: a.Name()}, query, time.Now(), 0, err)
return nil, err
}
ids := make([]string, len(cs))
@@ -52,12 +52,13 @@ func (s *Server) askSearchSignedIn(ctx context.Context, a provider.SearchAPI, v
var errs []error
for _, i := range searchKeyOrder(inOrder, ids, time.Now()) {
q := cs[i].p
ctx, cancel := context.WithTimeout(q.Via(ctx), searchTimeout/4)
ctx, _ := withSearchWire(q.Via(ctx), "")
ctx, cancel := context.WithTimeout(ctx, searchTimeout/4)
start := time.Now()
pages, err := s.askPluginSearchAs(ctx, v, q, query)
cancel()
rec := usage.Record{Requested: a.Name(), ProviderKeyID: searchKeyID(a.Vendor, ids[i]), ProviderKeyName: q.Account.User}
logSearch(ctx, rec, query, start, len(pages), err)
s.logSearch(ctx, rec, query, start, len(pages), err)
if err == nil {
wakeSearchKey(a.Vendor, ids[i])
return pages, nil
@@ -88,6 +89,7 @@ func SearchAccountsOn(p provider.Provider) int { return len(accountsOn(p, "")) }
// API signs in to.
func (s *Server) askPluginSearchAs(ctx context.Context, v provider.SearchVendor, p provider.Provider, query string) ([]foundPage, error) {
got, err := runPluginSearchAs(ctx, v.Plugin, v.PluginID, query, searchHits, p.PluginAccountKey())
notePluginSearch(ctx, v.Plugin, pluginSearchAsked(v, query, "", "", p.Account.User), got, err)
if err != nil {
var r plugin.SearchRefused
if errors.As(err, &r) {
+1
View File
@@ -76,6 +76,7 @@ func (s *Server) wbSearch(ctx context.Context, p provider.Provider, query string
r.Header.Set("X-Conversation-Message-ID", id)
}
res, err := p.Do(s.client, r) // a moved one's through its plugin
res = tapSearch(ctx, r, body, res)
if err != nil {
if ctx.Err() != nil {
return "", nil, fmt.Errorf("%s: no answer in time", p.Name)
+34
View File
@@ -0,0 +1,34 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/yetone/magpie/internal/usage"
)
// A search magpie asked a search API for (axelburks on Discord: 用量-请求
// 页面 能看到请求记录 但是无请求存档) is a row of the Requests page with the
// route the Routing page lists it under and the archive that keeps its
// request and answer, which the row's detail opens (View routing, the
// archive panel), though it rides the probes' lane.
func TestSearchRowKeepsRouteAndArchive(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
usageRoutes(mux, folderOnly{})
usage.Append(usage.Record{Time: time.Now(), Agent: "claude", Kind: "web_search", Source: usage.SourceSearch, Requested: "Tavily",
Host: "api.tavily.com", ProviderKeyName: "tvly…ab12", Status: 200, Millis: 800, RouteID: 1793851649094, Archive: "2026-11-05/040654-a02c8d68dfe256d8"})
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/usage/requests?period=all", nil))
var ledger ledgerJSON
if err := json.Unmarshal(w.Body.Bytes(), &ledger); err != nil || w.Code != 200 {
t.Fatalf("%d %v %s", w.Code, err, w.Body)
}
if len(ledger.Rows) != 1 || ledger.Rows[0].Source != usage.SourceSearch || ledger.Rows[0].RouteID != 1793851649094 ||
ledger.Rows[0].Archive != "2026-11-05/040654-a02c8d68dfe256d8" {
t.Fatalf("rows %s", w.Body)
}
}
+22 -6
View File
@@ -4,6 +4,9 @@
// Codex asks of gpt-6-luna on a hidden thread of its own, and the web
// searches magpie runs for DeepSeek on the model it searches with. Each
// says what it was by its model, and the search's story whose it was.
// A search magpie asked a search API for is listed too (axelburks on
// Discord: 搜索API代搜时 路由页面不显示是请求了哪个API): its story names the
// API, and its row the API, where it was asked and the key.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -20,7 +23,16 @@ const call = (id, i, agent, model, provider, extra) => ({
order: [seat(model, provider)], tries: [{ id: provider, model, start: at(i), done: true, status: 200, ms: 900 }],
done: true, status: 200, ms: 900, tokens: 1200,
});
// as the gateway lists a search API's ask (keepSearch): the API by name,
// its host, the key masked
const asked = {
id: 105, seq: 105, time: at(-0.5), agent: "magpie", model: "Tavily", provider: "api.tavily.com", kind: "web_search",
for: { agent: "codex", model: "deepseek/deepseek-flash" }, archive: "2026-11-05/040654-a02c8d68dfe256d8",
order: [{ id: "tavily:k1", provider: "Tavily", name: "Tavily", who: "tvly…ab12", kind: "key", model: "Tavily" }],
tries: [{ id: "tavily:k1", model: "Tavily", start: at(-0.5), done: true, status: 200, ms: 820 }], done: true, status: 200, ms: 820,
};
const routes = [
asked,
call(104, 0, "magpie", "gpt-6.1-sol", "codex", { kind: "web_search", for: { agent: "codex", model: "deepseek/deepseek-flash" } }),
call(103, 1, "magpie", "gpt-6.1-sol", "codex", { kind: "web_search" }),
call(102, 2, "codex", "deepseek-flash", "deepseek", {}),
@@ -59,8 +71,8 @@ function serve(lang) {
}
const want = {
en: { tags: ["Web search", "Web search", "", "Title"], story: /magpie ran this web search for Codex's deepseek\/deepseek-flash, which can't search the web by itself: codex\/gpt-6\.1-sol searched/, bare: /for a model that can't search the web by itself: codex\/gpt-6\.1-sol searched/, title: /Codex made this call itself \(Title\)/ },
zh: { tags: ["联网搜索", "联网搜索", "", "标题"], story: /magpie 代 Codex 的 deepseek\/deepseek-flash 发起的联网搜索.*由 codex\/gpt-6\.1-sol 搜索/, bare: /代一个无法自行搜索的模型发起的联网搜索:由 codex\/gpt-6\.1-sol 搜索/, title: /Codex 自行发起的调用(标题)/ },
en: { api: /Codex's deepseek\/deepseek-flash, which can't search the web by itself: Tavily searched/, tags: ["Web search", "Web search", "Web search", "", "Title"], story: /magpie ran this web search for Codex's deepseek\/deepseek-flash, which can't search the web by itself: codex\/gpt-6\.1-sol searched/, bare: /for a model that can't search the web by itself: codex\/gpt-6\.1-sol searched/, title: /Codex made this call itself \(Title\)/ },
zh: { api: /magpie 代 Codex 的 deepseek\/deepseek-flash 发起的联网搜索.*由 Tavily 搜索/, tags: ["联网搜索", "联网搜索", "联网搜索", "", "标题"], story: /magpie 代 Codex 的 deepseek\/deepseek-flash 发起的联网搜索.*由 codex\/gpt-6\.1-sol 搜索/, bare: /代一个无法自行搜索的模型发起的联网搜索:由 codex\/gpt-6\.1-sol 搜索/, title: /Codex 自行发起的调用(标题)/ },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -113,13 +125,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
return page.locator(".rt-steps li.kind");
};
let s = await story(0);
assert.match(await s.textContent(), want[lang].api);
const title = await page.locator(".rt-req").nth(0).getAttribute("title");
assert(title.includes("Tavily") && title.includes("api.tavily.com"), title);
s = await story(1);
assert.equal(await s.locator(".kind").textContent(), want[lang].tags[0]);
assert.match(await s.textContent(), want[lang].story);
s = await story(1);
assert.match(await s.textContent(), want[lang].bare);
s = await story(3);
assert.match(await s.textContent(), want[lang].title);
s = await story(2);
assert.match(await s.textContent(), want[lang].bare);
s = await story(4);
assert.match(await s.textContent(), want[lang].title);
s = await story(3);
assert.equal(await s.count(), 0);
assert.deepEqual(errors, []);
});
@@ -6,6 +6,9 @@
// worked; its tooltip says the query is not kept and it counts nowhere.
// A plan's own search service (Kimi Code's, #3528) is badged "Web search"
// under the plan's name.
// An ask with a route and an archive (axelburks on Discord: 搜索API代搜时
// 路由页面不显示是请求了哪个API … 无请求存档) opens both from its details:
// View routing, and the request and answer it sent the API.
// In every language, Chromium and WebKit, wide and narrow, light and dark;
// no backend, the API is faked.
const assert = require("node:assert/strict");
@@ -17,7 +20,13 @@ const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const tot = (calls, tokens, cost) => ({ calls, errors: 0, input: tokens * 0.2, output: tokens * 0.1, cache_write: 0, cache_read: tokens * 0.7, cost });
const ROW = { t: new Date().toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "anthropic", providerName: "Claude", model: "claude-sonnet-5", in: 2, out: 600, cache_write: 0, cache_read: 3900, ms: 2380, status: 200, cost: 0.08, priced: true };
const ASKED = { ...ROW, provider: "", providerName: "", model: "", req: "Tavily", host: "api.tavily.com", providerKeyName: "tvly…ab12", in: 0, out: 0, cache_read: 0, ms: 820, status: 200, cost: 0, priced: false, source: "search", kind: "web_search" };
const KEPT = "2026-11-05/040654-a02c8d68dfe256d8";
const ASKED = { ...ROW, provider: "", providerName: "", model: "", req: "Tavily", host: "api.tavily.com", providerKeyName: "tvly…ab12", in: 0, out: 0, cache_read: 0, ms: 820, status: 200, cost: 0, priced: false, source: "search", kind: "web_search", route_id: 1793851649094, archive: KEPT };
const ARCHIVED = {
id: KEPT, call: { kind: "web_search", model: "Tavily", provider: "api.tavily.com", status: 200 },
request: { method: "POST", path: "/search", headers: { Authorization: ["[REDACTED]"], "Content-Type": ["application/json"] }, body: '{"max_results":5,"query":"latest go","search_depth":"basic"}', size: 61 },
response: { status: 200, headers: { "Content-Type": ["application/json"] }, body: '{"results":[{"title":"Go downloads","url":"https://go.dev/dl/"}]}', size: 66 },
};
// a plan's own search service (#3528): under the plan, badged as a web search
const PLAN = { ...ASKED, t: new Date(Date.now() - 30000).toISOString(), provider: "kimi", providerName: "Kimi Code", req: "Kimi Code", host: "api.kimi.com", providerKeyName: "", ms: 1300 };
const FAILED = { ...ASKED, t: new Date(Date.now() - 60000).toISOString(), req: "Brave Search", host: "api.search.brave.com", providerKeyName: "", ms: 40, status: 0, err: "Get api.search.brave.com: EOF" };
@@ -41,6 +50,7 @@ function server(lang, theme, called, asked) {
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme }, fx: { rate: 7.2, at: new Date().toISOString() } });
if (url.pathname === "/api/usage/requests") { asked.push(url.searchParams); return json(page(url.searchParams, called)); }
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/archive") return json(`${url.searchParams.get("date")}/${url.searchParams.get("id")}` === KEPT ? ARCHIVED : { error: "not found" });
if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 1, output: 1, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 1, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" });
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
@@ -108,6 +118,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert((await plan.locator(".where-name").textContent()).includes("Kimi Code"));
const failed = p.locator(".led tr.led-row", { hasText: "Brave Search" });
assert((await failed.locator(".st").textContent()).startsWith(w.bad));
// its details: the route it went by, and the archive of what it
// sent the API and what came back
await asked.click();
const detail = p.locator(".led-detail").first();
await detail.locator(".led-route-link").waitFor();
const box = detail.locator(".led-archive .call-archive");
assert.equal(await box.locator(".call-archive-id").innerText(), KEPT);
await box.locator(".call-body-head button").first().click();
await box.locator(".call-details").waitFor();
const kept = await box.innerText();
assert(kept.includes("POST /search") && kept.includes("latest go") && kept.includes("go.dev/dl") && kept.includes("[REDACTED]"), kept);
await asked.click(); // closed again
await detail.waitFor({ state: "detached" });
// the purpose picker names it in the page's language
assert.equal(await p.evaluate(() => purposeOptions(["kind:web_search"], "")[0].name), w.purpose);
// no coloured stripe down its side, and the page doesn't scroll sideways