Files
magpie/internal/gateway/gemini_image_test.go
T
yetone 6da19bf181 provider: Factory's built-in is retired; its plugin serves it
"factory" joins retiredBuiltins: every Factory account is served by
@magpie-community/opencode-factory-auth, and the hourly MoveRetiring
moves the ones still on the built-in.

Removed: the built-in's sign-in (factory_signin.go, WorkOS's device
flow), keeping the sign-in (renew, lapse, org reconcile and mend,
headers, factoryGet), its provider and account (factoryProvider,
factoryAccount, factoryAlsoOn), its login list, switch, on/off and
forget, its usage card (factoryLoginQuota), droid's prompt and body
rewriting (factory_client.go), and its rows in signin.go, logins.go,
logins_on.go, login_usage.go, subscription_usage.go and account.go.
zcodeDecode/Encode, kept in zcode.go only for factory_client.go, go
with it. An API key always goes to the plugin now (factoryAddKey), and
`magpie accounts import factory` keeps saying to add it with accounts
add factory; its dead import branches are gone.

Kept: the mover and what it reads (factoryLogins, factorySaved,
factoryCreds, factoryMu); ImportFactoryKeys, factory_key.go and
factoryWhoami, for "Use an API key instead"; droid's model table with
factoryAPIs and factoryCore, since the plugin's provider is named
"factory" (account.go APIs, FactoryGemini and servedByFactory still
answer for it); factoryAPI for the moved provider's host
(builtinHost); factory_usage.go's limits reader behind
FactoryAllowanceForTest, which the gateway's pool tests use; the
gateway's "factory" lists (estimatedMoved, the account check), as the
Zed commit kept zed's; the parity tests.

Tests:
- git rm'd, built-in only: factory_test.go (sign-in, refresh, accounts,
  orgs), factory_client_test.go, gateway factory_agents_test.go
  (droid's line on every wire, the generate route to chat) and
  factory_think_off_test.go (TestPluginThinkingOff covers the plugin);
  TestFactoryAPIKey, TestFactoryKeyAgainReadsUsageAfresh,
  TestFactoryServesModelsAddedSinceItsFetch, TestUserAgentAccountUntouched
  (TestUserAgentFor still covers an account's User-Agent).
- Changed meaning: TestGeminiEmptyReplyIsAnError,
  TestGeminiEmptyRepliesAskedAgain and TestGeminiImageModelReturnsItsImage
  used Factory's generate route as a fake-able Gemini upstream; they now
  use a Gemini API of the user's own (saveGem), the same decoder, and the
  image test checks :streamGenerateContent instead of /api/llm/g/v1/generate.
  TestMovedShowsBuiltinHost's first check is now a plain plugin
  (fakeco), and a retired Factory with no migration record shows
  api.factory.ai. TestFactoryAPIKeyMoved checks factoryLogins() is empty
  instead of the removed factoryLookup. factorySite/factoryJSON moved
  into factory_key_test.go.

Run in this worktree:
  gofmt -l internal: nothing
  go vet -tags nogui ./internal/provider ./internal/gateway ./internal/cli
    ./internal/gui, GOOS=darwin, linux, windows: clean
  staticcheck -checks U1000 -tests=false (darwin, windows) on
    internal/provider: nothing new
  go test -tags nogui -count=1 -run 'Factory|Gemini|PaymentRequired|
    ResetsInWords|UserAgent|UsedWindow|Vertex|PayloadTooLarge|UsageCache|
    AnthropicImage|ThinkingOff|Moved|Retired|Mover|Migrat|Move|
    SayTheirPlugin|Allowance|Discovery|ClaudeModels|GrokPrice|
    LoopbackSignIns|AsksOwnBackend|SideLogin|Import|Accounts|ZCode|MiMo'
    on the four packages: ok (all four); TestFactoryAPIKeyMoved ran with
    Bun (PASS), not skipped.
Not run: whole packages, the full suite, the GUI suite (machine load
~300). Not tried with a real Factory account. docs/subsystems not
changed, as for Zed.
2026-10-17 23:11:00 +08:00

76 lines
2.9 KiB
Go

package gateway
import (
"net/http/httptest"
"path/filepath"
"strings"
"testing"
)
// An image model's picture reaches a Gemini client's generateContent: the
// upstream's inlineData part comes back, and a thought image (a draft)
// stays out (#620).
func TestGeminiImageModelReturnsItsImage(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
f := &fake{t: t, reply: `data: {"candidates":[{"content":{"parts":[` +
`{"thought":true,"inlineData":{"mimeType":"image/png","data":"ZHJhZnQ="}},` +
`{"text":"Here it is."},` +
`{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="},"thoughtSignature":"c2ln"}` +
`]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":1567}}` + "\n\n"}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
saveGem(t, up.URL, "gemini-3.1-pro-preview")
const ask = `{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`
check := func(kind, body string) {
t.Helper()
if !strings.Contains(body, `"inlineData":{"data":"aGVsbG8=","mimeType":"image/png"}`) {
t.Errorf("%s: image dropped: %s", kind, body)
}
if strings.Contains(body, "ZHJhZnQ=") {
t.Errorf("%s: thought image sent: %s", kind, body)
}
if i, j := strings.Index(body, "Here it is."), strings.Index(body, "aGVsbG8="); i < 0 || j < i {
t.Errorf("%s: text and image out of order: %s", kind, body)
}
}
// a Gemini API's stream decodes with Antigravity's decoder
code, body := post(t, "/v1beta/models/gem/gemini-3.1-pro-preview:generateContent", ask)
if code != 200 || strings.HasPrefix(body, "data:") {
t.Fatalf("json %d %s", code, body)
}
if f.path != "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent" {
t.Fatalf("upstream %s", f.path)
}
check("generateContent", body)
}
// Antigravity and Gemini CLI wrap each chunk in {response}; streamed to a
// Gemini client, the picture goes out as an inlineData chunk.
func TestCodeAssistStreamsImages(t *testing.T) {
rec := httptest.NewRecorder()
enc := &geminiEncoder{w: newSSEWriter(rec), model: "antigravity/gemini-3.1-flash-image"}
d := &codeAssistDecoder{}
for _, line := range []string{
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"inlineData":{"mimeType":"image/png","data":"ZHJhZnQ="}}]}}]}}`,
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"image/jpeg","data":"aGk="}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":1567}}}`,
} {
d.decode(line, enc.event)
}
enc.finish()
body := rec.Body.String()
if !strings.Contains(body, `"inlineData":{"data":"aGk=","mimeType":"image/jpeg"}`) {
t.Errorf("image dropped: %s", body)
}
if strings.Contains(body, "ZHJhZnQ=") {
t.Errorf("thought image sent: %s", body)
}
}