gateway, gui: Image recognition and Web search pick how hard their model thinks (MOMO on Discord)

MOMO asked on Discord, "外置模型能不能提供思考深度选项": the model that
describes images (Image recognition, analyze_image) and the searcher's
model (e.g. Antigravity's Gemini 3 Flash) had no reasoning level of
their own to pick.

Settings › Models now has a chip beside each of those two pickers. It
opens the app's menu (openProtoMenu, no native select) and offers
Default plus only the levels that model has (Efforts, weakest first;
none shown when the model's levels aren't known, or the row is Off).
The pick is saved as settings.visionEffort / searcherEffort, one of
catalog.EffortRank or empty, and is checked on save. prefsKeep carries
both, so saving another setting keeps them.

Default keeps what magpie did before. Image recognition is still asked
at the least level the model has (classifyEffort), and the searcher
still gets no level. A picked level is fitted to the model's levels at
call time (fitEffort), and only these two calls carry it
(side_effort.go):
- askVisionWith sends reasoning_effort. The image cache key includes
  the level, so changing the level reads the image again.
- searchBody puts thinking (disabled for none, else enabled with
  budgetOf's budget) and output_config.effort (except for pre-adaptive
  Claude) on the searcher's Anthropic body. The gateway's translation
  turns that into each vendor's own form: adaptive or between_tools
  for new Claude, reasoning.effort for Responses, and thinkingLevel
  for Gemini 3 on Code Assist / Antigravity.
- A picked level raises max_tokens by its budget (replyRoom), so the
  thinking doesn't eat the reply.
- ownSearch and Kimi's search service are sent no level. A fallback
  searcher is sent the level fitted to its own model.

docs/subsystems/gateway-routing.md: new "How hard a side model thinks".

Tests:
- TestVisionEffortPicked and TestVisionEffortOnAnthropic check the
  vision body.
- TestSearcherEffortPicked checks the searcher body on new Claude, old
  Claude and Responses.
- TestSearcherEffortOnGemini checks the searcher body through
  buildCodeAssist for antigravity.
- TestSideEffortChecked covers settings validation.
- side-effort.test.cjs covers the chips: levels shown, a pick saved,
  Default clears it, toggle and Escape, no scroll, fit in the row and
  the menu inside the window. It runs in Chromium and WebKit at 1100
  and 420, in en/zh/zh-TW/ja/de.

Run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 30m) on
  origin/main 3a9d73c5c + this change: everything passes except
  TestRateLimitIsWaitedOut "an hour away" (1.9s against its 1s bound,
  load ~190). That test passes on freshly fetched origin/main 41972b25f
  alone (-count=10) and in 8 parallel -cpu 1 copies. Filed as #1971.
- go test -tags nogui ./internal/settings/ ./internal/gui/: ok.
- Broken by hand, each goes red:
  - searchBody dropping the effort fails TestSearcherEffortPicked and
    TestSearcherEffortOnGemini;
  - askVisionWith back to classifyEffort fails TestVisionEffortPicked
    and TestVisionEffortOnAnthropic;
  - the settings check removed fails TestSideEffortChecked;
  - prefsKeep without the two fields fails side-effort.test.cjs.
- GUI:
  - side-effort.test.cjs: 10/10.
  - searcher-pick, images-*, vision-mcp, settings-search/sections/
    general, routing-vision-why and i18n-keys: 123/123.
  - 67 more Settings files: 778 pass. text-size "zh, dark ... 150%"
    failed in WebKit under parallel load; it passes 11/11 alone and is
    #1866.
- gofmt -l is clean. go vet passes for darwin, plus GOOS=linux and
  GOOS=windows with -tags nogui, on gateway, settings and gui. go build
  passes.
- Not tried against a real Antigravity or other real account: the
  request shapes are checked against fakes and the gateway's own
  translators.
