Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
provider: a plugin model's test is told a queue at once and warms its host first
yetoneba37e78b4cd2
diff --git a/internal/plugin/host.js b/internal/plugin/host.jsindex 924039656..f16968426 100644--- a/internal/plugin/host.js+++ b/internal/plugin/host.js@@ -551,10 +551,11 @@ function asked(input, init) {}// MAGPIE_ONLY are the headers magpie tells a plugin's fetch where the agent-// that asked works with (WorkDirHeader and WorkGitHeader in-// internal/provider): for the plugin to read, never for its vendor, so a-// plugin that sends on the headers it was given sends them nowhere.-const MAGPIE_ONLY = ["x-magpie-work-dir", "x-magpie-work-git"]+// that asked works (WorkDirHeader and WorkGitHeader in internal/provider)+// and that a queue needn't be waited out (FallbackHeader): for the plugin+// to read, never for its vendor, so a plugin that sends on the headers it+// was given sends them nowhere.+const MAGPIE_ONLY = ["x-magpie-work-dir", "x-magpie-work-git", "x-magpie-fallback"]function unsaid(input, init) {if (input instanceof Request && MAGPIE_ONLY.some((k) => input.headers.has(k))) {diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.jsindex a8093d099..e19e22651 100644--- a/internal/plugin/testdata/fake/index.js+++ b/internal/plugin/testdata/fake/index.js@@ -184,7 +184,11 @@ export const FakePlugin = async ({ client }) => ({}),},],- loader: async (getAuth, provider) => ({+ loader: async (getAuth, provider) => {+ // $FAKE_LOAD_WAIT: the loader takes that many ms (a sign-in renewed+ // on a slow line), as a cold host's first request waits for it+ if (process.env.FAKE_LOAD_WAIT) await new Promise((r) => setTimeout(r, Number(process.env.FAKE_LOAD_WAIT)))+ return {apiKey: "dummy",baseURL: process.env.FAKE_BASE,async fetch(url, init) {@@ -206,13 +210,26 @@ export const FakePlugin = async ({ client }) => ({// where magpie said the agent works, as the plugin read it; its own// headers go on too, as a plugin that sends on what it got sends// them, for the host to take off- for (const k of ["x-magpie-work-dir", "x-magpie-work-git"]) if (h.has(k)) h.set("x-saw-" + k.slice(9), h.get(k))+ for (const k of ["x-magpie-work-dir", "x-magpie-work-git", "x-magpie-fallback"]) if (h.has(k)) h.set("x-saw-" + k.slice(9), h.get(k))+ // $FAKE_QUEUE: that model is queued at the vendor, as Qoder's free+ // models are: waited out (here until magpie gives up) unless magpie+ // said it needn't be, then said at once with the queue's 503+ if (process.env.FAKE_QUEUE && typeof init.body === "string" && JSON.parse(init.body).model === process.env.FAKE_QUEUE) {+ if (h.get("x-magpie-fallback") === "1") {+ return new Response(JSON.stringify({ error: { message: `FakeCo queued the request for ${process.env.FAKE_QUEUE}; try again in 30s`, type: "queued" } }), { status: 503, headers: { "content-type": "application/json", "retry-after": "30" } })+ }+ await new Promise((_, no) => {+ const t = setTimeout(() => no(new Error("FakeCo's queue gave up")), 300e3)+ init.signal?.addEventListener("abort", () => (clearTimeout(t), no(init.signal.reason)))+ })+ }// $FAKE_H2: the request goes on node:http2 to that origin, as// Cursor's plugin runs its chatsif (process.env.FAKE_H2) return h2(process.env.FAKE_H2, new URL(url).pathname)return fetch(url, { ...init, headers: h })},- }),+ }+ },// magpie's: the account's allowance; "full@fake" has used its five// hours, which count only fake-claudeusage: async (getAuth) => {diff --git a/internal/provider/plugin_model_test_test.go b/internal/provider/plugin_model_test_test.gonew file mode 100644index 000000000..a90be5052--- /dev/null+++ b/internal/provider/plugin_model_test_test.go@@ -0,0 +1,120 @@+package provider++import (+ "context"+ "fmt"+ "net/http"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/plugin"+ "github.com/yetone/magpie/internal/testenv"+)++// testingPlugin installs the fake plugin with one signed-in account and+// gives its provider; the vendor is vendor.+func testingPlugin(t *testing.T, ctx context.Context, vendor http.Handler) Provider {+ t.Helper()+ bun := testenv.Bun(t)+ claudeHome(t)+ t.Setenv("MAGPIE_BUN", bun)+ testenv.FakeVendor(t, vendor)+ t.Cleanup(plugin.Settle)+ abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")+ if _, err := plugin.Add(ctx, abs); err != nil {+ t.Fatal(err)+ }+ k, err := plugin.Import(ctx, "fakeco", map[string]any{"type": "oauth", "refresh": "r-x", "access": "a", "expires": 9e15, "accountId": "a@fake"})+ if err != nil {+ t.Fatal(err)+ }+ saveLogins(t, savedLogin{Agent: "plugin:fakeco", User: "a@fake", Home: k, On: true})+ if _, err := plugin.Providers(ctx); err != nil {+ t.Fatal(err)+ }+ p, err := Find(PluginID("fakeco"))+ if err != nil {+ t.Fatal(err)+ }+ if !p.IsPlugin() {+ t.Fatal("not a plugin's provider")+ }+ return *p+}++// answers is a vendor that streams one word on chat completions, and+// keeps the X-Magpie-Fallback and X-Saw-Fallback each request came with.+type answers struct {+ mu sync.Mutex+ seen []string+}++func (a *answers) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ a.mu.Lock()+ a.seen = append(a.seen, fmt.Sprintf("fallback=%q saw=%q", r.Header.Get(FallbackHeader), r.Header.Get("X-Saw-Fallback")))+ a.mu.Unlock()+ w.Header().Set("Content-Type", "text/event-stream")+ fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n")+}++// A plugin's model its vendor has queued (Qoder's free models) is said+// queued at once by the models' test, not waited out until the test's+// time ran out ("qfmodel: context deadline exceeded", mingxia_16024);+// the model beside it answers; and the header that said so reaches the+// plugin only, never its vendor.+func TestPluginModelTestSaysQueued(t *testing.T) {+ t.Setenv("FAKE_QUEUE", "fake-1")+ defer func(w, pw time.Duration) { testWait, pluginTestWait = w, pw }(testWait, pluginTestWait)+ testWait, pluginTestWait = 5*time.Second, 5*time.Second+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ v := &answers{}+ p := testingPlugin(t, ctx, v)+ start := time.Now()+ res := p.TestModels(ctx, []string{"fake-1", "fake-claude"})+ took := time.Since(start)+ got := map[string]Result{}+ for _, r := range res {+ got[r.Model] = r+ }+ q := got["fake-1"]+ if q.OK || !strings.Contains(q.Error, "queued the request for fake-1") {+ t.Errorf("the queued model's test: ok %v, %q (%v); want the plugin's queue message", q.OK, q.Error, took)+ }+ if strings.Contains(q.Error, "deadline") {+ t.Errorf("the queued model's test ran out of time: %q", q.Error)+ }+ if r := got["fake-claude"]; !r.OK {+ t.Errorf("fake-claude's test: %+v", r)+ }+ v.mu.Lock()+ defer v.mu.Unlock()+ if len(v.seen) == 0 {+ t.Fatal("the vendor was never asked")+ }+ for _, s := range v.seen {+ if s != `fallback="" saw="1"` {+ t.Errorf("the vendor got %s; want the plugin to have seen it and the vendor not", s)+ }+ }+}++// A plugin whose host starts cold and whose loader is slow (a sign-in+// renewed) has its model's test answered when the vendor answers: the+// host's start and the loader don't spend the probe's time.+func TestPluginModelTestColdHost(t *testing.T) {+ t.Setenv("FAKE_LOAD_WAIT", "2500")+ defer func(w, pw time.Duration) { testWait, pluginTestWait = w, pw }(testWait, pluginTestWait)+ testWait, pluginTestWait = 2*time.Second, 2*time.Second+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ p := testingPlugin(t, ctx, &answers{})+ plugin.Restart() // cold: the next call starts a host, whose loader hasn't run+ res := p.TestModels(ctx, []string{"fake-claude"})+ if len(res) != 1 || !res[0].OK {+ t.Fatalf("a cold host's model test: %+v", res)+ }+}diff --git a/internal/provider/plugins.go b/internal/provider/plugins.goindex 317e86f54..4583823ea 100644--- a/internal/provider/plugins.go+++ b/internal/provider/plugins.go@@ -44,6 +44,30 @@ const (WorkGitHeader = "X-Magpie-Work-Git")+// FallbackHeader, "1", tells a plugin's fetch that magpie needn't have the+// answer waited for: a request its vendor queues (Qoder's free models)+// comes back at once with the queue's 503 and Retry-After instead of being+// waited out for minutes. Without it the plugin waits. A model's test+// sends it, so a queued model's test says it is queued instead of running+// out of time. The plugin host takes it off whatever the plugin sends on+// (host.js), as it does the two above.+const FallbackHeader = "X-Magpie-Fallback"++// warmPlugin starts p's plugin host and runs its account's loader, which+// may renew the sign-in, under ctx and through the account's proxy: what+// a plugin's first fetch waits for besides its vendor. A failure is left+// for the fetch to meet and say.+func (p Provider) warmPlugin(ctx context.Context) {+ if !p.IsPlugin() {+ return+ }+ id := p.Account.plugin.ID+ if cur, ok := PluginOf(p.ID); ok {+ id = cur.ID+ }+ _, _ = plugin.LoaderOptions(p.Via(ctx), id, p.Account.pluginKey)+}+// PluginID is the id magpie gives the provider OpenCode calls id: the same,// unless a preset or a built-in subscription has it (google, openai,// anthropic), or a provider of the user's own made before the plugin wasdiff --git a/internal/provider/test.go b/internal/provider/test.goindex 336d44aa4..de3556282 100644--- a/internal/provider/test.go+++ b/internal/provider/test.go@@ -211,10 +211,16 @@ func tinyBody(q Provider, proto Protocol, model string) (url, body string) {}// testWait is how long a probe waits for an answer; drawWait, for a-// picture, which takes an images API longer than a word takes chat.-const (- testWait = 20 * time.Second- drawWait = 2 * time.Minute+// picture, which takes an images API longer than a word takes chat;+// pluginTestWait, for a plugin's provider, whose fetch may renew the+// sign-in or ask its vendor more than once before it answers, as it does+// for the gateway, which gives it no such bound (mingxia_16024 on+// Discord: every Qoder and WorkBuddy model's test ended at 20s while+// agents were answered).+var (+ testWait = 20 * time.Second+ drawWait = 2 * time.Minute+ pluginTestWait = time.Minute)// drawsOnImages is whether model is asked on p's images API, as the@@ -547,6 +553,14 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []br.Error = "no model to try: expose one, or refresh the model list"return r}+ if p.IsPlugin() {+ // the plugin host started and the account's loader run (a+ // sign-in renewed) under the caller's time, as a warm host+ // answers the gateway, not the probe's: a cold host took the+ // whole of it (mingxia_16024)+ p.warmPlugin(ctx)+ wait = max(wait, pluginTestWait)+ }ctx, cancel := context.WithTimeout(probelog.WithModel(ctx, model), wait)defer cancel()rctx := ctx@@ -575,6 +589,11 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []bif client := testClient(ctx); client != "" {clientHeaders(client, req.Header)}+ if p.IsPlugin() {+ // a model its vendor has queued is said so at once, not waited+ // out for minutes as an agent's turn is (Qoder's free models)+ req.Header.Set(FallbackHeader, "1")+ }if err := p.Sign(ctx, req, proto, body); err != nil {r.Error = err.Error()return r