From dc507aefd3f8d50225628a4e2f2e4eda138c9e7c Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 18 Nov 2026 20:26:21 +0800 Subject: [PATCH] gateway: Automatic image recognition and web search stay with the provider that served them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hxy920830 on X added a Claude account only for account switching, and every agent's image recognition and web search moved onto it: with Settings › Models › Image recognition and Web search on Automatic, magpie ranked the picks again on each call, and a Claude account ranks first in both (seersRanked tier 0, searchRank 0). Adding a provider reassigned what another provider already served. - auto_picks.go holds each Automatic slot (Image recognition, Web search, Image generation, Video generation) to the provider magpie first picked, in auto-picks.json beside providers.json. seersRankedHeld and autoSearcherReady put the held provider before every other of its readiness; AutoDrawer and AutoVideomaker pick among its models while it has one. A default fills only a slot nothing serves: nothing held, or the held provider removed, off, or left with no model for it. - Allowance still comes first for the moment (#1801); the hold stays. - A model picked in Settings is untouched. The picker already shows the pick as "Automatic · ", where it can be changed. - A file that can't be read holds nothing and is not written over. Users already switched: holds begin once, when the gateway first serves (seedAutoPicks). It reads the last 30 days of the ledger's Image description calls (kind vision) and the searcher's Web search calls (kind web_search, not search API / native rows). A slot a later provider took over is given back to the provider that served the call just before the current pick's first, while it can still serve it. A switch older than 30 days, or one whose earlier provider is gone, is not restored: the current pick is held and the user picks in Settings › Models. Image and video generation have no Automatic call in the ledger and are held to the pick at the seed, nothing restored. Docs: docs/subsystems/gateway-routing.md, "Automatic picks are held to the provider that serves them". Run: - go test ./internal/gateway -run 'TestAddedProviderTakesNoAutomaticPick|TestAutoPicksSeededFromTheLedger|TestClaudeAccountAddedTakesNoImages' -v: ok (mica) - GOOS=linux go vet ./internal/gateway, GOOS=windows go vet ./internal/gateway: ok (mica) - go test -count=1 -timeout 45m ./... (mote, at 589e4ba6d + this change): every package ok (internal/gateway 1080s) except seven reds, each already filed and each passing alone at this tree on mica: capre TestCappedIsSmall (#5975); cli TestHealthcheckFindsTheRunning- GatewayWithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithout- MagpieAddr, TestUpdateFindsAMagpieThatWroteNoRecord (#6223, #6471: something serves on mote's 127.0.0.1:3425); gui TestAppReplacesIts- OlderGatewayOnceIdle (#6297), TestLaneLimitRoutes (#5150). The four cli and capre tests pass on origin/main 9314999a4 too. - After the rebase onto origin/main e08dc0fe5 (mica): go test ./internal/gateway -run 'the three|Vision|Searcher|Drawer|Videomaker' ok, GOOS=windows go vet ok. Broken by hand: heldPick returning "" (the old ranking) turns all three tests red: AutoVision = "anth/eye" after a provider was added, and "claude/claude-haiku-5-5" after the Claude account was signed in. Not tried: the real app with a real Claude account; no GUI file changed, so the GUI suite was not run. --- docs/subsystems/gateway-routing.md | 33 +++- internal/gateway/auto_picks.go | 254 ++++++++++++++++++++++++++++ internal/gateway/auto_picks_test.go | 225 ++++++++++++++++++++++++ internal/gateway/draw.go | 9 +- internal/gateway/search.go | 26 ++- internal/gateway/video.go | 16 ++ internal/gateway/vision.go | 22 ++- 7 files changed, 573 insertions(+), 12 deletions(-) create mode 100644 internal/gateway/auto_picks.go create mode 100644 internal/gateway/auto_picks_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 38b6a917b..930764f3c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -2926,12 +2926,43 @@ model that sees, see "An image the describer can't describe"), and a searcher named there is not handed on to another provider when it fails (see "A searcher that fails or finds nothing"). Image and video generation (`AutoDrawer`, -`AutoVideomaker`) are not held this way. +`AutoVideomaker`) are not held to allowance this way. Covered by `TestAutoVisionPassesOverOneOut`, `TestAutoVisionTierAmongThoseWithAllowance`, `TestSpentModelAcrossAccounts`, `TestVisionDoesNotAskSpentDescriber` and `TestSearcherPassesOverOneOut`. +## Automatic picks are held to the provider that serves them + +A slot Settings › Models leaves on Automatic (Image recognition, Web +search, Image generation, Video generation) is held to the provider +magpie first picked for it, in `auto-picks.json` beside providers.json +(`auto_picks.go`: `heldPick`, `settlePick`). `seersRankedHeld` and +`autoSearcherReady` put the held provider before every other of its +readiness; `AutoDrawer` and `AutoVideomaker` pick among its models while it +has one. A provider added later never takes a slot over: a Claude account +ranks first for images and search, and one added for account switching +alone took every agent's images and searches (hxy920830 on X). A default +fills only a slot nothing serves: nothing held yet, or the held provider +removed, turned off or left with no model for it; the next pick is then +held. Allowance still comes first for the moment (above), and the hold +stays. A model picked in Settings is the user's and no hold touches it; +the picker shows Automatic's pick as `Automatic · `. + +Holds begin once, when the gateway first serves (`KeepAutoPicksHeld`, +`seedAutoPicks`, `Seeded`); until then each pick is made as before, and a +file that can't be read holds nothing and is not written over. The seed +reads the last 30 days of the ledger: Image description calls (`vision`) +and the searcher's Web search calls (`web_search`, not `SourceSearch`). A +slot taken over by a provider added later (`pickBefore`: the one that +served the call just before the current pick's first) is given back while +that provider can still serve it; one the current pick served from the +first row is kept. Image and video generation have no Automatic call in +the ledger and are held to the pick at the seed. + +Covered by `TestAddedProviderTakesNoAutomaticPick`, +`TestAutoPicksSeededFromTheLedger` and `TestClaudeAccountAddedTakesNoImages`. + ## Hidden image models A provider's editor lists its image models (`gateway.Drawers`, the diff --git a/internal/gateway/auto_picks.go b/internal/gateway/auto_picks.go new file mode 100644 index 000000000..c120dfd83 --- /dev/null +++ b/internal/gateway/auto_picks.go @@ -0,0 +1,254 @@ +package gateway + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/steady" + "github.com/yetone/magpie/internal/usage" +) + +// What magpie picks by itself for a slot Settings leaves on Automatic — +// Image recognition (AutoVision), Web search (autoSearcher), Image +// generation (AutoDrawer) and Video generation (AutoVideomaker) — is held +// to the provider it first picked, in auto-picks.json, while that provider +// can still serve it. A provider added later never takes a slot over: +// hxy920830 on X added a Claude account for account switching alone, and +// every agent's images and web searches went to it, as a Claude account +// ranks first in both picks. A default fills only a slot nothing serves: +// the held provider removed, turned off or left with no model for it, or +// nothing held yet. Settings › Models shows the pick as Automatic · , +// and picking a model there is the user's own choice, which no hold +// touches. One with allowance left still goes before the held one out of +// it, as before (#1801): that is for the moment, and the hold stays. +const ( + slotVision = "vision" + slotSearcher = "searcher" + slotDrawer = "drawer" + slotVideo = "video" +) + +// autoPicksFile is auto-picks.json: each slot's held provider, and whether +// the ledger was read for the picks made before holds were kept (Seeded). +// Nothing is held until it is: until then each pick is made as before. +type autoPicksFile struct { + Vision string `json:"vision,omitempty"` + Searcher string `json:"searcher,omitempty"` + Drawer string `json:"drawer,omitempty"` + Video string `json:"video,omitempty"` + Seeded bool `json:"seeded,omitempty"` +} + +func (f *autoPicksFile) slot(s string) *string { + switch s { + case slotVision: + return &f.Vision + case slotSearcher: + return &f.Searcher + case slotDrawer: + return &f.Drawer + case slotVideo: + return &f.Video + } + return nil +} + +func autoPicksPath() string { + return filepath.Join(filepath.Dir(provider.Path()), "auto-picks.json") +} + +// heldPicks is auto-picks.json as last read, read again when the file +// changed: by another magpie, or a test's new HOME. +var heldPicks struct { + sync.Mutex + from string + mod time.Time + f autoPicksFile +} + +// readAutoPicks is the file's picks. Called with heldPicks held. A file +// that can't be read or parsed holds nothing (a pick is made as before) +// and is not written over by a hold: what it held is unknown. +func readAutoPicks() (autoPicksFile, bool) { + path := autoPicksPath() + fi, err := os.Stat(path) + if err != nil { + heldPicks.from, heldPicks.mod, heldPicks.f = path, time.Time{}, autoPicksFile{} + return autoPicksFile{}, os.IsNotExist(err) + } + if path == heldPicks.from && fi.ModTime().Equal(heldPicks.mod) { + return heldPicks.f, true + } + b, err := os.ReadFile(path) + var f autoPicksFile + if err != nil || json.Unmarshal(b, &f) != nil { + return autoPicksFile{}, false + } + heldPicks.from, heldPicks.mod, heldPicks.f = path, fi.ModTime(), f + return f, true +} + +// writeAutoPicks writes f through a temp file, only for this user to read. +// Called with heldPicks held. +func writeAutoPicks(f autoPicksFile) { + b, err := json.Marshal(f) + if err != nil { + return + } + path := autoPicksPath() + if os.MkdirAll(filepath.Dir(path), 0o700) != nil { + return + } + target, err := edit.Target(path) // a symlink stays, its target written + if err != nil { + return + } + tmp := target + ".magpie-tmp" + if os.WriteFile(tmp, b, 0o600) != nil { + return + } + if steady.Rename(tmp, target) != nil { + os.Remove(tmp) + return + } + if fi, err := os.Stat(path); err == nil { + heldPicks.from, heldPicks.mod, heldPicks.f = path, fi.ModTime(), f + } +} + +// heldPick is the provider slot is held to, "" for none: nothing held +// yet, or holds not begun (the ledger not read yet, seedAutoPicks). +func heldPick(slot string) string { + heldPicks.Lock() + defer heldPicks.Unlock() + f, _ := readAutoPicks() + if !f.Seeded { + return "" + } + return *f.slot(slot) +} + +// settlePick holds slot to pid, magpie's pick, when the slot holds none or +// the one it holds can't serve it any more (held, as heldPick said, and +// heldServes whether it still can). A pick of "" holds nothing. +func settlePick(slot, held string, heldServes bool, pid string) { + if pid == "" || held != "" && heldServes || pid == held { + return + } + heldPicks.Lock() + defer heldPicks.Unlock() + f, ok := readAutoPicks() + if !ok || !f.Seeded || *f.slot(slot) != held { + // unreadable, not begun, or another pick held it since + return + } + *f.slot(slot) = pid + writeAutoPicks(f) +} + +// providerOfRef is the provider of a "/" ref. +func providerOfRef(ref string) string { + id, _, _ := strings.Cut(ref, "/") + return id +} + +// pickedSince is how far back the ledger is read for a pick made before +// holds were kept. +const pickedSince = 30 * 24 * time.Hour + +// pickBefore is the provider a slot was served by before the provider +// that serves it now (current) took it over, read from rows, the slot's +// successful calls in the order they were made: the one that served the +// call just before current's first. "" when current served the slot from +// the first row read (nothing was taken over that the ledger shows), or +// when no call was made: current is kept then. When current made no call, +// the one that served the last call. +func pickBefore(rows []string, current string) string { + i := slices.Index(rows, current) + switch { + case len(rows) == 0 || i == 0: + return "" + case i < 0: + return rows[len(rows)-1] + } + return rows[i-1] +} + +// seedAutoPicks begins the holds, once: each Automatic slot is held to +// what served it before a provider added later took it over, when the +// ledger shows it (pickBefore) and that provider can still serve it, else +// to magpie's pick now. Image recognition and Web search are read from the +// ledger's Image description and Web search calls; Image and Video +// generation, which no call of the ledger names as Automatic's, are held +// to the pick now. +func seedAutoPicks() { + heldPicks.Lock() + f, ok := readAutoPicks() + heldPicks.Unlock() + if !ok || f.Seeded { + return + } + var vision, search []string + usage.Visit(time.Now().Add(-pickedSince), func(r usage.Record) { + if r.Provider == "" || r.Status < 200 || r.Status > 299 || r.IsRejected() { + return + } + switch { + case r.Kind == "vision": + vision = append(vision, r.Provider) + case r.Kind == "web_search" && r.Source != usage.SourceSearch: + // the searcher's model, not a search API or a provider's + // own search for its own model (logNativeSearches) + search = append(search, r.Provider) + } + }) + seed := autoPicksFile{Seeded: true} + cur := providerOfRef(AutoVision()) + seed.Vision = cur + if prev := pickBefore(vision, cur); prev != "" && seesFor(prev) { + seed.Vision = prev + } + if p, _, ok := autoSearcher(); ok { + seed.Searcher = p.ID + if prev := pickBefore(search, p.ID); prev != "" && searcherFor(prev) { + seed.Searcher = prev + } + } + seed.Drawer = providerOfRef(AutoDrawer()) + seed.Video = providerOfRef(AutoVideomaker()) + heldPicks.Lock() + defer heldPicks.Unlock() + if f, ok := readAutoPicks(); ok && !f.Seeded { + writeAutoPicks(seed) + } +} + +// seesFor is whether provider pid could be Image recognition's Automatic +// pick: it is on and has a model that sees (seersRanked). +func seesFor(pid string) bool { + return slices.ContainsFunc(seersRanked(nil), func(r rankedSeer) bool { return providerOfRef(r.model) == pid }) +} + +// searcherFor is whether provider pid could be Web search's Automatic +// pick: it is on, magpie may search with it, and it has a model to. +func searcherFor(pid string) bool { + p, err := provider.Find(pid) + if err != nil || !p.On() || searchRank(*p) < 0 { + return false + } + m, _ := searcherReady(*p) + return m != "" +} + +// KeepAutoPicksHeld begins the holds once the gateway serves. +func KeepAutoPicksHeld(context.Context) { seedAutoPicks() } + +func init() { WhileServing = append(WhileServing, KeepAutoPicksHeld) } diff --git a/internal/gateway/auto_picks_test.go b/internal/gateway/auto_picks_test.go new file mode 100644 index 000000000..6e8fc83f4 --- /dev/null +++ b/internal/gateway/auto_picks_test.go @@ -0,0 +1,225 @@ +package gateway + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// seeing saves a provider whose one enabled model, eye, sees, at price +// a million tokens in and out. +func seeing(t *testing.T, p provider.Provider, price float64) { + t.Helper() + p.Name, p.Key, p.Models = p.ID, p.ID+"-key", []string{"eye"} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + base := p.Responses + p.Anthropic + p.Chat + if err := catalog.SaveLive(p.ID, base, []catalog.Model{ + {ID: "eye", Images: true, ImageInput: imageInputBool(true), Price: &catalog.Price{Input: price, Output: price}}, + }); err != nil { + t.Fatal(err) + } +} + +func heldFile(t *testing.T) autoPicksFile { + t.Helper() + b, err := os.ReadFile(autoPicksPath()) + if err != nil { + t.Fatal(err) + } + var f autoPicksFile + if err := json.Unmarshal(b, &f); err != nil { + t.Fatal(err) + } + return f +} + +func autoSearcherID() string { + p, _, ok := autoSearcher() + if !ok { + return "" + } + return p.ID +} + +// A provider added while Image recognition and Web search are left on +// Automatic takes neither over (hxy920830 on X: a Claude account added +// for account switching alone took every agent's images and searches). +// What served them goes on serving them; one added later serves them +// only once it can't, and a model picked in Settings is still the one +// used. +func TestAddedProviderTakesNoAutomaticPick(t *testing.T) { + fresh(t) + // OpenAI's API: searches by itself (rank 3), sees at 5 + seeing(t, provider.Provider{ID: "oai", Responses: "https://api.openai.com/v1"}, 5) + seedAutoPicks() + if f := heldFile(t); !f.Seeded || f.Vision != "oai" || f.Searcher != "oai" { + t.Fatalf("held %+v, want oai for both", f) + } + + // Anthropic's API, added later: ranks before it for both (rank 2, + // cheaper), as a Claude account ranks first + seeing(t, provider.Provider{ID: "anth", Anthropic: "https://api.anthropic.com"}, 1) + if m := AutoVision(); m != "oai/eye" { + t.Fatalf("AutoVision = %q after a provider was added, want oai/eye still", m) + } + if id := autoSearcherID(); id != "oai" { + t.Fatalf("searcher = %q after a provider was added, want oai still", id) + } + if s := AutoSearcher(); !strings.HasPrefix(s, "oai") { + t.Fatalf("AutoSearcher = %q, Settings' Automatic would name another", s) + } + + // the user's own pick is the one used + st := settings.Load() + st.Vision, st.Searcher = "anth/eye", "anth" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + if m, _ := seer(); m != "anth/eye" { + t.Fatalf("seer = %q with anth/eye picked", m) + } + if p, _, ok := searcher(); !ok || p.ID != "anth" { + t.Fatalf("searcher = %q with anth picked", p.ID) + } + st.Vision, st.Searcher = "", "" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + + // the held provider turned off: the slot is empty, and the next fills it + p, err := provider.Find("oai") + if err != nil { + t.Fatal(err) + } + p.Off = true + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if m := AutoVision(); m != "anth/eye" { + t.Fatalf("AutoVision = %q with oai off", m) + } + if id := autoSearcherID(); id != "anth" { + t.Fatalf("searcher = %q with oai off", id) + } + if f := heldFile(t); f.Vision != "anth" || f.Searcher != "anth" { + t.Fatalf("held %+v with oai off, want anth", f) + } + // and turned on again it doesn't take the slot back from anth + p.Off = false + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if m := AutoVision(); m != "anth/eye" { + t.Fatalf("AutoVision = %q with oai back", m) + } +} + +// Before holds were kept, the provider added later took the slots: the +// first start with them gives each back to what served it before, as the +// ledger's Image description and Web search calls show, while it can +// still serve. One whose calls the ledger shows from the first row is +// kept, and so is the pick now when the one before is gone. +func TestAutoPicksSeededFromTheLedger(t *testing.T) { + ago := func(h int) time.Time { return time.Now().Add(-time.Duration(h) * time.Hour) } + call := func(at time.Time, kind, pid, source string) { + usage.Append(usage.Record{Time: at, Agent: "magpie", Kind: kind, Provider: pid, Model: "eye", Source: source, Status: 200}) + } + + t.Run("taken over", func(t *testing.T) { + fresh(t) + seeing(t, provider.Provider{ID: "oai", Responses: "https://api.openai.com/v1"}, 5) + seeing(t, provider.Provider{ID: "anth", Anthropic: "https://api.anthropic.com"}, 1) + // anth's own search for its own model, before it was magpie's pick: + // not a searcher's call + call(ago(9), "web_search", "anth", usage.SourceSearch) + call(ago(8), "vision", "oai", "") + call(ago(7), "web_search", "oai", "") + call(ago(6), "vision", "oai", "") + call(ago(5), "web_search", "oai", "") + // anth added: magpie picked it for both + call(ago(2), "vision", "anth", "") + call(ago(1), "web_search", "anth", "") + seedAutoPicks() + if f := heldFile(t); f.Vision != "oai" || f.Searcher != "oai" { + t.Fatalf("held %+v, want oai given back for both", f) + } + if m := AutoVision(); m != "oai/eye" { + t.Fatalf("AutoVision = %q", m) + } + if id := autoSearcherID(); id != "oai" { + t.Fatalf("searcher = %q", id) + } + }) + + t.Run("never taken over", func(t *testing.T) { + fresh(t) + seeing(t, provider.Provider{ID: "oai", Responses: "https://api.openai.com/v1"}, 5) + seeing(t, provider.Provider{ID: "anth", Anthropic: "https://api.anthropic.com"}, 1) + // anth served from the first call; oai only while anth was out + call(ago(8), "vision", "anth", "") + call(ago(6), "vision", "oai", "") + call(ago(2), "vision", "anth", "") + seedAutoPicks() + if f := heldFile(t); f.Vision != "anth" || f.Searcher != "anth" { + t.Fatalf("held %+v, want anth kept", f) + } + }) + + t.Run("the one before gone", func(t *testing.T) { + fresh(t) + seeing(t, provider.Provider{ID: "anth", Anthropic: "https://api.anthropic.com"}, 1) + call(ago(8), "vision", "removed", "") + call(ago(2), "vision", "anth", "") + seedAutoPicks() + if f := heldFile(t); f.Vision != "anth" { + t.Fatalf("held %+v, want anth: the one before is gone", f) + } + }) +} + +// The reporter's case: a Claude account, which ranks first for Image +// recognition, signed in after a key's model that sees served it. +func TestClaudeAccountAddedTakesNoImages(t *testing.T) { + claudeMadeFirst(t, false) + logins := filepath.Join(filepath.Dir(provider.Path()), "logins.json") + raw, err := os.ReadFile(logins) + if err != nil { + t.Fatal(err) + } + os.Remove(logins) + provider.ForgetAccounts() + t.Cleanup(provider.ForgetAccounts) + seeing(t, provider.Provider{ID: "keyed", Chat: "http://keyed.invalid/v1"}, 1) + seedAutoPicks() + if m := AutoVision(); m != "keyed/eye" { + t.Fatalf("AutoVision = %q before the Claude account", m) + } + + if err := os.WriteFile(logins, raw, 0o600); err != nil { + t.Fatal(err) + } + provider.ForgetAccounts() + if err := provider.Save(provider.Provider{ID: "claude", Models: []string{"claude-haiku-5-5"}}); err != nil { + t.Fatal(err) + } + yes := true + if err := provider.SetModelImage("claude/claude-haiku-5-5", &yes); err != nil { + t.Fatal(err) + } + if r := seersRankedHeld(nil, ""); len(r) == 0 || !strings.HasPrefix(r[0].model, "claude/") { + t.Fatalf("unheld, the Claude account isn't first: %v", r) + } + if m := AutoVision(); m != "keyed/eye" { + t.Fatalf("AutoVision = %q after the Claude account was added, want keyed/eye", m) + } +} diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index d9ffb8464..4392dda6b 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -559,9 +559,15 @@ func AutoDrawer() string { cands = append(cands, c) } } + // the provider the pick is held to draws while it can (heldPick, + // auto_picks.go): a ChatGPT account added later doesn't take it over + held := heldPick(slotDrawer) + heldDraws := held != "" && slices.ContainsFunc(cands, func(c cand) bool { + return providerOfRef(c.ref) == held && !(c.gen && c.key.less(newest)) + }) best, bestCost, bestDate := "", 0.0, "" for _, c := range cands { - if c.gen && c.key.less(newest) { + if c.gen && c.key.less(newest) || heldDraws && providerOfRef(c.ref) != held { continue } if c.gen && !c.priced && haveFamilyCost { @@ -571,6 +577,7 @@ func AutoDrawer() string { best, bestCost, bestDate = c.ref, c.cost, c.released } } + settlePick(slotDrawer, held, heldDraws, providerOfRef(best)) return best } diff --git a/internal/gateway/search.go b/internal/gateway/search.go index e8ef28f95..382b2b80d 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -400,23 +400,39 @@ func autoSearcher() (provider.Provider, string, bool) { func autoSearcherReady() (provider.Provider, string, bool, bool) { var best provider.Provider var model string - top, bestReady := -1, false + top, bestReady, have := 0, false, false + // the provider the pick is held to goes before every other of its + // readiness (heldPick, auto_picks.go): one added later, a Claude + // account's first of all, doesn't take the searches over + held, heldServes := heldPick(slotSearcher), false for _, p := range provider.All() { r := searchRank(p) - if r < 0 || !p.On() || (bestReady && r >= top) { + if r < 0 || !p.On() { + continue + } + if held != "" && p.ID == held { + r = -1 + } + if have && bestReady && r >= top { continue } m, ready := searcherReady(p) - if m == "" || top >= 0 && (bestReady && !ready || ready == bestReady && r >= top) { + if m != "" && r == -1 { + heldServes = true + } + if m == "" || have && (bestReady && !ready || ready == bestReady && r >= top) { continue } if codexSearches(p) { // by the backend's search, which spends no model's tokens m = codexSearchModel } - best, model, top, bestReady = p, m, r, ready + best, model, top, bestReady, have = p, m, r, ready, true } - return best, model, bestReady, top >= 0 + if have { + settlePick(slotSearcher, held, heldServes, best.ID) + } + return best, model, bestReady, have } // Why the searcher Settings names isn't used, and magpie picks one itself. diff --git a/internal/gateway/video.go b/internal/gateway/video.go index 4246bf668..3c134a6e9 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -320,6 +320,22 @@ func VideomakerMissingOf(v string) string { // second from the key's balance, and a key set up for chat would // otherwise take videos a subscription made before. func AutoVideomaker() string { + // the provider the pick is held to makes them while it can (heldPick, + // auto_picks.go): one added later doesn't take it over + held := heldPick(slotVideo) + m := autoVideomaker(held) + settlePick(slotVideo, held, held != "" && providerOfRef(m) == held, providerOfRef(m)) + return m +} + +func autoVideomaker(held string) string { + if held != "" { + if p, err := provider.Find(held); err == nil && p.On() && !p.DecideOnly() { + if ms := OfferedVideomakers(*p); len(ms) > 0 { + return p.ID + "/" + ms[0].ID + } + } + } paid := "" for _, p := range provider.All() { if !p.On() || p.DecideOnly() { diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index a3ae0610f..5508d8509 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -206,8 +206,8 @@ func autoSeerNote(see string) string { // AutoVision is the model magpie picks to describe images when the // Settings name none: a small model that sees, of the models the user -// enabled on the providers switched on (smallModel) — a -// Claude account's, a Codex account's, the cheapest of an API key's, +// enabled on the providers switched on (smallModel) — the provider it is +// held to's (heldPick, auto_picks.go), a Claude account's, a Codex account's, the cheapest of an API key's, // another account's. One with allowance left goes before one whose every // account or key is out of it (smallReady), whatever their order: the // one out is picked only when every model that sees is, so that agents @@ -221,10 +221,13 @@ func AutoVision() string { // autoVision is AutoVision's pick, and whether it has allowance left. func autoVision() (string, bool) { - if r := seersRanked(nil); len(r) > 0 { - return r[0].model, r[0].ready + held := heldPick(slotVision) + r := seersRankedHeld(nil, held) + if len(r) == 0 { + return "", false } - return "", false + settlePick(slotVision, held, slices.ContainsFunc(r, func(s rankedSeer) bool { return providerOfRef(s.model) == held }), providerOfRef(r[0].model)) + return r[0].model, r[0].ready } // rankedSeer is a model seersRanked names, and whether it has allowance. @@ -240,8 +243,17 @@ type rankedSeer struct { // passed over for the provider's next one (the describers a failed // description already asked, describeWith). func seersRanked(skip func(string) bool) []rankedSeer { + return seersRankedHeld(skip, heldPick(slotVision)) +} + +// seersRankedHeld is seersRanked with held, the provider Image +// recognition's Automatic pick is held to (heldPick), before every other +// of its readiness: a Claude account added later doesn't take it over. +func seersRankedHeld(skip func(string) bool, held string) []rankedSeer { tier := func(p provider.Provider) int { switch { + case held != "" && p.ID == held: + return -1 case p.Account != nil && p.Account.Agent == "claude": return 0 case p.Account != nil && p.Account.Agent == "codex":