Files
magpie/internal/gateway/plugin_parity_test.go
yetone 2da8fbe488 tests: every test that runs plugins on the bun on PATH runs it once first, through testenv.Bun, so a bun that has never run here doesn't time out internal/provider's and internal/plugin's plugin tests (#1306)
65dcc573 (ggbdpq's patch 1) warmed the bun on PATH before the root
package's one-minute plugin contexts. The same lookup of the bun on PATH
is in 40 more places in internal/provider (28), internal/gateway (8),
internal/plugin (3) and internal/gui (1), and in the root package's
TestPluginListSaysClash. Many of them then open a one- or two-minute
context (internal/provider's sign-in, fetch and move tests,
internal/plugin's sandbox), and there macOS's first-exec check of a
just-installed or upgraded bun landed inside the deadline. The rest
are covered the same way, so no test has to remember which is which.

testenv.Bun now does what the root package's pathBun did: it finds the
bun on PATH (skipping the test when there is none) and runs
`bun --version` before the test opens its context, once per bun per test
binary. pathBun is gone; every `exec.LookPath("bun")` + skip block in
the tests uses testenv.Bun instead. Three tests reach for the bun some
other way and are left as they were: TestHostRunsAsMagpieBun (7ddea2c2
covers its copy), the plugin_git test's realBun and netproxy's
TestBunThroughBridge, none of which runs the plugin host under a
deadline on the PATH bun. migrate_test.go needed two `err` declarations
that the removed block used to provide.

What was run (macOS arm64, bun 1.4.2), with a wrapper bun first on PATH
whose first exec sleeps 61s (marker-gated, then execs the real bun):
- Red, old code:
  - internal/provider TestPluginSignInTakesAPastedCallback: FAIL at
    61.1s, "pluginsignin_paste_test.go:36: starting plugins: context
    deadline exceeded".
  - internal/plugin TestFakePlugin: FAIL at 62.0s, "plugin_test.go:66:
    Plugins = [], starting plugins: context deadline exceeded".
  - internal/gateway TestPluginFailover passed on the old code too (its
    calls have no deadline that short), so the gateway is not shown red.
- Green, this change, same cold wrapper: the three tests passed (61.1s,
  62.9s, 61.2s).
- go test -tags nogui -count=1 for the root package and for
  internal/testenv, gateway, gui, plugin and provider, under a temp HOME
  with GOMODCACHE, GOCACHE and GOPATH pinned: all ok.
- gofmt -l on the changed files: clean. go vet of those packages for
  darwin (-tags nogui), GOOS=linux and GOOS=windows (-tags nogui), and
  GOOS=windows without the tag: clean.

Not run: a really cold bun on a loaded machine; the sleep stands in for
the check. Not run on Linux or Windows, where the warm-up is one extra
`bun --version` per test binary.
2026-10-10 10:22:59 +08:00

147 lines
5.0 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// movedFake is the fake plugin signed in as the built-in id it was moved
// onto, its requests going to up.
func movedFake(t *testing.T, id string, up http.Handler) {
t.Helper()
bun := testenv.Bun(t)
fresh(t)
t.Setenv("MAGPIE_BUN", bun)
t.Setenv("FAKE_ID", id)
t.Cleanup(plugin.Settle)
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
t.Setenv("FAKE_BASE", srv.URL+"/v1")
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]any{id: map[string]any{"state": provider.MovePlugin}})
if err := os.WriteFile(filepath.Join(dir, "migrations.json"), b, 0o600); err != nil {
t.Fatal(err)
}
if !provider.Moved(id) {
t.Fatalf("%s isn't marked moved", id)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
if _, err := plugin.APIKey(ctx, id, 0, nil, "k1", plugin.NewAccount); err != nil {
t.Fatal(err)
}
if p, err := provider.Find(id); err != nil || !p.IsPlugin() {
t.Fatalf("Find(%s) = %+v, %v", id, p, err)
}
}
// Factory moved onto its plugin counts a prompt's tokens as the built-in
// did, by estimate: the vendor isn't asked.
func TestMovedCountTokensEstimated(t *testing.T) {
var mu sync.Mutex
var asked []string
movedFake(t, "factory", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.URL.Path)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"input_tokens":999}`))
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages/count_tokens", strings.NewReader(`{"model":"factory/fake-claude","messages":[{"role":"user","content":"hello there"}]}`))
New().Handler().ServeHTTP(rec, req)
var got struct {
InputTokens int `json:"input_tokens"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); rec.Code != 200 || err != nil || got.InputTokens == 0 {
t.Fatalf("count_tokens: %d %s", rec.Code, rec.Body)
}
mu.Lock()
defer mu.Unlock()
if len(asked) > 0 || got.InputTokens == 999 {
t.Fatalf("the vendor was asked to count: %v, %d", asked, got.InputTokens)
}
}
// thoughtChat is a fast request with an assistant turn that reasoned, and
// chatBody the chat request built of it for host.
var thoughtChat = &Request{Fast: true, Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "pondered"}, {Kind: Text, Text: "hello"}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "again"}}},
}}
func chatBody(t *testing.T, host string) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(buildChat(thoughtChat, "m", host, false), &m); err != nil {
t.Fatal(err)
}
return m
}
// Cursor moved onto its plugin is told fast mode as the built-in told
// Cursor: its plugin reads the chat request's service_tier. No other
// chat upstream is told it.
func TestCursorPluginFast(t *testing.T) {
if m := chatBody(t, "cursor"); m["service_tier"] != "priority" {
t.Errorf("Cursor's plugin wasn't told fast: %v", m["service_tier"])
}
for _, host := range []string{"api.openai.com", "openrouter.ai", "zed", "api.deepseek.com", provider.CommandCodePlanID} {
if m := chatBody(t, host); m["service_tier"] != nil {
t.Errorf("%s was told a service tier", host)
}
}
}
// A Command Code Go conversation moved onto its plugin keeps its
// reasoning, as the built-in replayed it to /alpha/generate: its plugin
// reads reasoning_content. DeepSeek still gets it, others don't.
func TestCommandCodePluginReasoning(t *testing.T) {
reasoning := func(host string) any {
return chatBody(t, host)["messages"].([]any)[1].(map[string]any)["reasoning_content"]
}
for _, host := range []string{provider.CommandCodePlanID, "api.deepseek.com"} {
if got := reasoning(host); got != "pondered" {
t.Errorf("%s got reasoning %v", host, got)
}
}
for _, host := range []string{"api.openai.com", "cursor", "zed"} {
if got := reasoning(host); got != nil {
t.Errorf("%s got reasoning_content %v", host, got)
}
}
}
// A moved provider's account is told in the trace as its provider's, so
// its plan reads as the built-in's did, not as a plugin's.
func TestTraceNamesMovedAccount(t *testing.T) {
p := provider.Provider{ID: "grok", Name: "Grok", Account: &provider.Account{Agent: "plugin", User: "me@example.com", Plan: "SuperGrok Heavy"}}
w := weighed(candidate{p: p, rest: "grok", model: "grok-4"}, p, weighing{}, false, "")
if w.Kind != "account" || w.Agent != "grok" || w.Plan != "SuperGrok Heavy" {
t.Fatalf("weighed = %+v, want grok's account", w)
}
}