diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 5fed821ba..12b3a1162 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -2212,11 +2212,17 @@ keeps the mark, and backup and sync carry it with the rest of the entry. A mixed search spends every mixed API's quota, takes as long as the slowest, and gives the model up to twice the pages (20 at most). On the CLI, `magpie search mix ,` and `magpie search mix off` set it, and `magpie search` lists -a mixed one as mix. Settings' page doesn't show or set it yet. +a mixed one as mix. In Settings › Models › Web search, Advanced (shown +with two or more search APIs on, open while some are mixed) has "Ask the +search APIs": In order, or All at once, which marks every API on +(`POST /api/settings/search-api` with `mix`, the vendors, or `[]` for none; +heyiwei5 on X). A mix of only some of them has neither choice on, and its +line names them. Covered by `TestSearchAPIsMixedAskedTogether`, `TestSearchAPIsMixedOneDown`, `TestSearchAPIsMixedAllDownAsksTheRest`, `TestSearchAPIsMixedCapped`, -`TestMixSearchAPIs` and `TestSearchCLIMix`. +`TestMixSearchAPIs`, `TestSearchCLIMix`, `TestSearchAPIsMixedFromSettings` +and `search-mix.test.cjs`. ## A search API's keys diff --git a/internal/gui/api.go b/internal/gui/api.go index 5f4148fea..eabe868ab 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -673,6 +673,9 @@ type searchAPIJSON struct { Quota bool `json:"quota,omitempty"` // Off: switched off, kept but never asked (#2286) Off bool `json:"off,omitempty"` + // Mix: asked together with the others marked so, their pages merged + // (provider.SearchAPI.Mix, #2845) + Mix bool `json:"mix,omitempty"` // KeyList is each key in its order, masked, on or off, and resting // (辰林鸭~ on Discord) KeyList []searchKeyJSON `json:"keyList"` @@ -739,7 +742,7 @@ func searchState(s *settingsJSON) { } s.SearchAPIs, s.SearchVendors = []searchAPIJSON{}, []searchVendorJSON{} for _, a := range provider.StoredSearchAPIs() { - j := searchAPIJSON{Vendor: a.Vendor, Name: a.Name(), URL: a.URL, Ready: a.Ready(), Keys: len(a.Keys()), Pick: a.Pick, Quota: gateway.CanReadSearchQuota(a), Off: a.Off} + j := searchAPIJSON{Vendor: a.Vendor, Name: a.Name(), URL: a.URL, Ready: a.Ready(), Keys: len(a.Keys()), Pick: a.Pick, Quota: gateway.CanReadSearchQuota(a), Off: a.Off, Mix: a.Mix} if a.Key != "" { j.Key = a.MaskedKey() } @@ -3054,13 +3057,16 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { writeJSON(rw, settingsState()) }) // a web search API added, given a new key or address, switched on or - // off, or taken away; or the APIs put in a new order (#2286) + // off, or taken away; or the APIs put in a new order (#2286); or those + // asked together named (Mix: two or more, or none for one at a time, + // #2845) mux.HandleFunc("POST /api/settings/search-api", func(rw http.ResponseWriter, r *http.Request) { var in struct { Vendor, Key, URL, Pick string Remove bool On *bool Arrange []string + Mix []string // Append: the keys typed for an API added before go after its // own, which stay, rather than in their place Append bool @@ -3073,6 +3079,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { switch { case in.Arrange != nil: err = provider.ArrangeSearchAPIs(in.Arrange) + case in.Mix != nil: + err = provider.MixSearchAPIs(in.Mix) case in.Remove: err = provider.RemoveSearchAPI(in.Vendor) case in.On != nil: diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f92d3d864..71a2ad4ee 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1764,6 +1764,10 @@ const I18N = { "The other is asked when it fails": "失败时再用另一种", "Models that search by themselves": "自带联网搜索的模型", "Results per search": "每次搜索的结果条数", + "Ask the search APIs": "搜索 API 的调用方式", + "All at once": "同时调用", + "In order, the next only when one fails or finds nothing; or all at once, their results merged without repeats": "按顺序:前一个失败或没搜到才问下一个;同时调用:结果合并,去掉重复", + "Asked together now: {names}": "现在同时调用:{names}", "More results give the model more to read: each carries up to 1500 bytes of its page": "结果越多,模型要读的内容也越多:每条最多带 1500 字节的网页正文", "Search with their provider's own search, or with magpie's, as every other model does": "用供应商自带的联网搜索,或像其他模型一样用 magpie 代搜", "Their own": "自带搜索", @@ -7111,6 +7115,10 @@ const I18N = { "The other is asked when it fails": "失敗時再用另一種", "Models that search by themselves": "自帶聯網搜尋的模型", "Results per search": "每次搜尋的結果數", + "Ask the search APIs": "搜尋 API 的呼叫方式", + "All at once": "同時呼叫", + "In order, the next only when one fails or finds nothing; or all at once, their results merged without repeats": "按順序:前一個失敗或沒搜到才問下一個;同時呼叫:結果合併,去掉重複", + "Asked together now: {names}": "現在同時呼叫:{names}", "More results give the model more to read: each carries up to 1500 bytes of its page": "結果越多,模型要讀的內容也越多:每筆最多帶 1500 位元組的網頁內文", "Search with their provider's own search, or with magpie's, as every other model does": "用供應商內建的聯網搜尋,或像其他模型一樣用 magpie 代搜", "Their own": "內建搜尋", @@ -12427,6 +12435,10 @@ const I18N = { "The other is asked when it fails": "失敗したときはもう一方を使います", "Models that search by themselves": "自分でウェブ検索するモデル", "Results per search": "1 回の検索の結果数", + "Ask the search APIs": "検索 API の使い方", + "All at once": "同時に", + "In order, the next only when one fails or finds nothing; or all at once, their results merged without repeats": "順番:失敗したか何も見つからなかったときだけ次へ。同時に:結果をまとめ、重複を除きます", + "Asked together now: {names}": "いま同時に使用:{names}", "More results give the model more to read: each carries up to 1500 bytes of its page": "結果が多いほどモデルが読む量も増えます。1 件につきページ本文を最大 1500 バイト含みます", "Search with their provider's own search, or with magpie's, as every other model does": "プロバイダのネイティブなウェブ検索を使うか、ほかのモデルと同じく magpie の検索を使います", "Their own": "ネイティブ検索", @@ -17774,6 +17786,10 @@ const I18N = { "The other is asked when it fails": "Scheitert es, wird das andere gefragt", "Models that search by themselves": "Modelle, die selbst suchen", "Results per search": "Ergebnisse pro Suche", + "Ask the search APIs": "Such-APIs fragen", + "All at once": "Alle zugleich", + "In order, the next only when one fails or finds nothing; or all at once, their results merged without repeats": "Der Reihe nach, die nächste nur, wenn eine scheitert oder nichts findet; oder alle zugleich, ihre Ergebnisse ohne Doppelte zusammengeführt", + "Asked together now: {names}": "Jetzt zugleich gefragt: {names}", "More results give the model more to read: each carries up to 1500 bytes of its page": "Mehr Ergebnisse geben dem Modell mehr zu lesen: Jedes enthält bis zu 1500 Bytes seiner Seite", "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", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 842579a77..ce42981a0 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -438,6 +438,10 @@
Web search
+
Quick check
Replies
diff --git a/internal/gui/assets/plugins/search/settings.js b/internal/gui/assets/plugins/search/settings.js index f25b5303b..53bf7446b 100644 --- a/internal/gui/assets/plugins/search/settings.js +++ b/internal/gui/assets/plugins/search/settings.js @@ -195,6 +195,32 @@ function renderSearch(s, keep) { // where the reader is: gateway mode has no Library, and the Library can // be turned off mcp.querySelector(".who").append(...libWay("magpie-web-search", t("Give agents Magpie Web Search…"), "search-mcp-lib")); + searchMore(asked, set); +} + +// Web search's Advanced: the search APIs asked in order, or all at once +// with their results merged and repeats left out (#2845's mix, heyiwei5 +// on X). Seldom changed, so folded, and open while some are mixed; with +// fewer than two on there is nothing to mix. A mix of some of them, made +// with magpie search mix, has neither choice on, and the line names them. +function searchMore(asked, set) { + const more = $("#searchMore"), list = $("#searchMoreList"); + list.replaceChildren(); + more.hidden = asked.length < 2; + if (more.hidden) return; + const mixed = asked.filter((a) => a.mix); + const cur = mixed.length < 2 ? "order" : mixed.length === asked.length ? "all" : ""; + const r = el("div", "row pref"); + r.id = "searchMixRow"; + const who = el("div", "who"), val = el("div", "val"); + who.append(el("div", "name", t("Ask the search APIs")), + el("div", "sub", cur ? t("In order, the next only when one fails or finds nothing; or all at once, their results merged without repeats") + : t("Asked together now: {names}", { names: mixed.map((a) => a.name).join(", ") }))); + val.append(segs([["order", t("In order")], ["all", t("All at once")]], cur, + (v) => set({ mix: v === "all" ? asked.map((a) => a.vendor) : [] }))); + r.append(who, val); + list.append(r); + if (mixed.length > 1) more.open = true; } // Plugins › Built-in › Web search's own line (featGo): what a model that diff --git a/internal/gui/search_mix_test.go b/internal/gui/search_mix_test.go new file mode 100644 index 000000000..df7bcbcc0 --- /dev/null +++ b/internal/gui/search_mix_test.go @@ -0,0 +1,77 @@ +package gui + +import ( + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Settings › Web search › Advanced asks the search APIs together (#2845's +// mix, heyiwei5 on X): "mix" names two or more to ask at once, an empty +// list asks them one at a time again, and the settings say which are +// mixed. One named alone, or one not set up, is refused and changes +// nothing. +func TestSearchAPIsMixedFromSettings(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + post := func(body string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings/search-api", strings.NewReader(body))) + return rec + } + for _, b := range []string{`{"vendor":"tavily","key":"tvly-dev-aaaaaaaaaaaa1111"}`, `{"vendor":"brave","key":"BSAaaaaaaaaaaaaaaaaaaaaaaaa"}`, `{"vendor":"exa","key":"exa-aaaaaaaaaaaaaaaaaaaa"}`} { + if rec := post(b); rec.Code != 200 { + t.Fatalf("%s: %d %s", b, rec.Code, rec.Body) + } + } + mixed := func() (out []string) { + t.Helper() + var s settingsJSON + searchState(&s) + for _, a := range s.SearchAPIs { + if a.Mix { + out = append(out, a.Vendor) + } + } + return out + } + if rec := post(`{"mix":["tavily","brave","exa"]}`); rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if got := strings.Join(mixed(), ","); got != "tavily,brave,exa" { + t.Fatalf("mixed %q", got) + } + for _, as := range provider.SearchAPIs() { + if !as.Mix { + t.Fatalf("not saved as mixed: %+v", as.Vendor) + } + } + for _, b := range []string{`{"mix":["tavily"]}`, `{"mix":["tavily","you"]}`} { + if rec := post(b); rec.Code < 400 { + t.Errorf("%s: %d", b, rec.Code) + } + } + if got := strings.Join(mixed(), ","); got != "tavily,brave,exa" { + t.Fatalf("a refused mix changed it: %q", got) + } + // a key changed keeps the mark, as an edit from Settings sends none + if rec := post(`{"vendor":"brave","key":"BSAbbbbbbbbbbbbbbbbbbbbbbbb"}`); rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if got := strings.Join(mixed(), ","); got != "tavily,brave,exa" { + t.Fatalf("a new key unmixed it: %q", got) + } + if rec := post(`{"mix":[]}`); rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if got := mixed(); len(got) != 0 { + t.Fatalf("still mixed %v", got) + } +} diff --git a/internal/gui/tests/search-mix.test.cjs b/internal/gui/tests/search-mix.test.cjs new file mode 100644 index 000000000..899ceb970 --- /dev/null +++ b/internal/gui/tests/search-mix.test.cjs @@ -0,0 +1,134 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › Models › Web search › Advanced (#2845's mix, heyiwei5 on X): +// "Ask the search APIs" in order, or all at once with their results merged. +// The fold shows only with two or more APIs on, closed while none is mixed; +// All at once names every API on (POST /api/settings/search-api {mix}), In +// order names none, and the fold is open while some are mixed. A mix of +// some of them (magpie search mix) has neither choice on, and its line +// names them. 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: ["Ask the search APIs", "In order", "All at once", "Advanced"], + zh: ["搜索 API 的调用方式", "按顺序", "同时调用", "高级"], + "zh-TW": ["搜尋 API 的呼叫方式", "按順序", "同時呼叫", "進階"], + ja: ["検索 API の使い方", "順番", "同時に", "詳細設定"], + de: ["Such-APIs fragen", "Der Reihe nach", "Alle zugleich", null], +}; + +const API = { + tavily: { vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true }, + brave: { vendor: "brave", name: "Brave Search", key: "BSA…abcd", ready: true }, + exa: { vendor: "exa", name: "Exa", key: "exa…abcd", ready: true }, +}; + +function serve(lang, apis, posts) { + const settings = { lang, theme: "light", redact: true, searcher: "off", + searchVendors: Object.values(API).map((a) => ({ id: a.vendor, name: a.name })), + searchAPIs: apis }; + 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-api") { + const b = JSON.parse(r.request().postData()); + posts.push(b); + settings.searchAPIs = settings.searchAPIs.map((a) => ({ ...a, mix: b.mix.includes(a.vendor) || undefined })); + return json(settings); + } + if (url.pathname === "/api/settings") 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, apis, posts, width) { + 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, apis, posts)); + await watchSettingsReads(page); + await page.goto(`http://magpie.test/?view=settings&tab=models&lang=${lang}`); + await settingsDrawn(page); + 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, [name, inOrder, all, adv]] of Object.entries(words)) { + for (const width of [1100, 560]) { + test(`${engine} ${lang} ${width}px: the search APIs are asked all at once from Advanced, and in order again`, async (t) => { + const posts = []; + const { page, errors } = await open(engine, t, lang, [API.tavily, API.brave], posts, width); + const more = page.locator("#searchMore"); + await reach(page, more.locator("summary")); + assert.equal(await more.evaluate((d) => d.open), false, "closed while none is mixed"); + if (adv) assert.equal((await more.locator("summary").textContent()).trim(), adv); + await press(page, more.locator("summary")); + const row = page.locator("#searchMixRow"); + await reach(page, row); + assert.equal(await row.locator(".name").textContent(), name); + assert.notEqual(await row.locator(".sub").innerText(), ""); + assert.deepEqual(await row.locator(".segs button").evaluateAll((bs) => bs.map((b) => b.textContent.trim())), [inOrder, all]); + assert.equal(await row.locator(".segs button.on").textContent(), inOrder); + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "the page scrolls sideways"); + const rb = await row.boundingBox(); + for (const b of await row.locator(".segs button").all()) { + 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 press(page, row.locator(".segs button", { hasText: all })); + for (let i = 0; i < 50 && !posts.length; i++) await page.waitForTimeout(50); + assert.deepEqual(posts, [{ mix: ["tavily", "brave"] }]); + await page.locator("#searchMixRow .segs button.on", { hasText: all }).waitFor(); + assert.equal(await more.evaluate((d) => d.open), true, "open while some are mixed"); + + await press(page, page.locator("#searchMixRow .segs button", { hasText: inOrder })); + for (let i = 0; i < 50 && posts.length < 2; i++) await page.waitForTimeout(50); + assert.deepEqual(posts[1], { mix: [] }); + await page.locator("#searchMixRow .segs button.on", { hasText: inOrder }).waitFor(); + assert.deepEqual(errors, []); + }); + } + + test(`${engine} ${lang}: one search API has no Advanced; a mix of some names them`, async (t) => { + { + const { page, errors } = await open(engine, t, lang, [API.tavily, { ...API.brave, off: true }], [], 560); + await reach(page, page.locator("#searchMcpRow")); + assert.equal(await page.locator("#searchMore").isVisible(), false, "nothing to mix with one on"); + assert.deepEqual(errors, []); + } + const { page, errors } = await open(engine, t, lang, [{ ...API.tavily, mix: true }, API.exa, { ...API.brave, mix: true }], [], 560); + const row = page.locator("#searchMixRow"); + assert.equal(await page.locator("#searchMore").evaluate((d) => d.open), true); + await reach(page, row); + assert.equal(await row.locator(".segs button.on").count(), 0, "neither choice is what is set"); + const sub = await row.locator(".sub").innerText(); + assert(sub.includes("Tavily") && sub.includes("Brave Search") && !sub.includes("Exa"), sub); + assert.deepEqual(errors, []); + }); + } +}