Files
magpie/internal/gateway/gemini_image_config_test.go
T
JoeyWu-tech 7e7600439a gateway: generateContent with imageConfig asks the Gemini API, not Chat (#3820)
GuoJinguang's relay (#3820) has a Chat URL beside its Gemini one, and
their generateContent asking imageSize 4K went to its chat completions,
which drew 1024x1024. A Gemini client's request asked for one body is
translated (attempt: a Gemini API is always asked streamed), and with
relay off and no ownAPI it goes to the first API usable gives, Chat
where the provider has one. That default is meant (uaSetup in
user_agent_test.go), and the previous commit leaves it: there the
request reaches the Gemini URL only with the model's API set to Gemini.

Now one that asks an image's size or shape, a generationConfig holding
an imageConfig object, sets ownAPI on that rule, as a web search does
and as DashScope's request asked for one body does: it is translated
on the provider's Gemini API, the only one that takes the field, and
the previous commit carries the field there. Every other request
routes as before, so one without imageConfig still goes to Chat at a
provider with both. gateway-routing.md's One try says so.

What moves: a request asked for one body that carries imageConfig, at a
provider with both URLs and the model's API left on Auto, is asked on
its Gemini URL instead of its Chat URL. If that Gemini API turns the
model away in words magpie reads as the wrong API (wrongEndpoint), the
request is asked on Chat and the refusal remembered, as for any
translated request; any other refusal, such as a bare 404 for a model it
doesn't have, goes to the client, as it does today for the same client's
streamed requests, which are relayed there. What a translation drops
(safetySettings, topK and the rest parseGemini doesn't read) is dropped
on Gemini as it was on Chat.

Left as on main, as the previous commit says: a provider with no
Gemini URL has nowhere to send it (#3935), the images API sends
its size to Gemini as an aspect ratio (#3936), and a translated
Gemini request drops the rest of what parseGemini doesn't read
(#3937).

What was run (tree d7ae85a2, on origin/main 0c17aac2, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestGeminiImageConfigGoesToTheGeminiAPIBesideChat, new: the previous
  commit's five generationConfigs, generateContent, at a provider with
  both URLs on one fake relay. The three with imageConfig are asked at
  /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent with
  it, the two without at /v1/chat/completions. With
  TestGeminiImageConfigReachesTheGeminiAPI and ReachesCodeAssist,
  -count=5: 15 of 15 pass; -race -count=5: 15 of 15, no race.
- the new test on the previous commit's tree (2b421ece): red, the
  three with imageConfig "the relay was asked at /v1/chat/completions,
  want /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent".
- broken by hand, each alone:
  - the rule never setting ownAPI: the same 3 lines red;
  - the rule setting ownAPI for every request: the two without
    imageConfig red, "the relay was asked at
    /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent,
    want /v1/chat/completions".
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log
  kept; 8m37s, load 34 at its start): 72 packages ok, and 14 tests red
  in 5 packages, none of them this commit's tests or what they cover.
  internal/gateway ran to its end (506s), so the three passed in it.
  The reds: agent
  TestCodexDriftReached (#3398); TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077,
  #3640); gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649).

This commit is 44a63bd5 rebased: the same internal/ patch-id, and the
One try row of docs/subsystems/gateway-routing.md merged by hand, its
sentence unchanged. The rest is what was run for 44a63bd5, at tree
82a169ba on origin/main f8cd964a, the same code (not this tree):
- a probe at that tree, not kept, one server asked twice with
  imageConfig: the Gemini API answering 400 "Model does not support
  this protocol" (a wrongEndpoint wording): asked on Gemini, then on
  Chat, 200 from Chat, and the second ask on Chat alone; answering a
  bare 404 "models/... is not found for API version v1beta": the 404
  to the client both times, Chat not asked, as for a streamed request
  there, with or without imageConfig (relayed, also probed)

Not tried: the reporter's relay, or any real Gemini API; the relay
here is a fake. Not known: whether some relay's Gemini API lacks a
model its Chat API serves, the case where this commit turns a picture
at the default size into that 404.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00

231 lines
8.6 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// imageAsk is #3820's request (GuoJinguang): a frame and the words to redraw
// it, with gen as its generationConfig, none when "".
func imageAsk(gen string) string {
ask := `{"contents":[{"parts":[{"text":"Re-photorealize this render."},{"inlineData":{"mimeType":"image/png","data":"UE5HIGZyYW1l"}}]}]`
if gen != "" {
ask += `,"generationConfig":` + gen
}
return ask + `}`
}
// imageAsks are generationConfigs a Gemini client sends, each with the
// imageConfig a Gemini upstream should be sent for it.
var imageAsks = []struct{ gen, want string }{
// the reporter's
{`{"imageConfig":{"imageSize":"4K"}}`, `{"imageSize":"4K"}`},
{`{"thinkingConfig":{"thinkingLevel":"high"},"imageConfig":{"aspectRatio":"16:9","imageSize":"2K"}}`, `{"aspectRatio":"16:9","imageSize":"2K"}`},
// snake_case, as Google's API also reads it (geminiCamel)
{`{"image_config":{"image_size":"4K","aspect_ratio":"1:1"}}`, `{"imageSize":"4K","aspectRatio":"1:1"}`},
// none asked, none sent: no generationConfig, or one without it
{"", ""},
{`{"temperature":0.4}`, ""},
}
// drawnGemini is a Gemini API's stream with one image drawn.
const drawnGemini = `data: {"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1290,"candidatesTokenCount":2000}}`
// upstreamAsk is one request an upstream was sent.
type upstreamAsk struct {
path string
body []byte
}
// asksKept keeps what each request to an upstream sent it.
type asksKept struct {
mu sync.Mutex
got []upstreamAsk
}
func (rec *asksKept) keep(r *http.Request) {
b, _ := io.ReadAll(r.Body)
rec.mu.Lock()
rec.got = append(rec.got, upstreamAsk{r.URL.Path, b})
rec.mu.Unlock()
}
// last is the latest request, and how many there were.
func (rec *asksKept) last() (upstreamAsk, int) {
rec.mu.Lock()
defer rec.mu.Unlock()
if len(rec.got) == 0 {
return upstreamAsk{}, 0
}
return rec.got[len(rec.got)-1], len(rec.got)
}
// drawsBoth is a relay with a Gemini API and a Chat API, as #3820's: the
// Gemini API draws, and chat completions answers with the image in its
// text, as a relay that turns Gemini's parts into markdown does.
func drawsBoth(t *testing.T) (*httptest.Server, *asksKept) {
t.Helper()
rec := &asksKept{}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rec.keep(r)
w.Header().Set("Content-Type", "text/event-stream")
switch {
case strings.HasSuffix(r.URL.Path, ":streamGenerateContent"):
io.WriteString(w, sse(drawnGemini))
case strings.HasSuffix(r.URL.Path, ":generateContent"):
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, strings.TrimPrefix(drawnGemini, "data: "))
case strings.HasSuffix(r.URL.Path, "/chat/completions"):
io.WriteString(w, sse(`data: {"id":"c1","object":"chat.completion.chunk","model":"gemini-3-pro-image-preview","choices":[{"index":0,"delta":{"role":"assistant","content":"![image](data:image/png;base64,aGVsbG8=)"},"finish_reason":"stop"}]}`, `data: [DONE]`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(up.Close)
return up, rec
}
// sameConfig says whether two imageConfigs hold the same fields and values.
func sameConfig(got, want string) bool {
var g, w any
return json.Unmarshal([]byte(got), &g) == nil && json.Unmarshal([]byte(want), &w) == nil && jsonEqual(g, w)
}
// A Gemini client's generationConfig.imageConfig reaches a Gemini API as
// it was sent (#3820, GuoJinguang: imageSize 4K asked through magpie drew
// 1024x1024, where their relay asked itself drew 4096x4096). A request
// asked for one body is translated, and was built again without it; a
// streamed one is relayed. Beside a Chat API, one asked for one body
// goes to the Gemini API when the user set the model's API to Gemini. A
// request that asks for none is sent none.
func TestGeminiImageConfigReachesTheGeminiAPI(t *testing.T) {
const model = "gemini-3-pro-image-preview"
for _, tc := range []struct {
name string
chat bool // a Chat API beside the Gemini one
set bool // the user set the model's API to Gemini
method string
}{
{"its only API, generateContent", false, false, "generateContent"},
{"its only API, streamed", false, false, "streamGenerateContent?alt=sse"},
{"beside a Chat API, streamed", true, false, "streamGenerateContent?alt=sse"},
{"beside a Chat API, set to Gemini, generateContent", true, true, "generateContent"},
} {
t.Run(tc.name, func(t *testing.T) {
fresh(t)
up, rec := drawsBoth(t)
p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{model}, Gemini: up.URL + "/v1beta"}
if tc.chat {
p.Chat = up.URL + "/v1"
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if tc.set {
if err := provider.SetModelAPI("relay/"+model, "gemini"); err != nil {
t.Fatal(err)
}
}
asked := 0
for _, ask := range imageAsks {
code, body := post(t, "/v1beta/models/relay/"+model+":"+tc.method, imageAsk(ask.gen))
if code != 200 || !strings.Contains(body, "aGVsbG8=") {
t.Fatalf("asked %s: %d %s", ask.gen, code, body)
}
got, n := rec.last()
if n <= asked {
t.Fatalf("asked %s: nothing reached the relay", ask.gen)
}
asked = n
if !strings.HasPrefix(got.path, "/v1beta/models/") {
t.Fatalf("asked %s: the relay was asked at %s, not its Gemini API: %s", ask.gen, got.path, got.body)
}
switch sent := gjson.GetBytes(got.body, "generationConfig.imageConfig").Raw; {
case ask.want == "" && sent != "":
t.Errorf("asked for none: %s was sent %s", got.path, sent)
case ask.want != "" && !sameConfig(sent, ask.want):
t.Errorf("asked %s: %s was sent %q: %s", ask.gen, got.path, sent, got.body)
}
}
})
}
}
// The same reaches a Google sign-in's image model inside Code Assist's
// envelope: Antigravity is asked as a Gemini API is, its request a Gemini
// request.
func TestGeminiImageConfigReachesCodeAssist(t *testing.T) {
rec := &asksKept{}
s, _ := antigravityGroupFor(t, []string{"u@example.com"}, agDrawer, func(w http.ResponseWriter, r *http.Request) {
rec.keep(r)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(drawnPNG))
})
asked := 0
for _, method := range []string{"generateContent", "streamGenerateContent?alt=sse"} {
for _, ask := range imageAsks {
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/v1beta/models/antigravity/"+agDrawer+":"+method, strings.NewReader(imageAsk(ask.gen))))
if w.Code != 200 || !strings.Contains(w.Body.String(), "iVBORw0KGgo=") {
t.Fatalf("%s asked %s: %d %s", method, ask.gen, w.Code, w.Body.String())
}
got, n := rec.last()
if n <= asked {
t.Fatalf("%s asked %s: nothing reached Code Assist", method, ask.gen)
}
asked = n
switch sent := gjson.GetBytes(got.body, "request.generationConfig.imageConfig").Raw; {
case ask.want == "" && sent != "":
t.Errorf("%s asked for none: sent %s", method, sent)
case ask.want != "" && !sameConfig(sent, ask.want):
t.Errorf("%s asked %s: sent %q: %s", method, ask.gen, sent, got.body)
}
}
}
}
// A request asked for one body that asks an image's size or shape goes to
// the provider's Gemini API, not to the Chat API beside it, which has no
// field for it (#3820: GuoJinguang's relay has both, and asked on its chat
// completions imageSize 4K drew 1024x1024). One that asks for none goes to
// Chat as before.
func TestGeminiImageConfigGoesToTheGeminiAPIBesideChat(t *testing.T) {
const model = "gemini-3-pro-image-preview"
fresh(t)
up, rec := drawsBoth(t)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{model}, Chat: up.URL + "/v1", Gemini: up.URL + "/v1beta"}); err != nil {
t.Fatal(err)
}
asked := 0
for _, ask := range imageAsks {
code, body := post(t, "/v1beta/models/relay/"+model+":generateContent", imageAsk(ask.gen))
if code != 200 || !strings.Contains(body, "aGVsbG8=") {
t.Fatalf("asked %s: %d %s", ask.gen, code, body)
}
got, n := rec.last()
if n <= asked {
t.Fatalf("asked %s: nothing reached the relay", ask.gen)
}
asked = n
want := "/v1beta/models/" + model + ":streamGenerateContent"
if ask.want == "" {
want = "/v1/chat/completions"
}
if got.path != want {
t.Errorf("asked %s: the relay was asked at %s, want %s", ask.gen, got.path, want)
continue
}
if sent := gjson.GetBytes(got.body, "generationConfig.imageConfig").Raw; ask.want != "" && !sameConfig(sent, ask.want) {
t.Errorf("asked %s: sent %q: %s", ask.gen, sent, got.body)
}
}
}