mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
Merge pull request #8167 from feeeei/fix/gemini-group-image-generation-gate
fix(gemini): 分组「允许当前分组生图」开关对 Gemini 系入口生效
This commit is contained in:
22 files changed
+691
-46
No files matched your search
@@ -228,6 +228,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) {
|
||||
return
|
||||
}
|
||||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolAnthropicMessages, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.anthropicSecurityAuditError(c, decision)
|
||||
|
||||
@@ -113,6 +113,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
"This group is restricted to Claude Code clients (/v1/messages only)")
|
||||
return
|
||||
}
|
||||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIChat, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.openAISecurityAuditError(c, decision)
|
||||
|
||||
@@ -117,6 +117,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
"This group is restricted to Claude Code clients (/v1/messages only)")
|
||||
return
|
||||
}
|
||||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.responsesSecurityAuditError(c, decision)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// geminiImageGenerationRejected 在选号之前按客户端请求名、渠道映射名与请求体
|
||||
// 执行 Gemini 系分组的生图门禁。命中时把请求标记为本地功能门禁并返回 true,
|
||||
// 调用方按入口协议写出 400;账号级模型映射之后的判定由转发层负责。
|
||||
func geminiImageGenerationRejected(c *gin.Context, apiKey *service.APIKey, body []byte, models ...string) bool {
|
||||
if apiKey == nil || !service.GeminiImageGenerationDenied(apiKey.Group, body, models...) {
|
||||
return false
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"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"
|
||||
)
|
||||
|
||||
type geminiImageGateEndpoint struct {
|
||||
name string
|
||||
path string
|
||||
body string
|
||||
params gin.Params
|
||||
forcePlatform string
|
||||
call func(*GatewayHandler, *gin.Context)
|
||||
}
|
||||
|
||||
func geminiImageGateEndpoints(model string) []geminiImageGateEndpoint {
|
||||
return []geminiImageGateEndpoint{
|
||||
{
|
||||
name: "messages", path: "/v1/messages",
|
||||
body: `{"model":"` + model + `","max_tokens":16,"messages":[{"role":"user","content":"draw a cat"}]}`,
|
||||
call: (*GatewayHandler).Messages,
|
||||
},
|
||||
{
|
||||
name: "chat completions", path: "/v1/chat/completions",
|
||||
body: `{"model":"` + model + `","messages":[{"role":"user","content":"draw a cat"}]}`,
|
||||
call: (*GatewayHandler).ChatCompletions,
|
||||
},
|
||||
{
|
||||
name: "responses", path: "/v1/responses",
|
||||
body: `{"model":"` + model + `","input":"draw a cat"}`,
|
||||
call: (*GatewayHandler).Responses,
|
||||
},
|
||||
{
|
||||
name: "gemini native", path: "/v1beta/models/" + model + ":generateContent",
|
||||
body: `{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`,
|
||||
params: gin.Params{{Key: "modelAction", Value: "/" + model + ":generateContent"}},
|
||||
call: (*GatewayHandler).GeminiV1BetaModels,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func runGeminiImageGateEndpoint(t *testing.T, ep geminiImageGateEndpoint, group *service.Group, accountPlatform string) (*httptest.ResponseRecorder, *gin.Context, *groupScopedSchedulerCache) {
|
||||
t.Helper()
|
||||
const accountID = int64(9411)
|
||||
schedulerCache := &groupScopedSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{{
|
||||
ID: accountID, Platform: accountPlatform, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: group.ID}},
|
||||
}}}}
|
||||
gatewayService := service.NewGatewayService(
|
||||
nil, &groupMapRepo{fakeGroupRepo: &fakeGroupRepo{}, groups: map[int64]*service.Group{group.ID: group}},
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil),
|
||||
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheService.Stop)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gatewayService,
|
||||
billingCacheService: billingCacheService,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
maxAccountSwitches: 1,
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
groupID := group.ID
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9420, UserID: 9430, GroupID: &groupID, Group: group, Status: service.StatusActive,
|
||||
User: &service.User{ID: 9430, Concurrency: 10, Balance: 100},
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
req := httptest.NewRequest(http.MethodPost, ep.path, bytes.NewBufferString(ep.body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
c.Params = ep.params
|
||||
if ep.forcePlatform != "" {
|
||||
c.Set(string(middleware.ContextKeyForcePlatform), ep.forcePlatform)
|
||||
}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
|
||||
|
||||
ep.call(h, c)
|
||||
return recorder, c, schedulerCache
|
||||
}
|
||||
|
||||
func TestGatewayHandlers_GeminiImageGenerationDisabledGroupRejectsBeforeSelection(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, platform := range []string{service.PlatformGemini, service.PlatformAntigravity} {
|
||||
for _, ep := range geminiImageGateEndpoints("gemini-3-pro-image") {
|
||||
if platform == service.PlatformAntigravity && ep.params != nil {
|
||||
ep.path = "/antigravity" + ep.path
|
||||
ep.forcePlatform = service.PlatformAntigravity
|
||||
}
|
||||
t.Run(platform+"/"+ep.name, func(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 9400, Hydrated: true, Platform: platform, Status: service.StatusActive,
|
||||
AllowImageGeneration: false,
|
||||
}
|
||||
recorder, c, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, platform)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code)
|
||||
require.Contains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
_, reachedSelection := c.Get(opsAccountIDKey)
|
||||
require.False(t, reachedSelection)
|
||||
require.Empty(t, schedulerCache.queriedGroupIDs())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayHandlers_GeminiImageGenerationGateSkipsGroupsWithoutTheSwitch(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
// Anthropic 分组在后台不展示生图开关,混合调度 Antigravity 账号时不受门禁约束。
|
||||
for _, ep := range geminiImageGateEndpoints("gemini-3-pro-image")[:3] {
|
||||
t.Run(ep.name, func(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 9401, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive,
|
||||
AllowImageGeneration: false,
|
||||
}
|
||||
recorder, _, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, service.PlatformAnthropic)
|
||||
|
||||
require.NotContains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
require.NotEmpty(t, schedulerCache.queriedGroupIDs())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayHandlers_GeminiImageGenerationGateAllowsTextModelsAndEnabledGroups(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
cases := []struct {
|
||||
name string
|
||||
model string
|
||||
allow bool
|
||||
}{
|
||||
{name: "text model in disabled group", model: "gemini-3.7-flash", allow: false},
|
||||
{name: "image model in enabled group", model: "gemini-3-pro-image", allow: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
for _, ep := range geminiImageGateEndpoints(tc.model)[:3] {
|
||||
t.Run(tc.name+"/"+ep.name, func(t *testing.T) {
|
||||
group := &service.Group{
|
||||
ID: 9402, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive,
|
||||
AllowImageGeneration: tc.allow,
|
||||
}
|
||||
recorder, _, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, service.PlatformGemini)
|
||||
|
||||
require.NotContains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
require.NotEmpty(t, schedulerCache.queriedGroupIDs())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -328,6 +328,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
googleError(c, http.StatusBadRequest, "Invalid model in URL")
|
||||
return
|
||||
}
|
||||
urlModel := modelName
|
||||
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
|
||||
modelName = strings.TrimSpace(resolvedModel)
|
||||
}
|
||||
@@ -358,14 +359,19 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, modelName, body); decision != nil && !decision.AllowNextStage {
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName)
|
||||
reqModel := modelName // 保存映射前的原始模型名
|
||||
if action != "countTokens" && geminiImageGenerationRejected(c, apiKey, body, urlModel, reqModel, channelMapping.MappedModel) {
|
||||
googleError(c, http.StatusBadRequest, service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
googleSecurityAuditError(c, decision)
|
||||
return
|
||||
}
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName)
|
||||
reqModel := modelName // 保存映射前的原始模型名
|
||||
if channelMapping.Mapped {
|
||||
modelName = channelMapping.MappedModel
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ func createGroupIfNotExists(ctx context.Context, client *dbent.Client, name, pla
|
||||
SetSubscriptionType(service.SubscriptionTypeStandard).
|
||||
SetRateMultiplier(1.0).
|
||||
SetIsExclusive(false).
|
||||
SetAllowImageGeneration(platform == service.PlatformGrok).
|
||||
SetAllowImageGeneration(service.DefaultAllowImageGenerationForPlatform(platform)).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
if dbent.IsConstraintError(err) {
|
||||
|
||||
@@ -34,11 +34,18 @@ func TestEnsureSimpleModeDefaultGroups_CreatesMissingDefaults(t *testing.T) {
|
||||
assertGroupExists(service.PlatformAntigravity + "-default-1")
|
||||
assertGroupExists(service.PlatformAntigravity + "-default-2")
|
||||
|
||||
grokDefault, err := client.Group.Query().
|
||||
Where(group.NameEQ(service.PlatformGrok+"-default"), group.DeletedAtIsNil()).
|
||||
Only(seedCtx)
|
||||
require.NoError(t, err)
|
||||
require.True(t, grokDefault.AllowImageGeneration)
|
||||
for _, name := range []string{
|
||||
service.PlatformGrok + "-default",
|
||||
service.PlatformGemini + "-default",
|
||||
service.PlatformAntigravity + "-default-1",
|
||||
service.PlatformAntigravity + "-default-2",
|
||||
} {
|
||||
imageDefault, err := client.Group.Query().
|
||||
Where(group.NameEQ(name), group.DeletedAtIsNil()).
|
||||
Only(seedCtx)
|
||||
require.NoError(t, err)
|
||||
require.True(t, imageDefault.AllowImageGeneration, "expected group %s to allow image generation", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureSimpleModeDefaultGroups_BackfillsOnlyAutoCreatedGrokDefault(t *testing.T) {
|
||||
|
||||
@@ -311,10 +311,17 @@ func defaultModelsListCandidateIDs(platform string) []string {
|
||||
}
|
||||
}
|
||||
|
||||
func defaultAllowImageGenerationForPlatform(platform string) bool {
|
||||
// Grok image and video generation routes share the legacy image-generation gate.
|
||||
// Older clients send the false zero value, so Grok groups must default enabled.
|
||||
return platform == PlatformGrok
|
||||
// DefaultAllowImageGenerationForPlatform reports whether new groups on the platform allow
|
||||
// image generation. CreateGroup ORs the requested value with it, so a false in the create
|
||||
// request does not turn it off. Composite defaults disabled because the same switch also
|
||||
// gates OpenAI image generation there.
|
||||
func DefaultAllowImageGenerationForPlatform(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformGrok, PlatformGemini, PlatformAntigravity:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func compositeDefaultModelsListCandidateIDs() []string {
|
||||
@@ -525,7 +532,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
|
||||
mcpXMLInject = *input.MCPXMLInject
|
||||
}
|
||||
|
||||
allowImageGeneration := input.AllowImageGeneration || defaultAllowImageGenerationForPlatform(platform)
|
||||
allowImageGeneration := input.AllowImageGeneration || DefaultAllowImageGenerationForPlatform(platform)
|
||||
allowBatchImageGeneration := input.AllowBatchImageGeneration && allowImageGeneration && platform == PlatformGemini
|
||||
|
||||
// 如果指定了复制账号的源分组,先获取账号 ID 列表
|
||||
|
||||
@@ -593,41 +593,47 @@ func TestAdminService_CreateGroup_DefaultsGrokMediaGenerationEnabled(t *testing.
|
||||
require.True(t, group.AllowImageGeneration)
|
||||
}
|
||||
|
||||
func TestAdminService_CreateGroup_PreservesNonGrokImageGenerationDisabled(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
func TestAdminService_CreateGroup_DefaultsGeminiFamilyImageGenerationEnabled(t *testing.T) {
|
||||
for _, platform := range []string{PlatformGemini, PlatformAntigravity} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: "anthropic-text",
|
||||
Description: "Anthropic text group",
|
||||
Platform: PlatformAnthropic,
|
||||
RateMultiplier: 1.0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.False(t, repo.created.AllowImageGeneration)
|
||||
require.False(t, group.AllowImageGeneration)
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: platform + "-images",
|
||||
Description: "Gemini family group",
|
||||
Platform: platform,
|
||||
RateMultiplier: 1.0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.True(t, repo.created.AllowImageGeneration)
|
||||
require.True(t, group.AllowImageGeneration)
|
||||
require.False(t, repo.created.AllowBatchImageGeneration)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminService_CreateGroup_DisablesBatchImageWhenImageGenerationDisabled(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
func TestAdminService_CreateGroup_PreservesImageGenerationDisabledWithoutPlatformDefault(t *testing.T) {
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformComposite} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: "gemini-no-image",
|
||||
Description: "Gemini group without image generation",
|
||||
Platform: PlatformGemini,
|
||||
RateMultiplier: 1.0,
|
||||
AllowImageGeneration: false,
|
||||
AllowBatchImageGeneration: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.False(t, repo.created.AllowImageGeneration)
|
||||
require.False(t, repo.created.AllowBatchImageGeneration)
|
||||
require.False(t, group.AllowBatchImageGeneration)
|
||||
group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{
|
||||
Name: platform + "-text",
|
||||
Description: "Group without image default",
|
||||
Platform: platform,
|
||||
RateMultiplier: 1.0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, group)
|
||||
require.NotNil(t, repo.created)
|
||||
require.False(t, repo.created.AllowImageGeneration)
|
||||
require.False(t, group.AllowImageGeneration)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminService_CreateGroup_DisablesBatchImageForNonGeminiPlatform(t *testing.T) {
|
||||
|
||||
@@ -61,6 +61,9 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
|
||||
// 应用 thinking 模式自动后缀:如果 thinking 开启且目标是 claude-sonnet-4-5,自动改为 thinking 版本
|
||||
thinkingEnabled := claudeReq.Thinking != nil && (claudeReq.Thinking.Type == "enabled" || claudeReq.Thinking.Type == "adaptive")
|
||||
mappedModel = applyThinkingModelSuffix(mappedModel, thinkingEnabled)
|
||||
if geminiImageGenerationDenied(c, nil, originalModel, mappedModel) {
|
||||
return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage())
|
||||
}
|
||||
billingModel := mappedModel
|
||||
|
||||
// 获取 access_token
|
||||
|
||||
@@ -225,6 +225,9 @@ func (s *AntigravityGatewayService) prepareAntigravityCompatCall(
|
||||
thinkingEnabled := claudeRequest.Thinking != nil &&
|
||||
(claudeRequest.Thinking.Type == "enabled" || claudeRequest.Thinking.Type == "adaptive")
|
||||
mappedModel = applyThinkingModelSuffix(mappedModel, thinkingEnabled)
|
||||
if geminiImageGenerationDenied(c, nil, request.originalModel, mappedModel) {
|
||||
return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage())
|
||||
}
|
||||
|
||||
if s.tokenProvider == nil {
|
||||
return nil, s.writeAntigravityCompatError(c, http.StatusBadGateway, "api_error", "Antigravity token provider not configured")
|
||||
|
||||
@@ -96,6 +96,9 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
return nil, s.writeGoogleError(c, http.StatusForbidden, fmt.Sprintf("model %s not in whitelist", originalModel))
|
||||
}
|
||||
if geminiImageGenerationDenied(c, body, originalModel, mappedModel) {
|
||||
return nil, s.writeGoogleError(c, http.StatusBadRequest, ImageGenerationPermissionMessage())
|
||||
}
|
||||
forwardedModel := mappedModel
|
||||
|
||||
// 获取 access_token
|
||||
|
||||
@@ -100,6 +100,9 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
|
||||
if err != nil {
|
||||
return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
}
|
||||
if geminiImageGenerationDenied(c, geminiReq, originalModel, req.Model, mappedModel) {
|
||||
return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage())
|
||||
}
|
||||
geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq)
|
||||
geminiReq = applyGeminiCompatThinkingConfig(geminiReq, claudeBody, mappedModel, clientStream)
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// geminiImageModalityEnum 是 proto JSON 中 Modality.IMAGE 的整数枚举值。
|
||||
const geminiImageModalityEnum = 2
|
||||
|
||||
// GeminiImageGenerationDenied 判断 Gemini 系请求是否因分组关闭生图而必须拒绝。
|
||||
// 门禁只作用于后台展示该开关的 Gemini 系分组(gemini / antigravity / composite);
|
||||
// 无分组的 Key 与其他平台分组不受影响。models 中任一名字属于生图模型,
|
||||
// 或请求体要求输出 IMAGE 模态,即视为生图请求。
|
||||
func GeminiImageGenerationDenied(group *Group, geminiBody []byte, models ...string) bool {
|
||||
if group == nil || group.AllowImageGeneration {
|
||||
return false
|
||||
}
|
||||
switch group.Platform {
|
||||
case PlatformGemini, PlatformAntigravity, PlatformComposite:
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return isGeminiImageGenerationIntent(geminiBody, models...)
|
||||
}
|
||||
|
||||
// geminiImageGenerationDenied 是转发层在账号模型映射之后的门禁:models 传入
|
||||
// 转发时可见的模型名(入参模型名与账号映射后的上游模型名)。命中时把请求标记为
|
||||
// 本地功能门禁,调用方负责按各自协议写出 400。
|
||||
func geminiImageGenerationDenied(c *gin.Context, geminiBody []byte, models ...string) bool {
|
||||
if c == nil || !GeminiImageGenerationDenied(apiKeyGroup(getAPIKeyFromContext(c)), geminiBody, models...) {
|
||||
return false
|
||||
}
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
return true
|
||||
}
|
||||
|
||||
func isGeminiImageGenerationIntent(geminiBody []byte, models ...string) bool {
|
||||
return slices.ContainsFunc(models, isGeminiImageOutputModel) || geminiRequestAsksForImageOutput(geminiBody)
|
||||
}
|
||||
|
||||
// isGeminiImageOutputModel 匹配以图片为输出的 Gemini 模型名,与图片接口共用
|
||||
// isGeminiCompatibleImageModel 判定。
|
||||
func isGeminiImageOutputModel(model string) bool {
|
||||
return isGeminiCompatibleImageModel(strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "models/"))
|
||||
}
|
||||
|
||||
// geminiRequestAsksForImageOutput 判断 generationConfig.responseModalities 是否包含 IMAGE。
|
||||
// Gemini REST 同时接受 camelCase 与 snake_case 字段名、字符串与整数枚举;
|
||||
// 重复出现的键逐个检查。
|
||||
func geminiRequestAsksForImageOutput(body []byte) bool {
|
||||
if len(body) == 0 || !gjson.ValidBytes(body) {
|
||||
return false
|
||||
}
|
||||
found := false
|
||||
gjson.ParseBytes(body).ForEach(func(key, config gjson.Result) bool {
|
||||
if key.Str == "generationConfig" || key.Str == "generation_config" {
|
||||
found = geminiGenerationConfigAsksForImage(config)
|
||||
}
|
||||
return !found
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func geminiGenerationConfigAsksForImage(config gjson.Result) bool {
|
||||
if !config.IsObject() {
|
||||
return false
|
||||
}
|
||||
found := false
|
||||
config.ForEach(func(key, modalities gjson.Result) bool {
|
||||
if key.Str == "responseModalities" || key.Str == "response_modalities" {
|
||||
found = geminiModalitiesContainImage(modalities)
|
||||
}
|
||||
return !found
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func geminiModalitiesContainImage(modalities gjson.Result) bool {
|
||||
found := false
|
||||
modalities.ForEach(func(_, modality gjson.Result) bool {
|
||||
switch modality.Type {
|
||||
case gjson.String:
|
||||
found = strings.EqualFold(strings.TrimSpace(modality.Str), "IMAGE")
|
||||
case gjson.Number:
|
||||
found = modality.Num == geminiImageModalityEnum
|
||||
}
|
||||
return !found
|
||||
})
|
||||
return found
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestIsGeminiImageGenerationIntent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
models []string
|
||||
want bool
|
||||
}{
|
||||
{name: "pro image", models: []string{"gemini-3-pro-image"}, want: true},
|
||||
{name: "flash image preview with prefix", models: []string{"models/gemini-3.1-flash-image-preview"}, want: true},
|
||||
{name: "image generation experimental", models: []string{"gemini-2.0-flash-exp-image-generation"}, want: true},
|
||||
{name: "imageless suffix", models: []string{"gemini-3-pro-imageless"}, want: false},
|
||||
{name: "image without gemini prefix", models: []string{"unknown-image", "my-image-chat"}, want: false},
|
||||
{name: "banana alias without resolved image model", models: []string{"nano-banana-2"}, want: false},
|
||||
{name: "any resolved name", models: []string{"my-alias", "gemini-2.5-flash-image"}, want: true},
|
||||
{name: "text model", models: []string{"gemini-3.7-flash", "gemini-3.1-pro-preview"}, want: false},
|
||||
{name: "empty", models: []string{"", " "}, want: false},
|
||||
{name: "camelCase modalities", body: `{"generationConfig":{"responseModalities":["TEXT","IMAGE"]}}`, models: []string{"gemini-3.7-flash"}, want: true},
|
||||
{name: "snake_case modalities", body: `{"generation_config":{"response_modalities":["image"]}}`, want: true},
|
||||
{name: "mixed case keys", body: `{"generationConfig":{"response_modalities":[" Image "]}}`, want: true},
|
||||
{name: "text only modalities", body: `{"generationConfig":{"responseModalities":["TEXT"]}}`, models: []string{"gemini-3.7-flash"}, want: false},
|
||||
{name: "modalities string not array", body: `{"generationConfig":{"responseModalities":"IMAGE"}}`, want: true},
|
||||
{name: "no generation config", body: `{"contents":[{"parts":[{"text":"IMAGE"}]}]}`, want: false},
|
||||
{name: "integer enum modalities", body: `{"generationConfig":{"responseModalities":[1,2]}}`, want: true},
|
||||
{name: "integer enum text only", body: `{"generationConfig":{"responseModalities":[1]}}`, want: false},
|
||||
{name: "duplicate generationConfig keys", body: `{"generationConfig":{"responseModalities":["TEXT"]},"generationConfig":{"responseModalities":["IMAGE"]}}`, want: true},
|
||||
{name: "duplicate modalities keys", body: `{"generationConfig":{"responseModalities":["TEXT"],"responseModalities":["IMAGE"]}}`, want: true},
|
||||
{name: "invalid json", body: `{"generationConfig":{"responseModalities":["IMAGE"]`, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, isGeminiImageGenerationIntent([]byte(tc.body), tc.models...))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiImageGenerationDenied_GroupScope(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
group *Group
|
||||
want bool
|
||||
}{
|
||||
{name: "ungrouped key", group: nil, want: false},
|
||||
{name: "gemini disabled", group: &Group{Platform: PlatformGemini}, want: true},
|
||||
{name: "antigravity disabled", group: &Group{Platform: PlatformAntigravity}, want: true},
|
||||
{name: "composite disabled", group: &Group{Platform: PlatformComposite}, want: true},
|
||||
{name: "gemini enabled", group: &Group{Platform: PlatformGemini, AllowImageGeneration: true}, want: false},
|
||||
{name: "anthropic group without the switch", group: &Group{Platform: PlatformAnthropic}, want: false},
|
||||
{name: "openai group gated elsewhere", group: &Group{Platform: PlatformOpenAI}, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, GeminiImageGenerationDenied(tc.group, nil, "gemini-3-pro-image"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func withGeminiImageGateAPIKey(c *gin.Context, group *Group) {
|
||||
c.Set("api_key", &APIKey{ID: 1, Group: group})
|
||||
}
|
||||
|
||||
func imageDisabledGroup() *Group {
|
||||
return &Group{ID: 10, Platform: PlatformGemini, AllowImageGeneration: false}
|
||||
}
|
||||
|
||||
func requireGeminiImagePermissionError(t *testing.T, rec *httptest.ResponseRecorder, wantGoogleStatus string) {
|
||||
t.Helper()
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
|
||||
errObj, ok := payload["error"].(map[string]any)
|
||||
require.True(t, ok, "error object: %s", rec.Body.String())
|
||||
require.Equal(t, ImageGenerationPermissionMessage(), errObj["message"])
|
||||
if wantGoogleStatus != "" {
|
||||
require.Equal(t, wantGoogleStatus, errObj["status"])
|
||||
} else {
|
||||
require.Equal(t, "invalid_request_error", errObj["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiForwardNative_ImageGenerationDisabledGroupRejectsBeforeUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
textBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`)
|
||||
imageModalityBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}],"generationConfig":{"responseModalities":["TEXT","IMAGE"]}}`)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
model string
|
||||
mapping map[string]any
|
||||
body []byte
|
||||
}{
|
||||
{name: "image model", model: "gemini-3-pro-image", body: textBody},
|
||||
{name: "account mapping alias to image model", model: "my-draw", mapping: map[string]any{"my-draw": "gemini-3.1-flash-image"}, body: textBody},
|
||||
{name: "text model asking for image modality", model: "gemini-3.7-flash", body: imageModalityBody},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc, httpStub := newGeminiVertexAPIKeyTestService()
|
||||
c, rec := newGeminiNativeTestContext(t)
|
||||
withGeminiImageGateAPIKey(c, imageDisabledGroup())
|
||||
account := geminiVertexAPIKeyTestAccount("")
|
||||
if tc.mapping != nil {
|
||||
account.Credentials["model_mapping"] = tc.mapping
|
||||
}
|
||||
|
||||
result, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, tc.body)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, result)
|
||||
require.Zero(t, httpStub.calls)
|
||||
requireGeminiImagePermissionError(t, rec, "INVALID_ARGUMENT")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiForwardNative_ImageGenerationGateAllowsPermittedRequests(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
group *Group
|
||||
model string
|
||||
action string
|
||||
}{
|
||||
{name: "group allows image generation", group: &Group{ID: 34, Platform: PlatformGemini, AllowImageGeneration: true}, model: "gemini-3-pro-image", action: "generateContent"},
|
||||
{name: "ungrouped key", group: nil, model: "gemini-3-pro-image", action: "generateContent"},
|
||||
{name: "text model in disabled group", group: imageDisabledGroup(), model: "gemini-3.7-flash", action: "generateContent"},
|
||||
{name: "countTokens on image model", group: imageDisabledGroup(), model: "gemini-3-pro-image", action: "countTokens"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc, httpStub := newGeminiVertexAPIKeyTestService()
|
||||
c, rec := newGeminiNativeTestContext(t)
|
||||
withGeminiImageGateAPIKey(c, tc.group)
|
||||
|
||||
_, _ = svc.ForwardNative(context.Background(), c, geminiVertexAPIKeyTestAccount(""), tc.model, tc.action, false, body)
|
||||
require.Equal(t, 1, httpStub.calls)
|
||||
require.NotEqual(t, http.StatusBadRequest, rec.Code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiCompatForward_ImageGenerationDisabledGroupRejectsBeforeUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc, httpStub := newGeminiVertexAPIKeyTestService()
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
withGeminiImageGateAPIKey(c, imageDisabledGroup())
|
||||
body := []byte(`{"model":"gemini-3-pro-image","max_tokens":16,"messages":[{"role":"user","content":"draw a cat"}]}`)
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, geminiVertexAPIKeyTestAccount(""), body)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, result)
|
||||
require.Zero(t, httpStub.calls)
|
||||
requireGeminiImagePermissionError(t, rec, "")
|
||||
}
|
||||
|
||||
func TestGeminiForwardAsChatCompletions_ImageGenerationDisabledGroupRejectsBeforeUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc, httpStub := newGeminiVertexAPIKeyTestService()
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gemini-3.1-flash-image","messages":[{"role":"user","content":"draw a cat"}]}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
|
||||
withGeminiImageGateAPIKey(c, imageDisabledGroup())
|
||||
|
||||
result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiVertexAPIKeyTestAccount(""), body)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, result)
|
||||
require.Zero(t, httpStub.calls)
|
||||
requireGeminiImagePermissionError(t, rec, "")
|
||||
}
|
||||
|
||||
func newAntigravityImageGateAccount() *Account {
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
account.Credentials["model_mapping"] = map[string]any{
|
||||
"gemini-3-pro-image": "gemini-3-pro-image",
|
||||
"my-draw": "gemini-3.1-flash-image",
|
||||
}
|
||||
return account
|
||||
}
|
||||
|
||||
func TestAntigravityForwards_ImageGenerationGate(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
geminiBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`)
|
||||
claudeBody := []byte(`{"model":"my-draw","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"draw a cat"}]}`)
|
||||
chatBody := []byte(`{"model":"gemini-3-pro-image","stream":true,"messages":[{"role":"user","content":"draw a cat"}]}`)
|
||||
|
||||
forwards := []struct {
|
||||
name string
|
||||
path string
|
||||
body []byte
|
||||
wantGoogleStatus string
|
||||
forward func(*AntigravityGatewayService, *gin.Context, *Account) (*ForwardResult, error)
|
||||
}{
|
||||
{
|
||||
name: "ForwardGemini",
|
||||
path: "/v1beta/models/gemini-3-pro-image:streamGenerateContent",
|
||||
body: geminiBody,
|
||||
wantGoogleStatus: "INVALID_ARGUMENT",
|
||||
forward: func(svc *AntigravityGatewayService, c *gin.Context, account *Account) (*ForwardResult, error) {
|
||||
return svc.ForwardGemini(context.Background(), c, account, "gemini-3-pro-image", "streamGenerateContent", true, geminiBody, false)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Forward",
|
||||
path: "/v1/messages",
|
||||
body: claudeBody,
|
||||
forward: func(svc *AntigravityGatewayService, c *gin.Context, account *Account) (*ForwardResult, error) {
|
||||
return svc.Forward(context.Background(), c, account, claudeBody, false)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ForwardAsChatCompletions",
|
||||
path: "/v1/chat/completions",
|
||||
body: chatBody,
|
||||
forward: func(svc *AntigravityGatewayService, c *gin.Context, account *Account) (*ForwardResult, error) {
|
||||
return svc.ForwardAsChatCompletions(context.Background(), c, account, chatBody, nil)
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, fw := range forwards {
|
||||
t.Run(fw.name+"/disabled group rejects", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
c, rec := newAntigravityCompatContext(http.MethodPost, fw.path, fw.body)
|
||||
withGeminiImageGateAPIKey(c, &Group{ID: 20, Platform: PlatformAntigravity, AllowImageGeneration: false})
|
||||
|
||||
result, err := fw.forward(svc, c, newAntigravityImageGateAccount())
|
||||
require.Error(t, err)
|
||||
require.Nil(t, result)
|
||||
require.Zero(t, upstream.callCount)
|
||||
requireGeminiImagePermissionError(t, rec, fw.wantGoogleStatus)
|
||||
})
|
||||
t.Run(fw.name+"/enabled group reaches upstream", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
c, rec := newAntigravityCompatContext(http.MethodPost, fw.path, fw.body)
|
||||
withGeminiImageGateAPIKey(c, &Group{ID: 21, Platform: PlatformAntigravity, AllowImageGeneration: true})
|
||||
|
||||
_, _ = fw.forward(svc, c, newAntigravityImageGateAccount())
|
||||
require.Equal(t, 1, upstream.callCount)
|
||||
require.NotEqual(t, http.StatusBadRequest, rec.Code)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -555,6 +555,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
|
||||
if err != nil {
|
||||
return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
}
|
||||
if geminiImageGenerationDenied(c, geminiReq, originalModel, mappedModel) {
|
||||
return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage())
|
||||
}
|
||||
geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq)
|
||||
includeThoughts := req.Stream && claudeRequestEnablesThinking(body)
|
||||
geminiReq = applyGeminiCompatThinkingConfig(geminiReq, body, mappedModel, includeThoughts)
|
||||
@@ -1120,6 +1123,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
|
||||
if account.Type == AccountTypeAPIKey || account.Type == AccountTypeServiceAccount {
|
||||
mappedModel = account.GetMappedModel(originalModel)
|
||||
}
|
||||
if action != "countTokens" && geminiImageGenerationDenied(c, body, originalModel, mappedModel) {
|
||||
return nil, s.writeGoogleError(c, http.StatusBadRequest, ImageGenerationPermissionMessage())
|
||||
}
|
||||
|
||||
proxyURL := ""
|
||||
if account.ProxyID != nil && account.Proxy != nil {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- gemini / antigravity 分组的生图开关同时约束 Gemini 系入口,存量分组统一置为开启。
|
||||
-- composite 分组的同一开关还约束 OpenAI 生图,不在本迁移范围内。
|
||||
UPDATE groups
|
||||
SET allow_image_generation = true
|
||||
WHERE platform IN ('gemini', 'antigravity')
|
||||
AND allow_image_generation = false;
|
||||
@@ -0,0 +1,24 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEnableGeminiImageGenerationGroupsMigration(t *testing.T) {
|
||||
content, err := FS.ReadFile("246_enable_gemini_image_generation_groups.sql")
|
||||
require.NoError(t, err)
|
||||
|
||||
var statements []string
|
||||
for _, line := range strings.Split(string(content), "\n") {
|
||||
if !strings.HasPrefix(strings.TrimSpace(line), "--") {
|
||||
statements = append(statements, line)
|
||||
}
|
||||
}
|
||||
sql := strings.Join(strings.Fields(strings.Join(statements, " ")), " ")
|
||||
require.Equal(t,
|
||||
"UPDATE groups SET allow_image_generation = true WHERE platform IN ('gemini', 'antigravity') AND allow_image_generation = false;",
|
||||
sql)
|
||||
}
|
||||
@@ -4364,6 +4364,7 @@ import {
|
||||
type ReasoningEffortMappingRow,
|
||||
} from "./groupsReasoningEffort";
|
||||
import {
|
||||
defaultAllowImageGenerationForPlatform,
|
||||
getDefaultImagePreviewPrice,
|
||||
getDefaultVideoPreviewPrice,
|
||||
getImagePricePlaceholder,
|
||||
@@ -6726,6 +6727,7 @@ watch(
|
||||
createForm.require_oauth_only = false;
|
||||
createForm.require_privacy_set = false;
|
||||
}
|
||||
createForm.allow_image_generation = defaultAllowImageGenerationForPlatform(newVal);
|
||||
resetDisabledBatchImagePricing(createForm);
|
||||
resetModelAllowlistState(createModelAllowlistState);
|
||||
loadModelAllowlistCandidates("create", 0, newVal);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
defaultAllowImageGenerationForPlatform,
|
||||
getDefaultImagePreviewPrice,
|
||||
getDefaultVideoPreviewPrice,
|
||||
getImagePricePlaceholder,
|
||||
@@ -27,6 +28,14 @@ describe("groups image pricing platform support", () => {
|
||||
expect(supportsImagePricingPlatform("anthropic")).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults image generation on for Grok and Gemini-family groups only", () => {
|
||||
expect(defaultAllowImageGenerationForPlatform("grok")).toBe(true);
|
||||
expect(defaultAllowImageGenerationForPlatform("gemini")).toBe(true);
|
||||
expect(defaultAllowImageGenerationForPlatform("antigravity")).toBe(true);
|
||||
expect(defaultAllowImageGenerationForPlatform("composite")).toBe(false);
|
||||
expect(defaultAllowImageGenerationForPlatform("openai")).toBe(false);
|
||||
});
|
||||
|
||||
it("includes Composite groups in image pricing controls", () => {
|
||||
expect(supportsImagePricingPlatform("composite")).toBe(true);
|
||||
expect(imagePricingPlatforms.has("composite")).toBe(true);
|
||||
|
||||
@@ -9,6 +9,12 @@ export const imagePricingPlatforms = new Set([
|
||||
export const supportsImagePricingPlatform = (platform: string): boolean =>
|
||||
imagePricingPlatforms.has(platform);
|
||||
|
||||
// 与后端 DefaultAllowImageGenerationForPlatform 一致:这些平台新建分组默认允许生图。
|
||||
const imageGenerationDefaultPlatforms = new Set(["antigravity", "gemini", "grok"]);
|
||||
|
||||
export const defaultAllowImageGenerationForPlatform = (platform: string): boolean =>
|
||||
imageGenerationDefaultPlatforms.has(platform);
|
||||
|
||||
export const supportsVideoPricingPlatform = (platform: string): boolean =>
|
||||
platform === "grok";
|
||||
|
||||
|
||||
Reference in new issue
Block a user