From ba37e78b4cd21972c662bbc26baaae4c5e8503d0 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 28 Oct 2026 18:24:46 +0800 Subject: [PATCH] provider: a plugin model's test is told a queue at once and warms its host first mingxia_16024 on Discord (v0.1.1862): testing models on Qoder (CN and international) and WorkBuddy always failed with "qfmodel: context deadline exceeded", even though agents got answers from the same models. Cause, checked with the owner's real Qoder account in a sandbox HOME: - The test already takes the gateway's route: p.Do, then the plugin's fetch in the host. - The Qoder plugin waits out Qoder's free-plan queue (plan queue p3) for up to 4 minutes, unless X-Magpie-Fallback is "1". magpie never sent that header. - The probe gives up after 20s. A raw request with no deadline got its head after 3m49s. - The probe's 20s also had to cover the plugin host's cold start and the account loader's first run, which can renew the sign-in. A first WorkBuddy AI test took 8.4s. Changes: - For a plugin provider, probe sends X-Magpie-Fallback: 1, so a queued model answers at once with the plugin's queue message. - It starts the host and runs the account's loader (warmPlugin, through the account's proxy) under the caller's deadline, not the probe's. - A plugin probe waits up to pluginTestWait (60s). The GUI gives a model test 3 minutes. - host.js lists x-magpie-fallback in MAGPIE_ONLY, so no vendor receives it. "Recent calls" lists only the gateway's own calls, for every provider. A test is written to the Requests page as magpie's own test, timed-out tries included, so that is unchanged. The gateway still never sends the header when another candidate follows, which Qoder 0.2.40 and CodeArts 0.2.3 expect: #4049. Run (mote-run): - New tests TestPluginModelTestSaysQueued and TestPluginModelTestColdHost. They use the fake plugin's new $FAKE_QUEUE and $FAKE_LOAD_WAIT, with a cold host from plugin.Restart. - go test -tags nogui -timeout 45m ./... at 76218200a: every package ok (77), none FAIL. - GOOS=linux and GOOS=windows go vet of internal/provider and internal/plugin, go build ./..., and gofmt -l. - Real Qoder account, sandbox HOME, a TestModels of qfmodel: - before: failed at 20.00s, twice; - after: "Qoder queued the request for qfmodel (this plan's queue: p3); try again in 30s" in about 0.5s, twice. One more run got a 200 in 767ms. Broken by hand, each red: - Without the header set: SaysQueued fails with "context deadline exceeded" at its 5s wait. - Without warmPlugin: ColdHost fails with a deadline at 2001ms. - Without the MAGPIE_ONLY entry: the vendor gets fallback="1". Not tried: - WorkBuddy CN with a real account. It reads the desktop app's sign-in, which the sandbox doesn't have. - A cold start on a slow machine or on Windows. - The GUI button itself. The handler is unchanged. --- internal/plugin/host.js | 9 +- internal/plugin/testdata/fake/index.js | 23 +++- internal/provider/plugin_model_test_test.go | 120 ++++++++++++++++++++ internal/provider/plugins.go | 24 ++++ internal/provider/test.go | 27 ++++- 5 files changed, 192 insertions(+), 11 deletions(-) create mode 100644 internal/provider/plugin_model_test_test.go diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 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.js index 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 chats if (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-claude usage: async (getAuth) => { diff --git a/internal/provider/plugin_model_test_test.go b/internal/provider/plugin_model_test_test.go new file mode 100644 index 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.go index 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 was diff --git a/internal/provider/test.go b/internal/provider/test.go index 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 []b r.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 []b if 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