search: searchers picked to follow the one named, tried in their order when it fails (axelburks on Discord)

axelburks asked for more than one searcher, so that when one fails
another provider searches. A searcher named in Settings gave way to no
other provider before, only to the Search APIs. Automatic already fell
back to up to three.

- settings: SearcherThen, the searchers after the one named. Entries
  are trimmed. Blanks, "off", the named one and repeats are dropped.
- gateway: when the named searcher fails (the context still live),
  modelSearch asks each of SearcherThen in order and skips one that
  can't search now or is the same model. The first that searches
  answers, and the call is marked searchingInstead, so the Routing row
  says why the named one didn't search. If all of them fail, their
  errors go back together, saying "the searchers picked ..., in their
  order", and webSearch goes on to the Search APIs as before.
  SearchFailure.Instead names the one that searched in its place.
- gui api: searchFailed.instead. A save takes only searchers that
  Searchers() offers. A save without searcherThen keeps the list, since
  the page's prefsKeep doesn't send it, and [] clears it.
- Settings › Web search (plugins/search/settings.js, outside app.js's
  budget): an "If it fails" row under a named searcher, with numbered
  chips and Add. A chip's picker changes the chip or removes it. The
  row is hidden for Automatic and Off. The failure line names who
  searched instead, or says the ones after it failed too. The help
  text says the same in en, zh, zh-TW, ja and de.
- docs: gateway-routing's failing searcher, and gui-shell.

Tests:
- TestPickedSearchersInTheirOrder (gateway): one test where the named
  searcher answers without searching and one where it fails. A gone
  entry and one that can't search are skipped, and the third searches
  once. With no working entry, the error says so and Instead is empty.
- TestSearcherThenSaved (settings) and TestSearcherThenFromSettings
  (gui): what is saved, kept and cleared; refusing an entry that can't
  search. settings_keep_test sets SearcherThen.
- searcher-then.test.cjs: chromium and webkit, en, zh, zh-TW, ja, de,
  at 560 and 1000 wide. Checks the row's place and words, what Add
  offers, the posted lists, that the chips fit with no horizontal
  scroll, that no click moves the page, and both failure lines.
Broken by hand: running no fallback turned TestPickedSearchersInTheirOrder
red (both subtests: "ds2 searched []"). Not keeping the list on save
turned TestSearcherThenFromSettings and the keep test red.

Run on mote (mote-run):
- At the pre-rebase tree (base 21882a68d): go test of settings, and
  -run 'Searcher|Search' of gateway and gui: ok.
- searcher-then, searcher-pick and i18n-keys in both engines: 46 of 46.
- gofmt clean. go vet: darwin gateway, gui, settings; windows the same;
  linux gateway and settings on mote, gui with -tags gtk3 on the Linux
  box (wsl-run): ok.
- Rebased onto origin/main 1e6a27d4f, this tree: -run
  'Search|Searcher|CoreScriptBudget|SettingsSave' of gateway, gui and
  settings: gateway and settings ok; gui ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend on BusyLoad, red on main
  since 8d8df0639 (#4739, not this change; SearcherThen passes its
  check). The three GUI files above: 46 of 46.
  Pushed on origin/main e62a1bc51. Its 6 commits since touch routing,
  sessions and rex files only, none of these, and weren't run here.