This commit is contained in:
yetone
2026-10-13 16:40:24 +08:00
parent 23611ca6a5
commit dc2f0da820
12 changed files with 757 additions and 15 deletions
+33
View File
@@ -256,6 +256,39 @@ Covered by `TestPickedSearcherIsNotHandedOn`,
`TestSearchInPlaceOfAutoSaysWhy`, `TestSearcherFindingNothingGivesWay`,
`search-instead.test.cjs` and `searcher-pick.test.cjs`.
## How hard a side model thinks
Settings › Models has a chip beside Image recognition's model and the
searcher's (MOMO on Discord): `visionEffort` and `searcherEffort` in
[settings](../../internal/settings/settings.go), one of `catalog.EffortRank`
or empty. The chip offers only the model's own levels (`ModelEfforts`:
`Efforts`, weakest first; `visionEfforts`, `searchEfforts` in the settings
read), and none for a model whose levels aren't known. A level picked is
fitted to the model's levels (`sideEffort`, `fitEffort`) when the call is
made, so a saved level outlives a change of model. Empty keeps magpie's own:
Image recognition at the least level the model has (`classifyEffort`), the
searcher with no level at all. Only these two calls carry it
([`side_effort.go`](../../internal/gateway/side_effort.go)):
- `askVisionWith` sends Chat's `reasoning_effort`; the image cache key
(`describe`) has the level in it, so a new level reads the image again.
- `searchBody` sends the searcher's Anthropic body `thinking` (`disabled` for
`none`, else enabled with `budgetOf`'s budget, 1024 for `minimal`) and
`output_config.effort` unless the vendor model is a Claude older than
adaptive thinking. The gateway's translation then fits it to the vendor:
adaptive thinking or `between_tools` for new Claude, `reasoning.effort` for
Responses, `thinkingLevel` for Gemini 3 on Code Assist and Antigravity.
- A picked level raises the call's `max_tokens` by its budget
(`replyRoom`), so thinking doesn't spend the reply; the model's own limit
still caps it.
- A provider searching for its own models (`ownSearch`, Kimi Code's search
service) is sent none. A fallback searcher is sent the level fitted to its
own model.
Covered by `TestVisionEffortPicked`, `TestVisionEffortOnAnthropic`,
`TestSearcherEffortPicked`, `TestSearcherEffortOnGemini`,
`TestSideEffortChecked` and `side-effort.test.cjs`.
## A search API's base URL
Each search API ([`provider.SearchAPI`](../../internal/provider/search_api.go))
+43 -8
View File
@@ -594,7 +594,7 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
err = nil
}
if err == nil {
said, hits, err = s.searchBy(ctx, p, model, query)
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
@@ -631,7 +631,7 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
tried = append(tried, pick{c.Provider.ID, c.Small})
next := searcherSpent(c.Provider, c.Small)
if next == nil {
said, hits, next = s.searchWith(ctx, c.Provider, c.Small, query)
said, hits, next = s.searchWith(ctx, c.Provider, c.Small, query, searchEffort(c.Provider, c.Small))
}
if next != nil {
err = errors.Join(err, next)
@@ -756,12 +756,12 @@ var errNotSearched = fmt.Errorf("answered without searching the web: %w", errFou
// what it says found nothing: the model answered without searching (#669:
// DeepSeek on its Chat API, which has no search tool, said it couldn't, or
// wrote its own tool-call markup as text).
func (s *Server) searchWith(ctx context.Context, p provider.Provider, model, query string) (string, []Hit, error) {
body, _ := json.Marshal(map[string]any{
"model": p.ID + "/" + model, "max_tokens": 4096, "stream": false, "system": searchSystem,
"messages": []map[string]any{{"role": "user", "content": "Search the web for: " + query}},
"tools": []map[string]any{{"type": "web_search_20250305", "name": "web_search", "max_uses": 3}},
})
//
// effort is the level its model is asked to think at, "" for none sent:
// the searcher's is picked in Settings (searchEffort), and a provider
// searching for its own models is sent none.
func (s *Server) searchWith(ctx context.Context, p provider.Provider, model, query, effort string) (string, []Hit, error) {
body, _ := json.Marshal(searchBody(p, model, query, effort))
r, err := http.NewRequestWithContext(magpieChose(ctx), http.MethodPost, "http://magpie/v1/messages", nil)
if err != nil {
return "", nil, err
@@ -835,6 +835,41 @@ func (s *Server) searchWith(ctx context.Context, p provider.Provider, model, que
return said, found, nil
}
// searchBody is the Anthropic Messages request the searcher's model is
// asked to search with. A level of reasoning is asked as Claude Code asks
// it, a thinking budget with output_config.effort beside it, which the
// gateway fits to the vendor the model is on: adaptive thinking for a
// Claude that takes only that (adaptiveThinking), reasoning_effort, a
// Gemini thinking level. A Claude before adaptive thinking is sent the
// budget alone, as output_config.effort isn't its; "none" turns thinking
// off.
func searchBody(p provider.Provider, model, query, effort string) map[string]any {
q := map[string]any{
"model": p.ID + "/" + model, "max_tokens": replyRoom(4096, effort), "stream": false, "system": searchSystem,
"messages": []map[string]any{{"role": "user", "content": "Search the web for: " + query}},
"tools": []map[string]any{{"type": "web_search_20250305", "name": "web_search", "max_uses": 3}},
}
switch effort {
case "":
case "none":
q["thinking"] = map[string]any{"type": "disabled"}
default:
budget := 1024 // Anthropic's least
if effort != "minimal" {
budget = budgetOf(effortOf(effort))
}
q["thinking"] = map[string]any{"type": "enabled", "budget_tokens": budget}
vendor := model
if _, m, ok := provider.Resolve(p.ID + "/" + model); ok {
vendor = m
}
if _, _, claude := claudeVersionOf(vendor); !claude || adaptiveOnly(vendor) {
q["output_config"] = map[string]any{"effort": effort}
}
}
return q
}
// SearchAgent is the User-Agent of the searches magpie makes for a model.
const SearchAgent = "magpie-search/1"
+3 -3
View File
@@ -85,16 +85,16 @@ func (s *Server) ownSearch(ctx context.Context, p provider.Provider, query strin
}
ctx, cancel := context.WithTimeout(context.WithValue(ctx, searchingKey{}, true), searchTimeout)
defer cancel()
return s.searchWith(ctx, p, searcherModel(p), query)
return s.searchWith(ctx, p, searcherModel(p), query, "")
}
// searchBy searches with one searcher: a Kimi Code plan by its search
// service, any other by its model.
func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query string) (string, []Hit, error) {
func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query, effort string) (string, []Hit, error) {
if provider.KimiCodeSearch(p) != "" {
return s.kimiSearch(ctx, p, query)
}
return s.searchWith(ctx, p, model, query)
return s.searchWith(ctx, p, model, query, effort)
}
// kimiSearch asks a Kimi Code plan's search service.
+104
View File
@@ -0,0 +1,104 @@
package gateway
import (
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// The reasoning level picked in Settings for a model magpie asks on its
// own, beside the model in use: Image recognition's and the searcher's
// (MOMO on Discord, "外置模型能不能提供思考深度选项"). Only those calls
// are asked so; every other request goes as it did.
// ModelEfforts are the reasoning levels model ("<provider>/<model>") has,
// weakest first, for Settings to offer beside it; none for one whose
// levels aren't known, or a routing group.
func ModelEfforts(model string) []string {
p, m, ok := provider.Resolve(model)
if !ok {
return nil
}
return ByStrength(p.Efforts(m))
}
// sideEffort is want fitted to model's own levels: "" when none is
// wanted, or the model's levels aren't known, so nothing is sent that it
// might refuse.
func sideEffort(model, want string) string {
levels := ModelEfforts(model)
if want == "" || len(levels) == 0 {
return ""
}
return fitEffort(want, levels)
}
// visionEffort is the level the Image recognition model is asked to read
// an image at: the one picked in Settings, else magpie's own, the least
// it has (classifyEffort), as a description is wanted quickly.
func visionEffort(model string) string {
if e := sideEffort(model, provider.HeldSettings().VisionEffort); e != "" {
return e
}
return classifyEffort(model)
}
// VisionEffortNow is the level the Image recognition model in use is
// asked at when one is picked in Settings ("" when none is): the picked
// one fitted to the model's levels, for the row to show.
func VisionEffortNow() string {
m, ok := seer()
if !ok {
return ""
}
return sideEffort(m, provider.HeldSettings().VisionEffort)
}
// VisionEfforts are the levels of the model that describes images now.
func VisionEfforts() []string {
if m, ok := seer(); ok {
return ModelEfforts(m)
}
return nil
}
// searchEffort is the level the searcher's model, provider p's model, is
// asked to search at: the one picked in Settings fitted to its levels,
// or "" to send none.
func searchEffort(p provider.Provider, model string) string {
if model == "" {
return ""
}
return sideEffort(p.ID+"/"+model, settings.Load().SearcherEffort)
}
// SearchEffortNow is the level the searcher in use is asked at, when one
// is picked in Settings.
func SearchEffortNow() string {
if p, m, ok := searcher(); ok {
return searchEffort(p, m)
}
return ""
}
// SearchEfforts are the levels of the model that searches now: none for
// a Kimi Code plan's search service, which has no model.
func SearchEfforts() []string {
if p, m, ok := searcher(); ok && m != "" {
return ModelEfforts(p.ID + "/" + m)
}
return nil
}
// replyRoom is the reply limit a side call asked to think at effort is
// sent with: its usual limit with room for the thinking above it, so a
// level picked higher doesn't spend the reply on thinking and leave no
// answer. The model's own limit still caps it (withMaxOutput).
func replyRoom(usual int, effort string) int {
switch effort {
case "", "none":
return usual
case "minimal":
return usual + 1024
}
return usual + budgetOf(effortOf(effort))
}
+324
View File
@@ -0,0 +1,324 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// pickEfforts saves the levels picked in Settings for Image recognition's
// model and the searcher's.
func pickEfforts(t *testing.T, vision, searcher string) {
t.Helper()
st := settings.Load()
st.VisionEffort, st.SearcherEffort = vision, searcher
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
}
// The reasoning level picked for Image recognition (MOMO on Discord) is
// what its model is asked at, fitted to the levels it has, with room to
// think in; Default is magpie's own, the least it has, as before. The
// model's own requests, from an agent, are sent as they came.
func TestVisionEffortPicked(t *testing.T) {
fresh(t)
u := &eyeUp{}
up := httptest.NewServer(u)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "probe", Name: "Probe", Chat: up.URL + "/v1", Key: "key", Models: []string{"eye"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("probe", up.URL+"/v1", []catalog.Model{
{ID: "eye", Images: true, ImageInput: imageInputBool(true), Efforts: []string{"low", "medium", "high"}},
}); err != nil {
t.Fatal(err)
}
st := settings.Load()
st.Vision = "probe/eye"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
s := New()
h := lanGuard(s.Handler())
if got := VisionEfforts(); !slices.Equal(got, []string{"low", "medium", "high"}) {
t.Fatalf("the row is offered %q", got)
}
ask := func(img string) gjson.Result {
t.Helper()
m := readMCP(t, visionPost(h, "127.0.0.1:50000", analyzeCall("data:image/png;base64,"+img, "")))
if m.Result.IsError {
t.Fatalf("analyze_image: %+v", m)
}
sent := u.sent("eye")
return gjson.Parse(sent[len(sent)-1])
}
// Default: the least it has, in the reply limit it always had
if q := ask("aW1nMQ=="); q.Get("reasoning_effort").String() != "low" || q.Get("max_tokens").Int() != 4096 {
t.Fatalf("default sent %s", q.Raw)
}
if VisionEffortNow() != "" {
t.Fatalf("default shows %q", VisionEffortNow())
}
// picked: the level, with room for its thinking
pickEfforts(t, "high", "")
if q := ask("aW1nMg=="); q.Get("reasoning_effort").String() != "high" || q.Get("max_tokens").Int() != 4096+24000 {
t.Fatalf("high sent %s", q.Raw)
}
// one the model hasn't is the nearest it has
pickEfforts(t, "xhigh", "")
if q := ask("aW1nMw=="); q.Get("reasoning_effort").String() != "high" {
t.Fatalf("xhigh sent %s", q.Raw)
}
if VisionEffortNow() != "high" {
t.Fatalf("xhigh shows %q", VisionEffortNow())
}
// an image read before at another level is read again at this one
pickEfforts(t, "medium", "")
if q := ask("aW1nMw=="); q.Get("reasoning_effort").String() != "medium" {
t.Fatalf("medium sent %s", q.Raw)
}
// an agent's own request to the model is sent as it came
rec := httptest.NewRecorder()
h.ServeHTTP(rec, func() *http.Request {
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"probe/eye","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))
r.RemoteAddr, r.Host = "127.0.0.1:50000", "127.0.0.1:3425"
return r
}())
sent := u.sent("eye")
if rec.Code != 200 || strings.Contains(sent[len(sent)-1], "reasoning_effort") {
t.Fatalf("the agent's request: %d, sent %s", rec.Code, sent[len(sent)-1])
}
}
// Image recognition on a Claude is asked to think with a budget under its
// reply limit, which the gateway fits from the level picked.
func TestVisionEffortOnAnthropic(t *testing.T) {
fresh(t)
var mu sync.Mutex
var got []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
got = append(got, string(b))
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n"+
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"A red square.\"}}\n\n"+
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n"+
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "ant", Name: "Anthropic", Anthropic: up.URL, Key: "key", Models: []string{"claude-sonnet-4-5"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("ant", up.URL, []catalog.Model{
{ID: "claude-sonnet-4-5", Images: true, ImageInput: imageInputBool(true), Efforts: []string{"low", "medium", "high"}},
}); err != nil {
t.Fatal(err)
}
st := settings.Load()
st.Vision, st.VisionEffort = "ant/claude-sonnet-4-5", "medium"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
s := New()
if _, err := s.askVision(context.Background(), "ant/claude-sonnet-4-5", "data:image/png;base64,aGVsbG8="); err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("sent %d", len(got))
}
q := gjson.Parse(got[0])
if q.Get("thinking.type").String() != "enabled" || q.Get("thinking.budget_tokens").Int() != 10000 || q.Get("max_tokens").Int() <= 10000 {
t.Fatalf("sent %s", got[0])
}
}
// searchUp is a vendor's Messages API that answers a search, or its
// Responses API that turns it away, keeping each body it is sent.
type searchUp struct {
mu sync.Mutex
bodies []string
}
func (u *searchUp) last() gjson.Result {
u.mu.Lock()
defer u.mu.Unlock()
if len(u.bodies) == 0 {
return gjson.Result{}
}
return gjson.Parse(u.bodies[len(u.bodies)-1])
}
func (u *searchUp) serve(models ...string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
switch {
case strings.HasSuffix(r.URL.Path, "/models"):
var ms []string
for _, m := range models {
ms = append(ms, `{"id":"`+m+`"}`)
}
io.WriteString(w, `{"data":[`+strings.Join(ms, ",")+`]}`)
return
}
u.mu.Lock()
u.bodies = append(u.bodies, string(b))
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/responses") {
http.Error(w, `{"error":{"message":"only kept"}}`, 400)
return
}
io.WriteString(w, `{"id":"s","type":"message","role":"assistant","model":"m","content":[
{"type":"server_tool_use","id":"srv","name":"web_search","input":{"query":"go"}},
{"type":"web_search_tool_result","tool_use_id":"srv","content":[{"type":"web_search_result","title":"Go downloads","url":"https://go.dev/dl/"}]},
{"type":"text","text":"The latest Go is 1.27.1."}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":5}}`)
}
}
// The reasoning level picked for the searcher (MOMO on Discord) is asked
// of its model in its vendor's words: a Claude that thinks only
// adaptively is asked output_config.effort, an older Claude a budget
// alone, OpenAI's Responses reasoning.effort; "none" turns thinking off,
// and Default sends none, as before.
func TestSearcherEffortPicked(t *testing.T) {
fresh(t)
catalog.Reset()
t.Cleanup(catalog.Reset)
newClaude, oldClaude, oai := &searchUp{}, &searchUp{}, &searchUp{}
nc := httptest.NewServer(newClaude.serve("claude-sonnet-5-5"))
oc := httptest.NewServer(oldClaude.serve("claude-haiku-4-5"))
oa := httptest.NewServer(oai.serve("gpt-5-mini"))
for _, srv := range []*httptest.Server{nc, oc, oa} {
t.Cleanup(srv.Close)
}
for proto, urls := range map[provider.Protocol][]string{provider.Anthropic: {nc.URL, oc.URL}, provider.Responses: {oa.URL}} {
hosts := searchHosts[proto]
add := slices.Clone(hosts)
for _, u := range urls {
add = append(add, provider.HostOf(u))
}
searchHosts[proto] = add
t.Cleanup(func() { searchHosts[proto] = hosts })
}
levels := []string{"none", "low", "medium", "high", "xhigh", "max"}
for _, c := range []struct {
p provider.Provider
base string
model string
}{
{provider.Provider{ID: "new", Name: "New", Key: "k", Anthropic: nc.URL}, nc.URL, "claude-sonnet-5-5"},
{provider.Provider{ID: "old", Name: "Old", Key: "k", Anthropic: oc.URL}, oc.URL, "claude-haiku-4-5"},
{provider.Provider{ID: "oai", Name: "OpenAI", Key: "k", Responses: oa.URL + "/v1"}, oa.URL + "/v1", "gpt-5-mini"},
} {
if err := provider.Save(c.p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive(c.p.ID, c.base, []catalog.Model{{ID: c.model, Efforts: levels}}); err != nil {
t.Fatal(err)
}
}
s := New()
search := func(named, effort string) {
t.Helper()
st := settings.Load()
st.Searcher, st.SearcherEffort = named, effort
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
if p, m, ok := searcher(); !ok || p.ID+"/"+m != named {
t.Fatalf("searcher = %s/%s, want %s", p.ID, m, named)
}
// a Responses reply is streamed, which this one isn't: only what it
// was sent is looked at
if _, _, err := s.modelSearch(context.Background(), "latest go"); err != nil && !strings.HasPrefix(named, "oai/") {
t.Fatalf("%s at %q: %v", named, effort, err)
}
}
search("new/claude-sonnet-5-5", "")
if q := newClaude.last(); q.Get("thinking").Exists() && q.Get("thinking.type").String() != "disabled" || q.Get("output_config.effort").Exists() {
t.Fatalf("default sent %s", q.Raw)
}
if !slices.Equal(SearchEfforts(), levels) || SearchEffortNow() != "" {
t.Fatalf("the row is offered %q at %q", SearchEfforts(), SearchEffortNow())
}
search("new/claude-sonnet-5-5", "xhigh")
if q := newClaude.last(); q.Get("thinking.type").String() != "adaptive" || q.Get("output_config.effort").String() != "xhigh" {
t.Fatalf("a Claude that thinks adaptively was sent %s", q.Raw)
}
if SearchEffortNow() != "xhigh" {
t.Fatalf("the row shows %q", SearchEffortNow())
}
search("new/claude-sonnet-5-5", "none")
// off as this Claude takes it: between_tools on Sonnet 5.5 (#1454)
if q := newClaude.last(); q.Get("thinking.type").String() != "between_tools" || q.Get("output_config.effort").Exists() {
t.Fatalf("none was sent %s", q.Raw)
}
search("old/claude-haiku-4-5", "high")
if q := oldClaude.last(); q.Get("thinking.type").String() != "enabled" || q.Get("thinking.budget_tokens").Int() != 24000 ||
q.Get("max_tokens").Int() <= 24000 || q.Get("output_config").Exists() {
t.Fatalf("an older Claude was sent %s", q.Raw)
}
search("oai/gpt-5-mini", "medium")
if q := oai.last(); q.Get("reasoning.effort").String() != "medium" {
t.Fatalf("Responses was sent %s", q.Raw)
}
search("oai/gpt-5-mini", "")
if q := oai.last(); q.Get("reasoning.effort").Exists() {
t.Fatalf("Responses at the default was sent %s", q.Raw)
}
}
// A level that isn't one is refused, so a typo doesn't go to a vendor.
func TestSideEffortChecked(t *testing.T) {
fresh(t)
st := settings.Load()
st.SearcherEffort = "hard"
if err := settings.Save(st); err == nil {
t.Fatal("a level that isn't one was saved")
}
st.SearcherEffort, st.VisionEffort = " High ", "max"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
if got := settings.Load(); got.SearcherEffort != "high" || got.VisionEffort != "max" {
t.Fatalf("saved %+v", got)
}
}
// The reporter's searcher, Gemini 3 Flash on Antigravity, is asked the
// level picked as its thinkingLevel; at the default it is sent none.
func TestSearcherEffortOnGemini(t *testing.T) {
ag := provider.Provider{ID: "antigravity", Account: &provider.Account{Agent: "antigravity", User: "u"}}
level := func(effort string) string {
t.Helper()
b, _ := json.Marshal(searchBody(ag, "gemini-3-flash", "latest go", effort))
r, err := parseAnthropic(b)
if err != nil {
t.Fatal(err)
}
return gjson.GetBytes(buildCodeAssist(r, "gemini-3-flash", "antigravity"), "request.generationConfig.thinkingConfig.thinkingLevel").String()
}
for effort, want := range map[string]string{"": "", "low": "low", "medium": "medium", "high": "high"} {
if got := level(effort); got != want {
t.Errorf("%q: thinkingLevel %q, want %q", effort, got, want)
}
}
}
+7 -2
View File
@@ -262,7 +262,8 @@ type sight struct {
// image: a request that sends it again, or sends it while it is being
// described, is given the same description.
func (s *Server) describe(ctx context.Context, model, src string) (string, error) {
sum := sha256.Sum256([]byte(model + "\x00" + src))
// a level picked since is asked again, not given what was said at the last
sum := sha256.Sum256([]byte(model + "\x00" + visionEffort(model) + "\x00" + src))
key := hex.EncodeToString(sum[:])
s.sightMu.Lock()
if e, ok := s.sights[key]; ok {
@@ -324,8 +325,12 @@ func (s *Server) askVisionWith(ctx context.Context, model, src, system, text str
},
"max_tokens": 4096,
}
if effort := classifyEffort(model); effort != "" {
if effort := visionEffort(model); effort != "" {
req["reasoning_effort"] = effort
// a level picked in Settings is given room to think in
if picked := sideEffort(model, provider.HeldSettings().VisionEffort); picked != "" {
req["max_tokens"] = replyRoom(4096, picked)
}
}
body, _ := json.Marshal(req)
r, err := http.NewRequestWithContext(magpieChose(ctx), http.MethodPost, "http://magpie/v1/chat/completions", nil)
+11 -1
View File
@@ -395,6 +395,10 @@ type settingsJSON struct {
// the Vision the user picked when magpie can't find it any more:
// VisionAuto describes in its place, and the row says so
VisionMissing string `json:"visionMissing,omitempty"`
// the reasoning levels of the model that describes images now, and the
// one it is asked at when one is picked (VisionEffort fitted to them)
VisionEfforts []string `json:"visionEfforts,omitempty"`
VisionEffortNow string `json:"visionEffortNow,omitempty"`
// the models Codex's thread titles may be sent to (CodexTitles, #705)
TitleModels []modelRef `json:"titleModels"`
// what each of the disabled models (#1867) turns off now, by pattern
@@ -421,7 +425,11 @@ type settingsJSON struct {
SearchChoices []searchChoiceJSON `json:"searchChoices"`
SearchAuto string `json:"searchAuto,omitempty"`
SearchUnused string `json:"searchUnused,omitempty"`
SearchRelays []string `json:"searchRelays,omitempty"`
// the reasoning levels of the model that searches now, and the one it
// is asked at when one is picked (SearcherEffort fitted to them)
SearchEfforts []string `json:"searchEfforts,omitempty"`
SearchEffortNow string `json:"searchEffortNow,omitempty"`
SearchRelays []string `json:"searchRelays,omitempty"`
// the last search the one it names didn't make, since it last
// searched: no other provider searched in its place (Gearclickist on
// Discord)
@@ -525,6 +533,7 @@ func searchState(s *settingsJSON) {
}
s.SearchProvider = gateway.Searcher()
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}
}
@@ -608,6 +617,7 @@ func settingsState() settingsJSON {
s.CheckinPlugins = provider.PluginCheckins()
s.CheckinAccounts = provider.CheckinAccounts()
s.VisionAuto, s.VisionModels, s.VisionMissing = gateway.AutoVision(), []modelRef{}, gateway.VisionMissing()
s.VisionEfforts, s.VisionEffortNow = gateway.VisionEfforts(), gateway.VisionEffortNow()
for _, e := range provider.Served() {
if e.Images && (e.ImageInput == nil || *e.ImageInput) && (e.Group != "" || e.Provider.Ready()) {
m := modelRef{ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon}
+5
View File
@@ -3077,6 +3077,11 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
.prefs .val { display: inline-flex; align-items: center; gap: 2px; margin-left: auto; min-width: 0; max-width: 60%; flex: none; }
.prefs .val code { font-size: 12px; color: var(--fg-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; padding: 0 6px; }
.prefs .val .text { padding: 3px 6px; }
/* how hard a side model thinks, beside it: the model's chip gives way first (MOMO on Discord) */
.prefs .val:has(> .side-effort) { gap: 6px; }
.prefs .val:has(> .side-effort) > .rt-cond:not(.side-effort) { min-width: 0; flex: 0 1 auto; }
.prefs .val > .side-effort { flex: none; }
.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; }
.prefs .lan-address-row .val { max-width: 64%; }
+29 -1
View File
@@ -22532,6 +22532,8 @@ function renderImages(s, keep) {
onPick: (id) => { if (id !== v) savePrefs({ ...keep, vision: id }); } }, b, ev);
const val = el("div", "val");
val.append(b);
if (v !== "off") sideEffortChip(val, s.visionEfforts, s.visionEffort || "", s.visionEffortNow, "vision-effort",
"the least it has", (e) => savePrefs({ ...keep, visionEffort: e }));
r.append(who, val);
box.append(r);
renderImageGen(s, keep, box);
@@ -22815,10 +22817,36 @@ function renderSearcher(s, keep, box) {
onPick: (id) => { if (id !== v) savePrefs({ ...keep, searcher: id }); } }, b, ev);
const val = el("div", "val");
val.append(b);
if (!off) sideEffortChip(val, s.searchEfforts, s.searcherEffort || "", s.searchEffortNow, "searcher-effort",
"none sent, the model's own", (e) => savePrefs({ ...keep, searcherEffort: e }));
r.append(who, val);
box.append(r);
}
// sideEffortChip: beside a model magpie asks on its own (Image
// recognition's, the searcher's), how hard it thinks (MOMO on Discord,
// "外置模型能不能提供思考深度选项"): only the levels that model has, and
// Default, which leaves it as magpie asks it (dflt says how). Nothing is
// shown for a model whose levels aren't known.
function sideEffortChip(val, levels, saved, now, cls, dflt, save) {
if (!levels?.length) return;
const b = el("button", "rt-cond on side-effort " + cls);
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
const shown = saved ? now || saved : "";
b.setAttribute("aria-label", t("Thinking") + ": " + (shown ? t(shown) : t("Default")));
b.title = t("How hard this model thinks");
b.append(effortIcon({ options: levels.map((l) => ({ value: l })), value: shown }), el("span", "", shown ? t(shown) : t("Default")));
b.onclick = (e) => {
e.stopPropagation();
if (protoMenu?.anchor === b) { closeProtoMenu(); return; }
openProtoMenu(b, [{ v: "", name: "Default", note: dflt }, ...levels.map((l) => ({ v: l, name: l, note: "" }))], shown,
(e) => { if (e !== saved) save(e); }, "Thinking", "side-effort-menu", "right");
};
val.append(b);
}
// renderReplies: whether a reply's model names the member of magpie's
// that answered it (#822), for agents that count usage by it.
function renderReplies(s, keep) {
@@ -23747,7 +23775,7 @@ function prefsKeep(s) {
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats,
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, refusalRetries: s.refusalRetries ?? null,
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360,
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, vision: s.vision || "", imageGen: s.imageGen || "", searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
turnDoneAlert: s.turnDoneAlert || 0 };
}
+12
View File
@@ -2555,6 +2555,9 @@ const I18N = {
"Tool call": "工具调用",
"Tool result": "工具结果",
"Thinking": "思考",
"How hard this model thinks": "这个模型思考的深度",
"the least it has": "它最低的一档",
"none sent, the model's own": "不发送,由模型自己决定",
"Context": "上下文",
"Image": "图片",
"Show full content": "展开全部",
@@ -7226,6 +7229,9 @@ const I18N = {
"Tool call": "工具呼叫",
"Tool result": "工具結果",
"Thinking": "思考",
"How hard this model thinks": "這個模型思考的深度",
"the least it has": "它最低的一檔",
"none sent, the model's own": "不傳送,由模型自己決定",
"Context": "上下文",
"Image": "圖片",
"Show full content": "展開全部",
@@ -11896,6 +11902,9 @@ const I18N = {
"Tool call": "ツール呼び出し",
"Tool result": "ツールの結果",
"Thinking": "思考",
"How hard this model thinks": "このモデルの思考の深さ",
"the least it has": "最も低いレベル",
"none sent, the model's own": "送らず、モデル自身に任せる",
"Context": "コンテキスト",
"Image": "画像",
"Show full content": "すべて表示",
@@ -16566,6 +16575,9 @@ const I18N = {
"Tool call": "Tool-Aufruf",
"Tool result": "Tool-Ergebnis",
"Thinking": "Denken",
"How hard this model thinks": "Wie gründlich dieses Modell nachdenkt",
"the least it has": "seine niedrigste Stufe",
"none sent, the model's own": "nichts gesendet, das Modell entscheidet",
"Context": "Kontext",
"Image": "Bild",
"Show full content": "Gesamten Inhalt anzeigen",
+171
View File
@@ -0,0 +1,171 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// How hard the models magpie asks on its own think (MOMO on Discord,
// "外置模型能不能提供思考深度选项"): Settings › Models has, beside Image
// recognition's model and the searcher's, a chip that opens the app's menu
// (no native select) with Default and only the levels that model has. A
// level picked is saved as visionEffort / searcherEffort and shown on the
// chip; Default saves "" (nothing sent beyond magpie's own choice). Another
// setting saved keeps both (prefsKeep). A model whose levels aren't known,
// or a row turned off, has no chip. No click moves the page, and both chips
// fit their row at 1100 and 420. Every language, Chromium and WebKit, 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 } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const choices = [
{ id: "antigravity", name: "Antigravity", icon: "antigravity", small: "gemini-3-flash", own: true, models: [
{ id: "antigravity/gemini-3-flash", name: "Gemini 3 Flash", provider: "antigravity", providerName: "Antigravity" }] },
];
// the menu's head and Default, said in each language
const words = {
en: { head: "Thinking", dflt: "Default", visionNote: "the least it has", searchNote: "none sent, the model's own" },
zh: { head: "思考", dflt: "默认", visionNote: "它最低的一档", searchNote: "不发送,由模型自己决定" },
"zh-TW": { head: "思考", dflt: "預設", visionNote: "它最低的一檔", searchNote: "不傳送,由模型自己決定" },
ja: { head: "思考", dflt: "デフォルト", visionNote: "最も低いレベル", searchNote: "送らず、モデル自身に任せる" },
de: { head: "Denken", dflt: "Standard", visionNote: "seine niedrigste Stufe", searchNote: "nichts gesendet, das Modell entscheidet" },
};
function serve(lang, posted, st) {
const settings = () => ({ lang, theme: "light", gateway: "http://127.0.0.1:3999", port: 3999,
vision: st.vision, visionAuto: "codex/gpt-6.1-sol",
visionModels: [{ id: "codex/gpt-6.1-sol", name: "GPT-6.1 Sol", provider: "codex", providerName: "Codex", icon: "openai" }],
visionEfforts: st.vision === "off" ? undefined : st.visionLevels, visionEffort: st.visionEffort, visionEffortNow: st.visionEffort || undefined,
searchVendors: [], searchAPIs: [], searchChoices: choices, searchAuto: "Antigravity · gemini-3-flash",
searcher: st.searcher, searchProvider: "Gemini 3 Flash · Antigravity",
searchEfforts: st.searcher === "off" ? undefined : st.searchLevels, searcherEffort: st.searcherEffort, searchEffortNow: st.searcherEffort || undefined });
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 = ${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);
Object.assign(st, { vision: b.vision, searcher: b.searcher, visionEffort: b.visionEffort, searcherEffort: b.searcherEffort });
}
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: "" }));
};
}
const rows = [
{ name: "Image recognition", chip: "#imagesList button.vision-effort", key: "visionEffort", levels: "visionLevels", note: "visionNote" },
{ name: "the searcher", chip: "#searchList button.searcher-effort", key: "searcherEffort", levels: "searchLevels", note: "searchNote" },
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: Image recognition and the searcher pick how hard their model thinks`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posted = [];
const st = { vision: "codex/gpt-6.1-sol", searcher: "antigravity/gemini-3-flash", visionEffort: "", searcherEffort: "",
visionLevels: ["low", "medium", "high", "xhigh"], searchLevels: ["minimal", "low", "medium", "high"] };
await page.route("**/*", serve(lang, posted, st));
await watchSettingsReads(page);
const where = () => page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop, document.querySelector(".view:not([hidden]) ")?.scrollTop ?? 0, document.querySelector("main")?.scrollTop ?? 0]);
const press = async (loc) => {
const b = await loc.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
for (const width of [1100, 420]) {
await page.mouse.move(0, 0);
await page.setViewportSize({ width, height: 900 });
await page.goto("http://magpie.test/?view=settings&tab=models");
await settingsDrawn(page);
const tr = (k) => page.evaluate((k) => t(k), k);
for (const row of rows) {
const chip = page.locator(row.chip);
await reach(page, chip);
// the chip fits its row, beside the model's, and the page doesn't scroll sideways
const fit = await chip.evaluate((c) => {
const r = c.closest(".row").getBoundingClientRect(), b = c.getBoundingClientRect(), m = c.previousElementSibling.getBoundingClientRect();
return { inside: b.left >= r.left - 1 && b.right <= r.right + 1, beside: m.right <= b.left + 1 || m.bottom <= b.top + 1,
wide: document.documentElement.scrollWidth - document.documentElement.clientWidth, tag: c.tagName, native: !!c.closest(".row").querySelector("select") };
});
assert(fit.inside && fit.beside && fit.wide <= 0 && !fit.native, `${row.name} ${width}: ${JSON.stringify(fit)}`);
assert.equal(await chip.innerText(), w.dflt, `${row.name}: nothing picked reads Default`);
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await chip.locator("xpath=ancestor::div[contains(@class,'row')][1]").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${row.key}.png`) });
}
const before = await where();
// the menu: Default, then only the model's own levels
await press(chip);
const menu = page.locator(".proto-menu.side-effort-menu");
await menu.waitFor({ state: "visible" });
assert.equal(await menu.locator(".pm-head").innerText(), w.head);
const names = await menu.locator(".pm-name").allInnerTexts();
const want = [w.dflt, ...await Promise.all(st[row.levels].map(tr))];
assert.deepEqual(names, want, `${row.name}: only the model's levels`);
// German's minimal is the same word
if (lang !== "en") for (const l of st[row.levels]) if (!(lang === "de" && l === "minimal")) assert.notEqual(await tr(l), l, `${l} is said in ${lang}`);
assert.equal(await menu.locator(".pm-item").first().locator(".pm-note").innerText(), w[row.note]);
assert.equal(await menu.locator(".pm-item.on .pm-name").innerText(), w.dflt);
const mb = await menu.boundingBox();
assert(mb.x >= 0 && mb.x + mb.width <= width + 1, `menu in the window at ${width}: ${JSON.stringify(mb)}`);
// a level picked is saved and shown
await press(menu.locator(".pm-item").nth(3));
await page.waitForFunction(([sel, k]) => document.querySelector(sel)?.innerText === k, [row.chip, await tr(st[row.levels][2])]);
assert.equal(posted.at(-1)[row.key], st[row.levels][2]);
assert.equal(await page.locator(row.chip).getAttribute("aria-expanded"), "false");
// ticked when opened again, and Default clears it
await press(page.locator(row.chip));
await menu.waitFor({ state: "visible" });
assert.equal(await menu.locator(".pm-item.on .pm-name").innerText(), await tr(st[row.levels][2]));
await press(menu.locator(".pm-item").first());
await page.waitForFunction(([sel, d]) => document.querySelector(sel)?.innerText === d, [row.chip, w.dflt]);
assert.equal(posted.at(-1)[row.key], "");
// the chip again closes its menu, Escape too, and neither saves
const n = posted.length;
await press(page.locator(row.chip));
await menu.waitFor({ state: "visible" });
await press(page.locator(row.chip));
await menu.waitFor({ state: "detached" });
await press(page.locator(row.chip));
await menu.waitFor({ state: "visible" });
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
assert.equal(posted.length, n);
assert.deepEqual(await where(), before, `${row.name} ${width}: the clicks moved nothing`);
}
// another setting saved keeps both picks
st.visionEffort = "high"; st.searcherEffort = "minimal";
await page.evaluate(() => fetch("/api/settings").then((r) => r.json()).then((s) => { prefs = s; state.settings = s; renderSettings(); }));
await page.waitForFunction(() => document.querySelector("#imagesList button.vision-effort")?.innerText !== "" && document.querySelector("#searchList button.searcher-effort"));
await page.evaluate(() => savePrefs({ ...prefsKeep(prefs), noStats: true }));
assert.equal(posted.at(-1).visionEffort, "high");
assert.equal(posted.at(-1).searcherEffort, "minimal");
st.visionEffort = ""; st.searcherEffort = "";
}
// levels not known, or the row off: no chip
st.visionLevels = undefined;
st.searcher = "off";
await page.goto("http://magpie.test/?view=settings&tab=models");
await settingsDrawn(page);
await page.locator("#searchList button.searcher-pick").waitFor();
assert.equal(await page.locator("#imagesList button.vision-effort, #searchList button.searcher-effort").count(), 0);
assert.deepEqual(errors, []);
});
}
}
+15
View File
@@ -242,6 +242,11 @@ type Settings struct {
// it: a model's id (provider/model, group/<id>), "off" to turn such an
// image away, or empty for one magpie picks (see gateway.seer).
Vision string `json:"vision,omitempty"`
// VisionEffort is how hard the Image recognition model thinks as it
// reads an image (MOMO on Discord): a level of catalog.EffortRank,
// fitted to the model's own levels when it is asked, or empty for
// magpie's choice, the least the model has (gateway.visionEffort).
VisionEffort string `json:"visionEffort,omitempty"`
// ImageGen is the model magpie's generate_image tool draws with (the
// gateway's /v1/images/generations when a request names no model): a
// model's id, "off", or empty for one magpie picks (gateway.drawer).
@@ -254,6 +259,11 @@ 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"`
// 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
// model's own default (gateway.searchEffort).
SearcherEffort string `json:"searcherEffort,omitempty"`
// SearchFirst is what a model that can't search the web is searched
// for with first, when both a provider and a search API can (#928):
// SearchFirstAPI for the search APIs, the provider's search after them
@@ -1139,6 +1149,11 @@ func save(s Settings, recording bool) error {
return fmt.Errorf("the model for Codex's subagents must be a model's id such as codex/gpt-5.5, not %q", s.CodexSubagentModel)
}
s.Searcher = strings.TrimSpace(s.Searcher)
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)
}
}
if s.SearchFirst = strings.TrimSpace(s.SearchFirst); s.SearchFirst == SearchFirstModel {
s.SearchFirst = ""
}