diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b1345def8..39721b08c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -621,7 +621,8 @@ never fall back to a provider while this setting is off. Without a ready Search API, [`canSearchFor`](../../internal/gateway/search_kimi.go) does not offer magpie's replacement search tool. `searchesOwn` is the one check for a provider searching for its own models (Kimi Code, WorkBuddy, a Google sign-in), so `ownSearcher` and the model list another magpie reads (`webSearchOf`, which then says no search) follow it too. -A provider's native search on the client's protocol remains unchanged. +A provider's native search on the client's protocol remains unchanged, +unless `searchAll` is on (next section). An empty `searcher` still selects a provider automatically; an unavailable named provider (gone, off, can't search) still falls back to that selection. One that is available but fails a search is not replaced by another @@ -631,6 +632,31 @@ provider (below). Covered by `TestSearchProviderOff`, `TestSearchProviderOffForwarding`, `TestSearchProviderOffTellsRemoteMagpie`, `TestSearcherChosen`, `TestSettingsSearchProviderOff`, and `searcher-pick.test.cjs`. +## magpie's search for a model that searches by itself + +[Settings](../../internal/settings/settings.go)' `searchAll` (cybercaius on +Discord) gives a model whose provider searches the web by itself +(`searchesFor`) magpie's search too: the searcher and the search APIs, in +their usual order, as a model that can't search has. Settings › Models › +Web search shows it as "Models that search by themselves", Their own or +magpie's, when magpie has anything to search with. +[`magpieSearches`](../../internal/gateway/search.go) is the one check: on +in Settings, magpie can search for this provider (`canSearchFor`), and the +request isn't magpie's own searcher request (`searching`), which needs the +provider's search. Where it holds, `searchedForIt` stops the relay of a +body that asks for web search, and `translate` neither picks an API for +the provider's own search nor keeps it, so the provider is sent magpie's +web_search function tool. With nothing magpie can search with, the +provider keeps its own search and the relay as sent. + +Not covered: a Codex sign-in's turns relayed as Codex sent them +(`codexAsSent`) and a sealed agent message keep the provider's search, as +they keep the rest of the body; the model list another magpie reads +(`webSearchOf`) still says native. + +Covered by `TestSearchAllTakesTheSearchFromAProviderThatSearches` and +`search-all.test.cjs`. + ## WorkBuddy's search service A WorkBuddy plan's models (the China build's and WorkBuddy AI's, served by diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 4e9c7b00c..82161fa36 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4225,7 +4225,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P // apply_patch as a function, left web_search out and added // max_output_tokens, the shape such a relay turns away (maralica on // Discord). Its web_search goes to the relay as sent. - if relay && searchedForIt(p, from, model, body) && !(from == provider.Responses && (hasSealedAgentMessage(body) || codexAsSent(p, r.Header))) { + if relay && searchedForIt(r.Context(), p, from, model, body) && !(from == provider.Responses && (hasSealedAgentMessage(body) || codexAsSent(p, r.Header))) { relay, ownAPI = false, true } // Copilot seals an argument the tools mark "encrypted" (spawn_agent's @@ -6849,7 +6849,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr // (DeepSeek's Chat) it had no search tool and answered from // nothing (#669) for _, t := range s.usable(p, model) { - if searchesFor(p, t, model, request) { + if searchesFor(p, t, model, request) && !magpieSearches(r.Context(), p) { if from == provider.Responses && (to == provider.Responses) != (t == provider.Responses) { request, err = parseRequest(from, body, false, t == provider.Responses) if err != nil { @@ -6877,7 +6877,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr zen = &zenReply{z: zenFreeTools(request)} } if request.WebSearch { - if !searching(r.Context()) && canSearchFor(p) && !searchesFor(p, to, model, request) { + if !searching(r.Context()) && canSearchFor(p) && (!searchesFor(p, to, model, request) || magpieSearches(r.Context(), p)) { ask := antigravityRound(w, p, s.askTranslated(p, to, model, r.Header, w.Header())) if zen != nil { ask = zenRound(zen.z, ask) diff --git a/internal/gateway/search.go b/internal/gateway/search.go index c5025cd5a..7bebf03b9 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -96,6 +96,14 @@ func searchFor(ctx context.Context) *CallFor { return f } +// magpieSearches is whether magpie answers a client's web search for p +// though p searches the web by itself: Settings' SearchAll, while magpie +// can search for it. Never for magpie's own searcher request, which is +// the provider's search. +func magpieSearches(ctx context.Context, p provider.Provider) bool { + return !searching(ctx) && settings.Load().SearchAll && canSearchFor(p) +} + // searchesItself says whether the provider searches the web by itself when // asked on this API. func searchesItself(p provider.Provider, proto provider.Protocol) bool { @@ -275,8 +283,8 @@ func searchAsked(proto provider.Protocol, body []byte) bool { // that doesn't search by itself. What is known of the provider is asked // first: Codex offers web_search on every turn, and each relayed turn was // parsed whole to learn it, for a provider that searches by itself. -func searchedForIt(p provider.Provider, from provider.Protocol, model string, body []byte) bool { - return (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model)) && searchAsked(from, body) +func searchedForIt(ctx context.Context, p provider.Provider, from provider.Protocol, model string, body []byte) bool { + return (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model) || magpieSearches(ctx, p)) && searchAsked(from, body) } // searcher is the model magpie searches with: the one Settings names, while diff --git a/internal/gateway/search_all_test.go b/internal/gateway/search_all_test.go new file mode 100644 index 000000000..a78050e7c --- /dev/null +++ b/internal/gateway/search_all_test.go @@ -0,0 +1,135 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// Settings' SearchAll (cybercaius on Discord: "能否强制支持联网搜索的供应商 +// 模型走代搜 API"): a provider that searches the web by itself is sent the +// client's web_search as sent while it is off; on, magpie's search APIs +// answer it and the provider is sent no search tool of its own. With no +// search magpie can run, the provider keeps its own: the client's search +// isn't lost. +func TestSearchAllTakesTheSearchFromAProviderThatSearches(t *testing.T) { + var mu sync.Mutex + var got []string + relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/models" { + io.WriteString(w, `{"data":[{"id":"claude-haiku-4-5"}]}`) + return + } + b, _ := io.ReadAll(r.Body) + var q map[string]json.RawMessage + json.Unmarshal(b, &q) + mu.Lock() + got = append(got, string(q["stream"])+" "+string(q["tools"])) + mu.Unlock() + if string(q["stream"]) == "true" && strings.Contains(string(q["tools"]), "input_schema") && !strings.Contains(string(b), "tool_result") { + // magpie's own web_search tool: the model calls it + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[],"usage":{"input_tokens":5}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"web_search","input":{}}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"latest go release\"}"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)) + return + } + if string(q["stream"]) == "true" { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[],"usage":{"input_tokens":5}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Go 1.27.1 is out."}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"m","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[{"type":"text","text":"Go 1.27.1 is out."}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":5}}`) + })) + defer relay.Close() + var asked atomic.Int32 + tavily := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"query":"x","results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"go1.27.1","score":0.9}]}`) + })) + defer tavily.Close() + + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + setHome(t, t.TempDir()) // no signed-in agent searches for it + p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: relay.URL, Models: []string{"claude-haiku-4-5"}, Searches: true} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + body := `{"model":"relay/claude-haiku-4-5","max_tokens":1000,"stream":false, + "messages":[{"role":"user","content":"What is the latest Go release? Search the web."}], + "tools":[{"type":"web_search_20250305","name":"web_search","max_uses":8}], + "metadata":{"user_id":"u"}}` + ask := func() (int, string) { + t.Helper() + mu.Lock() + got = nil + mu.Unlock() + asked.Store(0) + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + mu.Lock() + defer mu.Unlock() + if len(got) == 0 { + t.Fatal("the provider was asked nothing") + } + return int(asked.Load()), got[0] + } + all := func(on bool) { + t.Helper() + st := settings.Load() + st.SearchAll = on + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + } + + // on, but magpie can't search: the provider keeps its own, relayed as + // sent (not built again, which streams) + all(true) + if n, tools := ask(); n != 0 || !strings.HasPrefix(tools, "false ") || !strings.Contains(tools, "web_search_20250305") { + t.Fatalf("no search of magpie's: %d asks, provider sent %s", n, tools) + } + + forgetSearchKeys() + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: "tvly-good-0001", URL: tavily.URL}); err != nil { + t.Fatal(err) + } + all(false) + if n, tools := ask(); n != 0 || !strings.Contains(tools, "web_search_20250305") { + t.Fatalf("off: %d search API asks, provider sent %s", n, tools) + } + + all(true) + if n, tools := ask(); n == 0 || strings.Contains(tools, "web_search_20250305") { + t.Fatalf("on: %d search API asks, provider sent %s", n, tools) + } + if !magpieSearches(context.Background(), p) || magpieSearches(context.WithValue(context.Background(), searchingKey{}, true), p) { + t.Error("magpie's own searcher request lost the provider's search, or a client's kept it") + } +} diff --git a/internal/gateway/search_test.go b/internal/gateway/search_test.go index 84bf1da2d..7b8edee33 100644 --- a/internal/gateway/search_test.go +++ b/internal/gateway/search_test.go @@ -668,17 +668,17 @@ func TestSearchAskedLooksCheaply(t *testing.T) { } asks := []byte(`{"model":"gpt-5","input":"` + long + `","tools":[{"type":"web_search"}]}`) codex := provider.Provider{ID: "codex", Responses: provider.CodexBase, Account: &provider.Account{Agent: "codex"}} - if searchedForIt(codex, provider.Responses, "gpt-5", asks) { + if searchedForIt(context.Background(), codex, provider.Responses, "gpt-5", asks) { t.Error("Codex searches by itself, and magpie searched for it") } - if n := testing.AllocsPerRun(20, func() { searchedForIt(codex, provider.Responses, "gpt-5", asks) }); n > 20 { + if n := testing.AllocsPerRun(20, func() { searchedForIt(context.Background(), codex, provider.Responses, "gpt-5", asks) }); n > 20 { t.Errorf("a provider that searches by itself: %v allocations, the body parsed", n) } other := provider.Provider{ID: "x", Responses: "https://example.test/v1"} - if !searchedForIt(other, provider.Responses, "gpt-5", asks) { + if !searchedForIt(context.Background(), other, provider.Responses, "gpt-5", asks) { t.Error("a provider that doesn't search: magpie didn't search for it") } - if searchedForIt(other, provider.Responses, "gpt-5", plain) { + if searchedForIt(context.Background(), other, provider.Responses, "gpt-5", plain) { t.Error("a body offering no search: magpie searched for it") } } @@ -692,13 +692,13 @@ func BenchmarkSearchedForIt(b *testing.B) { b.Run("codex-asks", func(b *testing.B) { b.ReportAllocs() for b.Loop() { - searchedForIt(codex, provider.Responses, "gpt-5", asks) + searchedForIt(context.Background(), codex, provider.Responses, "gpt-5", asks) } }) b.Run("other-plain", func(b *testing.B) { b.ReportAllocs() for b.Loop() { - searchedForIt(other, provider.Responses, "gpt-5", plain) + searchedForIt(context.Background(), other, provider.Responses, "gpt-5", plain) } }) } diff --git a/internal/gui/api.go b/internal/gui/api.go index 6acc547e2..7dbee684b 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1470,6 +1470,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { // used or left is the Usage page's toggle as much as Settings', set on its own in.QuotaLeft = cur.QuotaLeft in.QuotaReads = cur.QuotaReads // set on its own (quota-reads below) + in.SearchAll = cur.SearchAll // set on its own (search-all below) in.UsageOrder = cur.UsageOrder // the Usage page's, dragged there // and what the tray panel's Allowances tab leaves out, set there in.PanelUsageHidden = cur.PanelUsageHidden @@ -1639,6 +1640,24 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // whether magpie searches for a model whose provider searches by itself + // too (Settings › Models › Web search) + mux.HandleFunc("POST /api/settings/search-all", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + On bool `json:"on"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + s := settings.Load() + s.SearchAll = in.On + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // whether agents' sign-ins are read and served as subscriptions // (#1535): saved, the accounts read before are forgotten at once mux.HandleFunc("POST /api/settings/account-discovery", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/api_settings_test.go b/internal/gui/api_settings_test.go index 326680132..99d4a3597 100644 --- a/internal/gui/api_settings_test.go +++ b/internal/gui/api_settings_test.go @@ -439,3 +439,31 @@ func TestSettingsNoBird(t *testing.T) { } } } + +// "Models that search by themselves" (Settings › Models › Web search) is +// set on its own: the endpoint sets it, and a save of the whole page, which +// doesn't name it, keeps it. +func TestSettingsSearchAllSetOnItsOwn(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + h := Handler(nil, nil) + post := func(path, body string) { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + if rec.Code != http.StatusOK { + t.Fatalf("%s %s: %d %s", path, body, rec.Code, rec.Body) + } + } + post("/api/settings/search-all", `{"on":true}`) + if !settings.Load().SearchAll { + t.Fatal("search-all didn't set it") + } + post("/api/settings", `{"theme":"dark"}`) + if !settings.Load().SearchAll { + t.Fatal("a save of the page dropped searchAll") + } + post("/api/settings/search-all", `{"on":false}`) + if settings.Load().SearchAll { + t.Fatal("search-all didn't turn it off") + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 3a0b22f6f..6a4806b40 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1334,6 +1334,11 @@ const I18N = { "Image recognition MCP server": "识图 MCP 服务器", "Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer and the image as a URL or data URL.": "智能体可以把识图添加为 MCP 服务器(Streamable HTTP),提供一个 analyze_image 工具:用识图模型读取文件路径、URL 或 data URL 中的图片。从其他电脑访问时,请以 Authorization: Bearer 发送网关密钥,图片以 URL 或 data URL 传入。", "The other is asked when it fails": "失败时再用另一种", + "Models that search by themselves": "自带联网搜索的模型", + "Search with their provider's own search, or with magpie's, as every other model does": "用供应商自带的联网搜索,或像其他模型一样用 magpie 代搜", + "Their own": "自带搜索", + "magpie's": "magpie 代搜", + "When provider search is off, only configured Search APIs are used, for every model. Without a Search API, magpie does not add a search tool.": "关闭供应商代搜后,所有模型都只使用已配置的搜索 API;未配置时,Magpie 不添加搜索工具。", "Model search": "模型代搜", "No provider can search, so these are asked": "没有能搜索的供应商,由这些 API 来搜", "When provider search is off, only configured Search APIs are used. Without a Search API, magpie does not add a search tool. Providers' native web search is unchanged.": "关闭供应商代搜后,仅使用已配置的搜索 API;未配置时,Magpie 不添加搜索工具。供应商自带的联网搜索不受影响。", @@ -5566,6 +5571,11 @@ const I18N = { "Image recognition MCP server": "識圖 MCP 伺服器", "Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer and the image as a URL or data URL.": "智慧體可以把識圖新增為 MCP 伺服器(Streamable HTTP),提供一個 analyze_image 工具:用識圖模型讀取檔案路徑、URL 或 data URL 中的圖片。從其他電腦存取時,請以 Authorization: Bearer 傳送閘道金鑰,圖片以 URL 或 data URL 傳入。", "The other is asked when it fails": "失敗時再用另一種", + "Models that search by themselves": "自帶聯網搜尋的模型", + "Search with their provider's own search, or with magpie's, as every other model does": "用供應商內建的聯網搜尋,或像其他模型一樣用 magpie 代搜", + "Their own": "內建搜尋", + "magpie's": "magpie 代搜", + "When provider search is off, only configured Search APIs are used, for every model. Without a Search API, magpie does not add a search tool.": "關閉供應商代搜後,所有模型都只使用已設定的搜尋 API;未設定時,Magpie 不新增搜尋工具。", "Model search": "模型代搜", "No provider can search, so these are asked": "沒有能搜尋的供應商,由這些 API 來搜", "When provider search is off, only configured Search APIs are used. Without a Search API, magpie does not add a search tool. Providers' native web search is unchanged.": "關閉供應商代搜後,僅使用已設定的搜尋 API;未設定時,Magpie 不新增搜尋工具。供應商內建的聯網搜尋不受影響。", @@ -9769,6 +9779,11 @@ const I18N = { "Image recognition MCP server": "画像認識 MCP サーバー", "Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer and the image as a URL or data URL.": "エージェントは、画像認識を analyze_image ツール 1 つを持つ MCP サーバー(Streamable HTTP)として追加できます。画像認識のモデルで、ファイルパス、URL、data URL の画像を読み取ります。別のコンピューターからは、ゲートウェイキーを Authorization: Bearer として送り、画像は URL か data URL で渡してください。", "The other is asked when it fails": "失敗したときはもう一方を使います", + "Models that search by themselves": "自分でウェブ検索するモデル", + "Search with their provider's own search, or with magpie's, as every other model does": "プロバイダのネイティブなウェブ検索を使うか、ほかのモデルと同じく magpie の検索を使います", + "Their own": "ネイティブ検索", + "magpie's": "magpie の検索", + "When provider search is off, only configured Search APIs are used, for every model. Without a Search API, magpie does not add a search tool.": "プロバイダによる代行検索がオフの場合、どのモデルにも設定済みの検索 API のみを使用します。検索 API がない場合、magpie は検索ツールを追加しません。", "Model search": "モデルによる代理検索", "No provider can search, so these are asked": "検索できるプロバイダがないため、これらを使います", "When provider search is off, only configured Search APIs are used. Without a Search API, magpie does not add a search tool. Providers' native web search is unchanged.": "プロバイダによる代行検索がオフの場合、設定済みの検索 API のみを使用します。検索 API がない場合、magpie は検索ツールを追加しません。プロバイダのネイティブなウェブ検索には影響しません。", @@ -14002,6 +14017,11 @@ const I18N = { "Image recognition MCP server": "Bilderkennung als MCP-Server", "Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer and the image as a URL or data URL.": "Agenten können die Bilderkennung als MCP-Server (Streamable HTTP) mit einem analyze_image-Tool hinzufügen, das ein Bild aus einem Dateipfad, einer URL oder einer Data-URL mit dem Modell der Bilderkennung liest. Von einem anderen Computer aus einen Gateway-Schlüssel als Authorization: Bearer senden und das Bild als URL oder Data-URL übergeben.", "The other is asked when it fails": "Scheitert es, wird das andere gefragt", + "Models that search by themselves": "Modelle, die selbst suchen", + "Search with their provider's own search, or with magpie's, as every other model does": "Mit der nativen Websuche ihres Anbieters oder, wie jedes andere Modell, mit der von magpie", + "Their own": "Eigene Suche", + "magpie's": "Von magpie", + "When provider search is off, only configured Search APIs are used, for every model. Without a Search API, magpie does not add a search tool.": "Wenn die Anbietersuche ausgeschaltet ist, werden für jedes Modell nur konfigurierte Such-APIs verwendet. Ohne Such-API fügt magpie kein Suchwerkzeug hinzu.", "Model search": "Modellsuche", "No provider can search, so these are asked": "Kein Anbieter kann suchen, daher werden diese gefragt", "When provider search is off, only configured Search APIs are used. Without a Search API, magpie does not add a search tool. Providers' native web search is unchanged.": "Wenn die Anbietersuche ausgeschaltet ist, werden nur konfigurierte Such-APIs verwendet. Ohne Such-API fügt magpie kein Suchwerkzeug hinzu. Die native Websuche der Anbieter bleibt unverändert.", diff --git a/internal/gui/assets/plugins/search/settings.js b/internal/gui/assets/plugins/search/settings.js index 68614bc72..126005a92 100644 --- a/internal/gui/assets/plugins/search/settings.js +++ b/internal/gui/assets/plugins/search/settings.js @@ -159,6 +159,16 @@ function renderSearch(s, keep) { (v) => savePrefs({ ...keep, searchFirst: v === "api" ? "api" : "" }))); r.id = "searchFirstRow"; } + // a model whose provider searches the web by itself is given magpie's + // search instead, as every other model is (cybercaius on Discord); only + // while magpie has a search to give it + if (s.searchProvider || asked.length) { + const r = row(t("Models that search by themselves"), t("Search with their provider's own search, or with magpie's, as every other model does"), + segs([["own", t("Their own")], ["magpie", t("magpie's")]], s.searchAll ? "magpie" : "own", + (v) => writingPrefs(api("settings/search-all", { on: v === "magpie" })) + .then((ns) => { prefs = state.settings = ns; renderSettings(); }).catch(settingsErr))); + r.id = "searchAllRow"; + } // the same search as an MCP server of the gateway's (Kayphoon on // Discord), for an agent to mount as its web_search and web_fetch tools const mcpURL = mcpAddress(s, "/mcp/magpie/web-search"); @@ -307,7 +317,7 @@ function renderSearcher(s, keep, box) { const icOf = (id) => choices.find((x) => x.id === id.split("/")[0])?.icon; const r = el("div", "row pref searcher-row"); const who = el("div", "who"); - const sub = el("div", "sub", off ? t("When provider search is off, only configured Search APIs are used. Without a Search API, magpie does not add a search tool. Providers' native web search is unchanged.") : t("When a model can't search the web directly, the selected provider searches for it and returns the results. Searches may use the service's quota or incur charges; if the provider magpie picks fails, it tries other available sources, but a provider you select here is never replaced by another provider, only by your Search APIs.")); + const sub = el("div", "sub", off ? (s.searchAll ? t("When provider search is off, only configured Search APIs are used, for every model. Without a Search API, magpie does not add a search tool.") : t("When provider search is off, only configured Search APIs are used. Without a Search API, magpie does not add a search tool. Providers' native web search is unchanged.")) : t("When a model can't search the web directly, the selected provider searches for it and returns the results. Searches may use the service's quota or incur charges; if the provider magpie picks fails, it tries other available sources, but a provider you select here is never replaced by another provider, only by your Search APIs.")); if (!off && v && s.searchUnused) { const why = { gone: t("it is no longer in magpie"), off: t("it is turned off"), cant: t("it can't search the web by itself"), nomodel: t("it lists no model") }[s.searchUnused] || s.searchUnused; sub.append(" · ", el("span", "warn searcher-unused", t("{who} isn't used: {why}, so magpie picks one", { who: named(v), why }))); diff --git a/internal/gui/tests/search-all.test.cjs b/internal/gui/tests/search-all.test.cjs new file mode 100644 index 000000000..d7347ffef --- /dev/null +++ b/internal/gui/tests/search-all.test.cjs @@ -0,0 +1,141 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › Models › Web search (cybercaius on Discord: "能否强制支持联网搜索的 +// 供应商模型走代搜 API"): "Models that search by themselves" picks their +// provider's own search, as before, or magpie's, as every other model has. +// A click sets searchAll on its own (POST /api/settings/search-all), a save +// of the rest of the page doesn't send it (the server keeps it), and the +// page isn't moved. With nothing magpie +// can search with the row isn't there. With provider search off and +// searchAll on, the searcher's note no longer says a provider's own search +// is unchanged. In every language, wide and narrow. +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 { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const words = { + en: { name: "Models that search by themselves", own: "Their own", magpie: "magpie's", apis: "Search APIs", every: "for every model", unchanged: "unchanged" }, + zh: { name: "自带联网搜索的模型", own: "自带搜索", magpie: "magpie 代搜", apis: "搜索 API", every: "所有模型", unchanged: "不受影响" }, + "zh-TW": { name: "自帶聯網搜尋的模型", own: "內建搜尋", magpie: "magpie 代搜", apis: "搜尋 API", every: "所有模型", unchanged: "不受影響" }, + ja: { name: "自分でウェブ検索するモデル", own: "ネイティブ検索", magpie: "magpie の検索", apis: "検索 API", every: "どのモデルにも", unchanged: "影響しません" }, + de: { name: "Modelle, die selbst suchen", own: "Eigene Suche", magpie: "Von magpie", apis: "Such-APIs", every: "für jedes Modell", unchanged: "unverändert" }, +}; + +function serve(lang, saved, all, { provider = true, apis = true, searcher = "ds", searchAll = false } = {}) { + const settings = { lang, theme: "light", redact: true, searcher, searchAll, + searchProvider: provider ? "DeepSeek · deepseek-flash" : "", + searchVendors: [{ id: "tavily", name: "Tavily", keysURL: "https://app.tavily.com/home" }], + searchAPIs: apis ? [{ vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true }] : [], + searchChoices: [{ id: "ds", name: "DeepSeek", icon: "deepseek", small: "deepseek-flash", models: [] }] }; + const state = { agents: [], profiles: [], settings }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/settings/search-all") { + all.push(JSON.parse(r.request().postData())); + settings.searchAll = all.at(-1).on; + return json(settings); + } + if (url.pathname === "/api/settings") { + if (r.request().method() === "POST") { + saved.push(JSON.parse(r.request().postData())); + Object.assign(settings, saved.at(-1)); + } + return json(settings); + } + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + 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)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404 }); } + }; +} + +async function open(engine, t, lang, saved, opts, width = 1100, all = []) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, saved, all, opts)); + await watchSettingsReads(page); + await page.goto(`http://magpie.test/?view=settings&tab=models&lang=${lang}`); + await settingsDrawn(page); // rows found are the ones that stay (#1659) + return { page, errors }; +} + +async function press(page, locator) { + await reach(page, locator); + const b = await locator.boundingBox(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, w] of Object.entries(words)) { + for (const width of [1100, 560]) { + test(`${engine} ${lang} ${width}px: a model that searches by itself can be given magpie's search`, async (t) => { + const saved = [], all = []; + const { page, errors } = await open(engine, t, lang, saved, {}, width, all); + const row = page.locator("#searchList #searchAllRow"); + await reach(page, row); + assert.equal(await row.locator(".name").textContent(), w.name); + const own = row.locator(".segs button", { hasText: w.own }); + const mine = row.locator(".segs button", { hasText: w.magpie }); + assert(await own.evaluate((b) => b.classList.contains("on")), "their own search at first"); + assert(!await mine.evaluate((b) => b.classList.contains("on"))); + // the row fits the window: nothing wider than the page + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "the page scrolls sideways"); + const rb = await row.boundingBox(); + for (const b of [own, mine]) { + const bb = await b.boundingBox(); + assert(bb.x >= rb.x - 1 && bb.x + bb.width <= rb.x + rb.width + 1, `${await b.textContent()} sticks out of its row`); + } + + await reach(page, mine); + const before = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]); + await press(page, mine); + for (let i = 0; i < 50 && !all.length; i++) await page.waitForTimeout(50); + assert.deepEqual(all, [{ on: true }], "set once, on its own"); + assert.equal(saved.length, 0, "the rest of the settings not written"); + await page.waitForFunction(() => prefsBusy === 0); + await page.locator("#searchAllRow .segs button.on", { hasText: w.magpie }).waitFor(); + assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), before, "the click moved nothing"); + + // another choice saved on the page keeps it + await press(page, page.locator("#searchFirstRow .segs button", { hasText: w.apis })); + for (let i = 0; i < 50 && saved.length < 1; i++) await page.waitForTimeout(50); + assert.equal(saved.at(-1).searchFirst, "api"); + await page.waitForFunction(() => prefsBusy === 0); + await page.locator("#searchAllRow .segs button.on", { hasText: w.magpie }).waitFor(); + + // and back + await press(page, page.locator("#searchAllRow .segs button", { hasText: w.own })); + for (let i = 0; i < 50 && all.length < 2; i++) await page.waitForTimeout(50); + assert.deepEqual(all.at(-1), { on: false }); + assert.deepEqual(errors, []); + }); + } + + test(`${engine} ${lang}: with nothing magpie can search with there is nothing to choose`, async (t) => { + const { page } = await open(engine, t, lang, [], { provider: false, apis: false }); + await page.locator("#searchList .row.search-add").waitFor(); + assert.equal(await page.locator("#searchAllRow").count(), 0); + }); + + test(`${engine} ${lang}: provider search off, every model is searched with the APIs`, async (t) => { + const { page } = await open(engine, t, lang, [], { provider: false, searcher: "off", searchAll: true }); + await page.locator("#searchAllRow").waitFor(); + const note = await page.locator("#searchList .searcher-row .sub").first().innerText(); + assert(note.includes(w.every) && !note.includes(w.unchanged), note); + }); + } +} diff --git a/internal/gui/tests/search-first.test.cjs b/internal/gui/tests/search-first.test.cjs index e05c15992..6ca905a8d 100644 --- a/internal/gui/tests/search-first.test.cjs +++ b/internal/gui/tests/search-first.test.cjs @@ -10,7 +10,7 @@ const fs = require("node:fs/promises"); const path = require("node:path"); const { test } = require("node:test"); const { chromium, webkit } = require("playwright"); -const { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); +const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs"); const assets = path.resolve(__dirname, "../assets"); const words = { @@ -64,14 +64,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.goto("http://magpie.test/?view=settings&tab=models"); await settingsDrawn(page); // rows found are the ones that stay (#1659) const row = page.locator("#searchList #searchFirstRow"); - await row.waitFor(); - await row.scrollIntoViewIfNeeded(); + // the reader wheels it into sight: rows below it (searchAllRow) can + // put it under the window's foot, where the app undoes a scroll + // that isn't the reader's + await reach(page, row); assert.equal(await row.locator(".name").textContent(), w.name); const model = row.locator(".segs button", { hasText: w.model }); const apis = row.locator(".segs button", { hasText: w.apis }); assert(await model.evaluate((b) => b.classList.contains("on")), "model search first at first"); assert(!await apis.evaluate((b) => b.classList.contains("on"))); + await reach(page, apis); const before = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]); const b = await apis.boundingBox(); await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); @@ -88,6 +91,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), before, "the click moved nothing"); // and back + await reach(page, page.locator("#searchFirstRow .segs button", { hasText: w.model })); const m = await page.locator("#searchFirstRow .segs button", { hasText: w.model }).boundingBox(); await page.mouse.click(m.x + m.width / 2, m.y + m.height / 2); for (let i = 0; i < 50 && saved.length < 2; i++) await page.waitForTimeout(50); diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 399ae1a28..df20961b4 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -471,6 +471,12 @@ type Settings struct { // SearchFirstAPI for the search APIs, the provider's search after them // when they fail; empty for the provider first, as before. SearchFirst string `json:"searchFirst,omitempty"` + // SearchAll is that magpie searches for every model, one whose + // provider searches the web by itself too (cybercaius on Discord): + // the client's search is answered by the searcher and the search APIs, + // as for a model that can't, and the provider is sent no search tool. + // Only while magpie can search for it (gateway.magpieSearches). + SearchAll bool `json:"searchAll,omitempty"` // TrayUsages are the subscriptions and plans whose windows are shown // beside the tray icon, in the order shown, each by its provider and // account ("claude|a@b.c"); none when empty.