Skip to content
6 changes: 6 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,9 @@ backend/internal/handler/gateway_gemini_envelope_test.go
backend/internal/service/model_plaza_currency_test.go
backend/internal/service/model_plaza_currency_update_test.go
backend/internal/handler/model_plaza_currency_test.go

# Anthropic media fixtures share compatEffortPolicyUpstream, absent in historical RED.
# Current candidate/GREEN retains both files and the complete media assertions.
# Frozen candidate blobs: eb860ff6bb7a0900ed1243d29d58c7ae4ae0eb83 / a69b0b585c25073321953af8630d64c743db2893.
backend/internal/handler/gateway_anthropic_media_test.go
backend/internal/handler/gateway_anthropic_tool_media_test.go
133 changes: 133 additions & 0 deletions backend/internal/handler/gateway_anthropic_media_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
//go:build unit

package handler

import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)

// Use the real handlers, scheduler and converters, capturing only the HTTP boundary.
func TestGatewayAnthropicMediaHandlers(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, endpoint := range []string{"chat/completions", "responses"} {
for _, stream := range []bool{false, true} {
for _, field := range []string{"image", "file"} {
for _, tc := range []struct {
name string
uri string
blockType string
sourceType string
}{
{"png", "data:image/png;base64,c3ludGhldGlj", "image", "base64"},
{"jpeg", "data:image/jpeg;base64,c3ludGhldGlj", "image", "base64"},
{"gif", "data:image/gif;base64,c3ludGhldGlj", "image", "base64"},
{"webp", "data:image/webp;base64,c3ludGhldGlj", "image", "base64"},
{"pdf", "data:application/pdf;base64,c3ludGhldGlj", "document", "base64"},
{"plain", "data:text/plain;base64,c3ludGhldGlj", "document", "text"},
{"url", "https://example.invalid/private.png", "", ""},
{"video", "data:video/mp4;base64,cHJpdmF0ZQ==", "reject", ""},
{"audio", "data:audio/mpeg;base64,cHJpdmF0ZQ==", "reject", ""},
{"unknown", "data:application/octet-stream;base64,cHJpdmF0ZQ==", "reject", ""},
{"malformed", "data:image/png,private-payload", "reject", ""},
{"bad_base64", "data:image/png;base64,private-payload!", "reject", ""},
{"empty", "data:image/png;base64,", "reject", ""},
} {
t.Run(fmt.Sprintf("%s/stream=%t/%s/%s", endpoint, stream, field, tc.name), func(t *testing.T) {
cfg := &config.Config{}
groupID := int64(9810)
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1}
account := &service.Account{
ID: 9811, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{"api_key": "test-key"},
AccountGroups: []service.AccountGroup{{AccountID: 9811, GroupID: groupID}},
}
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil)
upstream := &compatEffortPolicyUpstream{}
usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
billingRepo := &compatStreamUsageBillingRepo{}
billing := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, usage, billingRepo, nil, nil, nil, nil, cfg,
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
h := &GatewayHandler{gatewayService: gateway, billingCacheService: billing, cfg: cfg, maxAccountSwitches: 1,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0)}
part := map[string]any{"type": "input_image", "image_url": tc.uri}
text := map[string]any{"type": "input_text", "text": "synthetic prompt"}
if field == "file" {
part = map[string]any{"type": "input_file", "file_data": tc.uri}
}
request := map[string]any{"model": "claude-sonnet-4-5", "stream": stream}
if endpoint == "chat/completions" {
text["type"] = "text"
part = map[string]any{"type": "image_url", "image_url": map[string]string{"url": tc.uri}}
if field == "file" {
part = map[string]any{"type": "file", "file": map[string]string{"file_data": tc.uri}}
}
request["messages"] = []any{map[string]any{"role": "user", "content": []any{text, part}}}
} else {
request["input"] = []any{map[string]any{"role": "user", "content": []any{text, part}}}
}
body, err := json.Marshal(request)
require.NoError(t, err)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx)
c.Request.Header.Set("Content-Type", "application/json")
// Use the new-key default; restricted keys reject opaque media
// during final context admission before this conversion oracle.
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 9812, UserID: 9813, GroupID: &groupID, Group: group, AllowLongContext: true, User: &service.User{ID: 9813, Balance: 100}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9813})
if endpoint == "chat/completions" {
h.ChatCompletions(c)
} else {
h.Responses(c)
}
if tc.blockType == "reject" {
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.Contains(t, recorder.Body.String(), "invalid_request_error")
require.NotEmpty(t, gjson.Get(recorder.Body.String(), "error.message").String())
require.NotContains(t, recorder.Body.String(), "private")
require.NotContains(t, recorder.Body.String(), "cHJpdmF0ZQ")
require.Empty(t, upstream.bodies)
require.Empty(t, usage.created)
require.Empty(t, billingRepo.commands)
return
}
require.Equal(t, http.StatusOK, recorder.Code)
require.Len(t, upstream.bodies, 1)
blocks := gjson.GetBytes(upstream.bodies[0], "messages.0.content").Array()
if tc.blockType == "" {
require.Len(t, blocks, 1) // preserve the legacy URL omission
} else {
require.Len(t, blocks, 2)
require.Equal(t, tc.blockType, blocks[1].Get("type").String())
require.Equal(t, tc.sourceType, blocks[1].Get("source.type").String())
if tc.sourceType == "text" {
require.Equal(t, "synthetic", blocks[1].Get("source.data").String())
}
}
})
}
}
}
}
}
157 changes: 157 additions & 0 deletions backend/internal/handler/gateway_anthropic_tool_media_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
//go:build unit

