diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7aab212fc..b1345def8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -948,6 +948,38 @@ Covered by `TestReadTavilyUsage`, `TestSearchKeysTakeTurnsRoundRobin`, `TestSearchKeyNeverInFull`, `TestSearchAPIKeysTakeTurns` and `search-keys.test.cjs`. +## A search API's asks in the request log + +Each ask of a search API with one key is a row of the request log +(cybercaius on Discord: which search API a search used couldn't be seen). +`logSearchAPI` in [`search_api.go`](../../internal/gateway/search_api.go) +writes it after every `askSearchAPI` in `askSearchAPIKeys`, a refused key +and the next one each a row: `Source` `search` (`usage.SourceSearch`), +`Kind` `web_search`, the agent the search was for (`searchFor`'s +`CallFor.Agent`, else `magpie`), the API's name as `Requested`, its host, +the key as `searchKeyID` and masked (`provider.MaskSearchKey`), how long +it took, and how it ended: 200, the API's status when it refused the key, +the error, or "found nothing". `Provider` stays empty: `deepseek` is a +provider's id as well as a search API's. The query is never kept: the +error is cut to the transport's own error and host when Go's says the +URL (an API asked by GET carries the query there), and the query, plain +or escaped, is taken out of what the API said back. + +The rows ride the probes' lane (`IsProbe`): listed under the Web search +purpose and found by the API's name in the search box, counted in no +total, budget or provider share, and never exported (`observeLedger`), so +telemetry, which reads no usage row, has nothing new to send. The Usage +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, 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`. + +Covered by `TestSearchAPIAsksAreLogged`, `TestSearchAPIFailureKeepsNoURL`, +`TestOwnSearchIsLogged`, `TestWorkBuddyPluginSearches`, +`TestSearchAPIRowsListedNotCounted` and `usage-ledger-search.test.cjs`. + ## Web search as an MCP server `SearchMCPPath`, `/mcp/magpie/web-search`, serves the same `webSearch` a diff --git a/internal/gateway/search_api.go b/internal/gateway/search_api.go index a4b6b8f10..1afc65f2e 100644 --- a/internal/gateway/search_api.go +++ b/internal/gateway/search_api.go @@ -16,7 +16,10 @@ import ( "time" "unicode/utf8" + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" ) // When no provider can search, magpie's web_search tool is answered by a @@ -141,8 +144,10 @@ func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, que one := a one.Key = keys[i] 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) if err == nil { wakeSearchKey(a.Vendor, keys[i]) return pages, nil @@ -164,6 +169,58 @@ func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, que return nil, errors.Join(errs...) } +// logSearchAPI writes the request log's row of one ask of a search API +// 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) { + 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) +} + +// 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) { + 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 != "" { + rec.Agent = f.Agent + } + who := access.Caller(ctx) + rec.CallerKeyID, rec.CallerKeyName = who.KeyID, who.KeyName + switch { + case err != nil && found == 0 && errors.Is(err, errFoundNothing): + rec.Error = "found nothing" + case err != nil: + said := err.Error() + var ue *url.Error // its URL holds the query of an API asked by GET + if errors.As(err, &ue) { + said = ue.Op + " " + provider.HostOf(ue.URL) + ": " + ue.Err.Error() + } + if q := strings.TrimSpace(query); q != "" { + for _, form := range []string{q, url.QueryEscape(q), url.PathEscape(q)} { + said = strings.ReplaceAll(said, form, "…") + } + } + rec.Error = keepMsg(said) + var r searchRefused + if errors.As(err, &r) { + rec.Status = r.status + } + case found == 0: + rec.Error = "found nothing" + default: + rec.Status = http.StatusOK + } + budget.Append(rec) +} + // searchRefused is a search API's refusal of the key it was asked with, // by its status: 401/403 turned away, 402/432/433 out of credit (Tavily's // plan and pay-as-you-go limits), 429 rate limited. diff --git a/internal/gateway/search_api_log_test.go b/internal/gateway/search_api_log_test.go new file mode 100644 index 000000000..bfb52547b --- /dev/null +++ b/internal/gateway/search_api_log_test.go @@ -0,0 +1,183 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +func searchRows(t *testing.T) ([]usage.Record, string) { + t.Helper() + all, text := loggedRows(t) + var out []usage.Record + for _, r := range all { + if r.Source == usage.SourceSearch { + out = append(out, r) + } + } + return out, text +} + +// cybercaius on Discord: which search API a search used couldn't be seen. +// Each ask of a search API with one key is a row of the request log: the +// agent it was for, the API by name, its host, the key masked, and how it +// ended (answered, refused with the API's status, failed, found nothing). +// The query is in no row, not even where the API said it back in an error. +func TestSearchAPIAsksAreLogged(t *testing.T) { + fresh(t) + const query = "kangaroo orbit 7781" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var q struct { + Query string `json:"query"` + } + b, _ := io.ReadAll(r.Body) + json.Unmarshal(b, &q) + w.Header().Set("Content-Type", "application/json") + switch strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") { + case "tvly-spent-0001": + w.WriteHeader(432) + io.WriteString(w, `{"detail":{"error":"This request exceeds your plan's set usage limit"}}`) + case "tvly-good-0002": + io.WriteString(w, `{"query":"x","results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"go1.27.1","score":0.9}]}`) + case "tvly-echo-0003": + w.WriteHeader(500) + io.WriteString(w, `{"detail":{"error":"could not search for `+q.Query+`"}}`) + default: + io.WriteString(w, `{"query":"x","results":[]}`) + } + })) + defer srv.Close() + s := New() + ctx := context.WithValue(context.Background(), searchForKey{}, &CallFor{Agent: "claude"}) + search := func(keys string) { + t.Helper() + forgetSearchKeys() + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: keys, URL: srv.URL}); err != nil { + t.Fatal(err) + } + s.apiSearch(ctx, query) + } + search("tvly-spent-0001\ntvly-good-0002") + search("tvly-echo-0003") + search("tvly-empty-0004") + if _, _, err := s.apiSearch(context.Background(), query); err != nil { // no CallFor: magpie's own + t.Log(err) + } + + rows, text := searchRows(t) + if len(rows) != 5 { + t.Fatalf("%d search rows: %+v", len(rows), rows) + } + host := provider.HostOf(srv.URL) + for i, r := range rows { + if r.Requested != "Tavily" || r.Host != host || r.Kind != "web_search" || r.Provider != "" || r.Model != "" || + r.ProviderKeyID == "" || r.ProviderKeyName == "" || strings.Contains(r.ProviderKeyName, "spent") || strings.Contains(r.ProviderKeyName, "good") { + t.Errorf("row %d: %+v", i, r) + } + if want := "claude"; i == 4 { + if r.Agent != "magpie" { + t.Errorf("row %d agent %q", i, r.Agent) + } + } else if r.Agent != want { + t.Errorf("row %d agent %q", i, r.Agent) + } + } + if r := rows[0]; r.Status != 432 || !r.Failed() { + t.Errorf("refused key: %+v", r) + } + if r := rows[1]; r.Status != 200 || r.Failed() { + t.Errorf("answered: %+v", r) + } + if r := rows[2]; !r.Failed() || r.Error == "" { + t.Errorf("failed: %+v", r) + } + if r := rows[3]; r.Error != "found nothing" { + t.Errorf("found nothing: %+v", r) + } + if rows[0].ProviderKeyID == rows[1].ProviderKeyID { + t.Errorf("two keys, one id: %q", rows[0].ProviderKeyID) + } + for _, w := range strings.Fields(query) { + if strings.Contains(text, w) { + t.Fatalf("the query's %q is in usage.jsonl:\n%s", w, text) + } + } + // counted in nothing: Load (totals, budgets) leaves them out + for _, r := range usage.Load(rows[0].Time.Add(-1)) { + if r.Source == usage.SourceSearch { + t.Fatalf("Load gave a search row: %+v", r) + } + } +} + +// An API asked by GET carries the query in its URL, which Go's transport +// errors say whole: the row says the host and what went wrong, not the URL. +func TestSearchAPIFailureKeepsNoURL(t *testing.T) { + fresh(t) + const query = "wombat lattice 4410" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, _, err := w.(http.Hijacker).Hijack() + if err == nil { + c.Close() // no answer at all + } + })) + defer srv.Close() + forgetSearchKeys() + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "brave", Key: "brave-k-0001", URL: srv.URL}); err != nil { + t.Fatal(err) + } + if _, _, err := New().apiSearch(context.Background(), query); err == nil { + t.Fatal("a closed connection answered") + } + rows, text := searchRows(t) + if len(rows) != 1 || rows[0].Requested != "Brave Search" || rows[0].Error == "" || !strings.Contains(rows[0].Error, provider.HostOf(srv.URL)) || strings.Contains(rows[0].Error, "?") { + t.Fatalf("rows %+v", rows) + } + for _, w := range strings.Fields(query) { + if strings.Contains(text, w) { + t.Fatalf("the query's %q is in usage.jsonl:\n%s", w, text) + } + } +} + +// A plan's own search service (Kimi Code's here, WorkBuddy's in +// TestWorkBuddyPluginSearches) writes the same row, under the plan's +// provider (#3528). +func TestOwnSearchIsLogged(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + setHome(t, t.TempDir()) + kimi := newKimiPlan(t) + p := provider.Provider{ID: "kimi", Name: "Kimi Code", Preset: "kimi-code-cn", Key: "sk-kimi", Chat: kimi.URL + "/coding/v1", Models: []string{"kimi-for-coding"}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + ctx := context.WithValue(searchingOn(context.Background(), p), searchForKey{}, &CallFor{Agent: "claude"}) + const query = "latest go" + if _, _, err := New().ownSearch(ctx, p, query); err != nil { + t.Fatal(err) + } + kimi.mu.Lock() + kimi.broken = true + kimi.mu.Unlock() + New().ownSearch(ctx, p, query) + rows, _ := searchRows(t) + if len(rows) != 2 { + t.Fatalf("%d rows: %+v", len(rows), rows) + } + for _, r := range rows { + if r.Provider != "kimi" || r.Requested != "Kimi Code" || r.Host != provider.HostOf(kimi.URL) || r.Agent != "claude" || r.Kind != "web_search" { + t.Errorf("row %+v", r) + } + } + if rows[0].Status != 200 || rows[0].Failed() || !rows[1].Failed() { + t.Errorf("outcomes %+v", rows) + } +} diff --git a/internal/gateway/search_kimi.go b/internal/gateway/search_kimi.go index d2a2f4157..689b29cad 100644 --- a/internal/gateway/search_kimi.go +++ b/internal/gateway/search_kimi.go @@ -8,9 +8,11 @@ import ( "fmt" "io" "net/http" + "time" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" ) // A Kimi Code plan searches the web with its own key, as kimi-cli's @@ -78,10 +80,16 @@ 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) != "" { - return s.kimiSearch(ctx, p, query) + 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 } if wbSearches(p) { - return s.wbSearch(ctx, p, query) + 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 } ctx, cancel := context.WithTimeout(context.WithValue(ctx, searchingKey{}, true), searchTimeout) defer cancel() @@ -97,6 +105,13 @@ func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query return s.searchWith(ctx, p, model, query, effort) } +// 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) +} + // kimiSearch asks a Kimi Code plan's search service. func (s *Server) kimiSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) { // the service gives itself 30 s, as kimi-cli asks diff --git a/internal/gateway/search_workbuddy_test.go b/internal/gateway/search_workbuddy_test.go index 4ffd513ac..26bd9876c 100644 --- a/internal/gateway/search_workbuddy_test.go +++ b/internal/gateway/search_workbuddy_test.go @@ -119,6 +119,11 @@ func TestWorkBuddyPluginSearches(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "web search quota exhausted (15001)") { t.Fatalf("refusal: %v", err) } + // each search is a row of the request log, under the plan (#3528) + if rows, _ := searchRows(t); len(rows) != 2 || rows[0].Provider != pid || rows[0].Status != 200 || rows[0].Failed() || + rows[1].Provider != pid || !strings.Contains(rows[1].Error, "15001") || strings.Contains(rows[0].Host+rows[1].Error, "Go 1.26") { + t.Fatalf("rows %+v", rows) + } // provider search off: WorkBuddy's isn't asked either st := settings.Load() diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index ea568b212..99d19f67f 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1537,7 +1537,7 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske .led .src.access-subscription { --badge-ink: var(--tk-k); } .led .src.proto { --badge-ink: var(--muted); font-weight: 500; } .led .src.reported { --badge-ink: var(--tk-o); } -.led .src.probe, .led .src.mcp { --badge-ink: var(--muted); } +.led .src.probe, .led .src.mcp, .led .src.search { --badge-ink: var(--muted); } .led .duration { font-weight: 550; } .led .duration-fast { color: var(--tk-s); } .led .duration-slow { color: var(--amber); } diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index f7f6ffc04..37db0ba7e 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -80,6 +80,7 @@ magpie.strings({ "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由发起请求的应用通过 POST /v1/magpie/usage/requests 上报:这次请求直接发给了服务商,没有经过 magpie。", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "这是 magpie 自己为测试供应商发出的请求(测试、检测协议或模型列表),不是 agent 发出的,不计入任何汇总。", "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} 调用了 magpie 的 MCP 服务器 {server} 的工具 {tool}。不保存调用参数,也不计入任何汇总:它发出的模型请求各有自己的一行。", + "magpie asked {api} to search the web for {agent}. The query is not kept, and it is not counted in any total.": "magpie 为 {agent} 请 {api} 做了一次联网搜索。不保存搜索内容,也不计入任何汇总。", "all requests": "全部请求", "Show only these requests": "只看这些请求", "Show every request again": "重新显示全部请求", @@ -316,6 +317,7 @@ magpie.strings({ "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由發出請求的應用程式透過 POST /v1/magpie/usage/requests 回報:這次請求直接送往服務商,沒有經過 magpie。", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "這是 magpie 自己為測試供應商發出的請求(測試、檢測協議或模型列表),不是 agent 發出的,不計入任何彙總。", "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} 呼叫了 magpie 的 MCP 伺服器 {server} 的工具 {tool}。不保存呼叫參數,也不計入任何彙總:它發出的模型請求各有自己的一列。", + "magpie asked {api} to search the web for {agent}. The query is not kept, and it is not counted in any total.": "magpie 為 {agent} 請 {api} 做了一次聯網搜尋。不保存搜尋內容,也不計入任何彙總。", "all requests": "全部請求", "Show only these requests": "只看這些請求", "Show every request again": "重新顯示全部請求", @@ -552,6 +554,7 @@ magpie.strings({ "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "リクエストを送ったアプリが POST /v1/magpie/usage/requests で報告したものです。このリクエストは magpie を経由せず、直接ベンダーに送られました。", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "プロバイダをテストするために magpie 自身が送ったリクエストです(テスト、API を検出、モデル一覧)。エージェントのものではなく、どの合計にも数えません。", "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} が magpie の MCP サーバー {server} のツール {tool} を呼び出しました。引数は保存せず、どの合計にも数えません。これが送ったモデルへのリクエストはそれぞれ別の行です。", + "magpie asked {api} to search the web for {agent}. The query is not kept, and it is not counted in any total.": "magpie が {agent} のために {api} でウェブ検索をしました。検索語は保存せず、どの合計にも数えません。", "all requests": "すべてのリクエスト", "Show only these requests": "これらのリクエストだけを表示", "Show every request again": "すべてのリクエストを再表示", @@ -788,6 +791,7 @@ magpie.strings({ "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "Von der App gemeldet, die die Anfrage gestellt hat (POST /v1/magpie/usage/requests): Die Anfrage ging direkt an den Anbieter, nicht über magpie.", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "magpie hat dies selbst gesendet, um den Anbieter zu testen (Testen, APIs erkennen oder eine Modellliste), nicht für einen Agent. Es zählt in keiner Summe.", "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} hat das Tool {tool} von magpies MCP-Server {server} aufgerufen. Seine Argumente werden nicht gespeichert, und es zählt in keiner Summe: die Modellanfragen, die es gesendet hat, sind eigene Zeilen.", + "magpie asked {api} to search the web for {agent}. The query is not kept, and it is not counted in any total.": "magpie hat {api} für {agent} im Web suchen lassen. Die Suchanfrage wird nicht gespeichert, und sie zählt in keiner Summe.", "all requests": "alle Anfragen", "Show only these requests": "Nur diese Anfragen zeigen", "Show every request again": "Wieder alle Anfragen zeigen", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 2fc24e097..8a7da03ea 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2276,6 +2276,8 @@ function renderLedger() { const probe = r.source === "probe"; // an agent's call to a tool of magpie's MCP servers (ferock on Discord) const mcp = r.source === "mcp"; + // magpie's ask of a search API, for a search an agent's model made (cybercaius on Discord) + const search = r.source === "search"; if (r.agent === "magpie") { const own = ownBadge(); if (probe) own.title = probeWhy(); @@ -2293,6 +2295,7 @@ function renderLedger() { // session. A row whose file names none says only that. const where = local ? (r.session_account || r.session_provider || t("Local session")) : mcp ? [r.providerName && t(r.providerName), r.host].filter(Boolean).join(" · ") || "—" + : search ? [r.providerName && t(r.providerName), r.host, r.providerKeyName].filter(Boolean).join(" · ") || "—" : t(r.providerName) + (r.host ? " · " + r.host : ""); const wc = td(el("div", "where-name", where), "where", where); const badges = el("div", "source-badges"); @@ -2336,6 +2339,12 @@ function renderLedger() { k.title = t("{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.", { agent: name, tool: r.req || "—", server: r.host || "magpie" }); badges.append(k); } + if (search) { + // a search API's, or a plan's own search service's (r.provider) + const k = el("span", "src search", t(r.provider ? "Web search" : "Search API")); + k.title = t("magpie asked {api} to search the web for {agent}. The query is not kept, and it is not counted in any total.", { api: r.req || "—", agent: name }); + badges.append(k); + } if (badges.childElementCount) wc.append(badges); // the model sent is what the gateway sent the vendor: a session file has none // The log names a model, but does not capture the outbound HTTP request. @@ -2383,7 +2392,7 @@ function renderLedger() { const st = el("span", "st"); // a status when the gateway logged the call; a session file has none, // and says only whether it went well - let word = r.status ? String(r.status) : r.source === "log" || mcp ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—"; + let word = r.status ? String(r.status) : r.source === "log" || mcp || search ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—"; if (r.status && bad && r.err_type) word += " · " + r.err_type; if (r.handed_on) word += " · " + t("handed on"); else if (r.tries > 1) word += " · " + t("{n} tries", { n: r.tries }); diff --git a/internal/gui/tests/usage-ledger-search.test.cjs b/internal/gui/tests/usage-ledger-search.test.cjs new file mode 100644 index 000000000..bac8fedfc --- /dev/null +++ b/internal/gui/tests/usage-ledger-search.test.cjs @@ -0,0 +1,129 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// magpie's ask of a search API for an agent's web search (cybercaius on +// Discord: which search API a search used couldn't be seen) is a row of +// the Requests tab: a "Search API" badge, the API's name where the model +// asked for is, its host and masked key, how long it took and whether it +// 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. +// In every language, Chromium and WebKit, wide and narrow, light and dark; +// no backend, the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +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" }; +// 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" }; + +function page(q, called) { + const rows = [ROW, ...(called ? [ASKED, PLAN, FAILED] : [])]; + return { + period: "today", rows, offset: 0, total: rows.length, ...tot(1, 4500, 0.08), reasoning: 0, unpriced: 0, + bucket: "hour", series: [], by: { provider: [], agent: [], model: [] }, + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "anthropic", name: "Claude", icon: "claudecode-color" }], + through: tot(1, 4500, 0.08), direct: tot(0, 0, 0), purposes: called ? ["kind:web_search", "unmarked"] : ["unmarked"], + }; +} + +function server(lang, theme, called, asked) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"${theme}",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + 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/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: {} }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// the badge, the purpose's name (a plan's badge too), a word of the tooltip that says it +// counts nowhere, and the failed status word +const L = { + en: { badge: "Search API", purpose: "Web search", why: "not counted in any total", bad: "Failed" }, + zh: { badge: "搜索 API", purpose: "联网搜索", why: "不计入任何汇总", bad: "失败" }, + "zh-TW": { badge: "搜尋 API", purpose: "聯網搜尋", why: "不計入任何彙總", bad: "失敗" }, + ja: { badge: "検索 API", purpose: "ウェブ検索", why: "どの合計にも数えません", bad: "失敗" }, + de: { badge: "Such-API", purpose: "Websuche", why: "zählt in keiner Summe", bad: "Fehlgeschlagen" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a search API ask is a row of its own", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const shots = process.env.ARTIFACT_DIR; + if (shots) await fs.mkdir(shots, { recursive: true }); + + const open = async (lang, { theme = "light", width = 1180, called = true } = {}) => { + const errors = [], asked = []; + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + t.after(() => context.close()); + const p = await context.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, theme, called, asked)); + await p.goto("http://magpie.test/"); + await p.locator('[data-view="usage"]').first().click(); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await p.locator("#ledVia .blk").first().waitFor(); + return { p, errors }; + }; + + for (const lang of Object.keys(L)) { + const w = L[lang]; + for (const width of [1180, 420]) { + await t.test(`${lang} at ${width}`, async () => { + const { p, errors } = await open(lang, { width, theme: width < 600 ? "dark" : "light" }); + const badge = p.locator(".led .src.search"); + await badge.first().waitFor(); + assert.equal(await badge.count(), 3); + assert.equal(await badge.first().textContent(), w.badge); + const why = await badge.first().getAttribute("title"); + assert(why.includes(w.why) && why.includes("Tavily") && why.includes("Claude Code"), why); + // the model row has none, and neither is a probe or an MCP call + assert.equal(await p.locator(".led .src.probe, .led .src.mcp").count(), 0); + const asked = p.locator(".led tr.led-row", { has: p.locator(".src.search") }).first(); + const text = await asked.textContent(); + assert(text.includes("Tavily") && text.includes("api.tavily.com") && text.includes("tvly…ab12"), text); + assert((await asked.locator(".st").textContent()).startsWith("200")); + const plan = p.locator(".led tr.led-row", { hasText: "api.kimi.com" }); + assert.equal(await plan.locator(".src.search").textContent(), w.purpose); + 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)); + // 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 + assert(parseFloat(await badge.first().evaluate((b) => getComputedStyle(b).borderLeftWidth)) <= 1); + assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "no sideways scroll"); + if (shots) await p.screenshot({ path: path.join(shots, `search-${engine}-${lang}-${width}.png`) }); + assert.deepEqual(errors, []); + }); + } + } + + await t.test("no search API ask: no badge", async () => { + const { p, errors } = await open("en", { called: false }); + await p.locator(".led tr", { hasText: "claude-sonnet-5" }).first().waitFor(); + assert.equal(await p.locator(".led .src.search").count(), 0); + assert.deepEqual(errors, []); + }); + }); +} diff --git a/internal/usage/probes.go b/internal/usage/probes.go index a703710a5..2056fe86a 100644 --- a/internal/usage/probes.go +++ b/internal/usage/probes.go @@ -29,18 +29,33 @@ const SourceProbe = "probe" // the model requests the tool made are rows of their own that are. const SourceMCP = "mcp" +// SourceSearch is Record.Source for one ask of a search API (Tavily, +// Brave, …) by a web search magpie ran (cybercaius on Discord: which +// search API each search used couldn't be seen). Its Kind is +// "web_search", Agent the agent the search was for, Requested the API's +// name, Host where it was asked, ProviderKeyID and ProviderKeyName the key +// (by a hash and masked), Millis how long it took, Status the API's when +// it refused the key, and Error what a failed one said ("found nothing" +// for an answer with no page). The query is never kept. It rides the +// probes' lane as an MCP call does: listed on the request log and counted +// nowhere, since it has no tokens and is no model's. +const SourceSearch = "search" + // KindMCP is an MCP tool call's Kind, the purpose the request log picks // them by. const KindMCP = "mcp" -// IsProbe is a request magpie sent on its own (SourceProbe), or an MCP -// tool call (SourceMCP): a row listed and counted nowhere. -func (r Record) IsProbe() bool { return r.Source == SourceProbe || r.Source == SourceMCP } +// IsProbe is a request magpie sent on its own (SourceProbe), an MCP tool +// call (SourceMCP) or a search API's (SourceSearch): a row listed and +// counted nowhere. +func (r Record) IsProbe() bool { + return r.Source == SourceProbe || r.Source == SourceMCP || r.Source == SourceSearch +} // IsProbe is a row of such a request. A packed row keeps the row's Source, // not its record's, so the request log asks the row. func (r Row) IsProbe() bool { - return r.Source == SourceProbe || r.Source == SourceMCP || r.Record.IsProbe() + return r.Source == SourceProbe || r.Source == SourceMCP || r.Source == SourceSearch || r.Record.IsProbe() } // probeRow is a probe's record and where its line ends in the log, as a @@ -121,6 +136,10 @@ func probeChunk(probes []probeRow, since time.Time, renames provider.Renames, ho c.add(Row{Record: r, Source: SourceMCP}, "", p.off, false) continue } + if r.Source == SourceSearch { // a search API is no provider + c.add(Row{Record: r, Source: SourceSearch}, "", p.off, false) + continue + } r.Provider = probeProvider(r, renames, hosts, sites) c.add(Row{Record: r, Source: SourceProbe}, "", p.off, false) } diff --git a/internal/usage/search_calls_test.go b/internal/usage/search_calls_test.go new file mode 100644 index 000000000..e2014555f --- /dev/null +++ b/internal/usage/search_calls_test.go @@ -0,0 +1,76 @@ +package usage + +import ( + "slices" + "testing" + "time" +) + +// cybercaius on Discord: which search API a search used, and how often, +// couldn't be seen. Each ask of a search API (SourceSearch) is a row of +// the request log of its own, picked by the Web search purpose, naming the +// API, where it was asked and the key, and counted in nothing: no provider, +// no total, no budget, nothing exported. A searcher model's own request +// (kind web_search, a real provider call) still counts. +func TestSearchAPIRowsListedNotCounted(t *testing.T) { + reportedHome(t) + spy := &ledgerSpy{} + t.Cleanup(Observe(spy)) + now := time.Now().Add(-time.Hour) + Append(Record{Time: now, Agent: "claude", Provider: "openai", Host: "api.openai.com", Model: "gpt-5-mini", Requested: "gpt-5-mini", Kind: "web_search", Status: 200, Millis: 3000}) + Append(Record{Time: now.Add(time.Second), Agent: "claude", Requested: "Tavily", Host: "api.tavily.com", ProviderKeyID: "k1", ProviderKeyName: "tvly…abcd", + Millis: 800, Status: 200, Kind: "web_search", Source: SourceSearch}) + Append(Record{Time: now.Add(2 * time.Second), Agent: "claude", Requested: "Brave Search", Host: "api.search.brave.com", Millis: 90, Status: 429, + Error: "rate limited", Kind: "web_search", Source: SourceSearch}) + Append(Record{Time: now.Add(3 * time.Second), Agent: "magpie", Requested: "DeepSeek", Host: "api.deepseek.com", Millis: 50, + Error: "found nothing", Kind: "web_search", Source: SourceSearch}) + + page := QueryPage(All, Filter{}, 0, 50) + if page.Total != 4 || len(page.Rows) != 4 { + t.Fatalf("total %d, %d rows: %+v", page.Total, len(page.Rows), page.Rows) + } + ds, brave, tavily := page.Rows[0], page.Rows[1], page.Rows[2] // newest first + if tavily.Source != SourceSearch || !tavily.IsProbe() || tavily.Requested != "Tavily" || tavily.Host != "api.tavily.com" || + tavily.ProviderKeyName != "tvly…abcd" || tavily.Failed() || tavily.Provider != "" || tavily.Millis != 800 { + t.Fatalf("tavily row %+v", tavily) + } + if brave.Source != SourceSearch || !brave.Failed() || brave.Status != 429 { + t.Fatalf("brave row %+v", brave) + } + // "deepseek" is a provider's id too: the search API's row is not its + if ds.Source != SourceSearch || ds.Provider != "" || !ds.Failed() { + t.Fatalf("deepseek row %+v", ds) + } + if page.Sum.Calls != 1 || page.Sum.Errors != 0 || page.Through.Calls != 1 { + t.Fatalf("sum %+v through %+v", page.Sum, page.Through) + } + for dim, shares := range page.By { + for _, s := range shares { + if slices.Contains([]string{"Tavily", "Brave Search", "DeepSeek", "deepseek"}, s.ID) || (dim == "provider" && s.Calls != 1) { + t.Fatalf("%s counts a search API ask: %+v", dim, shares) + } + } + } + if s := Summarize(All); s.Calls != 1 || s.Errors != 0 { + t.Fatalf("summary %+v", s.Totals) + } + if rs := Load(time.Time{}); len(rs) != 1 { + t.Fatalf("Load %+v", rs) + } + if len(spy.rows) != 1 || spy.rows[0].IsProbe() { + t.Fatalf("observer saw %+v", spy.rows) + } + // the Web search purpose lists both kinds of search, and the API's + // name narrows it to that API's asks + p := QueryPage(All, Filter{Purpose: PurposeOf("web_search")}, 0, 50) + if p.Total != 4 || p.Sum.Calls != 1 { + t.Fatalf("purpose filter: total %d sum %+v", p.Total, p.Sum) + } + p = QueryPage(All, Filter{Purpose: PurposeOf("web_search"), Query: "tavily"}, 0, 50) + if p.Total != 1 || p.Rows[0].Requested != "Tavily" { + t.Fatalf("query filter: total %d rows %+v", p.Total, p.Rows) + } + if hosts := readLogSnapshot().hosts; hosts["api.tavily.com"] != "" || hosts["api.deepseek.com"] != "" { + t.Fatalf("hosts %v", hosts) + } +}