diff --git a/internal/gateway/plugin_gemini_model_test_test.go b/internal/gateway/plugin_gemini_model_test_test.go new file mode 100644 index 000000000..b05b00d6e --- /dev/null +++ b/internal/gateway/plugin_gemini_model_test_test.go @@ -0,0 +1,94 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net/http" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// A plugin's Gemini model (@ai-sdk/google) is tested as the gateway asks +// it: Gemini's generateContent, through the plugin's fetch. Test models +// sent it the body of the plugin's first other API, which Zed's cloud +// read as a Google request and answered 400 "failed to parse Google AI +// request: missing field contents" (Been on Discord: every Gemini model +// failed its test while agents were answered). +func TestPluginGeminiModelTestedOnGenerateContent(t *testing.T) { + bun := testenv.Bun(t) + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + + type seen struct{ path, body string } + var mu sync.Mutex + var got []seen + up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + got = append(got, seen{r.URL.RequestURI(), string(b)}) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + switch { + case r.URL.Path == "/v1/chat/completions": + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + case strings.HasPrefix(r.URL.Path, "/v1/models/"): + fmt.Fprint(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"hi from gemini"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":2}}`+"\n\n") + default: + w.WriteHeader(404) + } + })) + defer up.Close() + + 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, "fakeco", 0, nil, "k1", plugin.NewAccount); err != nil { + t.Fatal(err) + } + p, err := provider.Find("fakeco") + if err != nil || !p.IsPlugin() { + t.Fatalf("Find = %+v, %v", p, err) + } + + res := p.TestModels(ctx, []string{"fake-gemini", "fake-1"}) + byModel := map[string]provider.Result{} + for _, r := range res { + byModel[r.Model] = r + } + if r := byModel["fake-gemini"]; !r.OK || r.Protocol != provider.CodeAssist { + t.Errorf("fake-gemini's test: %+v; want it answered on Code Assist", r) + } + if r := byModel["fake-1"]; !r.OK || r.Protocol != provider.Chat { + t.Errorf("fake-1's test: %+v; want it answered on chat, as before", r) + } + mu.Lock() + defer mu.Unlock() + var gemini []seen + for _, s := range got { + if strings.Contains(s.body, "fake-gemini") || strings.Contains(s.path, "fake-gemini") { + gemini = append(gemini, s) + } + } + if len(gemini) != 1 { + t.Fatalf("fake-gemini reached the vendor %d times: %+v", len(gemini), got) + } + g := gemini[0] + if !strings.HasPrefix(g.path, "/v1/models/fake-gemini:streamGenerateContent") || !strings.Contains(g.body, `"contents"`) || strings.Contains(g.body, `"request"`) { + t.Errorf("fake-gemini's test reached the vendor as %+v; want generateContent's contents, outside Code Assist's envelope", g) + } +} diff --git a/internal/provider/test.go b/internal/provider/test.go index ea8ce4674..19b3589d5 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -376,7 +376,7 @@ func (p Provider) testOne(ctx context.Context, model string) Result { if p.isClaudeAccount() { return p.testClaude(ctx, model) } - if p.testsTranslated() { + if p.testsTranslated() || client == "" && p.pluginTranslated(model) { return p.testTranslated(ctx, model) } var protos []Protocol diff --git a/internal/provider/translated_probe.go b/internal/provider/translated_probe.go index 5c5bd8e40..8a2db2f5e 100644 --- a/internal/provider/translated_probe.go +++ b/internal/provider/translated_probe.go @@ -2,6 +2,7 @@ package provider import ( "context" + "slices" "time" "github.com/yetone/magpie/internal/probelog" @@ -32,14 +33,30 @@ func (p Provider) testsTranslated() bool { return translatedProbe != nil && p.Account != nil && !p.IsPlugin() && p.Account.codeAssist != "" } -// testTranslated is the test of model on a provider testsTranslated. +// pluginTranslated is whether model is a plugin's that only Code Assist +// serves (@ai-sdk/google): the gateway asks it in Gemini's generateContent +// through the plugin's fetch, so a test does too. Sent as any of the +// plugin's other APIs, its vendor read a body of another shape (Zed's +// cloud: 400 "failed to parse Google AI request: missing field contents", +// Been on Discord). +func (p Provider) pluginTranslated(model string) bool { + return translatedProbe != nil && p.IsPlugin() && slices.Equal(p.APIs(model), []Protocol{CodeAssist}) +} + +// testTranslated is the test of model on a provider testsTranslated, or +// of a plugin's model pluginTranslated. func (p Provider) testTranslated(ctx context.Context, model string) Result { r := Result{Protocol: CodeAssist, Model: model, Account: p.Account.User} if model == "" { r.Error = "no model to try: expose one, or refresh the model list" return r } - ctx, cancel := context.WithTimeout(ctx, testWait) + wait := testWait + if p.IsPlugin() { + // its fetch may renew the sign-in first (pluginTestWait) + wait = max(wait, pluginTestWait) + } + ctx, cancel := context.WithTimeout(ctx, wait) defer cancel() start := time.Now() status, err := translatedProbe(probelog.Taken(ctx), p, CodeAssist, model)