package handler

import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)

type anthropicToolMediaUpstream struct{ compatEffortPolicyUpstream }

func (u *anthropicToolMediaUpstream) Do(req *http.Request, proxy string, id int64, concurrency int) (*http.Response, error) {
return u.DoWithTLS(req, proxy, id, concurrency, nil)
}

func TestGatewayAnthropicChatToolMediaRejectsBeforeFlattening(t *testing.T) {
testAnthropicChatToolMedia(t, false)
}

func TestNativeAnthropicChatToolMediaRejectsBeforeFlattening(t *testing.T) {
testAnthropicChatToolMedia(t, true)
}

func testAnthropicChatToolMedia(t *testing.T, native bool) {
t.Helper()
gin.SetMode(gin.TestMode)
for _, stream := range []bool{false, true} {
for _, role := range []string{"tool", "function"} {
for _, field := range []string{"image", "file"} {
for _, tc := range []struct {
name string
uri string
want string
}{
{"video", "data:video/mp4;base64,cHJpdmF0ZQ==", "reject"},
{"audio", "data:audio/mpeg;base64,cHJpdmF0ZQ==", "reject"},
{"unknown", "data:application/octet-stream;base64,cHJpdmF0ZQ==", "reject"},
{"malformed_header", "data:image/png,private-payload", "reject"},
{"malformed_base64", "data:image/png;base64,private-payload!", "reject"},
{"empty", "data:image/png;base64,", "reject"},
{"png", "data:image/png;base64,c3ludGhldGlj", "image"},
{"jpeg", "data:image/jpeg;base64,c3ludGhldGlj", "image"},
{"gif", "data:image/gif;base64,c3ludGhldGlj", "image"},
{"webp", "data:image/webp;base64,c3ludGhldGlj", "image"},
{"pdf", "data:application/pdf;base64,c3ludGhldGlj", "document"},
{"plain", "data:text/plain;base64,c3ludGhldGlj", "document"},
{"string_control", "literal data:video/mp4;base64,cHJpdmF0ZQ==", "string"},
} {
t.Run(fmt.Sprintf("stream=%t/%s/%s/%s", stream, role, field, tc.name), func(t *testing.T) {
cfg := &config.Config{RunMode: config.RunModeSimple}
platform, model := service.PlatformAnthropic, "claude-sonnet-4-5"
if native {
platform, model = service.PlatformKimi, "k3"
}
groupID := int64(3131)
group := &service.Group{ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1}
account := &service.Account{
ID: 9811, Platform: platform, Type: service.AccountTypeAPIKey, Status: service.StatusActive,
Schedulable: true, Concurrency: 1, GroupIDs: []int64{groupID},
Credentials: map[string]any{"api_key": "test-key", "api_protocol": service.APIProtocolAnthropic, "base_url": "https://anthropic.example"},
AccountGroups: []service.AccountGroup{{AccountID: 9811, GroupID: groupID}},
}
upstream := &anthropicToolMediaUpstream{}
usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
billingRepo := &compatStreamUsageBillingRepo{}
billing := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
media := map[string]any{"type": "image_url", "image_url": map[string]string{"url": tc.uri}}
if field == "file" {
media = map[string]any{"type": "file", "file": map[string]string{"file_data": tc.uri}}
}
var content any = []any{map[string]string{"type": "text", "text": "tool text"}, media}
if tc.want == "string" {
content = tc.uri
}
assistant := map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"id": "call_1", "type": "function", "function": map[string]string{"name": "read", "arguments": "{}"}}}}
result := map[string]any{"role": role, "tool_call_id": "call_1", "content": content}
if role == "function" {
assistant = map[string]any{"role": "assistant", "function_call": map[string]string{"name": "read", "arguments": "{}"}}
result = map[string]any{"role": role, "name": "read", "content": content}
}
body, err := json.Marshal(map[string]any{"model": model, "stream": stream, "messages": []any{map[string]string{"role": "user", "content": "read"}, assistant, result}})
require.NoError(t, err)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)).WithContext(ctx)
c.Request.Header.Set("Content-Type", "application/json")
// Match the new-key default so context admission does not
// reject opaque media before the MIME/preservation assertions.
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 99, UserID: 100, GroupID: &groupID, Group: group, AllowLongContext: true, User: &service.User{ID: 100, Balance: 100}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 100})
if native {
gateway := service.NewOpenAIGatewayService(
&openAIWSUsageHandlerAccountRepoStub{account: *account}, nil, usage, billingRepo, nil, nil, nil, nil, cfg,
nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, &service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
t.Cleanup(gateway.CloseOpenAIWSPool)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
h.ChatCompletions(c)
} else {
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil)
gateway := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, usage, billingRepo, nil, nil, nil, nil, cfg,
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
h := &GatewayHandler{gatewayService: gateway, billingCacheService: billing, cfg: cfg, maxAccountSwitches: 1,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0)}
h.ChatCompletions(c)
}
if tc.want == "reject" {
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.Contains(t, recorder.Body.String(), "invalid_request_error")
require.NotContains(t, recorder.Body.String(), "private")
require.NotContains(t, recorder.Body.String(), "cHJpdmF0ZQ")
require.Empty(t, upstream.bodies)
require.Empty(t, usage.created)
require.Empty(t, billingRepo.commands)
return
}
require.Equal(t, http.StatusOK, recorder.Code)
require.Len(t, upstream.bodies, 1)
toolContent := gjson.GetBytes(upstream.bodies[0], "messages.2.content.0.content")
if tc.want == "string" {
require.Equal(t, tc.uri, toolContent.String())
return
}
require.Equal(t, "tool text", toolContent.Get("0.text").String())
require.Equal(t, tc.want, toolContent.Get("1.type").String())
wantSource, wantData := "base64", "c3ludGhldGlj"
if tc.name == "plain" {
wantSource, wantData = "text", "synthetic"
}
require.Equal(t, wantSource, toolContent.Get("1.source.type").String())
require.Equal(t, wantData, toolContent.Get("1.source.data").String())
require.Equal(t, gjson.GetBytes(upstream.bodies[0], "messages.1.content.0.id").String(), gjson.GetBytes(upstream.bodies[0], "messages.2.content.0.tool_use_id").String())
})
}
}
}
}
}
11 changes: 11 additions & 0 deletions backend/internal/pkg/antigravity/request_transformer.go
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,10 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
parts = append(parts, part)