Not run before the tag: the whole GUI suite and the full go test of
gateway, gui and settings. They are queued behind other sessions'
suites on mote and run after the push; any red they find gets its own
commit.
Not tried: a real relay or a real searcher failing in the GUI app.
This commit is contained in:
yetone
2026-11-01 14:43:18 +08:00
parent 0b4aa96fd0
commit 4c815ac2a5
14 changed files with 483 additions and 29 deletions
+13 -4
View File
@@ -940,10 +940,19 @@ row of the search that answered says which searcher was asked first, for
whom, why it didn't search, and which one searched in its place
(`kindWhy`).
A searcher named in Settings gives way to no other provider. Its error goes
back to the model, and `webSearch` then asks the search APIs, when any are
set up. `namedFailed` keeps the last search it didn't make, cleared when it
next searches. Settings › Web search shows that (`SearcherFailed`,
A searcher named in Settings gives way only to the ones the user put
after it, `SearcherThen` (Settings › Web search's "If it fails" row), in
their order. One that can't search now, is the one named, or is the same
model is skipped. The first that searches answers, and the row says why
the named one didn't search (`searchingInstead`). No other provider
searches in their place (axelburks on Discord asked for this list). When
every one fails, their errors go back to the model together, and
`webSearch` then asks the search APIs, when any are set up. Covered by
`TestPickedSearchersInTheirOrder`; `TestSearcherThenSaved` and
`TestSearcherThenFromSettings` cover how the list is saved. Settings only
takes a provider `Searchers()` offers. A save without the list keeps it,
since the page's `prefsKeep` doesn't send it; `[]` clears it. `namedFailed` keeps the last search it didn't make, with the one that
searched in its place (`Instead`), and clears it when it next searches. Settings › Web search shows that (`SearcherFailed`,
`searchFailed`) at the start of the row's help, which wraps whole.
Gearclickist on Discord picked Grok. Their grok-4.7 rows were about 1.3k
tokens, the size of a request Grok ran no search for (one that searched
+1
View File
@@ -432,6 +432,7 @@ covers it in both engines, every language and a narrow window.
- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Lightweight mode, Prevent sleep, Session terminal). Codex's, Claude Code's and Grok Build's own settings (Codex subagents, Long conversations, which is all of Grok Build's, background compaction, thread titles and descriptions, composer predictions, the auto-review and memories models) aren't here: they are in the agent's opened row on the Agents page (`AGENT_PREFS`, `connectPanel`), the panel's row has a Settings line that opens them in a sheet (`openAgentPrefs`), as does the agent's menu, and Settings' search finds them with a row that opens that sheet (`#agentPrefLinks`). Each row is one element moved between its places, so its handlers and state go with it (the owner, 10-20; `agent-prefs.test.cjs`). Long conversations is the exception with no Codex, Claude Code or Grok Build here, in gateway mode or a magpie in Docker: it sets the windows the gateway serves, which agents on other computers read, so it stays in General (`renderAgentPrefLinks`, Linka on Discord). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`. Open at login reads `autostart.Enabled`, which on macOS 13 and later also asks Background Task Management about magpie's launch agent (`SMAppService.statusForLegacyURL:`, matched by the plist's Label, not its path); a record the user switched off in System Settings › General › Login Items reads as needing allowing, and the row keeps On with one line saying so and a button that opens Login Items (`/api/open` allows that one `x-apple.systempreferences` URL). The status read again when the window comes back to the front clears the line. On macOS 12, in a build without cgo, or when the system can't be asked, the plist alone decides, as before (#2120, `login-allow.test.cjs`, `login_allow_test.go`).
- A setting row's line under its name (`.row.pref .sub`, in Settings, Plugins › Built-in and an agent's own settings) wraps whole beside its control, never cut to one line with an ellipsis (arculongus on Discord, `settings-lines-wrap.test.cjs`).
- Settings' search-provider picker offers **Off**, saved as `searcher: "off"`. Its help explains API-only search and suppresses provider fallback/own-search hints while off; the search priority row is hidden because no provider competes with the APIs. See [gateway search behavior](gateway-routing.md#turning-provider-search-off), [`renderSearcher`](../../internal/gui/assets/plugins/search/settings.js), `TestSettingsSearchProviderOff` and `searcher-pick.test.cjs`.
- A searcher named there gets an "If it fails" row right under it (`renderSearcherThen`). The row holds numbered chips for `searcherThen`, the providers that search in its place, in order. Add offers every searcher but the one named and the ones already listed. A chip's picker changes it or removes it. The row isn't shown for Automatic or Off. The failure line names the one that searched instead (`searchFailed.instead`), or says the ones after it failed too. See `searcher-then.test.cjs`. A picker's item is pressed through `pickItem` in `reader.cjs`, which waits for the list drawn again after `/api/model-speeds` answers (#4274).
- Settings' search APIs are asked in their listed order: each API's row (with its keys' row) is dragged as one, or moved with Alt+↑/↓, and has a switch that turns it off without removing its key (#2286). See [the search APIs' order](gateway-routing.md#the-search-apis-order-and-one-switched-off), `searchArrange` in [`plugins/search/settings.js`](../../internal/gui/assets/plugins/search/settings.js) and `search-order.test.cjs`.
- Settings' Search APIs add row has a base URL field under the key for every API (#1580): the vendor's own address is its placeholder, picking an API already added fills in its saved URL so a new key alone keeps it, and Add with no key changes only the URL. See [a search API's base URL](gateway-routing.md#a-search-apis-base-url), [`renderSearch`](../../internal/gui/assets/plugins/search/settings.js) and `search-api.test.cjs`.
- Every user-visible string has zh, zh-TW, ja and de translations with the same placeholders. `gui-zh-tw.test.cjs`, `gui-ja.test.cjs` and `gui-de.test.cjs` fail on a missing one; `gui-zh-tw.test.cjs` also fails on a zh-TW string with a Simplified character left in it.
+51 -8
View File
@@ -784,11 +784,45 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
said, hits, err = s.searchBy(ctx, p, model, query, searchEffort(p, model))
}
if named {
// a search the agent stopped waiting for is no failure of its
// those Settings names after it, in their order (SearcherThen),
// and no other
instead, first := "", err
if err != nil && ctx.Err() == nil {
for _, v := range settings.Load().SearcherThen {
q, m, why := namedSearcher(v)
if why != "" || q == nil || q.ID == p.ID && m == model || ctx.Err() != nil {
continue
}
if instead == "" {
ctx = searchingInstead(ctx, p, model, first)
}
instead = searcherOf(*q, m)
var next error
if said, hits, next = s.searchBy(ctx, *q, m, query, searchEffort(*q, m)); next == nil {
err = nil
break
}
err = errors.Join(err, next)
}
if err == nil {
// what Settings says is the first's failure, and who
// searched in its place
if !errors.Is(ctx.Err(), context.Canceled) {
namedFailed(p, model, first, instead)
}
return said, hits, nil
}
}
// a search the agent stopped waiting for is no failure of its.
// Settings says the first's own failure, those after it having
// failed too
if !errors.Is(ctx.Err(), context.Canceled) {
namedFailed(p, model, err)
namedFailed(p, model, first, "")
}
if err != nil {
if len(settings.Load().SearcherThen) > 0 {
return "", nil, fmt.Errorf("%w (the searchers picked in Settings › Web search, in their order: no other provider searches in their place)", err)
}
return "", nil, fmt.Errorf("%w (the searcher picked in Settings › Web search: no other provider searches in its place)", err)
}
return said, hits, nil
@@ -843,14 +877,23 @@ type SearchFailure struct {
Why string // the error, when it neither found nothing nor didn't search
NothingFound bool // it searched and named no page
NotSearched bool // it answered without searching (errNotSearched)
At time.Time
// Instead is the searcher Settings names after it (SearcherThen) that
// searched in its place, "" when none did
Instead string
At time.Time
}
func namedFailed(p provider.Provider, model string, err error) {
name := p.ID
if model != "" {
name += "/" + model
// searcherOf is a searcher as Settings writes it: "<provider>/<model>",
// or "<provider>" for one that searches with no model.
func searcherOf(p provider.Provider, model string) string {
if model == "" {
return p.ID
}
return p.ID + "/" + model
}
func namedFailed(p provider.Provider, model string, err error, instead string) {
name := searcherOf(p, model)
lastNamedFail.Lock()
defer lastNamedFail.Unlock()
if err == nil {
@@ -859,7 +902,7 @@ func namedFailed(p provider.Provider, model string, err error) {
}
return
}
f := SearchFailure{Searcher: name, At: time.Now(), NotSearched: errors.Is(err, errNotSearched)}
f := SearchFailure{Searcher: name, At: time.Now(), NotSearched: errors.Is(err, errNotSearched), Instead: instead}
f.NothingFound = !f.NotSearched && errors.Is(err, errFoundNothing)
if !f.NothingFound && !f.NotSearched {
f.Why = strings.TrimPrefix(err.Error(), name+": ")
+58
View File
@@ -0,0 +1,58 @@
package gateway
import (
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// The searcher Settings names that fails, or answers without searching,
// gives way to the ones named after it, in their order (SearcherThen;
// axelburks on Discord: 代搜供应商能不能支持设置多个,一个失败了换另一个),
// and to no other: one named after it that is gone or can't search is
// passed over, and Settings says who searched in the first one's place.
func TestPickedSearchersInTheirOrder(t *testing.T) {
for _, tc := range []struct {
name string
failing bool
}{{"answered without searching", false}, {"failed", true}} {
t.Run(tc.name, func(t *testing.T) {
_, next, result := pickedSearchSetup(t, tc.failing, provider.Anthropic)
st := settings.Load()
st.Searcher = "ds/deepseek-flash"
st.SearcherThen = []string{"gone/m1", "glm", "ds2/deepseek-flash"}
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
searchForGLM(t, New())
if got := next.searches(); len(got) != 1 {
t.Fatalf("ds2 searched %q", got)
}
if r := result(); !strings.Contains(r, "22/17℃") {
t.Fatalf("the model was told %q", r)
}
f, ok := SearcherFailed()
if !ok || f.Searcher != "ds/deepseek-flash" || f.Instead != "ds2/deepseek-flash" {
t.Fatalf("SearcherFailed = %+v %v", f, ok)
}
// none after it that can search: as with none named after it
st.SearcherThen = []string{"gone/m1", "glm"}
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
searchForGLM(t, New())
if got := next.searches(); len(got) != 1 {
t.Fatalf("ds2, not named, searched %q", got)
}
if r := result(); strings.Contains(r, "22/17℃") || !strings.Contains(r, "no other provider searches in their place") {
t.Fatalf("the model was told %q", r)
}
if f, ok := SearcherFailed(); !ok || f.Instead != "" {
t.Fatalf("SearcherFailed = %+v %v", f, ok)
}
})
}
}
+15 -6
View File
@@ -625,7 +625,7 @@ func searchState(s *settingsJSON) {
s.SearchAuto, s.SearchUnused = gateway.AutoSearcher(), gateway.SearcherUnused()
s.SearchEfforts, s.SearchEffortNow = gateway.SearchEfforts(), gateway.SearchEffortNow()
if f, ok := gateway.SearcherFailed(); ok {
s.SearchFailed = &searchFailedJSON{Searcher: f.Searcher, Why: f.Why, NothingFound: f.NothingFound, NotSearched: f.NotSearched, At: f.At}
s.SearchFailed = &searchFailedJSON{Searcher: f.Searcher, Why: f.Why, NothingFound: f.NothingFound, NotSearched: f.NotSearched, Instead: f.Instead, At: f.At}
}
s.SearchChoices = []searchChoiceJSON{}
for _, c := range gateway.Searchers() {
@@ -653,6 +653,7 @@ type searchFailedJSON struct {
Why string `json:"why,omitempty"`
NothingFound bool `json:"nothingFound,omitempty"`
NotSearched bool `json:"notSearched,omitempty"`
Instead string `json:"instead,omitempty"` // who, named after it, searched in its place
At time.Time `json:"at"`
}
@@ -1559,11 +1560,19 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
return
}
}
if v := strings.TrimSpace(in.Searcher); v != "" && v != "off" && v != cur.Searcher {
id, _, _ := strings.Cut(v, "/")
if !slices.ContainsFunc(gateway.Searchers(), func(c gateway.SearcherChoice) bool { return c.Provider.ID == id }) {
fail(rw, fmt.Errorf("%s can't search the web for other models", id))
return
// the searchers after the one named, set in their own row: a save
// that doesn't send them (prefsKeep has none) keeps them, and an
// empty list clears them
if in.SearcherThen == nil {
in.SearcherThen = cur.SearcherThen
}
for _, v := range append([]string{in.Searcher}, in.SearcherThen...) {
if v = strings.TrimSpace(v); v != "" && v != "off" && v != cur.Searcher && !slices.Contains(cur.SearcherThen, v) {
id, _, _ := strings.Cut(v, "/")
if !slices.ContainsFunc(gateway.Searchers(), func(c gateway.SearcherChoice) bool { return c.Provider.ID == id }) {
fail(rw, fmt.Errorf("%s can't search the web for other models", id))
return
}
}
}
if err := settings.Save(in); err != nil {
+4
View File
@@ -3809,6 +3809,10 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
.prefs .val.with-effort { gap: 6px; }
.prefs .val.with-effort > .rt-cond:not(.side-effort) { min-width: 0; flex: 0 1 auto; }
.prefs .val > .side-effort { flex: none; }
/* Web search's searchers after the one named, in order: chips that wrap */
.prefs .val.searcher-then-list { flex-wrap: wrap; justify-content: flex-end; gap: 6px; }
.prefs .val.searcher-then-list > .rt-cond { min-width: 0; max-width: 100%; }
.searcher-then-n { color: var(--muted); font-variant-numeric: tabular-nums; }
.side-effort .effort-ic svg { width: 100%; height: 100%; }
.row.pref.lan-address-row { position: relative; height: 50px; transition: height .28s var(--ease); }
.row.pref.lan-address-row .who { position: absolute; top: 16px; left: 14px; }
+20 -4
View File
@@ -1389,7 +1389,11 @@ const I18N = {
"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 不添加搜索工具。供应商自带的联网搜索不受影响。",
"Provider search is off; only these APIs are used": "已关闭供应商代搜,仅使用这些 API",
"Searches for other models": "代搜供应商",
"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.": "当模型无法直接联网搜索时,由所选供应商代为搜索并返回结果。代搜可能消耗所用服务的额度或产生费用;magpie 自动选择的供应商失败时会尝试其他可用来源,但在此手动选中的供应商不会被换成其他供应商,只会改用你配置的搜索 API。",
"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 replaced only by the ones you add after it, in their order, then by your Search APIs.": "当模型无法直接联网搜索时,由所选供应商代为搜索并返回结果。代搜可能消耗所用服务的额度或产生费用;magpie 自动选择的供应商失败时会尝试其他可用来源,而在此手动选中的供应商只会按顺序换成你在它后面添加的供应商,再改用你配置的搜索 API。",
"{who} didn't search {when}: {why}. {next} searched in its place.": "{who} {when}没能搜索:{why}。已由 {next} 代为搜索。",
"{who} didn't search {when}: {why}. The ones after it didn't search either; add another provider after it, or a Search API.": "{who} {when}没能搜索:{why}。排在它后面的供应商也都没能搜索;可在它后面再添加一个供应商,或添加搜索 API。",
"If it fails": "失败时依次换用",
"These providers search in its place, in this order, when the one above fails; no other provider does.": "上面的供应商搜索失败时,按此顺序由这些供应商代为搜索;不会换用其他供应商。",
"{who} didn't search {when}: {why}. No other provider searched in its place; pick Automatic or another provider, or add a Search API.": "{who} {when}没能搜索:{why}。没有换用其他供应商代搜;可改选“自动”或其他供应商,或添加搜索 API。",
"it answered without searching the web, so its account or plan may not offer web search": "它没有联网搜索就直接回答了,它的账号或套餐可能不支持联网搜索",
"no provider that searches": "没有能搜索的供应商",
@@ -5731,7 +5735,11 @@ const I18N = {
"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 不新增搜尋工具。供應商內建的聯網搜尋不受影響。",
"Provider search is off; only these APIs are used": "已關閉供應商代搜,僅使用這些 API",
"Searches for other models": "代搜供應商",
"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.": "當模型無法直接聯網搜尋時,由所選供應商代為搜尋並返回結果。代搜可能消耗所用服務的額度或產生費用;magpie 自動選擇的供應商失敗時會嘗試其他可用來源,但在此手動選中的供應商不會被換成其他供應商,只會改用你設定的搜尋 API。",
"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 replaced only by the ones you add after it, in their order, then by your Search APIs.": "當模型無法直接聯網搜尋時,由所選供應商代為搜尋並返回結果。代搜可能消耗所用服務的額度或產生費用;magpie 自動選擇的供應商失敗時會嘗試其他可用來源,而在此手動選中的供應商只會依序換成你在它後面新增的供應商,再改用你設定的搜尋 API。",
"{who} didn't search {when}: {why}. {next} searched in its place.": "{who} {when}沒能搜尋:{why}。已由 {next} 代為搜尋。",
"{who} didn't search {when}: {why}. The ones after it didn't search either; add another provider after it, or a Search API.": "{who} {when}沒能搜尋:{why}。排在它後面的供應商也都沒能搜尋;可在它後面再新增一個供應商,或新增搜尋 API。",
"If it fails": "失敗時依序換用",
"These providers search in its place, in this order, when the one above fails; no other provider does.": "上面的供應商搜尋失敗時,依此順序由這些供應商代為搜尋;不會換用其他供應商。",
"{who} didn't search {when}: {why}. No other provider searched in its place; pick Automatic or another provider, or add a Search API.": "{who} {when}沒能搜尋:{why}。沒有換用其他供應商代搜;可改選「自動」或其他供應商,或新增搜尋 API。",
"it answered without searching the web, so its account or plan may not offer web search": "它沒有聯網搜尋就直接回答了,它的帳號或方案可能不支援聯網搜尋",
"no provider that searches": "沒有能搜尋的供應商",
@@ -10043,7 +10051,11 @@ const I18N = {
"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 は検索ツールを追加しません。プロバイダのネイティブなウェブ検索には影響しません。",
"Provider search is off; only these APIs are used": "プロバイダによる代行検索はオフです。これらの API のみを使用します",
"Searches for other models": "他のモデルの代わりに検索",
"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.": "モデルが直接ウェブ検索できない場合、選択したプロバイダが代わりに検索し、結果を返します。検索にはサービスの利用枠を消費したり、料金が発生したりする場合があります。magpie が自動で選んだプロバイダが失敗すると他の利用可能な検索元を試しますが、ここで選んだプロバイダが別のプロバイダに置き換えられることはなく、設定済みの検索 API だけが代わりに使われます。",
"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 replaced only by the ones you add after it, in their order, then by your Search APIs.": "モデルが直接ウェブ検索できない場合、選択したプロバイダが代わりに検索し、結果を返します。検索にはサービスの利用枠を消費したり、料金が発生したりする場合があります。magpie が自動で選んだプロバイダが失敗すると他の利用可能な検索元を試しますが、ここで選んだプロバイダの代わりに使われるのは、その後ろに追加したプロバイダ(その順番で)と、設定済みの検索 API だけです。",
"{who} didn't search {when}: {why}. {next} searched in its place.": "{who} は{when}、検索できませんでした:{why}。代わりに {next} が検索しました。",
"{who} didn't search {when}: {why}. The ones after it didn't search either; add another provider after it, or a Search API.": "{who} は{when}、検索できませんでした:{why}。後ろのプロバイダも検索できませんでした。後ろに別のプロバイダを追加するか、検索 API を追加してください。",
"If it fails": "失敗したとき",
"These providers search in its place, in this order, when the one above fails; no other provider does.": "上のプロバイダが検索に失敗すると、これらのプロバイダがこの順番で代わりに検索します。他のプロバイダは使われません。",
"{who} didn't search {when}: {why}. No other provider searched in its place; pick Automatic or another provider, or add a Search API.": "{who} は{when}、検索できませんでした:{why}。他のプロバイダが代わりに検索することはありません。「自動」か別のプロバイダを選ぶか、検索 API を追加してください。",
"it answered without searching the web, so its account or plan may not offer web search": "ウェブ検索をせずに回答しました。アカウントやプランがウェブ検索に対応していない可能性があります",
"no provider that searches": "検索できるプロバイダなし",
@@ -14386,7 +14398,11 @@ const I18N = {
"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.",
"Provider search is off; only these APIs are used": "Die Anbietersuche ist ausgeschaltet; nur diese APIs werden verwendet",
"Searches for other models": "Sucht für andere Modelle",
"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.": "Wenn ein Modell nicht direkt im Web suchen kann, übernimmt der ausgewählte Anbieter die Suche und liefert die Ergebnisse. Suchen können das Kontingent des Dienstes verbrauchen oder Kosten verursachen. Schlägt der von magpie gewählte Anbieter fehl, versucht magpie andere verfügbare Quellen; ein hier ausgewählter Anbieter wird jedoch nie durch einen anderen Anbieter ersetzt, nur durch Ihre Such-APIs.",
"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 replaced only by the ones you add after it, in their order, then by your Search APIs.": "Wenn ein Modell nicht direkt im Web suchen kann, übernimmt der ausgewählte Anbieter die Suche und liefert die Ergebnisse. Suchen können das Kontingent des Dienstes verbrauchen oder Kosten verursachen. Schlägt der von magpie gewählte Anbieter fehl, versucht magpie andere verfügbare Quellen; ein hier ausgewählter Anbieter wird nur durch die Anbieter ersetzt, die Sie danach hinzufügen, in ihrer Reihenfolge, und dann durch Ihre Such-APIs.",
"{who} didn't search {when}: {why}. {next} searched in its place.": "{who} hat {when} nicht gesucht: {why}. {next} hat an seiner Stelle gesucht.",
"{who} didn't search {when}: {why}. The ones after it didn't search either; add another provider after it, or a Search API.": "{who} hat {when} nicht gesucht: {why}. Die Anbieter danach haben auch nicht gesucht; fügen Sie danach einen weiteren Anbieter oder eine Such-API hinzu.",
"If it fails": "Wenn er fehlschlägt",
"These providers search in its place, in this order, when the one above fails; no other provider does.": "Diese Anbieter suchen an seiner Stelle, in dieser Reihenfolge, wenn der obige fehlschlägt; kein anderer Anbieter.",
"{who} didn't search {when}: {why}. No other provider searched in its place; pick Automatic or another provider, or add a Search API.": "{who} hat {when} nicht gesucht: {why}. Kein anderer Anbieter hat an seiner Stelle gesucht; wählen Sie Automatisch oder einen anderen Anbieter, oder fügen Sie eine Such-API hinzu.",
"it answered without searching the web, so its account or plan may not offer web search": "es hat ohne Websuche geantwortet, daher bietet sein Konto oder Tarif möglicherweise keine Websuche",
"no provider that searches": "kein Anbieter mit Suche",
+42 -2
View File
@@ -329,7 +329,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 ? (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."));
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 replaced only by the ones you add after it, in their order, then 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 })));
@@ -341,7 +341,10 @@ function renderSearcher(s, keep, box) {
const failed = s.searchFailed;
if (!off && v && !s.searchUnused && failed) {
const why = failed.notSearched ? t("it answered without searching the web, so its account or plan may not offer web search") : failed.nothingFound ? t("its reply named no page it found") : failed.why || t("it failed");
sub.prepend(el("span", "warn searcher-failed", t("{who} didn't search {when}: {why}. No other provider searched in its place; pick Automatic or another provider, or add a Search API.", { who: named(v), when: ago(failed.at), why })), " · ");
const said = failed.instead ? t("{who} didn't search {when}: {why}. {next} searched in its place.", { who: named(failed.searcher), when: ago(failed.at), why, next: named(failed.instead) })
: (s.searcherThen || []).length ? t("{who} didn't search {when}: {why}. The ones after it didn't search either; add another provider after it, or a Search API.", { who: named(v), when: ago(failed.at), why })
: t("{who} didn't search {when}: {why}. No other provider searched in its place; pick Automatic or another provider, or add a Search API.", { who: named(v), when: ago(failed.at), why });
sub.prepend(el("span", "warn searcher-failed", said), " · ");
}
const plans = choices.filter((c) => c.service).map((c) => c.name);
if (!off && plans.length) sub.append(" · ", el("span", "searcher-own",
@@ -389,4 +392,41 @@ function renderSearcher(s, keep, box) {
"none sent, the model's own", (e) => savePrefs({ ...keep, searcherEffort: e }));
r.append(who, val);
box.append(r);
if (!off && v && !s.searchUnused) renderSearcherThen(s, keep, box, options, named, icOf);
}
// renderSearcherThen: the providers asked, in their order, when the one
// named above fails to search, and no other (axelburks on Discord: "代搜
// 供应商能不能支持设置多个,这样可以一个失败了换另一个供应商"). Each
// is a chip that changes or removes it, and Add puts one at the end.
function renderSearcherThen(s, keep, box, options, named, icOf) {
const v = s.searcher || "";
const then = s.searcherThen || [];
const save = (list) => savePrefs({ ...keep, searcherThen: list });
// what can still be added: not the one above, nor one listed already
const free = (keepOne) => options.filter((o) => !o.reset && o.value !== v && (o.value === keepOne || !then.includes(o.value)));
const r = el("div", "row pref searcher-then");
const who = el("div", "who");
who.append(el("div", "name", t("If it fails")),
el("div", "sub", t("These providers search in its place, in this order, when the one above fails; no other provider does.")));
const val = el("div", "val searcher-then-list");
then.forEach((x, n) => {
const b = el("button", "rt-cond on searcher-then-pick");
b.type = "button";
b.append(el("span", "searcher-then-n", `${n + 1}.`), icon(icOf(x) || "generic"), el("span", "", named(x)));
b.onclick = (ev) => openPicker({ id: "", name: "", fields: [] }, { key: "searcherThen", label: "model", value: x,
options: [{ value: "", label: t("Remove"), reset: true }, ...free(x)],
onPick: (id) => { if (id !== x) save(id ? then.map((y, i) => i === n ? id : y) : then.filter((_, i) => i !== n)); } }, b, ev);
val.append(b);
});
const left = free("");
if (left.length) {
const add = el("button", "text searcher-then-add", t("Add"));
add.type = "button";
add.onclick = (ev) => openPicker({ id: "", name: "", fields: [] }, { key: "searcherThen", label: "model", value: "", options: left,
onPick: (id) => { if (id) save([...then, id]); } }, add, ev);
val.append(add);
}
r.append(who, val);
box.append(r);
}
+62
View File
@@ -3,8 +3,11 @@ package gui
import (
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// A custom provider on OpenAI's Responses API, saved by the editor with
@@ -41,3 +44,62 @@ func TestSearcherPickerOffersResponsesRelay(t *testing.T) {
t.Errorf("relays %v, left out %v", s.SearchRelays, s.SearchLeftOut)
}
}
// Settings saves the searchers after the one named (searcherThen) when
// each can search, keeps them through a save that doesn't send them (the
// page's other rows), and clears them on an empty list.
func TestSearcherThenFromSettings(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
srv := httptest.NewServer(http.NotFoundHandler())
t.Cleanup(srv.Close)
mux := http.NewServeMux()
providerRoutes(mux, nil)
for _, name := range []string{"One", "Two"} {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(
`{"new":true,"name":"`+name+`","responses":"`+srv.URL+`/v1","baseAPI":"responses","key":"k-`+name+`","searches":true,"icon":"generic","models":["gpt-5.5"]}`)))
if w.Code != 200 {
t.Fatalf("save %s: %d %s", name, w.Code, w.Body)
}
}
var st settingsJSON
searchState(&st)
if len(st.SearchChoices) != 2 {
t.Fatalf("choices = %+v", st.SearchChoices)
}
one, two := st.SearchChoices[0].Models[0].ID, st.SearchChoices[1].Models[0].ID
post := func(body string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
Handler(nil, nil).ServeHTTP(w, httptest.NewRequest("POST", "/api/settings", strings.NewReader(body)))
return w
}
if w := post(`{"searcher":"` + one + `","searcherThen":["nowhere/m1"]}`); w.Code == 200 || !strings.Contains(w.Body.String(), "can't search the web") {
t.Errorf("one that can't search: %d %s", w.Code, w.Body)
}
if got := settings.Load().SearcherThen; len(got) != 0 {
t.Errorf("saved after a refusal: %v", got)
}
if w := post(`{"searcher":"` + one + `","searcherThen":["` + two + `"]}`); w.Code != 200 {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
if got := settings.Load().SearcherThen; !slices.Equal(got, []string{two}) {
t.Errorf("saved %v", got)
}
if w := post(`{"searcher":"` + one + `","theme":"dark"}`); w.Code != 200 {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
if got := settings.Load().SearcherThen; !slices.Equal(got, []string{two}) {
t.Errorf("after a save without it: %v", got)
}
if w := post(`{"searcher":"` + one + `","searcherThen":[]}`); w.Code != 200 {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
if got := settings.Load().SearcherThen; len(got) != 0 {
t.Errorf("after clearing: %v", got)
}
}
+1
View File
@@ -200,6 +200,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
was.RequestArchiveLocal, was.RequestArchiveLocalMB = true, 256
was.ProxyCustom = "http://me:secret@proxy.example:8080"
was.PanelShortcut = "Ctrl+Alt+K"
was.SearcherThen = []string{"fake/m1", "fake/m2"} // set in its own row
if err := settings.Save(was); err != nil {
t.Fatal(err)
}
+5 -5
View File
@@ -22,7 +22,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, reach } = require("./reader.cjs");
const { watchSettingsReads, settingsDrawn, reach, pickItem } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const choices = [
@@ -50,22 +50,22 @@ const words = {
};
const helpWords = {
en: {
help: "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.",
help: "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 replaced only by the ones you add after it, in their order, then by your Search APIs.",
relays: "These relays must be selected manually and are not used for automatic selection or fallback: MyRelay.",
left: "These providers can't be selected to search for other models with the current configuration: MiniMax, Kimi For Coding. Their models can still get search results through other available search providers or configured search APIs.",
},
zh: {
help: "当模型无法直接联网搜索时,由所选供应商代为搜索并返回结果。代搜可能消耗所用服务的额度或产生费用;magpie 自动选择的供应商失败时会尝试其他可用来源,但在此手动选中的供应商不会被换成其他供应商,只会改用你配置的搜索 API。",
help: "当模型无法直接联网搜索时,由所选供应商代为搜索并返回结果。代搜可能消耗所用服务的额度或产生费用;magpie 自动选择的供应商失败时会尝试其他可用来源,而在此手动选中的供应商只会按顺序换成你在它后面添加的供应商,再改用你配置的搜索 API。",
relays: "以下中转服务需手动指定,不参与自动选择或自动回退:MyRelay。",
left: "以下供应商在当前配置下不可选为代搜供应商:MiniMax, Kimi For Coding。它们的模型仍可通过其他可用的代搜供应商或已配置的搜索 API 获取搜索结果。",
},
ja: {
help: "モデルが直接ウェブ検索できない場合、選択したプロバイダが代わりに検索し、結果を返します。検索にはサービスの利用枠を消費したり、料金が発生したりする場合があります。magpie が自動で選んだプロバイダが失敗すると他の利用可能な検索元を試しますが、ここで選んだプロバイダが別のプロバイダに置き換えられることはなく、設定済みの検索 API だけが代わりに使われます。",
help: "モデルが直接ウェブ検索できない場合、選択したプロバイダが代わりに検索し、結果を返します。検索にはサービスの利用枠を消費したり、料金が発生したりする場合があります。magpie が自動で選んだプロバイダが失敗すると他の利用可能な検索元を試しますが、ここで選んだプロバイダの代わりに使われるのは、その後ろに追加したプロバイダ(その順番で)と、設定済みの検索 API だけです。",
relays: "次の中継サービスは手動で選択する必要があり、自動選択や自動フォールバックの対象にはなりません:MyRelay。",
left: "次のプロバイダは現在の設定では他のモデルの検索用に選択できません:MiniMax, Kimi For Coding。これらのモデルも、他の利用可能な検索用プロバイダや設定済みの検索 API を通じて検索結果を取得できます。",
},
de: {
help: "Wenn ein Modell nicht direkt im Web suchen kann, übernimmt der ausgewählte Anbieter die Suche und liefert die Ergebnisse. Suchen können das Kontingent des Dienstes verbrauchen oder Kosten verursachen. Schlägt der von magpie gewählte Anbieter fehl, versucht magpie andere verfügbare Quellen; ein hier ausgewählter Anbieter wird jedoch nie durch einen anderen Anbieter ersetzt, nur durch Ihre Such-APIs.",
help: "Wenn ein Modell nicht direkt im Web suchen kann, übernimmt der ausgewählte Anbieter die Suche und liefert die Ergebnisse. Suchen können das Kontingent des Dienstes verbrauchen oder Kosten verursachen. Schlägt der von magpie gewählte Anbieter fehl, versucht magpie andere verfügbare Quellen; ein hier ausgewählter Anbieter wird nur durch die Anbieter ersetzt, die Sie danach hinzufügen, in ihrer Reihenfolge, und dann durch Ihre Such-APIs.",
relays: "Diese Relays müssen manuell ausgewählt werden und werden weder automatisch noch als Fallback gewählt: MyRelay.",
left: "Diese Anbieter können mit der aktuellen Konfiguration nicht für die Suche anderer Modelle ausgewählt werden: MiniMax, Kimi For Coding. Ihre Modelle können weiterhin über andere verfügbare Suchanbieter oder konfigurierte Such-APIs Suchergebnisse erhalten.",
},
+176
View File
@@ -0,0 +1,176 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Settings' Web search: the providers that search, in their order, when the
// one named fails (axelburks on Discord: "代搜供应商能不能支持设置多个,这样
// 可以一个失败了换另一个供应商"). A row under the one named lists them as
// numbered chips; Add offers every searcher but the one named, Automatic,
// Off and those listed, and puts the pick at the end; a chip's picker
// changes it or removes it. Saved as searcherThen. With none named (or Off)
// there is no such row. The failure note says who searched in its place.
// Every language, Chromium and WebKit, at a narrow and a wide window, with
// the API 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 { watchSettingsReads, settingsDrawn, reach, pickItem } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const choices = [
{ id: "claude", name: "Claude", icon: "claude", small: "claude-haiku-4-5", models: [
{ id: "claude/claude-haiku-4-5", name: "Claude Haiku 4.5", provider: "claude", providerName: "Claude" },
{ id: "claude/claude-opus-4-5", name: "Claude Opus 4.5", provider: "claude", providerName: "Claude" }] },
{ id: "openai", name: "OpenAI", icon: "openai", small: "gpt-5-mini", models: [
{ id: "openai/gpt-5-mini", name: "GPT-5 mini", provider: "openai", providerName: "OpenAI" },
{ id: "openai/gpt-5.5", name: "GPT Five Five", provider: "openai", providerName: "OpenAI" }] },
{ id: "relay", name: "MyRelay", icon: "generic", small: "gpt-5.5", models: [
{ id: "relay/gpt-5.5", name: "gpt-5.5", provider: "relay", providerName: "MyRelay" }] },
];
const words = {
en: { name: "If it fails", sub: "These providers search in its place, in this order, when the one above fails; no other provider does.", add: "Add", remove: "Remove",
instead: /^GPT Five Five · OpenAI didn't search .+: 400 search quota used up\. Claude Opus 4\.5 · Claude searched in its place\.$/,
none: /^GPT Five Five · OpenAI didn't search .+: 400 search quota used up\. The ones after it didn't search either; add another provider after it, or a Search API\.$/ },
zh: { name: "失败时依次换用", sub: "上面的供应商搜索失败时,按此顺序由这些供应商代为搜索;不会换用其他供应商。", add: "添加", remove: "移除",
instead: /^GPT Five Five · OpenAI .+没能搜索:400 search quota used up。已由 Claude Opus 4\.5 · Claude 代为搜索。$/,
none: /^GPT Five Five · OpenAI .+没能搜索:400 search quota used up。排在它后面的供应商也都没能搜索;/ },
"zh-TW": { name: "失敗時依序換用", sub: "上面的供應商搜尋失敗時,依此順序由這些供應商代為搜尋;不會換用其他供應商。", add: "新增", remove: "移除",
instead: /^GPT Five Five · OpenAI .+沒能搜尋:400 search quota used up。已由 Claude Opus 4\.5 · Claude 代為搜尋。$/,
none: /^GPT Five Five · OpenAI .+沒能搜尋:400 search quota used up。排在它後面的供應商也都沒能搜尋;/ },
ja: { name: "失敗したとき", sub: "上のプロバイダが検索に失敗すると、これらのプロバイダがこの順番で代わりに検索します。他のプロバイダは使われません。", add: "追加", remove: "削除",
instead: /^GPT Five Five · OpenAI は.+、検索できませんでした:400 search quota used up。代わりに Claude Opus 4\.5 · Claude が検索しました。$/,
none: /^GPT Five Five · OpenAI は.+、検索できませんでした:400 search quota used up。後ろのプロバイダも検索できませんでした。/ },
de: { name: "Wenn er fehlschlägt", sub: "Diese Anbieter suchen an seiner Stelle, in dieser Reihenfolge, wenn der obige fehlschlägt; kein anderer Anbieter.", add: "Hinzufügen", remove: "Entfernen",
instead: /^GPT Five Five · OpenAI hat .+ nicht gesucht: 400 search quota used up\. Claude Opus 4\.5 · Claude hat an seiner Stelle gesucht\.$/,
none: /^GPT Five Five · OpenAI hat .+ nicht gesucht: 400 search quota used up\. Die Anbieter danach haben auch nicht gesucht;/ },
};
function serve(lang, posted, st) {
const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], searchChoices: choices,
searchAuto: "Claude · claude-haiku-4-5", searchProvider: st.searcher, searchRelays: ["MyRelay"], searchLeftOut: [],
searcher: st.searcher, searcherThen: st.then, searchUnused: "", searchFailed: st.failed });
return async (r) => {
const url = new URL(r.request().url());
const json = (data, status = 200) => r.fulfill({ status, json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ 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({ agents: [], profiles: [], settings: settings() });
if (url.pathname === "/api/settings") {
if (r.request().method() === "POST") {
const b = JSON.parse(r.request().postData());
posted.push(b);
st.searcher = b.searcher ?? st.searcher;
if (b.searcherThen) st.then = b.searcherThen;
}
return json(settings());
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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)];
const body = await fs.readFile(file).catch(() => null);
await (body ? r.fulfill({ body, contentType }) : r.fulfill({ status: 404, body: "" }));
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const [lang, w] of Object.entries(words)) {
for (const width of [560, 1000]) {
test(`${engine} ${lang} ${width}: the searchers after the one named, in their order`, async (t) => {
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 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posted = [];
const st = { searcher: "", then: [], failed: null };
await page.route("**/*", serve(lang, posted, st));
const load = async () => {
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=models");
await settingsDrawn(page);
await page.locator("#searchList .searcher-row").waitFor();
};
const redraw = () => page.evaluate(() => fetch("/api/settings").then((r) => r.json()).then((s) => { prefs = s; state.settings = s; renderSettings(); }));
const chips = () => page.locator("#searchList .searcher-then button.searcher-then-pick").allInnerTexts().then((x) => x.map((s) => s.replace(/\s+/g, " ").trim()));
const offered = () => page.locator("#list li:not(.group)").allInnerTexts();
// none named, or Off: nothing to follow it
await load();
assert.equal(await page.locator("#searchList .searcher-then").count(), 0, "automatic");
st.searcher = "off";
await redraw();
await page.waitForFunction(() => document.querySelector("#searchList button.searcher-pick")?.innerText.length > 0);
assert.equal(await page.locator("#searchList .searcher-then").count(), 0, "off");
// one named: the row under it, said in the language, empty
st.searcher = "openai/gpt-5.5";
await load();
const row = page.locator("#searchList .row.searcher-then");
await row.waitFor();
assert.equal(await row.locator(".name").innerText(), w.name);
assert.equal(await row.locator(".sub").innerText(), w.sub);
assert.deepEqual(await chips(), []);
assert.equal(await row.evaluate((r) => r.previousElementSibling?.classList.contains("searcher-row")), true, "right under the one named");
await reach(page, row);
const before = await page.evaluate(() => [scrollY, document.querySelector("main")?.scrollTop ?? 0]);
// Add: every searcher but the one named, Automatic and Off
await pickItem(page, row.locator("button.searcher-then-add"));
await page.locator("#pop").waitFor({ state: "visible" });
let items = await offered();
assert(!items.some((x) => x.includes("GPT Five Five")), "not the one named: " + items.join(" | "));
assert(!items.some((x) => x.startsWith("Automatic") || x.startsWith(w.remove)), items.join(" | "));
assert(items.some((x) => x.includes("Claude Opus 4.5")) && items.some((x) => x.includes("MyRelay")), items.join(" | "));
await pickItem(page, page.locator("#list li:not(.group)", { hasText: "Claude Opus 4.5" }));
await page.waitForFunction(() => document.querySelectorAll("#searchList .searcher-then-pick").length === 1);
assert.deepEqual(posted.at(-1).searcherThen, ["claude/claude-opus-4-5"]);
assert.equal(posted.at(-1).searcher, "openai/gpt-5.5", "the one named is kept");
assert.deepEqual(await chips(), ["1. Claude Opus 4.5 · Claude"]);
// a second goes after it; the first is not offered again
await pickItem(page, row.locator("button.searcher-then-add"));
await page.locator("#pop").waitFor({ state: "visible" });
items = await offered();
assert(!items.some((x) => x.includes("Claude Opus 4.5")), "listed already: " + items.join(" | "));
await pickItem(page, page.locator("#list li:not(.group)", { hasText: "MyRelay" }).last());
await page.waitForFunction(() => document.querySelectorAll("#searchList .searcher-then-pick").length === 2);
assert.deepEqual(posted.at(-1).searcherThen, ["claude/claude-opus-4-5", "relay"]);
assert.deepEqual(await chips(), ["1. Claude Opus 4.5 · Claude", "2. MyRelay · gpt-5.5"]);
// the row fits the window, its chips wrapped in it
const fits = await row.evaluate((r) => {
const a = r.getBoundingClientRect();
return [...r.querySelectorAll("button")].every((b) => { const c = b.getBoundingClientRect(); return c.left >= a.left - 1 && c.right <= a.right + 1; })
&& document.scrollingElement.scrollWidth <= innerWidth;
});
assert(fits, "chips inside the row");
// a chip's picker: change it, or remove it
await pickItem(page, row.locator("button.searcher-then-pick").first());
await page.locator("#pop").waitFor({ state: "visible" });
items = await offered();
assert(items.some((x) => x.trim() === w.remove) && items.some((x) => x.includes("MyRelay")) === false, "Remove, and none listed after it: " + items.join(" | "));
await pickItem(page, page.locator("#list li:not(.group)").filter({ hasText: new RegExp(`^\\s*${w.remove}\\s*$`) }));
await page.waitForFunction(() => document.querySelectorAll("#searchList .searcher-then-pick").length === 1);
assert.deepEqual(posted.at(-1).searcherThen, ["relay"]);
assert.deepEqual(await chips(), ["1. MyRelay · gpt-5.5"]);
assert.deepEqual(await page.evaluate(() => [scrollY, document.querySelector("main")?.scrollTop ?? 0]), before, "no click moved the page");
// the failure note: who searched in its place, or that none did
const at = new Date(Date.now() - 5 * 60e3).toISOString();
st.then = ["claude/claude-opus-4-5"];
st.failed = { searcher: "openai/gpt-5.5", why: "400 search quota used up", instead: "claude/claude-opus-4-5", at };
await load();
assert.match(await page.locator("#searchList .searcher-failed").innerText(), w.instead);
st.failed = { searcher: "openai/gpt-5.5", why: "400 search quota used up", at };
await load();
assert.match(await page.locator("#searchList .searcher-failed").innerText(), w.none);
assert.deepEqual(errors, []);
});
}
}
}
+22
View File
@@ -0,0 +1,22 @@
package settings
import (
"strings"
"testing"
)
// SearcherThen is kept in its order, without the searcher it follows, a
// repeat, "off" or a blank.
func TestSearcherThenSaved(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
st := Load()
st.Searcher = "a/m"
st.SearcherThen = []string{" b/m ", "a/m", "off", "", "c", "b/m"}
if err := Save(st); err != nil {
t.Fatal(err)
}
if got := strings.Join(Load().SearcherThen, ","); got != "b/m,c" {
t.Errorf("SearcherThen = %q", got)
}
}
+13
View File
@@ -485,6 +485,12 @@ type Settings struct {
// (gateway.searcher). "off" allows only configured search APIs.
// One that is gone, off or can't search gives way to magpie's pick.
Searcher string `json:"searcher,omitempty"`
// SearcherThen are the searchers asked in turn, in this order, when
// the one Searcher names fails or finds nothing, each written as
// Searcher is (axelburks on Discord: a second provider when the first
// fails). Read only while Searcher names one; magpie's own pick hands
// on to the next it would pick by itself.
SearcherThen []string `json:"searcherThen,omitempty"`
// SearcherEffort is how hard the searcher's model thinks as it searches
// (MOMO on Discord): a level of catalog.EffortRank, fitted to the
// model's own levels when it is asked, or empty to send none, the
@@ -2042,6 +2048,13 @@ func saveOwn(s Settings, recording, reads bool) error {
return fmt.Errorf("%q is not a reasoning effort for Claude Desktop's subagents", e)
}
s.Searcher = strings.TrimSpace(s.Searcher)
var then []string
for _, v := range s.SearcherThen {
if v = strings.TrimSpace(v); v != "" && v != "off" && v != s.Searcher && !slices.Contains(then, v) {
then = append(then, v)
}
}
s.SearcherThen = then
for _, e := range []*string{&s.VisionEffort, &s.SearcherEffort} {
if *e = strings.ToLower(strings.TrimSpace(*e)); *e != "" && !slices.Contains(catalog.EffortRank, *e) {
return fmt.Errorf("a model's reasoning must be one of %s, or empty for the default, not %q", strings.Join(catalog.EffortRank, ", "), *e)