case "image", "document":
if block.Type == "document" && block.Source != nil && block.Source.Type == "text" && block.Source.MediaType == "text/plain" {
parts = append(parts, GeminiPart{Text: block.Source.Data})
continue
}
if block.Source != nil && block.Source.Type == "base64" && strings.TrimSpace(block.Source.Data) != "" {
parts = append(parts, GeminiPart{
InlineData: &GeminiInlineData{
Expand Down Expand Up @@ -633,6 +637,13 @@ func parseToolResultContent(content json.RawMessage, isError bool) string {
if text, ok := item["text"].(string); ok {
texts = append(texts, text)
}
if item["type"] == "document" {
if source, ok := item["source"].(map[string]any); ok && source["type"] == "text" && source["media_type"] == "text/plain" {
if text, ok := source["data"].(string); ok {
texts = append(texts, text)
}
}
}
}
result := strings.Join(texts, "\n")
if strings.TrimSpace(result) == "" {
Expand Down
17 changes: 17 additions & 0 deletions backend/internal/pkg/antigravity/tool_result_images_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,23 @@ import (
"github.com/tidwall/gjson"
)

func TestResponsesPlainDocumentSurvivesAnthropicBridge(t *testing.T) {
var req apicompat.ResponsesRequest
require.NoError(t, json.Unmarshal([]byte(`{"input":[{"role":"user","content":[{"type":"input_file","file_data":"data:text/plain;base64,c3ludGhldGlj"}]}]}`), &req))
anthropic, err := apicompat.ResponsesToAnthropicRequest(&req)
require.NoError(t, err)
body, err := json.Marshal(anthropic)
require.NoError(t, err)
var claude ClaudeRequest
require.NoError(t, json.Unmarshal(body, &claude))
wire, err := TransformClaudeToGeminiWithOptions(&claude, "test-project", "gemini-2.5-flash", TransformOptions{})
require.NoError(t, err)
require.Equal(t, "synthetic", gjson.GetBytes(wire, "request.contents.0.parts.0.text").String())
content := json.RawMessage(`[{"type":"document","source":{"type":"text","media_type":"text/plain","data":"synthetic"}}]`)
require.Equal(t, "synthetic", parseToolResultContent(content, false))
require.Empty(t, extractToolResultInlineParts(content), "plain text must stay in the function response text")
}

func TestResponsesToolResultImagesStayWithTheirCalls(t *testing.T) {
for _, model := range []string{"gemini-3.8-flash", "gemini-4-argon"} {
t.Run(model, func(t *testing.T) {
Expand Down
Loading
Loading