diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index b68a06ac54..0902593dad 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -190,7 +190,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache) proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig) proxyLatencyCache := repository.NewProxyLatencyCache(redisClient) - adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService) + adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, billingService) adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService) groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache) groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig) diff --git a/backend/ent/channelmonitor/channelmonitor.go b/backend/ent/channelmonitor/channelmonitor.go index 5fa6966c45..552b2ec3a4 100644 --- a/backend/ent/channelmonitor/channelmonitor.go +++ b/backend/ent/channelmonitor/channelmonitor.go @@ -184,6 +184,7 @@ const ( ProviderDeepseek Provider = "deepseek" ProviderMinimax Provider = "minimax" ProviderOpencodeGo Provider = "opencode_go" + ProviderOllamaCloud Provider = "ollama_cloud" ) func (pr Provider) String() string { @@ -193,7 +194,7 @@ func (pr Provider) String() string { // ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save. func ProviderValidator(pr Provider) error { switch pr { - case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo: + case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud: return nil default: return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr) diff --git a/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go b/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go index d5ce2cc890..b9528672ff 100644 --- a/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go +++ b/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go @@ -110,6 +110,7 @@ const ( ProviderDeepseek Provider = "deepseek" ProviderMinimax Provider = "minimax" ProviderOpencodeGo Provider = "opencode_go" + ProviderOllamaCloud Provider = "ollama_cloud" ) func (pr Provider) String() string { @@ -119,7 +120,7 @@ func (pr Provider) String() string { // ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save. func ProviderValidator(pr Provider) error { switch pr { - case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo: + case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud: return nil default: return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr) diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index ceefcc684f..1309a1e6ef 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -623,7 +623,7 @@ var ( {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, - {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}}, + {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}}, {Name: "check_mode", Type: field.TypeString, Size: 32, Default: "probe"}, {Name: "account_id", Type: field.TypeInt64, Nullable: true}, {Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"}, @@ -776,7 +776,7 @@ var ( {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, - {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}}, + {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}}, {Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"}, {Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""}, {Name: "extra_headers", Type: field.TypeJSON}, diff --git a/backend/ent/schema/channel_monitor.go b/backend/ent/schema/channel_monitor.go index 0e0330fe5e..ab1203fd77 100644 --- a/backend/ent/schema/channel_monitor.go +++ b/backend/ent/schema/channel_monitor.go @@ -36,7 +36,7 @@ func (ChannelMonitor) Fields() []ent.Field { MaxLen(100), field.Enum("provider"). Values("openai", "anthropic", "gemini", "grok", - "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"), + "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"), // check_mode: 'probe' | 'quota' | 'quota_probe' // probe - LLM 探活(默认,原有行为) // quota - 仅查关联账号的用量/余额(零 LLM 成本;endpoint/api_key 可空) diff --git a/backend/ent/schema/channel_monitor_request_template.go b/backend/ent/schema/channel_monitor_request_template.go index 3fe78fe3e2..ed2bdea90c 100644 --- a/backend/ent/schema/channel_monitor_request_template.go +++ b/backend/ent/schema/channel_monitor_request_template.go @@ -40,7 +40,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field { MaxLen(100), field.Enum("provider"). Values("openai", "anthropic", "gemini", "grok", - "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"), + "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"), field.String("api_mode"). Default("chat_completions"). MaxLen(32). diff --git a/backend/ent/schema/user_platform_quota.go b/backend/ent/schema/user_platform_quota.go index 20c0b3aa14..b77b8869f4 100644 --- a/backend/ent/schema/user_platform_quota.go +++ b/backend/ent/schema/user_platform_quota.go @@ -42,7 +42,7 @@ func (UserPlatformQuota) Fields() []ent.Field { // 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。 switch s { case "anthropic", "openai", "gemini", "antigravity", "grok", - "kimi", "zhipu", "deepseek", "minimax", "opencode_go": + "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud": return nil default: return fmt.Errorf("platform %q is not allowed", s) diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index e82c1df1dc..6a89e97b9d 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -31,16 +31,24 @@ const ( // PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。 // 值保持 opencode_go 以兼容已落库的分组、配额与 Composite 路由 CHECK。 PlatformOpenCodeGo = "opencode_go" - PlatformComposite = "composite" + // PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游(多协议 API Key 网关)。 + PlatformOllamaCloud = "ollama_cloud" + PlatformComposite = "composite" ) // Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。 // 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。 +// ollama_cloud 的两代额度语义同存于此键:legacy 是 5h/7d 滚动窗口(与 Go 订阅同类, +// 受阈值停调保护);credits 是 2026-08-31 新定价后的月度美元信用池(无滚动窗口, +// 用完不硬停,不走阈值停调)。 const ( AccountModePayG = "payg" // 按量付费:消耗余额,做余额检测冷却 AccountModeCoding = "coding" // Coding Plan:滚动用量窗口冷却(5h / weekly) AccountModeZen = "zen" // OpenCode Zen:按量付费,https://opencode.ai/zen/v1 AccountModeGo = "go" // OpenCode Go:订阅额度窗口,https://opencode.ai/zen/go/v1 + + AccountModeOllamaLegacy = "ollama_legacy" // Ollama Cloud legacy:5h / 7d 滚动窗口 + AccountModeOllamaCredits = "ollama_credits" // Ollama Cloud 月度美元信用池 ) // API protocol constants 国产供应商的上游 API 协议维度。存储于 diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 754105c46b..3f56a808c0 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1199,13 +1199,14 @@ func (h *AccountHandler) Update(c *gin.Context) { // scheduleOpenAIResponsesProbe 异步触发 OpenAI APIKey 账号的 Responses API 能力探测。 // -// 仅对 platform=openai && type=apikey 账号生效;其他账号无操作。 +// 仅对 platform=openai / 国产供应商 / ollama_cloud && type=apikey 账号生效;其他账号 +// 无操作(国产与 ollama_cloud 在探针内按协议直接落标,不发网络请求)。 // 探测本身在 goroutine 中执行(会发一次 HTTP 请求到上游),不会阻塞 // 当前请求。探测错误仅记录日志,不向上下文传播:探测失败时标记保持缺失, // 网关会按"现状即证据"默认走 Responses。 func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) { if account == nil || account.Type != service.AccountTypeAPIKey || - (account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform)) { + (account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform) && !account.IsOllamaCloud()) { return } if h.accountTestService == nil { diff --git a/backend/internal/handler/admin/channel_handler.go b/backend/internal/handler/admin/channel_handler.go index 3b65ac97a8..812c80a340 100644 --- a/backend/internal/handler/admin/channel_handler.go +++ b/backend/internal/handler/admin/channel_handler.go @@ -634,6 +634,11 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) { // platformToLiteLLMProvider maps a channel platform name to the corresponding // LiteLLM provider string used as the key in the pricing catalog. +// +// ollama_cloud 故意不在本表(C24):LiteLLM 目录没有 ollama 条目,加了映射只会 +// 绕过 SyncPricingModels 的 unsupported 分支返回空列表(静默空池)。保持缺席, +// 让 sync-models?platform=ollama_cloud 显式返回 400 UNSUPPORTED_PLATFORM; +// ollama 定价走 billing_service.go fallbackPrices 的 ollama 条目(B2-② 落点)。 var platformToLiteLLMProvider = map[string]string{ service.PlatformAnthropic: "anthropic", service.PlatformOpenAI: "openai", diff --git a/backend/internal/handler/admin/channel_handler_test.go b/backend/internal/handler/admin/channel_handler_test.go index d735c54707..583cf3c5ba 100644 --- a/backend/internal/handler/admin/channel_handler_test.go +++ b/backend/internal/handler/admin/channel_handler_test.go @@ -566,6 +566,35 @@ func TestSyncPricingModels_ValidPlatform_EmptyService(t *testing.T) { } } +// C24:ollama_cloud 故意不进 platformToLiteLLMProvider(LiteLLM 目录无 ollama +// 条目,加映射只会返回空列表 = 静默空池),必须保持 400 UNSUPPORTED_PLATFORM; +// 其余平台不受影响。 +func TestSyncPricingModels_OllamaCloudUnsupported(t *testing.T) { + svc := service.NewPricingService(nil, nil) + router := setupSyncPricingModelsRouter(svc) + + req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+service.PlatformOllamaCloud, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code) + var body struct { + Code int `json:"code"` + Reason string `json:"reason"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.Equal(t, http.StatusBadRequest, body.Code) + require.Equal(t, "UNSUPPORTED_PLATFORM", body.Reason) + + // 非回归:其它平台照常 200。 + for _, platform := range []string{"anthropic", "openai", service.PlatformOpenCodeGo} { + req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+platform, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, "platform=%s", platform) + } +} + func setupModelDefaultPricingRouter() *gin.Engine { gin.SetMode(gin.TestMode) router := gin.New() diff --git a/backend/internal/handler/admin/channel_monitor_handler.go b/backend/internal/handler/admin/channel_monitor_handler.go index 3cb8d4c1d5..9854e65355 100644 --- a/backend/internal/handler/admin/channel_monitor_handler.go +++ b/backend/internal/handler/admin/channel_monitor_handler.go @@ -40,7 +40,7 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch type channelMonitorCreateRequest struct { Name string `json:"name" binding:"required,max=100"` - Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"` + Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"` APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Endpoint string `json:"endpoint" binding:"omitempty,max=500"` APIKey string `json:"api_key" binding:"omitempty,max=2000"` @@ -64,7 +64,7 @@ type channelMonitorCreateRequest struct { type channelMonitorUpdateRequest struct { Name *string `json:"name" binding:"omitempty,max=100"` - Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"` + Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"` APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Endpoint *string `json:"endpoint" binding:"omitempty,max=500"` APIKey *string `json:"api_key" binding:"omitempty,max=2000"` diff --git a/backend/internal/handler/admin/channel_monitor_template_handler.go b/backend/internal/handler/admin/channel_monitor_template_handler.go index 497e3d195b..e820a57db0 100644 --- a/backend/internal/handler/admin/channel_monitor_template_handler.go +++ b/backend/internal/handler/admin/channel_monitor_template_handler.go @@ -25,8 +25,10 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon // --- DTO --- type channelMonitorTemplateCreateRequest struct { - Name string `json:"name" binding:"required,max=100"` - Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"` + Name string `json:"name" binding:"required,max=100"` + // Provider 为历史短列表:CN 5 平台缺失属历史债(本批不扩),仅补 ollama_cloud + // 与监控/模板的 service 层放行对齐。模板按 provider 与监控匹配(应用时校验一致)。 + Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok ollama_cloud"` APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Description string `json:"description" binding:"max=500"` ExtraHeaders map[string]string `json:"extra_headers"` diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go index 4af0492550..350e408286 100644 --- a/backend/internal/handler/admin/group_handler.go +++ b/backend/internal/handler/admin/group_handler.go @@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) { type CreateGroupRequest struct { Name string `json:"name" binding:"required"` Description string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go composite"` + Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go ollama_cloud composite"` RateMultiplier float64 `json:"rate_multiplier"` IsExclusive bool `json:"is_exclusive"` SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"` @@ -258,7 +258,7 @@ type CreateGroupRequest struct { type UpdateGroupRequest struct { Name string `json:"name"` Description *string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go composite"` + Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go ollama_cloud composite"` RateMultiplier *float64 `json:"rate_multiplier"` IsExclusive *bool `json:"is_exclusive"` Status string `json:"status" binding:"omitempty,oneof=active inactive"` @@ -332,7 +332,7 @@ type UpdateGroupRequest struct { type CompositeRouteRequest struct { PublicModel string `json:"public_model" binding:"required"` MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"` - TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go"` + TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go ollama_cloud"` UpstreamModel string `json:"upstream_model"` Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"` Priority int `json:"priority"` diff --git a/backend/internal/handler/admin/group_handler_platform_test.go b/backend/internal/handler/admin/group_handler_platform_test.go index 0c820868b4..d1b6b4a6d4 100644 --- a/backend/internal/handler/admin/group_handler_platform_test.go +++ b/backend/internal/handler/admin/group_handler_platform_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/require" ) -// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go 必须能通过 Create/Update 的 -// binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof 白名单漏加, -// 导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。 +// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go/ollama_cloud 必须能通过 +// Create/Update 的 binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof +// 白名单漏加,导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。 func bindGroupPlatformJSON(t *testing.T, target any, body string) error { t.Helper() gin.SetMode(gin.TestMode) @@ -27,7 +27,7 @@ func bindGroupPlatformJSON(t *testing.T, target any, body string) error { func TestGroupPlatformBinding_AllowedPlatforms(t *testing.T) { allowed := []string{ "anthropic", "openai", "gemini", "antigravity", "grok", - "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "composite", + "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud", "composite", } for _, platform := range allowed { t.Run("create_"+platform, func(t *testing.T) { @@ -72,7 +72,7 @@ func TestGroupPlatformBinding_RejectsInvalidPlatforms(t *testing.T) { } func TestCompositeRouteTargetPlatform_AllowsCNProviders(t *testing.T) { - for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go"} { + for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"} { var req CompositeRouteRequest body := fmt.Sprintf(`{"public_model":"m","target_platform":%q}`, platform) require.NoError(t, bindGroupPlatformJSON(t, &req, body)) diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 7704a129a0..322439a2b4 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -51,6 +51,22 @@ func TestOpenAICompatibleTextTargetAllowsCompositeProviders(t *testing.T) { } } +// ollama_cloud 目标不会经 DetectModelPlatform 的模型名前缀产生(无 ollama 前缀, +// fail closed),只能来自 composite 路由已解析的 context;这里预置解析结果后 +// 断言文本目标白名单放行 ollama_cloud。 +func TestOpenAICompatibleTextTargetAllowsOllamaCloudResolvedRoute(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, path := range []string{"/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1/responses/input_tokens", "/v1/messages/count_tokens"} { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", path, nil) + c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformOllamaCloud)) + apiKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformComposite}} + + require.True(t, openAICompatibleTextTargetAllowed(c, apiKey, "gpt-oss:20b"), "path=%s", path) + } +} + // WS ingress 对 CN 账号既过不了 transport 过滤、HTTP 桥也没有 Responses 转换, // 放行只会把明确的策略拒绝换成 "no available account",因此 WS 白名单保持 openai+grok。 func TestResponsesWebSocketCompositePlatformGuardKeepsOpenAIAndGrokOnly(t *testing.T) { diff --git a/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go b/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go new file mode 100644 index 0000000000..5257cb5ec9 --- /dev/null +++ b/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go @@ -0,0 +1,57 @@ +package dto + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// ollama_cloud 平台账号无论合格与否都下发 ollama_cloud_usage state:不合格 +// 时管理端要靠 EligibleReason 解释「为什么没有窗口/余额」。legacy 宿主平台 +// (openai/kimi 等)无法与普通同平台账号区分,不合格时不挂 state。 +func TestAccountFromServiceShallow_OllamaCloudUsageAttachment(t *testing.T) { + t.Parallel() + + ollamaCloud := func() *service.Account { + return &service.Account{ + ID: 1, + Platform: service.PlatformOllamaCloud, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://ollama.example.test", // 反代 → 不合格 + "api_key": "key-1", + }, + } + } + + ineligible := AccountFromServiceShallow(ollamaCloud()) + require.NotNil(t, ineligible.OllamaCloudUsage) + require.False(t, ineligible.OllamaCloudUsage.Eligible) + require.Equal(t, "unsupported_base_url", ineligible.OllamaCloudUsage.EligibleReason) + + eligibleAccount := ollamaCloud() + eligibleAccount.Credentials["base_url"] = "https://ollama.com" + eligible := AccountFromServiceShallow(eligibleAccount) + require.NotNil(t, eligible.OllamaCloudUsage) + require.True(t, eligible.OllamaCloudUsage.Eligible) + + // legacy 宿主平台不合格账号:不挂 state(普通 openai 账号不受影响)。 + cnHost := &service.Account{ + ID: 2, + Platform: service.PlatformKimi, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"base_url": "https://api.kimi.com", "api_key": "key-2"}, + } + require.Nil(t, AccountFromServiceShallow(cnHost).OllamaCloudUsage) + + // 完全无关平台(如 gemini):照旧不挂 state。 + gemini := &service.Account{ + ID: 3, + Platform: service.PlatformGemini, + Type: service.AccountTypeOAuth, + Credentials: map[string]any{}, + } + require.Nil(t, AccountFromServiceShallow(gemini).OllamaCloudUsage) +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index bb29600c67..bfe1249300 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -238,7 +238,11 @@ func AccountFromServiceShallow(a *service.Account) *Account { redactedCreds, credsStatus := RedactCredentials(a.Credentials) extra := redactAccountManagedExtra(a.Extra) var ollamaCloudUsage *service.OllamaCloudUsageState - if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible { + // platform=ollama_cloud 一律下发 state:不合格账号(反代 base_url、oauth + // 类型)也要把 EligibleReason 送到前端用量格做可解释提示。legacy 宿主 + // 平台(openai/anthropic/国产)无法与普通同平台账号区分,维持仅在 + // eligible 时下发,避免给正常 CN/OpenAI 账号挂上无意义的 ineligible 状态。 + if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible || a.Platform == service.PlatformOllamaCloud { ollamaCloudUsage = state } out := &Account{ diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 4e975f0ad7..5b43a25a54 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1258,6 +1258,13 @@ func (h *GatewayHandler) Models(c *gin.Context) { return } + // ollama_cloud 账号侧清单缺失时回落实测默认目录(DefaultOllamaCloudModelIDs), + // 不得回落 Claude 默认模型。 + if platform == service.PlatformOllamaCloud { + writeModelsList(c, platform, service.DefaultOllamaCloudModelIDs()) + return + } + writeModelsListResponse(c, claude.DefaultModels) } @@ -1341,7 +1348,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID * seen := make(map[string]struct{}) models := make([]string, 0) schedulablePlatforms := h.gatewayService.GetSchedulablePlatforms(ctx, groupID) - for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} { + for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud} { platformModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform) if len(platformModels) == 0 { // CN 供应商没有静态默认模型列表(defaultModelIDsForPlatform 的 @@ -1525,10 +1532,12 @@ func defaultModelIDsForPlatform(platform string) []string { return xai.DefaultModelIDs() case service.PlatformOpenCodeGo: return service.DefaultOpenCodeGoModelIDs() + case service.PlatformOllamaCloud: + return service.DefaultOllamaCloudModelIDs() case service.PlatformComposite: ids := make([]string, 0) seen := make(map[string]struct{}) - for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} { + for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud} { for _, id := range defaultModelIDsForPlatform(concretePlatform) { if _, ok := seen[id]; ok { continue diff --git a/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go b/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go new file mode 100644 index 0000000000..a1d63ebd09 --- /dev/null +++ b/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go @@ -0,0 +1,119 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + middleware2 "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" +) + +// ollama_cloud 的默认模型目录 = DefaultOllamaCloudModelIDs:defaultModelIDsForPlatform +// 不得回落 Claude 列表(default 分支),/models 在账号侧清单缺失时回落该目录。 +func TestDefaultModelIDsForPlatform_OllamaCloudReturnsDefaultCatalog(t *testing.T) { + require.Equal(t, service.DefaultOllamaCloudModelIDs(), defaultModelIDsForPlatform(service.PlatformOllamaCloud)) + require.NotEmpty(t, defaultModelIDsForPlatform(service.PlatformAnthropic)) + for _, id := range defaultModelIDsForPlatform(service.PlatformOllamaCloud) { + require.NotContains(t, id, "claude") + } +} + +func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(9201) + h := newGatewayModelsHandlerForTest( + &gatewayModelsAccountRepoStub{ + byGroup: map[int64][]service.Account{ + groupID: { + { + ID: 1, + Platform: service.PlatformOllamaCloud, + Credentials: map[string]any{}, + Extra: map[string]any{service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}}, + }, + }, + }, + }, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud}, + }) + + h.Models(c) + + require.Equal(t, http.StatusOK, rec.Code) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Equal(t, []string{"gpt-oss:120b"}, modelIDsForTest(got.Data)) +} + +// 账号侧清单缺失(deny-all)时 /models 回落 ollama 默认目录,而不是 Claude 列表。 +func TestGatewayModels_OllamaCloudGroupWithoutListFallsBackToDefaultCatalog(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(9202) + h := newGatewayModelsHandlerForTest( + &gatewayModelsAccountRepoStub{ + byGroup: map[int64][]service.Account{ + groupID: { + {ID: 1, Platform: service.PlatformOllamaCloud, Credentials: map[string]any{}}, + }, + }, + }, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud}, + }) + + h.Models(c) + + require.Equal(t, http.StatusOK, rec.Code) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Equal(t, service.DefaultOllamaCloudModelIDs(), modelIDsForTest(got.Data), + "ollama_cloud 不得回落 Claude 默认模型列表,应回落实测默认目录") +} + +// ollama_cloud 分组的 composite 白名单来源不串入 Claude 目录之外的默认回落。 +func TestGatewayModels_CompositeIncludesOllamaDefaultCatalog(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(9203) + h := newGatewayModelsHandlerForTest( + &gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: {}}}, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + + h.Models(c) + + require.Equal(t, http.StatusOK, rec.Code) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + ids := modelIDsForTest(got.Data) + idsSet := make(map[string]struct{}, len(ids)) + for _, id := range ids { + idsSet[id] = struct{}{} + } + for _, id := range service.DefaultOllamaCloudModelIDs() { + require.Contains(t, idsSet, id, "composite /v1/models 兜底须含 ollama 目录条目 %q", id) + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 2aa8acc199..c8af543dcd 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -347,7 +347,7 @@ func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, m return compositeTargetPlatformAllowed(c, apiKey, model, service.PlatformOpenAI, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo) + service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud) } // isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket diff --git a/backend/internal/model/error_passthrough_rule.go b/backend/internal/model/error_passthrough_rule.go index a0c81934d7..425f9e0f6e 100644 --- a/backend/internal/model/error_passthrough_rule.go +++ b/backend/internal/model/error_passthrough_rule.go @@ -46,6 +46,7 @@ const ( PlatformDeepseek = domain.PlatformDeepseek PlatformMiniMax = domain.PlatformMiniMax PlatformOpenCodeGo = domain.PlatformOpenCodeGo + PlatformOllamaCloud = domain.PlatformOllamaCloud ) // AllPlatforms 返回所有支持的平台列表 @@ -61,6 +62,7 @@ func AllPlatforms() []string { PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud, } } diff --git a/backend/internal/model/error_passthrough_rule_test.go b/backend/internal/model/error_passthrough_rule_test.go index 34ceb414e8..63a2312bf6 100644 --- a/backend/internal/model/error_passthrough_rule_test.go +++ b/backend/internal/model/error_passthrough_rule_test.go @@ -18,5 +18,6 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) { "deepseek", "minimax", "opencode_go", + "ollama_cloud", }, AllPlatforms()) } diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index d5b506ab7a..2be8bae189 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "strings" "time" dbent "github.com/Wei-Shaw/sub2api/ent" @@ -15,17 +16,29 @@ const ( ollamaCloudBaseURLRegexSQL = `^[hH][tT][tT][pP][sS]://([wW][wW][wW]\.)?[oO][lL][lL][aA][mM][aA]\.[cC][oO][mM](:443)?(/v1)?$` ollamaCloudBaseURLMatchSQLPrefix = "btrim(" ollamaCloudBaseURLMatchSQLSuffix = ") ~ '" + ollamaCloudBaseURLRegexSQL + "'" - // ollamaCloudUsagePlatformsSQL 是 service.isOllamaCloudUsagePlatform 的 SQL - // 镜像:Ollama Cloud key 允许挂在 openai/anthropic 与国产 OpenAI 兼容平台 - // 下复用。所有平台白名单 SQL 只允许引用本常量,不得各处重写字面量,防止漂移。 - ollamaCloudUsagePlatformsSQL = "'openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'" - ollamaCloudUsageEligibleSQL = ` +) + +// ollamaCloudUsagePlatformsSQL 是 service.OllamaCloudUsagePlatforms(权威平台 +// 白名单,含 platform=ollama_cloud 本体与 legacy 宿主平台)派生的 SQL IN +// 字面量。派生自同一列表,两侧结构上不可能漂移;原先的手工镜像注释随之作废。 +// 所有平台白名单 SQL 只允许引用本变量,不得各处重写字面量。 +var ollamaCloudUsagePlatformsSQL = ollamaCloudPlatformsSQLLiteral(service.OllamaCloudUsagePlatforms) + +var ollamaCloudUsageEligibleSQL = ` platform IN (` + ollamaCloudUsagePlatformsSQL + `) AND type = 'apikey' AND ` + ollamaCloudBaseURLMatchSQLPrefix + `credentials ->> 'base_url'` + ollamaCloudBaseURLMatchSQLSuffix + ` AND jsonb_typeof(credentials -> 'api_key') = 'string' ` -) + +// ollamaCloudPlatformsSQLLiteral 把平台列表渲染为 SQL IN 字面量('a', 'b')。 +func ollamaCloudPlatformsSQLLiteral(platforms []string) string { + quoted := make([]string, len(platforms)) + for i, platform := range platforms { + quoted[i] = "'" + platform + "'" + } + return strings.Join(quoted, ", ") +} func ollamaCloudBaseURLMatchesSQL(expression string) string { return ollamaCloudBaseURLMatchSQLPrefix + expression + ollamaCloudBaseURLMatchSQLSuffix diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage_test.go b/backend/internal/repository/account_repo_ollama_cloud_usage_test.go index 6891eb7b80..42617672b3 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage_test.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "regexp" + "slices" "strings" "testing" "time" @@ -179,7 +180,7 @@ func TestListOllamaCloudUsageGroupAccountsUsesOneStrictBatchQuery(t *testing.T) require.Empty(t, accounts) query := normalizeSQLWhitespace(capturedSQL) require.Contains(t, query, "credentials ->> 'api_key' = ANY($1)") - require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')") + require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+")") require.Contains(t, query, "jsonb_typeof(credentials -> 'api_key') = 'string'") require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'")) require.NotContains(t, query, "~*") @@ -207,7 +208,7 @@ func TestListDueOllamaCloudUsageAccountsFiltersOrdersAndLimits(t *testing.T) { for _, clause := range []string{ "deleted_at IS NULL", "status = 'active'", - "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')", + "platform IN (" + ollamaCloudUsagePlatformsSQL + ")", "type = 'apikey'", ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"), "jsonb_typeof(extra -> 'ollama_cloud_usage_session') = 'string'", @@ -251,7 +252,7 @@ func TestBulkUpdateOllamaIdentityCleanupIsValueConditional(t *testing.T) { require.Contains(t, query, "NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'")) require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("$1::jsonb ->> 'base_url'")) require.NotContains(t, query, "~*") - require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey'") + require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey'") require.Contains(t, query, "- 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'") payload, ok := exec.execArgs[0][0].([]byte) require.True(t, ok) @@ -317,7 +318,7 @@ func TestUpdateCredentialsCleanupBranchRequiresChangedCredentials(t *testing.T) require.NoError(t, mock.ExpectationsWereMet()) } -// SQL 平台白名单常量与 service 判定必须互为镜像:对每个已知平台,常量里的 +// SQL 平台白名单与 service 判定必须互为镜像:对每个已知平台,常量里的 // 成员关系都要与 IsOllamaCloudUsageAccount(apikey + 官方 ollama.com)一致, // 防止两侧平台列表各自漂移。 func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) { @@ -326,13 +327,11 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) for _, match := range matches { sqlPlatforms[match[1]] = struct{}{} } - require.Len(t, sqlPlatforms, 6) - for _, platform := range []string{ - service.PlatformOpenAI, service.PlatformAnthropic, - service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, + require.Len(t, sqlPlatforms, len(service.OllamaCloudUsagePlatforms)) + for _, platform := range append(slices.Clone(service.OllamaCloudUsagePlatforms), service.PlatformGemini, service.PlatformGrok, service.PlatformAntigravity, service.PlatformComposite, "kiro", - } { + ) { account := ollamaCloudUsageRepositoryAccount() account.Platform = platform _, inSQL := sqlPlatforms[platform] @@ -340,6 +339,24 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) } } +// TestOllamaCloudUsagePlatformsMirror 锁定 SQL 平台白名单由 service 权威列表 +// (OllamaCloudUsagePlatforms,含 ollama_cloud 本体)派生这一事实:字面量可 +// 完整解析、成员一致、eligible 拼接结果包含全部平台项。若有人把派生改回手工 +// 字面量并漏掉/多写平台,本测试立即红。 +func TestOllamaCloudUsagePlatformsMirror(t *testing.T) { + matches := regexp.MustCompile(`'([^']+)'`).FindAllStringSubmatch(ollamaCloudUsagePlatformsSQL, -1) + sqlPlatforms := make([]string, 0, len(matches)) + for _, match := range matches { + sqlPlatforms = append(sqlPlatforms, match[1]) + } + require.Len(t, matches, len(service.OllamaCloudUsagePlatforms), "SQL 字面量解析出的平台项数量必须与权威列表一致") + require.ElementsMatch(t, service.OllamaCloudUsagePlatforms, sqlPlatforms) + require.Contains(t, sqlPlatforms, service.PlatformOllamaCloud) + for _, platform := range service.OllamaCloudUsagePlatforms { + require.Contains(t, ollamaCloudUsageEligibleSQL, "'"+platform+"'") + } +} + // 语义等价性:平台放开后,普通(非 ollama)kimi apikey 账号改凭证会从通用 // apikey 分支落到 Ollama 分支——多减三个它本来就不存在的 ollama 键。分支必须 // 仍然清掉 probe 快照,且不得减其它任何 extra 键。 @@ -373,7 +390,7 @@ func TestUpdateCredentialsPlainCNAPIKeyAccountCleanupStaysSemanticallyEquivalent require.NoError(t, err) query := normalizeSQLWhitespace(capturedSQL) require.Contains(t, query, - "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb") + "platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb") require.Contains(t, query, "THEN COALESCE(extra, '{}'::jsonb) - 'upstream_billing_probe' - 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'") require.NotContains(t, query, "- 'upstream_billing_probe_enabled'") diff --git a/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go b/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go index 7d0eb8957b..595a48ddfd 100644 --- a/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go +++ b/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go @@ -30,7 +30,7 @@ func TestProxyUpdateInvalidatesBoundProbeSnapshotsAndEnqueuesOutboxAtomically(t AddRow("http", "old.example", 8080, "user", "pass", service.StatusActive)) mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1)) expectProxyUpdateReload(mock, 9, "new.example", "user", "pass") - mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). + mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). WithArgs(int64(9)). WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)).AddRow(int64(18))) mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")). @@ -70,7 +70,7 @@ func TestProxyUpdateRollsBackWhenProbeInvalidationOutboxFails(t *testing.T) { AddRow("http", "old.example", 8080, "", "", service.StatusActive)) mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1)) expectProxyUpdateReload(mock, 9, "new.example", "", "") - mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). + mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). WithArgs(int64(9)). WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17))) mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")). diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 02a1fcf3be..e257e09dde 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1016,6 +1016,11 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { // 走网关报 no available accounts"。 "openai_passthrough", "openai_oauth_passthrough", + // ollama_cloud 空 mapping 的出站白名单必须进投影:候选过滤的 + // Account.IsModelSupported 以它为白名单(无清单即 deny-all)。 + // 裁掉它,白名单账号会在选号阶段被整体误判为 model_not_supported, + // 表现为 ollama_cloud 分组恒 no available accounts。 + service.OllamaCloudAllowedModelsExtraKey, "codex_fingerprint_mode", "codex_fingerprint_seed", "codex_5h_used_percent", diff --git a/backend/internal/repository/scheduler_cache_ollama_cloud_test.go b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go new file mode 100644 index 0000000000..63473073b3 --- /dev/null +++ b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go @@ -0,0 +1,39 @@ +//go:build unit + +package repository + +import ( + "encoding/json" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// ollama_cloud 空 mapping 的出站白名单(extra.allowed_models)必须穿过调度投影: +// 候选过滤的 Account.IsModelSupported 以它为白名单(无清单即 deny-all)。裁掉它, +// 白名单账号会在选号阶段被整体误判为 model_not_supported(#4936 同款投影缺失)。 +func TestFilterSchedulerExtra_KeepsOllamaCloudAllowedModels(t *testing.T) { + extra := map[string]any{ + service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}, + "unknown_key": "must-be-dropped", + } + + filtered := filterSchedulerExtra(extra) + require.Len(t, filtered, 1) + + kept, ok := filtered[service.OllamaCloudAllowedModelsExtraKey] + require.True(t, ok, "allowed_models 必须保留在调度投影中") + require.Contains(t, kept, "gpt-oss:120b") + + // 走真实的序列化/反序列化路径:sched:meta 里的 []string 会以 []any 读回, + // ollamaCloudOutboundModelNames 两种形态都必须能解析。 + payload, err := json.Marshal(filtered) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(payload, &decoded)) + + account := service.Account{ID: 1, Platform: service.PlatformOllamaCloud, Extra: decoded} + require.True(t, account.IsModelSupported("gpt-oss:120b")) + require.False(t, account.IsModelSupported("totally-unpriced-model")) +} diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 986a691a5a..5a06c24f3b 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -863,7 +863,7 @@ func TestAPIContracts(t *testing.T) { "force_email_on_third_party_signup": false, "default_concurrency": 5, "default_balance": 1.25, - "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, + "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, "auth_source_default_email_platform_quotas": null, "auth_source_default_github_platform_quotas": null, "auth_source_default_google_platform_quotas": null, @@ -1182,7 +1182,7 @@ func TestAPIContracts(t *testing.T) { "purchase_subscription_url": "", "table_default_page_size": 20, "table_page_size_options": [10, 20, 50], - "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, + "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, "auth_source_default_email_platform_quotas": null, "auth_source_default_github_platform_quotas": null, "auth_source_default_google_platform_quotas": null, @@ -1454,7 +1454,12 @@ func newContractDeps(t *testing.T) *contractDeps { apiKeyCache := stubApiKeyCache{} groupRepo := &stubGroupRepo{} userSubRepo := &stubUserSubscriptionRepo{} - accountRepo := stubAccountRepo{} + accountRepo := stubAccountRepo{ + accounts: map[int64]*service.Account{ + 101: {ID: 101, Name: "bulk-anthropic-1", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true}, + 102: {ID: 102, Name: "bulk-anthropic-2", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true}, + }, + } proxyRepo := stubProxyRepo{} redeemRepo := &stubRedeemCodeRepo{} @@ -1480,7 +1485,7 @@ func newContractDeps(t *testing.T) *contractDeps { settingRepo := newStubSettingRepo() settingService := service.NewSettingService(settingRepo, cfg) - adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil, nil) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil) @@ -1854,6 +1859,7 @@ func (stubGroupRepo) CreateFromSource(ctx context.Context, group *service.Group, type stubAccountRepo struct { bulkUpdateIDs []int64 + accounts map[int64]*service.Account } func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account) error { @@ -1869,7 +1875,13 @@ func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Accou } func (s *stubAccountRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) { - return nil, errors.New("not implemented") + out := make([]*service.Account, 0, len(ids)) + for _, id := range ids { + if account, ok := s.accounts[id]; ok { + out = append(out, account) + } + } + return out, nil } func (s *stubAccountRepo) ExistsByID(ctx context.Context, id int64) (bool, error) { diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index c20298a61d..7ea39b9d7f 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -46,6 +46,8 @@ func RegisterGatewayRoutes( // 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。 groupModelAllowlist := middleware.GroupModelAllowlist() + // 单目标与账号池统一走 dispatcher:池候选全属 OpenAI 兼容族进 OpenAI + // CountTokens,其余(跨族池 / 非兼容族单目标)落通用网关。 countTokensHandler := func(c *gin.Context) { dispatchOpenAICompatibleCountTokens(c, h.OpenAIGateway.CountTokens, h.OpenAIGateway.GrokCountTokens, h.Gateway.CountTokens) } @@ -499,12 +501,12 @@ func getGroupPlatform(c *gin.Context) string { } // isOpenAICompatibleGatewayFamilyPlatform 报告单个平台是否经 OpenAI 网关转发 -// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go)。 +// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go/Ollama Cloud)。 func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool { switch platform { case service.PlatformOpenAI, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo: + service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud: // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。 return true default: @@ -603,7 +605,7 @@ func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grok return } switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo: + case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud: compatibleHandler(c) case service.PlatformGrok: grokHandler(c) diff --git a/backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go b/backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go new file mode 100644 index 0000000000..b9c7640760 --- /dev/null +++ b/backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go @@ -0,0 +1,103 @@ +package routes + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + servermiddleware "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" +) + +// familyRouteHits 记录 stub terminal handler 各自被命中的次数。 +type familyRouteHits struct { + openAICompatible int + grok int + generic int +} + +// newOllamaCloudFamilyRouter 按 RegisterGatewayRoutes 的文本端点装配方式搭最小 +// 路由:APIKey 注入普通分组(非 composite、无池候选),composite 中间件原样接 +// 入(对非 composite 分组直接放行),messages/responses/chat completions 走真实 +// dispatchOpenAICompatibleGateway,count_tokens 走真实 +// dispatchOpenAICompatibleCountTokens,terminal handler 用 stub 标记实际进入的 +// 网关家族。 +func newOllamaCloudFamilyRouter(t *testing.T, groupPlatform string) (*gin.Engine, *familyRouteHits) { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: groupPlatform}, + }) + c.Next() + }))) + router.Use(compositeTargetPlatformMiddleware(service.NewCompositeRouteResolver(compositeRouteRepoStub{}))) + + hits := &familyRouteHits{} + openAICompatible := func(c *gin.Context) { hits.openAICompatible++; c.Status(http.StatusNoContent) } + grokCompatible := func(c *gin.Context) { hits.grok++; c.Status(http.StatusNoContent) } + generic := func(c *gin.Context) { hits.generic++; c.Status(http.StatusNoContent) } + + // 与 RegisterGatewayRoutes 相同的注册闭包:族分发交给生产 dispatcher。 + router.POST("/v1/messages", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAICompatible, generic) + }) + router.POST("/v1/responses", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAICompatible, generic) + }) + router.POST("/v1/chat/completions", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAICompatible, generic) + }) + router.POST("/v1/messages/count_tokens", func(c *gin.Context) { + dispatchOpenAICompatibleCountTokens(c, openAICompatible, grokCompatible, generic) + }) + return router, hits +} + +// ollama_cloud 普通分组(非 composite、无池候选)的三种文本入站端点必须全部 +// 进入 OpenAI 兼容网关,而不是通用 Anthropic 网关。族判定的唯一源头是 +// isOpenAICompatibleGatewayFamilyPlatform:清单缺 ollama_cloud 时,下列断言会以 +// generic 命中的形式失败,而不是静默通过。 +func TestOllamaCloudGroupRoutesTextEndpointsIntoOpenAICompatibleGateway(t *testing.T) { + require.True(t, isOpenAICompatibleGatewayFamilyPlatform(service.PlatformOllamaCloud), + "ollama_cloud must belong to the OpenAI-compatible gateway family") + + router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud) + + for _, path := range []string{"/v1/messages", "/v1/responses", "/v1/chat/completions"} { + before := *hits + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"llama3.1"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code, "%s must reach a terminal handler", path) + require.Equal(t, before.openAICompatible+1, hits.openAICompatible, + "%s must route the ollama_cloud group into the OpenAI-compatible gateway", path) + require.Equal(t, before.generic, hits.generic, + "%s must not fall through to the generic Anthropic gateway", path) + } +} + +// count_tokens 对 ollama_cloud 普通分组沿用兼容分支语义:走 OpenAI +// CountTokens(compatible stub),不落 Grok 本地估算,也不落通用处理。 +func TestOllamaCloudGroupCountTokensUsesCompatibleBranch(t *testing.T) { + router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud) + + req := httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", + strings.NewReader(`{"model":"llama3.1","messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code) + require.Equal(t, 1, hits.openAICompatible, "count_tokens must take the compatible branch for ollama_cloud") + require.Zero(t, hits.grok) + require.Zero(t, hits.generic, "count_tokens must not fall through to the generic handler for ollama_cloud") +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index b5268e9102..2d5a1e42fc 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -294,11 +294,32 @@ func (a *Account) IsCNProvider() bool { return a != nil && IsCNProvider(a.Platform) } +// IsOllamaCloud 报告账号平台是否为 Ollama Cloud。 +func (a *Account) IsOllamaCloud() bool { + return a != nil && IsOllamaCloud(a.Platform) +} + +// GetOllamaCloudAccountMode 返回 Ollama Cloud 账号的额度模式 +// (AccountModeOllamaLegacy / AccountModeOllamaCredits)。非 ollama_cloud 平台 +// 或非 apikey 类型返回空串;credentials 未设置或值不认识时默认 legacy +// (保守:legacy 有 5h/7d 滚动窗口 → 受阈值停调保护,默认 credits 会让存量 +// legacy 账号失去保护)。与 GetAccountMode(国产 payg/coding 白名单)互不影响。 +func (a *Account) GetOllamaCloudAccountMode() string { + if a == nil || !a.IsOllamaCloud() || a.Type != AccountTypeAPIKey { + return "" + } + if strings.TrimSpace(a.GetCredential("account_mode")) == AccountModeOllamaCredits { + return AccountModeOllamaCredits + } + return AccountModeOllamaLegacy +} + // IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。 // openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions -// 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。 +// 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI +// 网关按模型/协议分流。 func (a *Account) IsOpenAICompatible() bool { - return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo()) + return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo() || a.IsOllamaCloud()) } func (a *Account) GeminiOAuthType() string { @@ -417,6 +438,36 @@ func (a *Account) GetCredentialAsInt64(key string) int64 { return 0 } +// GetCredentialAsFloat64 返回浮点型凭据值,缺失或无法解析时返回 0。与 +// GetCredentialAsInt64 同样的类型容忍(JSONB 数字为 float64/json.Number, +// 运营也可能手写成字符串),供 Ollama Cloud monthly_credit_usd 等金额键读取。 +func (a *Account) GetCredentialAsFloat64(key string) float64 { + if a == nil || a.Credentials == nil { + return 0 + } + val, ok := a.Credentials[key] + if !ok || val == nil { + return 0 + } + switch v := val.(type) { + case float64: + return v + case int64: + return float64(v) + case int: + return float64(v) + case json.Number: + if f, err := v.Float64(); err == nil { + return f + } + case string: + if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil { + return f + } + } + return 0 +} + func (a *Account) IsTempUnschedulableEnabled() bool { if a.Credentials == nil { return false @@ -861,6 +912,26 @@ func (a *Account) IsModelSupported(requestedModel string) bool { if a.IsOpenAIOAuth() { return isOpenAIOAuthServableModel(requestedModel) } + // ollama_cloud 运行时白名单:空映射时 extra.allowed_models 清单就是 + // 唯一可出站白名单;既无映射也无清单则 deny-all(不支持任何模型)。 + // 与保存期门禁 validateOllamaCloudAccountModelPricingGate 的「mapping + // 或清单至少其一」语义对齐。空映射下请求的公开模型名即出站名 + // (ResolveMappedModel 原样透传),清单项又是按出站名断言过定价的, + // 因此对公开名做精确匹配即可;保存期门禁已确保清单不含通配符 + // (通配符串无法解析到定价,保存即被拒)。 + if a.IsOllamaCloud() { + allowed := ollamaCloudOutboundModelNames(a) + if len(allowed) == 0 { + return false + } + trimmed := strings.TrimSpace(requestedModel) + for _, model := range allowed { + if model == trimmed { + return true + } + } + return false + } return true // 无映射 = 允许所有 } if mappingSupportsRequestedModel(mapping, requestedModel) { @@ -1343,10 +1414,10 @@ func (a *Account) IsOpenAIApiKey() bool { } // GetOpenAIBaseURL 解析 OpenAI 协议族账号的上游 base_url。 -// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go; -// grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。 +// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与 +// Ollama Cloud;grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。 func (a *Account) GetOpenAIBaseURL() string { - if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() { + if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() && !a.IsOllamaCloud() { return "" } if a.IsMultiProtocolAPIKey() && a.IsAdaptiveAPIProtocol() { @@ -1379,7 +1450,14 @@ func (a *Account) GetOpenAIBaseURL() string { return DefaultMiniMaxBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultChatBaseURL() + case PlatformOllamaCloud: + return DefaultOllamaCloudBaseURL default: + if a.IsMultiProtocolAPIKey() { + // 多协议网关(CN / OpenCode / Ollama Cloud)的缺省端点必须由上面的平台 + // 分支显式给出:回落官方域名会把第三方 key 明文发到 api.openai.com。 + return "" + } return "https://api.openai.com" } } @@ -1402,10 +1480,11 @@ func (a *Account) IsCodingPlan() bool { return a.GetAccountMode() == AccountModeCoding } -// GetAPIProtocol 返回国产供应商账号的上游 API 协议。存储于 +// GetAPIProtocol 返回多协议 API Key 账号的上游 API 协议。存储于 // credentials["api_protocol"];缺失或与平台不匹配时回退 chat_completions -// (与既有行为完全一致)。responses 协议仅 deepseek / kimi / minimax 支持(官方原生 -// Responses 端点,适配 Codex);zhipu 无此端点。 +// (与既有行为完全一致),opencode_go / ollama_cloud 例外:缺省为 adaptive +// (按入站协议选择供应商原生端点)。responses 协议仅 deepseek / kimi / minimax 支持 +// (官方原生 Responses 端点,适配 Codex);zhipu 无此端点。 func (a *Account) GetAPIProtocol() string { if a == nil || !a.IsMultiProtocolAPIKey() { return APIProtocolChatCompletions @@ -1422,7 +1501,7 @@ func (a *Account) GetAPIProtocol() string { case APIProtocolChatCompletions: return APIProtocolChatCompletions } - if a.IsOpenCodeGo() { + if a.IsOpenCodeGo() || a.IsOllamaCloud() { return APIProtocolAdaptive } return APIProtocolChatCompletions @@ -1430,13 +1509,14 @@ func (a *Account) GetAPIProtocol() string { // SupportsNativeCNResponses 报告该国产供应商是否提供原生 Responses 端点。 // DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为 -// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。 +// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses; +// Ollama Cloud 为 /v1/responses(non-stateful,见 normalizeDeepSeekResponsesRequestBody)。 func (a *Account) SupportsNativeCNResponses() bool { if a == nil { return false } switch a.Platform { - case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return true default: return false @@ -1501,6 +1581,8 @@ func (a *Account) defaultCNProtocolBaseURL(protocol string) string { return DefaultMiniMaxAnthropicBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultAnthropicBaseURL() + case PlatformOllamaCloud: + return DefaultOllamaCloudAnthropicBaseURL } case APIProtocolChatCompletions, APIProtocolResponses: switch a.Platform { @@ -1520,6 +1602,8 @@ func (a *Account) defaultCNProtocolBaseURL(protocol string) string { return DefaultMiniMaxBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultChatBaseURL() + case PlatformOllamaCloud: + return DefaultOllamaCloudBaseURL } } return "" @@ -1560,6 +1644,11 @@ func (a *Account) GetAnthropicProtocolBaseURL() string { return DefaultMiniMaxAnthropicBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultAnthropicBaseURL() + case PlatformOllamaCloud: + // 与 adaptive 分支(defaultCNProtocolBaseURL)同源:官方 Anthropic + // 兼容端点不带 /v1 前缀。缺失时 pinned-anthropic 的 ollama_cloud 账号 + // 会拿到空 base,转发与连接测试都报「no anthropic protocol base url」。 + return DefaultOllamaCloudAnthropicBaseURL default: return "" } diff --git a/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go b/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go index 029b4fb009..6668c0b554 100644 --- a/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go +++ b/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go @@ -217,7 +217,7 @@ func TestDuplicateCreatePathMintsFreshSeedWhenEligible(t *testing.T) { func TestAccountServiceCreateAndUpdateCodexSeedLifecycle(t *testing.T) { ctx := context.Background() repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} - svc := NewAccountService(repo, nil) + svc := NewAccountService(repo, nil, nil) created, err := svc.Create(ctx, CreateAccountRequest{ Name: "legacy-create", diff --git a/backend/internal/service/account_header_override.go b/backend/internal/service/account_header_override.go index 7f05e253ac..5ffeecf8ac 100644 --- a/backend/internal/service/account_header_override.go +++ b/backend/internal/service/account_header_override.go @@ -78,7 +78,7 @@ func (a *Account) IsHeaderOverrideEligible() bool { return false } switch a.Platform { - case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return a.Type == AccountTypeAPIKey case PlatformGrok: return a.Type == AccountTypeAPIKey || a.Type == AccountTypeOAuth diff --git a/backend/internal/service/account_ollama_cloud_mode_test.go b/backend/internal/service/account_ollama_cloud_mode_test.go new file mode 100644 index 0000000000..511bd99ab5 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_mode_test.go @@ -0,0 +1,92 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGetOllamaCloudAccountMode(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + platform string + accountType string + credentials map[string]any + want string + }{ + { + name: "defaults to legacy when unset", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: nil, + want: AccountModeOllamaLegacy, + }, + { + name: "explicit legacy", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": AccountModeOllamaLegacy}, + want: AccountModeOllamaLegacy, + }, + { + name: "explicit credits", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + want: AccountModeOllamaCredits, + }, + { + name: "unknown value falls back to legacy", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": "bogus"}, + want: AccountModeOllamaLegacy, + }, + { + name: "oauth account returns empty", + platform: PlatformOllamaCloud, + accountType: AccountTypeOAuth, + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + want: "", + }, + { + name: "non ollama platform returns empty", + platform: PlatformOpenAI, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + want: "", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + account := &Account{ + Platform: tc.platform, + Type: tc.accountType, + Credentials: tc.credentials, + } + require.Equal(t, tc.want, account.GetOllamaCloudAccountMode()) + }) + } +} + +func TestGetAccountMode_IgnoresOllamaCloudModes(t *testing.T) { + t.Parallel() + + // 防回归:GetAccountMode 是国产 payg/coding 的白名单解析器, + // 不得被 ollama_cloud 的新 mode 值污染。 + for _, mode := range []string{AccountModeOllamaLegacy, AccountModeOllamaCredits} { + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"account_mode": mode}, + } + require.Empty(t, account.GetAccountMode()) + } +} diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate.go b/backend/internal/service/account_ollama_cloud_pricing_gate.go new file mode 100644 index 0000000000..5a81b87935 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_pricing_gate.go @@ -0,0 +1,154 @@ +package service + +import ( + "fmt" + "slices" + "strings" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// OllamaCloudAllowedModelsExtraKey 是 ollama_cloud 账号在 model_mapping 为空时 +// 声明可出站模型清单的 extra 键。值为字符串数组(如 ["gpt-oss:120b","qwen3.5:397b"])。 +// +// 背景:account.IsModelSupported 对空 model_mapping 一律放行所有模型名,因此 +// 只扫 mapping 目标值的校验对空 mapping 账号零覆盖;ollama_cloud 的计费又是 +// 白名单语义(未列价的模型名显式拒绝计费),所以保存期必须拿到一个有限的 +// 可出站模型名集合来断言「全部可被 GetModelPricing 解析」,否则只能全量拒绝。 +const OllamaCloudAllowedModelsExtraKey = "allowed_models" + +// accountModelPricingLookup 是保存期无价门禁所需的最小定价查询面, +// *BillingService 以同一查价链(LiteLLM → fallback,含 :tag 两级 fallback)实现。 +type accountModelPricingLookup interface { + GetModelPricing(model string) (*ModelPricing, error) +} + +// validateOllamaCloudAccountModelPricingGate 是 B2-③ 的保存期无价门禁: +// ollama_cloud 账号保存时断言「该账号可出站的模型名集合均可被 GetModelPricing 解析」。 +// +// 可出站集合的取法与 account.IsModelSupported 的放行语义对齐: +// - 非空 model_mapping → 扫全部目标值(映射后真正发往上游的名字); +// - 空 model_mapping → 必须同时提供 OllamaCloudAllowedModelsExtraKey 显式清单, +// 清单全量纳入断言;空 mapping 且无清单一律拒绝(此时账号对全部模型名放行, +// 门禁对它零覆盖,是静默零计费的敞口)。 +// +// 只对 ollama_cloud 生效:其它平台的保存路径行为不变(多数平台定价缺失走 +// 请求期零成本兜底,属于既有的全平台 fail-open 设计,见 +// openai_gateway_usage.go 的 pricing_missing_record_zero_cost 分支)。 +// lookup 为 nil 时跳过(生产 wire 必然注入 *BillingService;仅直接构造 +// struct 的单元测试/内部调用会出现)。 +// +// 与请求期转发前预检的刻意不对称(设计限制,非缺陷):请求期预检走完整定价 +// 解析链(Group → Channel → LiteLLM → fallback),「只有渠道价/分组价」的模型 +// 运行时允许出站;本门禁只查全局基础价(GetModelPricing,LiteLLM → fallback), +// 因此仅在渠道/分组层配置定价的模型会在保存时被 MODEL_PRICING_MISSING 拒绝。 +// 这是刻意比运行时更严格的策略:账号与分组是多对多,保存时拿不到确定的 +// channel/group 上下文,「门禁查渠道价」在语义上不成立;而 ollama 的真实模型 +// 全部有全局基础价,实践中不会误拒。 +func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup, account *Account) error { + if lookup == nil || account == nil || !account.IsOllamaCloud() { + return nil + } + + models := ollamaCloudOutboundModelNames(account) + if len(models) == 0 { + return infraerrors.BadRequest("MODEL_PRICING_MISSING", + fmt.Sprintf("ollama_cloud 账号 model_mapping 为空时必须在 extra.%s 提供显式的可出站模型清单,否则无法保证全部模型可计费", + OllamaCloudAllowedModelsExtraKey)) + } + + unpriced := make([]string, 0) + for _, model := range models { + if _, err := lookup.GetModelPricing(model); err != nil { + unpriced = append(unpriced, model) + } + } + if len(unpriced) > 0 { + return infraerrors.BadRequest("MODEL_PRICING_MISSING", + fmt.Sprintf("以下 ollama_cloud 模型缺少全局基础定价,无法保证计费。此校验要求每个可出站模型都有全局基础价(LiteLLM 或内置 fallback),仅在渠道/分组层配置的定价不会被接受:请先在全局模型定价中补价,或调整 model_mapping/extra.%s。缺价模型: %s", + OllamaCloudAllowedModelsExtraKey, strings.Join(unpriced, ", "))) + } + return nil +} + +// ollamaCloudPricingGateRevalidationNeeded 报告一次账号更新是否需要重跑保存期无价门禁。 +// +// 门禁只拦「可能改变可出站模型集合或影响调度准入」的更新: +// - platform 变化(可出站模型集合的判定语义随平台切换); +// - 可出站模型集合的实际输入变化(prevOutboundSet 是更新前 +// ollamaCloudOutboundModelNames 的快照,覆盖 credentials.model_mapping 与 +// extra.allowed_models 两条来源); +// - 从不可调度改为可调度(启用):存量 legacy 账号(无 mapping/清单)的维护性 +// 编辑平时放行,但启用调度前必须补齐并通过门禁。 +// +// name、notes、并发数、优先级、状态停用等维护性更新放行 —— 否则迁移过来的存量 +// 账号连改备注都会被 MODEL_PRICING_MISSING 锁死。调用方必须在应用本次请求的 +// 字段变更**之前**采集 prevPlatform / prevOutboundSet / prevSchedulable 快照。 +func ollamaCloudPricingGateRevalidationNeeded(prevPlatform string, prevOutboundSet []string, prevSchedulable bool, next *Account) bool { + if next == nil || !next.IsOllamaCloud() { + return false + } + if prevPlatform != next.Platform { + return true + } + nextSet := append([]string(nil), ollamaCloudOutboundModelNames(next)...) + slices.Sort(prevOutboundSet) + slices.Sort(nextSet) + if !slices.Equal(prevOutboundSet, nextSet) { + return true + } + return !prevSchedulable && ollamaCloudSchedulableBySave(next) +} + +// ollamaCloudSchedulableBySave 只看保存路径能改变的两个调度准入开关 +// (status 是否 active、手动 Schedulable 开关),不含时间窗等运行态。 +func ollamaCloudSchedulableBySave(a *Account) bool { + return a != nil && a.IsActive() && a.Schedulable +} + +// ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合 +// (去重、去空)。空 mapping 且无有效清单时返回 nil。 +// +// 清单值兼容两种形态:JSON 反序列化出的 []any(元素为 string),以及程序化 +// 构造的 []string。非字符串元素跳过(由清单「缺失即拒绝」的语义兜底不严的 +// 情况——含非字符串元素的清单视同未提供,见下方 return nil)。 +func ollamaCloudOutboundModelNames(account *Account) []string { + seen := make(map[string]struct{}) + out := make([]string, 0) + appendModel := func(model string) { + trimmed := strings.TrimSpace(model) + if trimmed == "" { + return + } + if _, dup := seen[trimmed]; dup { + return + } + seen[trimmed] = struct{}{} + out = append(out, trimmed) + } + + if mapping := account.GetModelMapping(); len(mapping) > 0 { + for _, target := range mapping { + appendModel(target) + } + return out + } + + switch list := account.Extra[OllamaCloudAllowedModelsExtraKey].(type) { + case []any: + for _, item := range list { + model, ok := item.(string) + if !ok { + return nil + } + appendModel(model) + } + case []string: + for _, model := range list { + appendModel(model) + } + default: + return nil + } + return out +} diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate_test.go b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go new file mode 100644 index 0000000000..bd0eee2acc --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go @@ -0,0 +1,673 @@ +package service + +// B2-③ 保存期无价门禁回归测试(ollama_cloud): +// ① mapping 目标含未定价名 → Create/Update 返回 400 MODEL_PRICING_MISSING 且 +// message 含该模型名; +// ② 空 mapping 无 allowed_models 清单 → 400; +// ③ 空 mapping + 显式清单(全部已定价,含真实 :tag 形态)→ 通过; +// ④ 非 ollama 平台同样配置不受影响(回归)。 +// +// 门禁同时接在两条保存路径上: +// - AccountService.Create/Update(本文件,spec 权威位置); +// - adminServiceImpl.CreateAccount/UpdateAccount(生产 admin handler 实际走 +// 的路径,见 TestAdminCreateAccount.../TestAdminUpdateAccount...)。 + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func newOllamaGateAccountService(repo AccountRepository) *AccountService { + return NewAccountService(repo, nil, NewBillingService(&config.Config{}, nil)) +} + +func requireModelPricingMissing(t *testing.T, err error, wantNames ...string) { + t.Helper() + require.Error(t, err) + require.Equal(t, 400, infraerrors.Code(err), "必须映射为 400: %v", err) + require.Equal(t, "MODEL_PRICING_MISSING", infraerrors.Reason(err)) + for _, name := range wantNames { + require.Contains(t, infraerrors.Message(err), name, "message 必须列出未定价模型名") + } +} + +func TestAccountServiceCreateOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + + t.Run("mapping目标含未定价名_400并列出该名", func(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + _, err := svc.Create(ctx, CreateAccountRequest{ + Name: "ollama-bad-mapping", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + require.Empty(t, repo.accounts, "被拒绝的账号不得落库") + }) + + t.Run("空mapping且无清单_400", func(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + _, err := svc.Create(ctx, CreateAccountRequest{ + Name: "ollama-no-list", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, + }) + requireModelPricingMissing(t, err) + require.Contains(t, infraerrors.Message(err), OllamaCloudAllowedModelsExtraKey) + require.Empty(t, repo.accounts) + }) + + t.Run("空mapping加已定价清单_通过", func(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + created, err := svc.Create(ctx, CreateAccountRequest{ + Name: "ollama-with-list", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k", "base_url": "https://ollama.com/v1"}, + Extra: map[string]any{ + OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "qwen3.5:397b"}, + }, + }) + require.NoError(t, err) + require.NotNil(t, created) + require.NotEmpty(t, repo.accounts) + }) + + t.Run("mapping目标全部已定价_通过", func(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + _, err := svc.Create(ctx, CreateAccountRequest{ + Name: "ollama-priced-mapping", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "k", + "model_mapping": map[string]any{"big": "gpt-oss:120b", "coder": "qwen3.5:397b"}, + }, + }) + require.NoError(t, err) + }) + + t.Run("非ollama平台不受影响_回归", func(t *testing.T) { + for _, platform := range []string{PlatformOpenAI, PlatformKimi, PlatformAnthropic} { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + created, err := svc.Create(ctx, CreateAccountRequest{ + Name: "legacy-" + platform, + Platform: platform, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, + }) + require.NoError(t, err, "platform=%s 的空 mapping 账号保存不得被门禁拦截", platform) + require.NotNil(t, created) + } + }) +} + +func TestAccountServiceUpdateOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + + newOllamaAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) { + t.Helper() + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + created, err := svc.Create(ctx, CreateAccountRequest{ + Name: "ollama-update", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "k", + "model_mapping": map[string]any{"big": "gpt-oss:120b"}, + }, + }) + require.NoError(t, err) + return repo, svc, created + } + + t.Run("改成未定价目标_400", func(t *testing.T) { + _, svc, created := newOllamaAccount(t) + _, err := svc.Update(ctx, created.ID, UpdateAccountRequest{ + Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + }) + + t.Run("清空mapping且无清单_400", func(t *testing.T) { + _, svc, created := newOllamaAccount(t) + _, err := svc.Update(ctx, created.ID, UpdateAccountRequest{ + Credentials: &map[string]any{"api_key": "k"}, + }) + requireModelPricingMissing(t, err) + }) + + t.Run("换成已定价清单_通过", func(t *testing.T) { + repo, svc, created := newOllamaAccount(t) + updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{ + Credentials: &map[string]any{"api_key": "k"}, + Extra: &map[string]any{ + OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b"}, + }, + }) + require.NoError(t, err) + require.Equal(t, []any{"gpt-oss:20b"}, updated.Extra[OllamaCloudAllowedModelsExtraKey]) + require.NotNil(t, repo.accounts[created.ID]) + }) + + t.Run("非ollama平台更新不受影响_回归", func(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + created, err := svc.Create(ctx, CreateAccountRequest{ + Name: "kimi-update", + Platform: PlatformKimi, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "kimi-k2-0905-preview"}}, + }) + require.NoError(t, err) + updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{ + Credentials: &map[string]any{"api_key": "k"}, + }) + require.NoError(t, err, "kimi 账号清空 mapping 的更新不得被门禁拦截") + require.NotNil(t, updated) + }) +} + +// 生产 admin handler 实际走的保存路径(adminServiceImpl.CreateAccount/UpdateAccount) +// 同样必须挂门禁——只测 AccountService 而 admin 路径漏挂,等于门禁空转。 +func TestAdminCreateAccountOllamaCloudPricingGate(t *testing.T) { + svc := &adminServiceImpl{accountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}, billingService: NewBillingService(&config.Config{}, nil)} + _, err := svc.CreateAccount(context.Background(), &CreateAccountInput{ + Name: "ollama-admin-unpriced", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + SkipDefaultGroupBind: true, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + + created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{ + Name: "ollama-admin-priced", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "nemotron-3-super"}}, + SkipDefaultGroupBind: true, + }) + require.NoError(t, err) + require.NotNil(t, created) +} + +func TestAdminUpdateAccountOllamaCloudPricingGate(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + + created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{ + Name: "ollama-admin-update", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}, + SkipDefaultGroupBind: true, + }) + require.NoError(t, err) + + _, err = svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{ + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + + updated, err := svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{ + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "qwen3.5:397b"}}, + }) + require.NoError(t, err) + require.NotNil(t, updated) +} + +// gate helper 单元测试:清单值形态与非 ollama 平台短路。 +func TestOllamaCloudOutboundModelNames(t *testing.T) { + account := &Account{Platform: PlatformOllamaCloud, Credentials: map[string]any{ + "model_mapping": map[string]any{"a": "gpt-oss:120b", "b": "", "c": "qwen3.5:397b", "d": "gpt-oss:120b"}, + }} + // map 迭代顺序不定,只断言集合内容(去空、去重)。 + require.ElementsMatch(t, []string{"gpt-oss:120b", "qwen3.5:397b"}, ollamaCloudOutboundModelNames(account)) + + account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{ + OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", " "}, + }} + require.Equal(t, []string{"gpt-oss:20b"}, ollamaCloudOutboundModelNames(account)) + + account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{ + OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", 42}, + }} + require.Nil(t, ollamaCloudOutboundModelNames(account), "含非字符串元素的清单视同未提供(拒绝语义)") + + account = &Account{Platform: PlatformOpenAI} + require.Nil(t, ollamaCloudOutboundModelNames(account)) +} + +// 门禁触发收窄回归:缺 mapping/清单的存量 legacy 账号不得被维护性更新锁死, +// 只有可能改变「可出站模型集合」或影响调度准入的更新才重验。 +func TestAccountServiceUpdateOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) { + ctx := context.Background() + + seedLegacyAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) { + t.Helper() + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + // legacy 形态:无 model_mapping、无 allowed_models 清单。Create 路径有门禁, + // 直接经 repo 落库模拟迁移过来的存量账号。 + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-legacy", + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"api_key": "k"}, + } + require.NoError(t, repo.Create(ctx, account)) + return repo, svc, account + } + + t.Run("legacy账号仅改name_必须成功", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Name: strPtr("ollama-legacy-renamed")}) + require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 拦截") + require.Equal(t, "ollama-legacy-renamed", updated.Name) + }) + + t.Run("legacy账号改notes与并发数_放行", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + concurrency := 5 + updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{ + Notes: strPtr("migrated account"), + Concurrency: &concurrency, + }) + require.NoError(t, err) + require.Equal(t, "migrated account", *updated.Notes) + require.Equal(t, 5, updated.Concurrency) + }) + + t.Run("legacy账号加未定价mapping_仍400", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + _, err := svc.Update(ctx, account.ID, UpdateAccountRequest{ + Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + }) + + t.Run("legacy账号加未定价清单_仍400", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + _, err := svc.Update(ctx, account.ID, UpdateAccountRequest{ + Extra: &map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + }) + + t.Run("不可调度改可调度_必须校验", func(t *testing.T) { + repo, svc, account := seedLegacyAccount(t) + // 停用态(手动开关仍开):经 Update 把 status 改回 active 即「启用」, + // 必须先通过门禁。 + repo.accounts[account.ID].Status = StatusDisabled + _, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusActive)}) + requireModelPricingMissing(t, err) + }) + + t.Run("停用legacy账号_放行", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusDisabled)}) + require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截") + require.Equal(t, StatusDisabled, updated.Status) + }) + + t.Run("非ollama平台行为不变_回归", func(t *testing.T) { + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + created, err := svc.Create(ctx, CreateAccountRequest{ + Name: "kimi-legacy-update", + Platform: PlatformKimi, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, + }) + require.NoError(t, err) + updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{ + Name: strPtr("kimi-renamed"), + Notes: strPtr("notes only"), + }) + require.NoError(t, err, "非 ollama 平台的维护性更新行为必须保持不变") + require.Equal(t, "kimi-renamed", updated.Name) + }) +} + +// 门禁触发收窄在生产 admin handler 路径(adminServiceImpl.UpdateAccount)同样生效: +// 全对象 PUT 编辑会原样带回 credentials/extra,集合未变时不得重验锁死 legacy 账号。 +func TestAdminUpdateAccountOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) { + ctx := context.Background() + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-admin-legacy", + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"api_key": "k"}, + } + require.NoError(t, repo.Create(ctx, account)) + + t.Run("仅改name_必须成功", func(t *testing.T) { + updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Name: "ollama-admin-legacy-renamed"}) + require.NoError(t, err, "admin 路径维护性更新(仅改 name)不得被拦截") + require.Equal(t, "ollama-admin-legacy-renamed", updated.Name) + }) + + t.Run("全对象PUT带回原credentials与extra_不重验放行", func(t *testing.T) { + updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{ + Name: "ollama-admin-legacy", + Credentials: map[string]any{"api_key": "k"}, + Extra: map[string]any{"remark": "unchanged set"}, + }) + require.NoError(t, err, "可出站集合未变的全对象 PUT 不得触发门禁") + require.NotNil(t, updated) + }) + + t.Run("加未定价mapping_仍400", func(t *testing.T) { + _, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{ + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + }) + + t.Run("不可调度改可调度_必须校验", func(t *testing.T) { + repo.accounts[account.ID].Status = StatusDisabled + _, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Status: StatusActive}) + requireModelPricingMissing(t, err) + }) +} + +// ───────────────────────────────────────────────────────────────────────────── +// 评审收口回归:三条此前绕过门禁的 admin 写路径(BulkUpdateAccounts / +// DuplicateAccount / SetAccountSchedulable)。定位是「门禁不可绕过」的一致性—— +// 运行时白名单与转发前定价预检已兜底最坏情形,本组测试锁的是保存期拦截行为 +// 本身:不合规整批拒绝且不落库、错误点名账号、维护性更新与非 ollama 平台放行。 +// ───────────────────────────────────────────────────────────────────────────── + +// ollamaGateSchedulableCall 记录一次 SetSchedulable 调用,用于断言「拒绝时未触达 DB」。 +type ollamaGateSchedulableCall struct { + accountID int64 + schedulable bool +} + +// ollamaGateAdminRepoStub 在 upstreamBillingProbeAccountRepo 之上补齐本组回归所需的 +// 两个写入口:SetSchedulable(记录调用)与 CreateWithAccountGroups(复制路径的原子创建)。 +type ollamaGateAdminRepoStub struct { + *upstreamBillingProbeAccountRepo + schedulableCalls []ollamaGateSchedulableCall +} + +func newOllamaGateAdminRepoStub() *ollamaGateAdminRepoStub { + return &ollamaGateAdminRepoStub{ + upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}, + } +} + +func (r *ollamaGateAdminRepoStub) SetSchedulable(_ context.Context, id int64, schedulable bool) error { + r.mu.Lock() + defer r.mu.Unlock() + if account := r.accounts[id]; account != nil { + account.Schedulable = schedulable + } + r.schedulableCalls = append(r.schedulableCalls, ollamaGateSchedulableCall{accountID: id, schedulable: schedulable}) + return nil +} + +func (r *ollamaGateAdminRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, _ []AccountGroup) error { + return r.Create(ctx, account) +} + +// seedOllamaGateAccount 直接经 repo 落库一个账号(绕过 Create 路径门禁), +// 用于模拟「门禁上线前迁移过来的存量账号」。 +func seedOllamaGateAccount(t *testing.T, repo *ollamaGateAdminRepoStub, mutate func(*Account)) *Account { + t.Helper() + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-gate-seed", + Status: StatusActive, + Schedulable: false, + Credentials: map[string]any{"api_key": "k"}, + } + if mutate != nil { + mutate(account) + } + require.NoError(t, repo.Create(context.Background(), account)) + return account +} + +func TestAdminBulkUpdateAccountsOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) { + t.Helper() + repo := newOllamaGateAdminRepoStub() + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + return repo, svc + } + + t.Run("bulk写入未定价mapping_整批拒绝点名账号且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-a" }) + second := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-bulk-b" + a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}} + }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{first.ID, second.ID}, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + // 批量操作要能定位:错误信息必须点名每个不合规账号。 + require.Contains(t, infraerrors.Message(err), first.Name) + require.Contains(t, infraerrors.Message(err), second.Name) + // 整批拒绝:任何账号都不得写入。 + require.Empty(t, repo.bulkUpdates, "被拒绝的批量更新不得触达 DB") + }) + + t.Run("bulk写入已定价mapping_通过", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, nil) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "gpt-oss:120b"}}, + }) + require.NoError(t, err) + require.Len(t, repo.bulkUpdates, 1) + }) + + t.Run("bulk启用legacy无配置账号_拒绝且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-a" }) + second := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-b" }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{first.ID, second.ID}, + Schedulable: boolPtr(true), + }) + requireModelPricingMissing(t, err) + require.Contains(t, infraerrors.Message(err), first.Name) + require.Contains(t, infraerrors.Message(err), second.Name) + require.Empty(t, repo.bulkUpdates) + }) + + t.Run("bulk停用_放行", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-bulk-disable" + a.Schedulable = true + }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Schedulable: boolPtr(false), + }) + require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截") + require.Len(t, repo.bulkUpdates, 1) + }) + + t.Run("bulk仅改name_legacy账号放行", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy" }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Name: "ollama-bulk-legacy-renamed", + }) + require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 锁死") + require.Len(t, repo.bulkUpdates, 1) + }) + + t.Run("非ollama平台bulk不受影响_回归", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "kimi-bulk" + a.Platform = PlatformKimi + a.Schedulable = false + }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Credentials: map[string]any{ + "api_key": "k", + "model_mapping": map[string]any{"k2": "totally-unpriced-model"}, + }, + Schedulable: boolPtr(true), + }) + require.NoError(t, err, "非 ollama 平台的批量更新行为必须保持不变") + require.Len(t, repo.bulkUpdates, 1) + }) +} + +func TestAdminDuplicateAccountOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) { + t.Helper() + repo := newOllamaGateAdminRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + return repo, svc + } + + t.Run("复制不合规账号_拒绝且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-dup-bad" + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}} + }) + _, err := svc.DuplicateAccount(ctx, source.ID, "", "") + requireModelPricingMissing(t, err, "totally-unpriced-model") + require.Len(t, repo.accounts, 1, "被拒绝的复制不得落库") + }) + + t.Run("复制无配置legacy账号_拒绝", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-dup-legacy" }) + _, err := svc.DuplicateAccount(ctx, source.ID, "", "") + requireModelPricingMissing(t, err) + require.Len(t, repo.accounts, 1) + }) + + t.Run("复制已配置清单账号_通过且保持暂停", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-dup-good" + a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}} + }) + duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "") + require.NoError(t, err) + require.NotNil(t, duplicate) + require.Len(t, repo.accounts, 2) + require.False(t, duplicate.Schedulable, "复制产物必须保持暂停,等人工复核后再启用") + }) + + t.Run("非ollama平台复制不受影响_回归", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "kimi-dup" + a.Platform = PlatformKimi + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}} + }) + duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "") + require.NoError(t, err, "非 ollama 平台的复制行为必须保持不变") + require.NotNil(t, duplicate) + require.Len(t, repo.accounts, 2) + }) +} + +func TestAdminSetAccountSchedulableOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) { + t.Helper() + repo := newOllamaGateAdminRepoStub() + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + return repo, svc + } + + t.Run("启用无配置legacy账号_拒绝且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-enable-legacy" }) + _, err := svc.SetAccountSchedulable(ctx, account.ID, true) + requireModelPricingMissing(t, err) + require.Empty(t, repo.schedulableCalls, "被拒绝的启用不得触达 DB") + }) + + t.Run("停用_放行", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-disable" + a.Schedulable = true + }) + updated, err := svc.SetAccountSchedulable(ctx, account.ID, false) + require.NoError(t, err, "停用(true→false)属于维护性操作,不得被拦截") + require.NotNil(t, updated) + require.Len(t, repo.schedulableCalls, 1) + require.False(t, repo.schedulableCalls[0].schedulable) + }) + + t.Run("启用未定价mapping账号_拒绝", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-enable-unpriced" + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}} + }) + _, err := svc.SetAccountSchedulable(ctx, account.ID, true) + requireModelPricingMissing(t, err, "totally-unpriced-model") + require.Empty(t, repo.schedulableCalls) + }) + + t.Run("启用已定价账号_通过", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-enable-priced" + a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}} + }) + updated, err := svc.SetAccountSchedulable(ctx, account.ID, true) + require.NoError(t, err) + require.NotNil(t, updated) + require.Len(t, repo.schedulableCalls, 1) + }) + + t.Run("非ollama平台启用不受影响_回归", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "kimi-enable" + a.Platform = PlatformKimi + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}} + }) + updated, err := svc.SetAccountSchedulable(ctx, account.ID, true) + require.NoError(t, err, "非 ollama 平台的手动启用行为必须保持不变") + require.NotNil(t, updated) + require.Len(t, repo.schedulableCalls, 1) + }) +} diff --git a/backend/internal/service/account_ollama_cloud_whitelist_test.go b/backend/internal/service/account_ollama_cloud_whitelist_test.go new file mode 100644 index 0000000000..aa18eb01d2 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_whitelist_test.go @@ -0,0 +1,162 @@ +package service + +// ollama_cloud 运行时白名单回归测试(钉死独立评审的探针场景): +// - 空 model_mapping + extra.allowed_models 清单 → IsModelSupported 只放行 +// 清单内模型,清单外(含未定价模型名)一律拒绝、调度不选中; +// - 空 mapping 且无清单 → deny-all; +// - 非 ollama 平台空 mapping 仍放行所有(回归护栏); +// - /models 列表路径(GetAvailableModels)并入 allowed_models 清单。 +// +// 与保存期门禁(account_ollama_cloud_pricing_gate_test.go)合起来形成闭环: +// 白名单决定能发什么,预检决定发出去的东西是否有价。 + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func newOllamaCloudWhitelistAccount(credentials map[string]any, extra map[string]any) *Account { + return &Account{ + ID: 9101, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: credentials, + Extra: extra, + } +} + +// 评审探针场景:空 mapping + 清单只含 gpt-oss:120b → totally-unpriced-model +// 必须不被支持、不被调度选中(评审当前观测到「仍 supported」)。 +func TestOllamaCloudWhitelist_ProbeUnpricedModelNotSupported(t *testing.T) { + t.Parallel() + + // Extra 走 JSON 反序列化的真实形态([]any 元素为 string)。 + account := newOllamaCloudWhitelistAccount( + map[string]any{}, + map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}}, + ) + + require.False(t, account.IsModelSupported("totally-unpriced-model"), + "清单外未定价模型名不得放行(评审探针场景)") + require.False(t, account.IsModelSupported("claude-sonnet-4-6"), + "其它平台默认模型名同样在清单外") + require.True(t, account.IsModelSupported("gpt-oss:120b"), "清单内模型必须放行") + + // 程序化构造形态([]string)语义一致。 + stringListAccount := newOllamaCloudWhitelistAccount( + nil, + map[string]any{OllamaCloudAllowedModelsExtraKey: []string{"gpt-oss:120b"}}, + ) + require.False(t, stringListAccount.IsModelSupported("totally-unpriced-model")) + require.True(t, stringListAccount.IsModelSupported("gpt-oss:120b")) + + // 调度候选过滤同样拒绝:不被选中。 + ctx := context.Background() + reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit( + ctx, account, PlatformOllamaCloud, "totally-unpriced-model", false, OpenAIEndpointCapabilityChatCompletions) + require.Equal(t, "model_not_supported", reason) + reason = openAICompatibleAccountEligibilityFailureReasonBeforeProfit( + ctx, account, PlatformOllamaCloud, "gpt-oss:120b", false, OpenAIEndpointCapabilityChatCompletions) + require.Empty(t, reason, "清单内模型必须保持可选中") +} + +func TestOllamaCloudWhitelist_EmptyMappingNoListDeniesAll(t *testing.T) { + t.Parallel() + + account := newOllamaCloudWhitelistAccount(map[string]any{}, map[string]any{}) + for _, model := range []string{"gpt-oss:120b", "totally-unpriced-model", "claude-sonnet-4-6", ""} { + require.False(t, account.IsModelSupported(model), + "空 mapping 且无清单必须 deny-all: %q", model) + } + + // 清单存在但全为空白项:视同未提供,仍然 deny-all(与保存期门禁的 + // 「清单缺失即拒绝」语义一致)。 + blankAccount := newOllamaCloudWhitelistAccount( + nil, + map[string]any{OllamaCloudAllowedModelsExtraKey: []any{" ", ""}}, + ) + require.False(t, blankAccount.IsModelSupported("gpt-oss:120b")) +} + +func TestOllamaCloudWhitelist_NonEmptyMappingKeepsMappingSemantics(t *testing.T) { + t.Parallel() + + account := newOllamaCloudWhitelistAccount( + map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}}, + nil, + ) + require.True(t, account.IsModelSupported("alias:latest"), "mapping 键即公开白名单") + require.False(t, account.IsModelSupported("totally-unpriced-model")) + // 既有语义:非 ollama 也一样——mapping 目标值不是公开名,不因本次改动改变。 + require.False(t, account.IsModelSupported("gpt-oss:120b"), "mapping 目标值不是公开名") +} + +// 回归护栏:非 ollama 平台的空 mapping 仍放行所有(钉住 4 处风险面语义)。 +// 不含 antigravity / grok:这两个平台空 mapping 的既有语义是注入平台默认映射 +// (resolveModelMapping),从来不是「放行所有」,与本次改动无关。 +// 不含 deepseek:其空 mapping 的模型能力由 DeepSeek 自身的名单测试守护, +// 本护栏只钉住 ollama_cloud 白名单改动不误伤其它平台,不替其它平台的能力 +// 定义背书。 +func TestOllamaCloudWhitelist_NonOllamaEmptyMappingStillAllowsAll(t *testing.T) { + t.Parallel() + + for _, platform := range []string{ + "", PlatformAnthropic, PlatformOpenAI, PlatformGemini, + PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo, + } { + account := &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{}} + require.Truef(t, account.IsModelSupported("totally-unpriced-model"), + "平台 %s 空 mapping 必须仍放行所有模型", platform) + } +} + +// /models 列表路径:GetAvailableModels 并入 ollama_cloud 的 allowed_models 清单。 +func TestGetAvailableModels_MergesOllamaCloudAllowedModels(t *testing.T) { + t.Parallel() + + groupID := int64(9102) + repo := &modelsListAccountRepoStub{ + byGroup: map[int64][]Account{ + groupID: { + { + ID: 1, + Platform: PlatformOllamaCloud, + Credentials: map[string]any{}, + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}}, + }, + { + ID: 2, + Platform: PlatformOllamaCloud, + Credentials: map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}}, + }, + { + ID: 3, + Platform: PlatformOllamaCloud, + Credentials: map[string]any{}, + }, + }, + }, + } + svc := &GatewayService{accountRepo: repo} + + models := svc.GetAvailableModels(context.Background(), &groupID, PlatformOllamaCloud) + require.Equal(t, []string{"alias:latest", "gpt-oss:120b", "qwen3:32b"}, models) + + // 全部账号都是 deny-all(无 mapping 无清单)→ 无可用模型列表。 + denyAllGroup := int64(9103) + repo.byGroup[denyAllGroup] = []Account{ + {ID: 4, Platform: PlatformOllamaCloud, Credentials: map[string]any{}}, + } + require.Nil(t, svc.GetAvailableModels(context.Background(), &denyAllGroup, PlatformOllamaCloud)) + + // 非 ollama 平台的既有语义不变:无任何 mapping → 仍返回 nil(用默认列表)。 + nonOllamaGroup := int64(9104) + repo.byGroup[nonOllamaGroup] = []Account{ + {ID: 5, Platform: PlatformDeepseek, Credentials: map[string]any{}}, + } + require.Nil(t, svc.GetAvailableModels(context.Background(), &nonOllamaGroup, PlatformDeepseek)) +} diff --git a/backend/internal/service/account_scheduling_threshold_eval.go b/backend/internal/service/account_scheduling_threshold_eval.go index 345f997a15..e876d556c2 100644 --- a/backend/internal/service/account_scheduling_threshold_eval.go +++ b/backend/internal/service/account_scheduling_threshold_eval.go @@ -60,6 +60,8 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string] winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now) case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo: winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now) + case PlatformOllamaCloud: + winner = pickLatestResetSchedulingCandidate(ollamaCloudThresholdCandidates(account), threshold, now) default: return decision } @@ -393,6 +395,40 @@ func cnThresholdCandidate(extra map[string]any, provider, window string) *accoun } } +// ollamaCloudThresholdCandidates 读取 ollama_cloud 账号 5h / 7d 滚动窗口的用量快照 +// (由 OllamaCloudUsageService 写入 account.Extra,经 decodeOllamaCloudUsageSnapshot +// 解出嵌套 struct —— 与 CN 的扁平 extra 键不同构,不复用 cnThresholdCandidate)。 +// +// 仅 legacy 账号有滚动窗口;credits 型是月度美元信用池、没有窗口 reset 可等, +// 候选恒空(credits 赗欠告警走余额告警通道,不写 TempUnschedulableUntil)。 +// 快照缺失 / status != ok / 无窗口数据时同样返回 nil —— 宁可不停调也不基于 +// 坏快照误停。窗口语义与 openai/anthropic/kimi 同类:取最晚 reset。 +func ollamaCloudThresholdCandidates(account *Account) []*accountSchedulingThresholdCandidate { + if account == nil || account.GetOllamaCloudAccountMode() != AccountModeOllamaLegacy { + return nil + } + snapshot := decodeOllamaCloudUsageSnapshot(account.Extra) + if snapshot == nil || snapshot.Status != OllamaCloudUsageStatusOK || snapshot.Data == nil { + return nil + } + return []*accountSchedulingThresholdCandidate{ + ollamaCloudThresholdCandidate(snapshot.Data.FiveHour, "5h"), + ollamaCloudThresholdCandidate(snapshot.Data.SevenDay, "weekly"), + } +} + +func ollamaCloudThresholdCandidate(window *OllamaCloudUsageWindow, label string) *accountSchedulingThresholdCandidate { + if window == nil { + return nil + } + return &accountSchedulingThresholdCandidate{ + window: label, + scope: PlatformOllamaCloud, + usedPercent: window.UsedPercent, + until: cloneTimePtr(window.ResetAt), + } +} + func pickLatestResetSchedulingCandidate(candidates []*accountSchedulingThresholdCandidate, threshold int, now time.Time) *accountSchedulingThresholdCandidate { var winner *accountSchedulingThresholdCandidate for _, candidate := range candidates { diff --git a/backend/internal/service/account_scheduling_threshold_eval_test.go b/backend/internal/service/account_scheduling_threshold_eval_test.go index 5e7e9fa77e..b7dfd41e6e 100644 --- a/backend/internal/service/account_scheduling_threshold_eval_test.go +++ b/backend/internal/service/account_scheduling_threshold_eval_test.go @@ -471,3 +471,147 @@ func TestEvaluateAccountSchedulingThreshold_GrokUsesOnlyHeaderQuotaWindow(t *tes require.NotNil(t, decision.Until) require.True(t, headerUntil.Equal(*decision.Until)) } + +// ollamaCloudSnapshotExtra 构造 account.Extra 里 ollama_cloud 用量快照的测试夹具, +// 形状与 DB JSONB 反序列化后的嵌套 map 一致(decodeOllamaCloudUsageSnapshot 走 +// marshal/unmarshal 往返,map 形式即生产读取路径)。 +func ollamaCloudSnapshotExtra(status string, data map[string]any) map[string]any { + snapshot := map[string]any{"status": status} + if data != nil { + snapshot["data"] = data + } + return map[string]any{OllamaCloudUsageSnapshotExtraKey: snapshot} +} + +func ollamaCloudUsageWindowFixture(usedPercent float64, resetAt time.Time) map[string]any { + return map[string]any{ + "used_percent": usedPercent, + "reset_at": resetAt.Format(time.RFC3339), + } +} + +func TestEvaluateAccountSchedulingThreshold_OllamaCloud(t *testing.T) { + t.Parallel() + + now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC) + fiveHourReset := now.Add(2 * time.Hour) + sevenDayReset := now.Add(5 * 24 * time.Hour) + newSnapshotAccount := func(mode string, extra map[string]any) *Account { + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Extra: extra, + } + if mode != "" { + account.Credentials = map[string]any{"account_mode": mode} + } + return account + } + okExtra := ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset), + "seven_day": ollamaCloudUsageWindowFixture(40, sevenDayReset), + }) + + cases := []struct { + name string + account *Account + shouldPause bool + wantWindow string + wantUntil time.Time + }{ + { + name: "legacy pauses at exhausted five hour window", + account: newSnapshotAccount("ollama_legacy", okExtra), + shouldPause: true, + wantWindow: "5h", + wantUntil: fiveHourReset, + }, + { + name: "mode unset defaults to legacy and pauses", + account: newSnapshotAccount("", okExtra), + shouldPause: true, + wantWindow: "5h", + wantUntil: fiveHourReset, + }, + { + name: "unknown mode value falls back to legacy and pauses", + account: newSnapshotAccount("bogus", okExtra), + shouldPause: true, + wantWindow: "5h", + wantUntil: fiveHourReset, + }, + { + // 防回归护栏:credits 型是月度美元信用池、没有滚动窗口 reset, + // 即使快照里解析出 5h/7d 数据也绝不停调。 + name: "credits never pauses despite fully populated snapshot", + account: newSnapshotAccount("ollama_credits", okExtra), + shouldPause: false, + }, + { + name: "failed snapshot does not pause", + account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusFailed, nil)), + shouldPause: false, + }, + { + name: "ok snapshot without window data does not pause", + account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{})), + shouldPause: false, + }, + { + // 防回归护栏:A6 纳入白名单后,无快照的账号同样不得停调。 + name: "missing snapshot does not pause", + account: newSnapshotAccount("ollama_legacy", map[string]any{}), + shouldPause: false, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + decision := EvaluateAccountSchedulingThreshold(tc.account, map[string]int{ + PlatformOllamaCloud: 80, + }, now) + + require.Equal(t, tc.shouldPause, decision.ShouldPause) + if !tc.shouldPause { + return + } + require.Equal(t, PlatformOllamaCloud, decision.Platform) + require.Equal(t, tc.wantWindow, decision.Window) + require.Equal(t, PlatformOllamaCloud, decision.Scope) + require.NotNil(t, decision.Until) + require.True(t, tc.wantUntil.Equal(*decision.Until)) + }) + } +} + +func TestEvaluateAccountSchedulingThreshold_OllamaCloudPicksLatestResetWindow(t *testing.T) { + t.Parallel() + + // 与 openai/anthropic/kimi 同类取最晚 reset(不是 CN 供应商的最早 reset)。 + now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC) + fiveHourReset := now.Add(2 * time.Hour) + sevenDayReset := now.Add(5 * 24 * time.Hour) + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "account_mode": "ollama_legacy", + }, + Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset), + "seven_day": ollamaCloudUsageWindowFixture(90, sevenDayReset), + }), + } + + decision := EvaluateAccountSchedulingThreshold(account, map[string]int{ + PlatformOllamaCloud: 80, + }, now) + + require.True(t, decision.ShouldPause) + require.Equal(t, "weekly", decision.Window) + require.Equal(t, PlatformOllamaCloud, decision.Scope) + require.NotNil(t, decision.Until) + require.True(t, sevenDayReset.Equal(*decision.Until)) +} diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 205907abc1..feb7d21a9a 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -207,6 +207,8 @@ type UpdateAccountRequest struct { type AccountService struct { accountRepo AccountRepository groupRepo GroupRepository + // B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。 + billingService *BillingService } type groupExistenceBatchChecker interface { @@ -214,10 +216,11 @@ type groupExistenceBatchChecker interface { } // NewAccountService 创建账号服务实例 -func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository) *AccountService { +func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository, billingService *BillingService) *AccountService { return &AccountService{ - accountRepo: accountRepo, - groupRepo: groupRepo, + accountRepo: accountRepo, + groupRepo: groupRepo, + billingService: billingService, } } @@ -250,6 +253,11 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) ( account.AutoPauseOnExpired = true } + // B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。 + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } + if err := s.accountRepo.Create(ctx, account); err != nil { return nil, fmt.Errorf("create account: %w", err) } @@ -320,6 +328,11 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount return nil, fmt.Errorf("get account: %w", err) } + // B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。 + prevPlatform := account.Platform + prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...) + prevSchedulable := ollamaCloudSchedulableBySave(account) + // 更新字段 if req.Name != nil { account.Name = *req.Name @@ -374,6 +387,16 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount } } + // B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。 + // 只在可能改变可出站模型集合(platform / model_mapping / allowed_models) + // 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性 + // 更新放行,避免锁死缺 mapping/清单的存量账号。 + if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } + } + // 执行更新 if err := s.accountRepo.Update(ctx, account); err != nil { return nil, fmt.Errorf("update account: %w", err) @@ -515,8 +538,9 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error { case PlatformGrok: // Grok OAuth credentials are validated via token exchange/refresh and request-path probes. return nil - case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: - // 国产 OpenAI 兼容供应商与 OpenCode:凭证为 API Key,实际可用性经余额/额度探测与转发路径验证。 + case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: + // 国产 OpenAI 兼容供应商、OpenCode 与 Ollama Cloud:凭证为 API Key, + // 实际可用性经余额/额度探测与转发路径验证。 return nil default: return fmt.Errorf("unsupported platform: %s", account.Platform) diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index b56861ebb6..a738a58f38 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -389,6 +389,10 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int return s.testOpenCodeGoAccountConnection(c, account, modelID, prompt) } + if account.IsOllamaCloud() { + return s.testOllamaCloudAccountConnection(c, account, modelID, prompt) + } + return s.testClaudeAccountConnection(c, account, modelID) } @@ -415,13 +419,16 @@ func (s *AccountTestService) testOpenCodeGoAccountConnection(c *gin.Context, acc case APIProtocolAnthropic: return s.testCNProviderAnthropicConnection(c, account, testModelID) case APIProtocolResponses: - return s.testOpenCodeGoResponsesConnection(c, account, testModelID) + return s.testNativeResponsesConnection(c, account, testModelID) default: return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt) } } -func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, account *Account, testModelID string) error { +// testNativeResponsesConnection probes a multi-protocol API-key account's +// native Responses endpoint (the same probe the adaptive path uses, including +// the stateless body normalization). Shared by OpenCode Go and Ollama Cloud. +func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, account *Account, testModelID string) error { authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey()) if authToken == "" { return s.sendErrorAndEnd(c, "No API key available") @@ -435,6 +442,43 @@ func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, a return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken) } +// testOllamaCloudAccountConnection probes an Ollama Cloud account's native +// endpoints per GetAPIProtocol. Falling through to the generic Claude tester +// sent Claude Code payloads to {base}/v1/messages?beta=true, so ollama accounts +// always failed the connection test regardless of account health. Adaptive +// (the default protocol for ollama_cloud) probes Chat Completions + Anthropic +// + native Responses in sequence; a pinned protocol probes that single endpoint. +func (s *AccountTestService) testOllamaCloudAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error { + testModelID := strings.TrimSpace(modelID) + if testModelID == "" { + // 无静态目录:默认探测账号自身的第一个可出站模型(保存期门禁保证 + // mapping 或 allowed_models 至少其一非空)。 + testModelID = defaultOllamaCloudTestModel(account) + } + switch account.GetAPIProtocol() { + case APIProtocolAdaptive: + // 复用 CN adaptive 三端点探针:base_url 解析、Anthropic Bearer 头与 + // Responses 无状态归一化均已按 ollama_cloud 适配。 + return s.testCNProviderAdaptiveConnection(c, account, testModelID, prompt) + case APIProtocolAnthropic: + return s.testCNProviderAnthropicConnection(c, account, testModelID) + case APIProtocolResponses: + return s.testNativeResponsesConnection(c, account, testModelID) + default: + return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt) + } +} + +// defaultOllamaCloudTestModel 返回 ollama_cloud 账号连接测试的默认模型: +// model_mapping 目标优先,其次 extra.allowed_models 首项;两者皆空时退回 +// OpenAI 测试模型(仅出现在未过保存期门禁的账号上,由上游报错暴露)。 +func defaultOllamaCloudTestModel(account *Account) string { + if models := ollamaCloudOutboundModelNames(account); len(models) > 0 { + return models[0] + } + return openai.DefaultTestModel +} + func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error { testModelID := strings.TrimSpace(modelID) if testModelID == "" { diff --git a/backend/internal/service/account_test_service_cn_adaptive.go b/backend/internal/service/account_test_service_cn_adaptive.go index a68a691d27..4efd92638d 100644 --- a/backend/internal/service/account_test_service_cn_adaptive.go +++ b/backend/internal/service/account_test_service_cn_adaptive.go @@ -162,11 +162,14 @@ func (s *AccountTestService) testCNProviderAdaptiveResponsesConnection(c *gin.Co apiURL := buildOpenAIResponsesURLForPlatform(account.Platform, baseURL) payload := createOpenAITestPayload(testModelID, false) - // DeepSeek / Kimi native Responses endpoints are stateless and do not need - // the OpenAI probe's synthetic instructions. + // DeepSeek / Kimi / Ollama Cloud native Responses endpoints are stateless and + // do not need the OpenAI probe's synthetic instructions. delete(payload, "instructions") payloadBytes, _ := json.Marshal(payload) - payloadBytes = normalizeDeepSeekResponsesRequestBody(account, payloadBytes) + payloadBytes, payloadErr := normalizeDeepSeekResponsesRequestBody(account, payloadBytes) + if payloadErr != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Adaptive Responses payload rejected: %s", payloadErr.Error())) + } s.sendEvent(c, TestEvent{Type: "status", Text: "正在通过原生 /responses 测试自适应 Responses 端点"}) req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes)) diff --git a/backend/internal/service/account_test_service_ollama_cloud_test.go b/backend/internal/service/account_test_service_ollama_cloud_test.go new file mode 100644 index 0000000000..da56d2dd76 --- /dev/null +++ b/backend/internal/service/account_test_service_ollama_cloud_test.go @@ -0,0 +1,132 @@ +//go:build unit + +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// ollamaCloudTestAccount 构造官方默认 base_url(credentials 不带 base_url)的 +// ollama_cloud 账号,让测试同时钉住「正确回落平台默认端点」这件事。 +func ollamaCloudTestAccount(id int64, credentials map[string]any) *Account { + base := map[string]any{ + "api_key": "sk-ollama-test", + } + for key, value := range credentials { + base[key] = value + } + return &Account{ + ID: id, + Name: "ollama-cloud-test", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Concurrency: 1, + Credentials: base, + Extra: map[string]any{ + OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}, + }, + } +} + +// C36 核心验收:adaptive(ollama_cloud 默认协议)账号依次探测 CC → Anthropic → +// Responses 三个原生端点,URL 正确、无 ?beta=true,不再落入 Claude 测试路径。 +func TestAccountTestService_OllamaCloudAdaptiveProbesAllThreeEndpoints(t *testing.T) { + account := ollamaCloudTestAccount(501, map[string]any{"api_protocol": APIProtocolAdaptive}) + svc, upstream := adaptiveCNAccountTestService( + account, + adaptiveCNChatTestResponse(), + adaptiveCNAnthropicTestResponse(), + adaptiveCNResponsesTestResponse(), + ) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 3) + require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String()) + require.Equal(t, "https://ollama.com/v1/messages", upstream.requests[1].URL.String()) + require.Equal(t, "https://ollama.com/v1/responses", upstream.requests[2].URL.String()) + for i, req := range upstream.requests { + require.Empty(t, req.URL.RawQuery, "request %d must not carry the Claude tester ?beta=true suffix", i) + } + // ollama 官方 host 的 Anthropic 端点强制 Bearer(非 CN 的 x-api-key)。 + require.Equal(t, "Bearer sk-ollama-test", upstream.requests[1].Header.Get("Authorization")) + require.Empty(t, upstream.requests[1].Header.Get("x-api-key")) + // Responses 探针按无状态端点归一化:store=false。 + require.False(t, gjson.GetBytes(upstream.bodies[2], "store").Bool()) + + require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_start"`)) + require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`)) + require.Contains(t, recorder.Body.String(), "已通过原生 /responses 验证") +} + +// 空模型默认取账号 allowed_models 首项(保存期门禁保证非空清单存在)。 +func TestAccountTestService_OllamaCloudEmptyModelDefaultsToAllowedModels(t *testing.T) { + account := ollamaCloudTestAccount(502, map[string]any{"api_protocol": APIProtocolChatCompletions}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + require.Equal(t, "gpt-oss:120b-cloud", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Contains(t, recorder.Body.String(), "gpt-oss:120b-cloud") +} + +// 钉 chat_completions:单端点探测,不触发 Anthropic/Responses。 +func TestAccountTestService_OllamaCloudPinnedChatProtocol(t *testing.T) { + account := ollamaCloudTestAccount(503, map[string]any{"api_protocol": APIProtocolChatCompletions}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String()) + require.Equal(t, "Bearer sk-ollama-test", upstream.requests[0].Header.Get("Authorization")) + require.NotContains(t, upstream.requests[0].URL.Path, "/messages") + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} + +// 钉 anthropic:官方默认 Anthropic base(https://ollama.com)+ /v1/messages, +// 无 ?beta=true,Bearer 鉴权。 +func TestAccountTestService_OllamaCloudPinnedAnthropicProtocol(t *testing.T) { + account := ollamaCloudTestAccount(504, map[string]any{"api_protocol": APIProtocolAnthropic}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "", "", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + req := upstream.requests[0] + require.Equal(t, "https://ollama.com/v1/messages", req.URL.String()) + require.Empty(t, req.URL.RawQuery) + require.Equal(t, "Bearer sk-ollama-test", req.Header.Get("Authorization")) + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} + +// 钉 responses:单端点 /v1/responses + 无状态归一化(store=false)。 +func TestAccountTestService_OllamaCloudPinnedResponsesProtocol(t *testing.T) { + account := ollamaCloudTestAccount(505, map[string]any{"api_protocol": APIProtocolResponses}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + req := upstream.requests[0] + require.Equal(t, "https://ollama.com/v1/responses", req.URL.String()) + require.Equal(t, HTTPUpstreamProfileOpenAI, HTTPUpstreamProfileFromContext(req.Context())) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} diff --git a/backend/internal/service/adaptive_api_protocol_test.go b/backend/internal/service/adaptive_api_protocol_test.go index 3aef38698a..d7fe4da357 100644 --- a/backend/internal/service/adaptive_api_protocol_test.go +++ b/backend/internal/service/adaptive_api_protocol_test.go @@ -264,3 +264,25 @@ func TestFixedCNResponsesProtocolOverridesStaleChatMode(t *testing.T) { }) } } + +// TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses 验证 C31 的连锁 +// 语义:SupportsNativeCNResponses 纳入 ollama_cloud 后,/v1/responses 入站不再被 +// C32 判定降级为 raw CC(https://ollama.com/v1/chat/completions),而是走平台原生 +// /v1/responses 端点;且 normalizeDeepSeekResponsesRequestBody 对 ollama 生效—— +// store 强制 false、previous_response_id 被剥离(Ollama /v1/responses 为 +// non-stateful,透传状态字段会被上游 400)。 +func TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hello","store":true,"previous_response_id":"resp_old","stream":false}`) + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + // api_base_urls 为空 → adaptive 解析到平台默认端点 https://ollama.com/v1。 + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + _, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + require.False(t, gjson.GetBytes(upstream.lastBody, "previous_response_id").Exists()) + require.True(t, gjson.GetBytes(upstream.lastBody, "input").Exists()) +} diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 5d778b75ce..5437a21275 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -332,6 +332,12 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor } // A copied credential must be reviewed before it can share live traffic with its source. duplicate.Schedulable = false + // B2-③ 保存期无价门禁:复制是创建路径的变体,产物与手工创建同样必须过门禁 + // (评审收口)——否则不合规的存量账号可以被无限复制放大。用「将要创建的账号」 + // 校验,credentials/extra 此时已是深拷贝后的最终形态。 + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, duplicate); err != nil { + return nil, err + } if s.accountDuplicateRepo == nil { return nil, errors.New("account duplicate repository is not configured") } @@ -527,6 +533,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou if err != nil { return nil, err } + // B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。 + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil { return nil, err } @@ -574,6 +584,10 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err != nil { return nil, err } + // B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。 + prevPlatform := account.Platform + prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...) + prevSchedulable := ollamaCloudSchedulableBySave(account) var normalizedExtra map[string]any if input.Extra != nil { normalizedExtra, err = normalizeOpenAILongContextBillingUpdateExtra(account, input) @@ -837,6 +851,19 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U } } + // B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。 + // 放在全部字段/Extra 变更应用完、任何写操作之前,credentials(含 + // model_mapping)与 extra(含 allowed_models)读到的都是本次请求生效后的状态。 + // 只在可能改变可出站模型集合(platform / model_mapping / allowed_models) + // 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性 + // 更新放行,避免锁死缺 mapping/清单的存量账号(全对象 PUT 编辑会原样带回 + // credentials/extra,集合未变时不重验)。 + if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } + } + billingSettingsAppliedAtomically := false updater := s.accountBillingRepo if updater == nil { @@ -970,9 +997,11 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp needMixedChannelCheck := input.GroupIDs != nil && !input.SkipMixedChannelCheck - // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。 + // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查/ollama_cloud 保存期门禁共用, + // 避免多次 DB 查询。ollama_cloud 门禁需要读到「变更后状态」(credentials/extra 合并、 + // status/schedulable 切换),所以携带这些输入时也必须预取。 var cachedTargets []*Account - if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil { + if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || input.Schedulable != nil || input.Status != "" || len(input.Extra) > 0 { loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs) if err != nil { return nil, err @@ -1138,6 +1167,15 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp repoUpdates.Schedulable = input.Schedulable } + // B2-③ 保存期无价门禁:批量路径同样不可绕过(评审收口)。先按仓库的同款合并 + // 语义(JSONB 顶层 key 合并 + 列覆盖)算出每个受影响 ollama_cloud 账号「本次 + // 请求生效后的状态」,再复用与单账号 UpdateAccount 相同的门禁与触发收窄判定。 + // 任何账号不合规即整批拒绝、不落库,错误信息点名账号与未定价模型,便于批量 + // 操作定位。 + if err := s.validateOllamaCloudPricingGateForBulkUpdate(input.AccountIDs, targetsByID, repoUpdates); err != nil { + return nil, err + } + // Run bulk update for column/jsonb fields first. if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil { return nil, err @@ -1180,6 +1218,48 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp return result, nil } +// validateOllamaCloudPricingGateForBulkUpdate 把保存期无价门禁应用到批量更新: +// 对每个受影响的 ollama_cloud 账号,先把 AccountBulkUpdate 按仓库 BulkUpdate 的 +// 实际生效方式模拟到「变更后的账号」上(credentials/extra 顶层 key 合并,status/ +// schedulable 列覆盖),再复用 ollamaCloudPricingGateRevalidationNeeded + 门禁本体, +// 与单账号 UpdateAccount 保持同一判定,不另写一份规则。命中不合规时收集全部 +// 违规项,由调用方整批拒绝(不产生任何写入)。 +func (s *adminServiceImpl) validateOllamaCloudPricingGateForBulkUpdate(accountIDs []int64, targetsByID map[int64]*Account, updates AccountBulkUpdate) error { + var failures []string + for _, id := range accountIDs { + current, ok := targetsByID[id] + if !ok || !current.IsOllamaCloud() { + continue + } + next := *current + next.Credentials = mergeMap(nil, current.Credentials) + for key, value := range updates.Credentials { + next.Credentials[key] = value + } + next.Extra = mergeMap(nil, current.Extra) + for key, value := range updates.Extra { + next.Extra[key] = value + } + if updates.Status != nil { + next.Status = *updates.Status + } + if updates.Schedulable != nil { + next.Schedulable = *updates.Schedulable + } + if !ollamaCloudPricingGateRevalidationNeeded(current.Platform, ollamaCloudOutboundModelNames(current), ollamaCloudSchedulableBySave(current), &next) { + continue + } + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil { + failures = append(failures, fmt.Sprintf("#%d(%s): %s", id, current.Name, infraerrors.Message(err))) + } + } + if len(failures) == 0 { + return nil + } + return infraerrors.BadRequest("MODEL_PRICING_MISSING", + fmt.Sprintf("批量更新被 ollama_cloud 保存期门禁拒绝,整批未写入(不合规账号: %s)", strings.Join(failures, "; "))) +} + func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool { for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { if _, ok := credentials[key]; ok { @@ -1307,6 +1387,21 @@ func (s *adminServiceImpl) SetAccountError(ctx context.Context, id int64, errorM } func (s *adminServiceImpl) SetAccountSchedulable(ctx context.Context, id int64, schedulable bool) (*Account, error) { + // B2-③ 保存期无价门禁:手动启用调度(false→true)与保存路径的「启用」是同一 + // 调度准入开关,ollama_cloud 账号必须先过门禁,否则存量不合规账号可被一键放量 + // (评审收口)。判定复用 ollamaCloudSchedulableBySave(active + Schedulable), + // 与单账号 Update 的启用语义一致;停用(true→false)属维护性操作,放行不校验。 + if schedulable { + account, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return nil, err + } + if account.IsOllamaCloud() && !ollamaCloudSchedulableBySave(account) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } + } + } if err := s.accountRepo.SetSchedulable(ctx, id, schedulable); err != nil { return nil, err } diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index c779f5b7f6..6038f3cb56 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -296,6 +296,8 @@ func defaultModelsListCandidateIDs(platform string) []string { return xai.DefaultModelIDs() case PlatformOpenCodeGo: return DefaultOpenCodeGoModelIDs() + case PlatformOllamaCloud: + return DefaultOllamaCloudModelIDs() case PlatformComposite: return compositeDefaultModelsListCandidateIDs() default: @@ -316,7 +318,7 @@ func defaultAllowImageGenerationForPlatform(platform string) bool { func compositeDefaultModelsListCandidateIDs() []string { seen := make(map[string]struct{}) ids := make([]string, 0) - for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} { for _, id := range defaultModelsListCandidateIDs(platform) { if _, ok := seen[id]; ok { continue diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 7a3644a597..0f6c3a523c 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -709,6 +709,9 @@ type adminServiceImpl struct { affiliateService adminRechargeAffiliateAccruer compositeRouteRepo CompositeModelRouteRepository compositeResolver *CompositeRouteResolver + // B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。 + // 生产 wire 注入;直接构造 struct 的单测可为 nil(门禁对 nil 跳过)。 + billingService *BillingService // 分组平台变更后用来失效渠道缓存;可为 nil(缓存会在 TTL 到期后自然重建) channelCacheInvalidator ChannelCacheInvalidator } @@ -752,6 +755,7 @@ func NewAdminService( compositeRouteRepo CompositeModelRouteRepository, compositeResolver *CompositeRouteResolver, channelCacheInvalidator ChannelCacheInvalidator, + billingService *BillingService, ) AdminService { return &adminServiceImpl{ cfg: cfg, @@ -780,6 +784,7 @@ func NewAdminService( affiliateService: affiliateService, compositeRouteRepo: compositeRouteRepo, compositeResolver: compositeResolver, + billingService: billingService, channelCacheInvalidator: channelCacheInvalidator, } diff --git a/backend/internal/service/anthropic_apikey_auth.go b/backend/internal/service/anthropic_apikey_auth.go index 8bd8c4ba8f..f1d666438a 100644 --- a/backend/internal/service/anthropic_apikey_auth.go +++ b/backend/internal/service/anthropic_apikey_auth.go @@ -16,12 +16,15 @@ const ( // Anthropic API-key accounts. Missing or invalid values keep the historical // x-api-key behavior. CN providers using their native Anthropic endpoints // (api_protocol=anthropic) share the same override knob — Kimi/DeepSeek default -// to x-api-key, Zhipu can opt into Authorization: Bearer. +// to x-api-key, Zhipu can opt into Authorization: Bearer. Ollama Cloud accounts +// may read the knob too: it only matters for relay bases (the official +// ollama.com base is forced to Bearer by host in setAnthropicAPIKeyAuthHeader +// regardless of this value). func (a *Account) GetAnthropicAPIKeyAuthScheme() string { if a == nil || a.Type != AccountTypeAPIKey { return AnthropicAPIKeyAuthSchemeXAPIKey } - if a.Platform != PlatformAnthropic && !a.IsCNProvider() { + if a.Platform != PlatformAnthropic && !a.IsCNProvider() && a.Platform != PlatformOllamaCloud { return AnthropicAPIKeyAuthSchemeXAPIKey } diff --git a/backend/internal/service/anthropic_apikey_auth_ollama_test.go b/backend/internal/service/anthropic_apikey_auth_ollama_test.go index 6870d7e299..a935dba490 100644 --- a/backend/internal/service/anthropic_apikey_auth_ollama_test.go +++ b/backend/internal/service/anthropic_apikey_auth_ollama_test.go @@ -142,6 +142,60 @@ func TestSetAnthropicAPIKeyAuthHeader_OllamaCloudForcesBearer(t *testing.T) { } } +// TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride:C34 残余——平台化 +// 的 ollama_cloud 账号挂反代 base 时可经 extra 显式选 Bearer;缺省仍 x-api-key; +// 官方 ollama.com base 的强制 Bearer 不经本函数、不受影响(host 分支先行)。 +func TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride(t *testing.T) { + tests := []struct { + name string + base string + extra map[string]any + want string + }{ + { + name: "反代 base + extra 显式 Bearer → Bearer", + base: "https://relay.example.com", + extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer}, + want: AnthropicAPIKeyAuthSchemeAuthorizationBearer, + }, + { + name: "反代 base 无 extra → 保持 x-api-key", + base: "https://relay.example.com", + want: AnthropicAPIKeyAuthSchemeXAPIKey, + }, + { + name: "官方 ollama.com base 也读 extra(强制 Bearer 由 host 分支保证)", + base: "https://ollama.com", + extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer}, + want: AnthropicAPIKeyAuthSchemeAuthorizationBearer, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := newOllamaCloudAnthropicAuthAccount(tt.base, tt.extra) + account.Platform = PlatformOllamaCloud + require.Equal(t, tt.want, account.GetAnthropicAPIKeyAuthScheme()) + }) + } + + // 官方 base 恒 Bearer 不受 extra 影响:ollama_cloud 账号 + 显式 x_api_key + // extra,host 分支仍强制 Bearer。 + account := newOllamaCloudAnthropicAuthAccount("https://ollama.com", map[string]any{ + anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey, + }) + account.Platform = PlatformOllamaCloud + header := http.Header{} + setAnthropicAPIKeyAuthHeader(header, account, "ollama-cloud-key", "https://ollama.com") + require.Equal(t, "Bearer ollama-cloud-key", header.Get("Authorization")) + require.Empty(t, header.Get("x-api-key")) + + // Anthropic 平台回归:显式 x_api_key extra → x-api-key 不变。 + anthropicAccount := newOllamaCloudAnthropicAuthAccount("https://api.anthropic.com", map[string]any{ + anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey, + }) + require.Equal(t, AnthropicAPIKeyAuthSchemeXAPIKey, anthropicAccount.GetAnthropicAPIKeyAuthScheme()) +} + // TestSetAnthropicAPIKeyAuthHeader_CNAdaptiveBaseURLResolution:adaptive 账号经 // GetCNProtocolBaseURL(anthropic) / GetAnthropicProtocolBaseURL 选出的分协议地址 // 才是判定依据,Chat Completions 地址(GetOpenAIBaseURL 选到的 CC base)不参与。 diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 55e4f08d9b..b5157e5be1 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -836,6 +836,69 @@ func (s *BillingService) initFallbackPricing() { SupportsCacheBreakdown: false, } + // ---- Ollama Cloud 托管模型(ollama 独占,别家无同名条目)---- + // Source: https://ollama.com/pricing(官方定价页,2026-09-12 检索)。 + // 与别家同名的 ollama 模型(glm-5.3 / kimi-k3 / minimax-m3 / deepseek-v4-pro + // 等)复用上方既有同名条目,不在此重复。键名用 /v1/models 的 API id 形态; + // 家族匹配规则见 getFallbackPricing 的 Ollama 分支。Ollama 无 priority tier + // 公布价,*Priority 字段一律不填;未列出的 ollama 模型名保持 nil(白名单 + // 语义,getFallbackPricing 末尾 return nil),显式拒绝而非误配。 + // gpt-oss 两档(120b / 20b)价差约 4 倍,匹配必须按完整 tag 前缀分开, + // 禁止裸 "gpt-oss" 前缀(见 getFallbackPricing)。 + s.fallbackPrices["gpt-oss:120b"] = &ModelPricing{ + InputPricePerToken: 0.15e-6, // $0.15 per MTok + OutputPricePerToken: 0.60e-6, // $0.60 per MTok + CacheReadPricePerToken: 0.014e-6, // $0.014 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + s.fallbackPrices["gpt-oss:20b"] = &ModelPricing{ + InputPricePerToken: 0.07e-6, // $0.07 per MTok + OutputPricePerToken: 0.30e-6, // $0.30 per MTok + CacheReadPricePerToken: 0.035e-6, // $0.035 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + s.fallbackPrices["gemma4:31b"] = &ModelPricing{ + InputPricePerToken: 0.14e-6, // $0.14 per MTok + OutputPricePerToken: 0.40e-6, // $0.40 per MTok + CacheReadPricePerToken: 0.05e-6, // $0.05 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + // mistral-large-3 / qwen3.5 / nemotron-3-nano 官方未公布 cached-input 档 + // (定价页标注 "-",非 0)。CacheReadPricePerToken 为 0 的语义是把缓存输入 + // 按免费计(computeTokenBreakdown 直接乘该字段),为不低估成本,保守取输入价。 + s.fallbackPrices["mistral-large-3:675b"] = &ModelPricing{ + InputPricePerToken: 0.50e-6, // $0.50 per MTok + OutputPricePerToken: 1.50e-6, // $1.50 per MTok + CacheReadPricePerToken: 0.50e-6, // cached-input 未公布,保守按输入价 + SupportsCacheBreakdown: false, + } + s.fallbackPrices["qwen3.5:397b"] = &ModelPricing{ + InputPricePerToken: 0.60e-6, // $0.60 per MTok + OutputPricePerToken: 3.60e-6, // $3.60 per MTok + CacheReadPricePerToken: 0.60e-6, // cached-input 未公布,保守按输入价 + SupportsCacheBreakdown: false, + } + // nemotron 三款价差约 12 倍(输出 $0.24 vs $3.00 per MTok),逐款精确匹配, + // 禁止裸 "nemotron" 兜底前缀(见 getFallbackPricing)。 + s.fallbackPrices["nemotron-3-super"] = &ModelPricing{ + InputPricePerToken: 0.015e-6, // $0.015 per MTok + OutputPricePerToken: 0.60e-6, // $0.60 per MTok + CacheReadPricePerToken: 0.015e-6, // $0.015 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + s.fallbackPrices["nemotron-3-nano:30b"] = &ModelPricing{ + InputPricePerToken: 0.06e-6, // $0.06 per MTok + OutputPricePerToken: 0.24e-6, // $0.24 per MTok + CacheReadPricePerToken: 0.06e-6, // cached-input 未公布,保守按输入价 + SupportsCacheBreakdown: false, + } + s.fallbackPrices["nemotron-3-ultra"] = &ModelPricing{ + InputPricePerToken: 0.10e-6, // $0.10 per MTok + OutputPricePerToken: 3.00e-6, // $3.00 per MTok + CacheReadPricePerToken: 0.10e-6, // $0.10 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + // xAI Grok 4.5: $2 input / $0.30 cached input / $6 output below 200k; // long-context rates are $4 / $0.60 / $12 (>=200k prompt tokens). s.fallbackPrices["grok-4.5"] = &ModelPricing{ @@ -1097,6 +1160,37 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { return s.fallbackPrices["minimax-m2"] } + // ---- Ollama Cloud 托管模型(ollama 独占,Source: https://ollama.com/pricing)---- + // gpt-oss 两档(120b/20b)价差约 4 倍,必须按完整 tag 前缀分开匹配,禁止裸 + // "gpt-oss" 前缀;nemotron 三款价差约 12 倍,逐款精确匹配,禁止裸 "nemotron" + // 兜底。前缀/子串规则天然覆盖 "-cloud" 变体(真实请求形态,见 + // openai_gateway_ollama_cloud_max_tokens_test.go)与其它 tag 后缀。未列出的 + // ollama 模型名沿用白名单语义:落到函数末尾 return nil(拒绝计费)。 + if strings.HasPrefix(modelLower, "gpt-oss:120b") { + return s.fallbackPrices["gpt-oss:120b"] + } + if strings.HasPrefix(modelLower, "gpt-oss:20b") { + return s.fallbackPrices["gpt-oss:20b"] + } + if strings.Contains(modelLower, "gemma4") { + return s.fallbackPrices["gemma4:31b"] + } + if strings.Contains(modelLower, "mistral-large-3") { + return s.fallbackPrices["mistral-large-3:675b"] + } + if strings.HasPrefix(modelLower, "qwen3.5:397b") { + return s.fallbackPrices["qwen3.5:397b"] + } + if strings.Contains(modelLower, "nemotron-3-super") { + return s.fallbackPrices["nemotron-3-super"] + } + if strings.Contains(modelLower, "nemotron-3-nano") { + return s.fallbackPrices["nemotron-3-nano:30b"] + } + if strings.Contains(modelLower, "nemotron-3-ultra") { + return s.fallbackPrices["nemotron-3-ultra"] + } + // 火山方舟 豆包 Embedding(多模态向量化)。 // most-specific-first:放在未来任何 doubao-embedding / doubao 宽匹配之前。 // 覆盖带版本后缀的别名(如 doubao-embedding-vision-251215)。 @@ -1235,7 +1329,26 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) { // getModelPricingAt 是 GetModelPricing 的带计费时点内部变体:pricingAt 显式 // 驱动 DeepSeek pro→Flash 切换判定(切换点前 Pro 价、之后 Flash 价),使 // 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。 +// +// 两级查价:字面名完整跑一遍查找链(LiteLLM → fallback),未命中且名含 +// ":tag" 时用剥 tag 名重跑一次同一查找链(pricingAt 原样传递)。字面优先: +// bedrock canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0) +// 本身含 ":0",字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见 +// normalizePricingModelNameForLookup。 func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) { + pricing, err := s.getModelPricingAtOnce(model, pricingAt) + if err == nil { + return pricing, nil + } + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt); retryErr == nil { + return retry, nil + } + } + return nil, err +} + +func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time) (*ModelPricing, error) { // 标准化模型名称(转小写) model = strings.ToLower(model) diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go index a310288bf9..e1b67371e5 100644 --- a/backend/internal/service/channel_monitor_checker.go +++ b/backend/internal/service/channel_monitor_checker.go @@ -176,6 +176,10 @@ var providerAdapters = map[string]providerAdapter{ MonitorProviderZhipu: providerZhipuChatAdapter, MonitorProviderDeepseek: providerDeepseekChatAdapter, MonitorProviderMiniMax: providerMiniMaxChatAdapter, + // ollama_cloud:官方 OpenAI 兼容 Chat Completions(/v1/chat/completions), + // 与国产 3 家同构;api_mode 仍只支持 chat_completions(responses 探活 + // 仅 openai,见 validateAPIMode)。 + MonitorProviderOllamaCloud: providerOllamaCloudChatAdapter, MonitorProviderAnthropic: { buildPath: func(string) string { return providerAnthropicPath }, buildBody: func(model, prompt string) ([]byte, error) { @@ -230,6 +234,9 @@ var providerDeepseekChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIP //nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。 var providerMiniMaxChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath) +//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。 +var providerOllamaCloudChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath) + func newOpenAICompatibleChatAdapter(path string) providerAdapter { return providerAdapter{ buildPath: func(string) string { return path }, @@ -463,6 +470,8 @@ var bodyMergeKeyDenyList = map[string]map[string]bool{ MonitorProviderZhipu: {"model": true, "messages": true, "stream": true}, MonitorProviderDeepseek: {"model": true, "messages": true, "stream": true}, MonitorProviderMiniMax: {"model": true, "messages": true, "stream": true}, + // ollama_cloud 同为 OpenAI Chat Completions 同构。 + MonitorProviderOllamaCloud: {"model": true, "messages": true, "stream": true}, } func checkAPIMode(opts *CheckOptions) string { diff --git a/backend/internal/service/channel_monitor_const.go b/backend/internal/service/channel_monitor_const.go index 447581ddb2..36af368e98 100644 --- a/backend/internal/service/channel_monitor_const.go +++ b/backend/internal/service/channel_monitor_const.go @@ -70,6 +70,9 @@ const ( MonitorProviderZhipu = "zhipu" MonitorProviderDeepseek = "deepseek" MonitorProviderMiniMax = "minimax" + // MonitorProviderOllamaCloud:官方提供 OpenAI 兼容 /v1/chat/completions, + // 探活复用通用 OpenAI 兼容 adapter(与国产 3 家同构)。 + MonitorProviderOllamaCloud = "ollama_cloud" // MonitorCheckMode 检测模式(channel_monitors.check_mode)。 // probe - LLM 探活(默认,原有行为) @@ -152,7 +155,7 @@ var ( "CHANNEL_MONITOR_NOT_FOUND", "channel monitor not found", ) ErrChannelMonitorInvalidProvider = infraerrors.BadRequest( - "CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax", + "CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ollama_cloud", ) ErrChannelMonitorInvalidCheckMode = infraerrors.BadRequest( "CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota", diff --git a/backend/internal/service/channel_monitor_ollama_cloud_test.go b/backend/internal/service/channel_monitor_ollama_cloud_test.go new file mode 100644 index 0000000000..5acb3c95bf --- /dev/null +++ b/backend/internal/service/channel_monitor_ollama_cloud_test.go @@ -0,0 +1,243 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +// --- provider 放行(M-1 的 service 层一半) --- + +func TestOllamaCloudMonitorProviderAllowlists(t *testing.T) { + require.NoError(t, validateProvider(MonitorProviderOllamaCloud)) + require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, "")) + require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions)) + // responses 探活仍仅 openai(与所有非 openai provider 一致)。 + require.ErrorIs(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeResponses), ErrChannelMonitorInvalidAPIMode) + + // ollama_cloud 官方有 OpenAI 兼容 Chat Completions → 三种模式全部放行 + //(对比 antigravity 只允许 quota)。 + require.True(t, providerSupportsProbe(MonitorProviderOllamaCloud)) + require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeProbe)) + require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuota)) + require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuotaProbe)) +} + +// 行为钉:opencode_go 在 handler binding 里放行、但 service 层 monitorProviders +// 没有(upstream 有单独修复,本分支尚未合入)——钉住现状,防止被误认为本批回归。 +func TestOpenCodeGoMonitorProviderStillMissingFromServiceAllowlist(t *testing.T) { + require.ErrorIs(t, validateProvider("opencode_go"), ErrChannelMonitorInvalidProvider) +} + +// --- 探活 adapter --- + +func TestOllamaCloudMonitorAdapterProbesOpenAIChatCompletions(t *testing.T) { + h := &openAICaptureHandler{} + endpoint := setupFakeOpenAI(t, h) + + res := runCheckForModel(context.Background(), MonitorProviderOllamaCloud, endpoint+"/v1", "sk-ollama", "gpt-oss:120b-cloud", nil) + + require.Equal(t, MonitorStatusOperational, res.Status) + require.Equal(t, providerOpenAIPath, h.lastPath) + require.Equal(t, "gpt-oss:120b-cloud", h.lastBody["model"]) + require.Equal(t, "Bearer sk-ollama", h.lastHeaders.Get("Authorization")) +} + +func TestOllamaCloudMonitorMergeDenyListProtectsChallenge(t *testing.T) { + adapter, apiMode, ok := providerAdapterFor(MonitorProviderOllamaCloud, "") + require.True(t, ok) + require.Equal(t, MonitorAPIModeChatCompletions, apiMode) + + body, err := buildRequestBody(adapter, MonitorProviderOllamaCloud, apiMode, "gpt-oss:120b-cloud", "2+2=?", &CheckOptions{ + BodyOverrideMode: MonitorBodyOverrideModeMerge, + BodyOverride: map[string]any{"model": "evil", "temperature": 0.5}, + }) + require.NoError(t, err) + + var parsed map[string]any + require.NoError(t, json.Unmarshal(body, &parsed)) + require.Equal(t, "gpt-oss:120b-cloud", parsed["model"], "model 命中黑名单不得被覆盖") + require.InDelta(t, 0.5, parsed["temperature"], 0.0001, "非黑名单 key 应正常合并") +} + +// --- quota 取数(C29) --- + +func ollamaCloudQuotaTestAccount(id int64, extra map[string]any) *Account { + return &Account{ + ID: id, + Name: "ollama-quota-test", + Platform: domain.PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-ollama", + "base_url": "https://ollama.com/v1", + }, + Extra: extra, + } +} + +func ollamaCloudUsageSnapshotExtra(status string, fetchedAt time.Time, data *OllamaCloudUsageData, lastError string) map[string]any { + snapshot := map[string]any{ + "status": status, + "last_attempt_at": fetchedAt, + "next_refresh_at": fetchedAt, + "fetched_at": fetchedAt, + } + if data != nil { + snapshot["data"] = data + } + if lastError != "" { + snapshot["last_error"] = lastError + } + return map[string]any{ + OllamaCloudUsageSnapshotExtraKey: snapshot, + } +} + +func TestQuotaFetcher_OllamaCloudOkSnapshotMapsTiersAndBalance(t *testing.T) { + fetcher, usage, cnQuota, cnBalance, accounts := newQuotaFetcherTestSetup(t) + fetchedAt := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second) + accounts.accounts[31] = ollamaCloudQuotaTestAccount(31, ollamaCloudUsageSnapshotExtra( + OllamaCloudUsageStatusOK, fetchedAt, + &OllamaCloudUsageData{ + Plan: "pro", + FiveHour: &OllamaCloudUsageWindow{UsedPercent: 42.5}, + SevenDay: &OllamaCloudUsageWindow{UsedPercent: 10}, + Balance: "$9.50", + }, + "", + )) + + snapshot := fetcher.Fetch(context.Background(), 31) + + require.True(t, snapshot.Success) + require.Equal(t, "ollama_quota", snapshot.Source) + require.Equal(t, "pro", snapshot.PlanLevel) + require.False(t, snapshot.CredentialInvalid) + require.Empty(t, snapshot.Error) + // 快照是被动抓取的历史值:FetchedAt 沿用真实抓取时间。 + require.True(t, fetchedAt.Equal(snapshot.FetchedAt)) + + require.Len(t, snapshot.Tiers, 2) + require.Equal(t, "5h", snapshot.Tiers[0].Window) + require.InDelta(t, 42.5, snapshot.Tiers[0].UsedPercent, 0.001) + require.Equal(t, "7d", snapshot.Tiers[1].Window) + require.InDelta(t, 10, snapshot.Tiers[1].UsedPercent, 0.001) + + require.NotNil(t, snapshot.Balance) + require.InDelta(t, 9.5, *snapshot.Balance, 0.001) + require.Equal(t, "USD", snapshot.Currency) + + require.Equal(t, 0, usage.getCalls(), "ollama 走快照读取,不得打海外 usage 服务") + require.Equal(t, 0, cnQuota.calls) + require.Equal(t, 0, cnBalance.calls) + require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status) +} + +// credits 类账号:只有余额没有窗口 → only-balance 降级(余额文本可解析时透出)。 +func TestQuotaFetcher_OllamaCloudBalanceOnlySnapshot(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + accounts.accounts[32] = ollamaCloudQuotaTestAccount(32, ollamaCloudUsageSnapshotExtra( + OllamaCloudUsageStatusOK, time.Now(), + &OllamaCloudUsageData{Balance: "USD$12"}, + "", + )) + + snapshot := fetcher.Fetch(context.Background(), 32) + + require.True(t, snapshot.Success) + require.Empty(t, snapshot.Tiers) + require.NotNil(t, snapshot.Balance) + require.InDelta(t, 12, *snapshot.Balance, 0.001) +} + +// 无法解析的余额文本跳过(余额仅展示,不做停调判定)。 +func TestQuotaFetcher_OllamaCloudUnparsableBalanceSkipped(t *testing.T) { + _, ok := parseOllamaCloudBalanceUSD("") + require.False(t, ok) + _, ok = parseOllamaCloudBalanceUSD("$9.50 / $20.00") + require.False(t, ok) + + value, ok := parseOllamaCloudBalanceUSD("USD$1,234.50") + require.True(t, ok) + require.InDelta(t, 1234.5, value, 0.001) +} + +// status!=ok(unauthorized/failed)→ 错误快照,带 last_error 与 fetched_at; +// unauthorized 是抓取通道(settings 页会话)过期,不判凭据失效 → 推导 error 而非 failed。 +func TestQuotaFetcher_OllamaCloudFailedSnapshotsYieldErrors(t *testing.T) { + cases := []struct { + name string + status string + wantSub string + }{ + {name: "unauthorized session", status: OllamaCloudUsageStatusUnauthorized, wantSub: "session expired"}, + {name: "scrape failed", status: OllamaCloudUsageStatusFailed, wantSub: "usage page unreachable"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + fetchedAt := time.Now().Add(-3 * time.Hour).UTC() + accounts.accounts[33] = ollamaCloudQuotaTestAccount(33, ollamaCloudUsageSnapshotExtra( + tc.status, fetchedAt, nil, tc.wantSub, + )) + + snapshot := fetcher.Fetch(context.Background(), 33) + + require.False(t, snapshot.Success) + require.False(t, snapshot.CredentialInvalid) + require.Contains(t, snapshot.Error, tc.wantSub) + require.Contains(t, snapshot.Error, "fetched at") + require.Contains(t, snapshot.Error, fetchedAt.Format("2006-01-02")) + require.Equal(t, MonitorStatusError, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status) + }) + } +} + +// eligible=false(host 门禁:反代域名)→ 带原因码的可解释错误,不是笼统报错。 +func TestQuotaFetcher_OllamaCloudIneligibleBaseURLYieldsExplainableError(t *testing.T) { + fetcher, usage, _, _, accounts := newQuotaFetcherTestSetup(t) + account := ollamaCloudQuotaTestAccount(34, nil) + account.Credentials["base_url"] = "https://proxy.example.com/v1" + accounts.accounts[34] = account + + snapshot := fetcher.Fetch(context.Background(), 34) + + require.False(t, snapshot.Success) + require.Contains(t, snapshot.Error, "unsupported_base_url") + require.Equal(t, 0, usage.getCalls()) +} + +// 尚无快照(未配置会话或还没有请求活动)→ 可解释错误。 +func TestQuotaFetcher_OllamaCloudNoSnapshotYieldsExplainableError(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + accounts.accounts[35] = ollamaCloudQuotaTestAccount(35, nil) + + snapshot := fetcher.Fetch(context.Background(), 35) + + require.False(t, snapshot.Success) + require.Contains(t, snapshot.Error, "no ollama cloud usage snapshot yet") +} + +// 回归:opencode_go 仍走 CN quota 路由,kimi coding 仍走 CN quota(kimi 已有 +// 独立用例,这里钉 opencode_go 与 ollama 互不串线)。 +func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) { + fetcher, usage, cnQuota, _, accounts := newQuotaFetcherTestSetup(t) + accounts.accounts[36] = &Account{ID: 36, Platform: domain.PlatformOpenCodeGo, Type: AccountTypeAPIKey} + cnQuota.result = &CNProviderQuotaProbeResult{Success: true} + + snapshot := fetcher.Fetch(context.Background(), 36) + + require.True(t, snapshot.Success) + require.Equal(t, "cn_quota", snapshot.Source) + require.Equal(t, 1, cnQuota.calls) + require.Equal(t, 0, usage.getCalls()) +} diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index 868def18d3..ade5e760c5 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -23,6 +23,8 @@ import ( // - 国产 coding plan(kimi/zhipu/deepseek)→ CNProviderQuotaService.QueryUsageForAccount // - 国产 payg(kimi/deepseek)→ CNProviderBalanceService.QueryBalanceForAccount // (zhipu payg 无公开余额端点,探测会返回该错误,原样透出) +// - ollama_cloud → 账号 extra 里的官方用量快照(OllamaCloudUsageService 随请求 +// 活动被动维护,此处只读取、不实时探测;数据可能陈旧,FetchedAt 如实透出) // 数据源统一接受已加载的 *Account:fetchUncached 路由前 GetByID 一次并传下去, // 下游服务不再各自重载(每次 GetByID 含 proxies/groups 联查)。 // @@ -223,6 +225,8 @@ func (f *ChannelMonitorQuotaFetcher) fetchUncached(ctx context.Context, accountI return f.fetchCNBalance(ctx, account, now) case domain.PlatformOpenCodeGo: return f.fetchCNQuota(ctx, account, now) + case domain.PlatformOllamaCloud: + return f.fetchOllamaCloudQuota(account, now) default: return f.fetchUsage(ctx, account, now) } @@ -455,6 +459,118 @@ func (f *ChannelMonitorQuotaFetcher) fetchCNBalance(ctx context.Context, account return snapshot } +// fetchOllamaCloudQuota ollama_cloud:读取 OllamaCloudUsageService 维护在账号 +// extra 里的官方用量快照(请求活动驱动的被动抓取,此处不做实时探测),映射为 +// 配额快照;FetchedAt 沿用快照真实抓取时间——静默账号的数据会陈旧,时间戳 +// 如实透出,不伪装成刚刚抓取。eligible=false(如 base_url 为反代域名)或 +// 快照缺失/失败时返回带可解释原因的错误快照,而不是笼统的「不支持用量查询」。 +func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now time.Time) *domain.MonitorQuotaSnapshot { + if reason := ollamaCloudUsageEligibilityReason(account); reason != "" { + return quotaErrorSnapshot("ollama_quota", "ollama cloud usage unavailable: "+ollamaCloudUsageReasonHint(reason), now) + } + snapshot := decodeOllamaCloudUsageSnapshot(account.Extra) + if snapshot == nil { + return quotaErrorSnapshot("ollama_quota", + "no ollama cloud usage snapshot yet; snapshots are captured from the official ollama.com usage page on request activity", now) + } + fetchedAt := now + if snapshot.FetchedAt != nil { + fetchedAt = *snapshot.FetchedAt + } + if snapshot.Status != OllamaCloudUsageStatusOK { + return &domain.MonitorQuotaSnapshot{ + Source: "ollama_quota", + // 401 是 settings 页会话过期(抓取通道凭据),不是账号 API key 失效, + // 不置 CredentialInvalid——渠道本身可能仍然健康。 + Success: false, + Error: truncateMessage(sanitizeErrorMessage(fmt.Sprintf( + "ollama cloud usage snapshot status %s (fetched at %s): %s", + snapshot.Status, formatOllamaCloudFetchedAt(snapshot.FetchedAt), + firstNonEmpty(snapshot.LastError, "unknown error")))), + FetchedAt: now, + } + } + if snapshot.Data == nil { + return quotaErrorSnapshot("ollama_quota", + fmt.Sprintf("ollama cloud usage snapshot has no data (fetched at %s)", formatOllamaCloudFetchedAt(snapshot.FetchedAt)), now) + } + out := &domain.MonitorQuotaSnapshot{ + Source: "ollama_quota", + Success: true, + PlanLevel: snapshot.Data.Plan, + FetchedAt: fetchedAt, + } + out.Tiers = ollamaCloudQuotaTiers(snapshot.Data) + if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok { + out.Balance = &balance + out.Currency = "USD" + } + return out +} + +// ollamaCloudQuotaTiers 把官方用量窗口归一为 tier 列表(窗口缺失时跳过)。 +func ollamaCloudQuotaTiers(data *OllamaCloudUsageData) []domain.MonitorQuotaTier { + if data == nil { + return nil + } + tiers := make([]domain.MonitorQuotaTier, 0, 2) + appendOllamaCloudQuotaTier(&tiers, "5h", data.FiveHour) + appendOllamaCloudQuotaTier(&tiers, "7d", data.SevenDay) + if len(tiers) == 0 { + return nil + } + return tiers +} + +func appendOllamaCloudQuotaTier(tiers *[]domain.MonitorQuotaTier, window string, w *OllamaCloudUsageWindow) { + if w == nil { + return + } + tier := domain.MonitorQuotaTier{Window: window, UsedPercent: w.UsedPercent} + if w.ResetAt != nil { + tier.ResetAt = w.ResetAt.UTC().Format(time.RFC3339) + } + *tiers = append(*tiers, tier) +} + +// parseOllamaCloudBalanceUSD 把官方页面抓到的余额文本(如 "$9.50" / "USD$9.50") +// 解析为美元数值;解析失败返回 false(余额仅作展示,无月度信用总额可用于 +// 派生百分比,故 credits 账号只透出余额,不参与 used_percent 告警)。 +func parseOllamaCloudBalanceUSD(raw string) (float64, bool) { + raw = strings.TrimSpace(raw) + raw = strings.TrimPrefix(raw, "USD") + raw = strings.TrimPrefix(raw, "$") + raw = strings.ReplaceAll(strings.TrimSpace(raw), ",", "") + if raw == "" { + return 0, false + } + value, err := strconv.ParseFloat(raw, 64) + if err != nil { + return 0, false + } + return value, true +} + +// ollamaCloudUsageReasonHint 把 EligibleReason 原因码翻译成运维可读的提示 +// (原因码语义见 OllamaCloudUsageState.EligibleReason)。 +func ollamaCloudUsageReasonHint(reason string) string { + switch reason { + case ollamaCloudUsageIneligibleBaseURL: + return "unsupported_base_url (base_url is not the official ollama.com host; usage snapshots are only captured for official-host accounts)" + case ollamaCloudUsageIneligibleAccountType: + return "wrong_account_type (usage snapshots require an apikey account)" + default: + return reason + } +} + +func formatOllamaCloudFetchedAt(t *time.Time) string { + if t == nil { + return "unknown" + } + return t.UTC().Format(time.RFC3339) +} + // quotaErrorSnapshot 构造统一错误快照。 func quotaErrorSnapshot(source, message string, now time.Time) *domain.MonitorQuotaSnapshot { return &domain.MonitorQuotaSnapshot{ diff --git a/backend/internal/service/channel_monitor_template_types.go b/backend/internal/service/channel_monitor_template_types.go index 0b824d577d..99c586ff43 100644 --- a/backend/internal/service/channel_monitor_template_types.go +++ b/backend/internal/service/channel_monitor_template_types.go @@ -55,7 +55,7 @@ var ( "CHANNEL_MONITOR_TEMPLATE_NOT_FOUND", "channel monitor request template not found", ) ErrChannelMonitorTemplateInvalidProvider = infraerrors.BadRequest( - "CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok", + "CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok/ollama_cloud", ) ErrChannelMonitorTemplateInvalidAPIMode = infraerrors.BadRequest( "CHANNEL_MONITOR_TEMPLATE_INVALID_API_MODE", "template api_mode must be chat_completions or responses; responses is only supported for openai", diff --git a/backend/internal/service/channel_monitor_validate.go b/backend/internal/service/channel_monitor_validate.go index 0aa1c248d4..309d3d2269 100644 --- a/backend/internal/service/channel_monitor_validate.go +++ b/backend/internal/service/channel_monitor_validate.go @@ -23,6 +23,7 @@ var monitorProviders = map[string]struct{}{ MonitorProviderZhipu: {}, MonitorProviderDeepseek: {}, MonitorProviderMiniMax: {}, + MonitorProviderOllamaCloud: {}, } // probeCapableProviders 支持探活(probe / quota_probe)的 provider。 @@ -38,6 +39,8 @@ var probeCapableProviders = map[string]struct{}{ MonitorProviderZhipu: {}, MonitorProviderDeepseek: {}, MonitorProviderMiniMax: {}, + // ollama_cloud 官方提供 OpenAI 兼容 /v1/chat/completions,可真实探活。 + MonitorProviderOllamaCloud: {}, } // validateProvider 校验 provider 字符串。 diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go index 0d34f44014..0252ff2393 100644 --- a/backend/internal/service/channel_service.go +++ b/backend/internal/service/channel_service.go @@ -367,7 +367,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool { // fallback used before a request target has been resolved. func matchingPlatforms(groupPlatform string) []string { if groupPlatform == PlatformComposite { - return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} + return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} } return []string{groupPlatform} } diff --git a/backend/internal/service/channel_service_test.go b/backend/internal/service/channel_service_test.go index 9b85aa3e00..9781479cdc 100644 --- a/backend/internal/service/channel_service_test.go +++ b/backend/internal/service/channel_service_test.go @@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) { {"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}}, {"gemini returns itself", PlatformGemini, []string{PlatformGemini}}, {"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}}, - {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}}, + {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud}}, } for _, tt := range tests { diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 7165b29537..c9b3396118 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -531,6 +531,9 @@ func TestNormalizeOpenAICompatiblePlatform_SchedulerExactMatch(t *testing.T) { require.Equal(t, PlatformZhipu, NormalizeOpenAICompatiblePlatform(PlatformZhipu)) require.Equal(t, PlatformDeepseek, NormalizeOpenAICompatiblePlatform(PlatformDeepseek)) require.Equal(t, PlatformOpenCodeGo, NormalizeOpenAICompatiblePlatform(PlatformOpenCodeGo)) + // ollama_cloud 同样保留原值:归一为 openai 会让 ollama_cloud 分组查 openai + // 候选桶 → 静默空池(调度不到账号)。 + require.Equal(t, PlatformOllamaCloud, NormalizeOpenAICompatiblePlatform(PlatformOllamaCloud)) // 其他平台(含空、anthropic、未知)一律归一为 openai。 require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform("")) require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform(PlatformAnthropic)) @@ -642,6 +645,8 @@ func TestGetAPIProtocol(t *testing.T) { require.Equal(t, APIProtocolChatCompletions, (&Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}).GetAPIProtocol(), "非 CN 供应商恒为默认") require.Equal(t, APIProtocolAdaptive, mk(PlatformOpenCodeGo, "").GetAPIProtocol(), "opencode go 默认 adaptive") require.Equal(t, APIProtocolResponses, mk(PlatformOpenCodeGo, APIProtocolResponses).GetAPIProtocol()) + require.Equal(t, APIProtocolAdaptive, mk(PlatformOllamaCloud, "").GetAPIProtocol(), "ollama cloud 默认 adaptive") + require.Equal(t, APIProtocolResponses, mk(PlatformOllamaCloud, APIProtocolResponses).GetAPIProtocol(), "ollama cloud 原生 Responses 端点,显式 responses 不被吞成 adaptive") } func TestSupportsNativeCNResponses(t *testing.T) { @@ -651,6 +656,7 @@ func TestSupportsNativeCNResponses(t *testing.T) { require.True(t, (&Account{Platform: PlatformKimi, Credentials: map[string]any{"account_mode": AccountModeCoding}}).SupportsNativeCNResponses()) require.True(t, (&Account{Platform: PlatformMiniMax}).SupportsNativeCNResponses()) require.True(t, (&Account{Platform: PlatformOpenCodeGo}).SupportsNativeCNResponses()) + require.True(t, (&Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}).SupportsNativeCNResponses(), "ollama cloud 有原生 /v1/responses 端点") require.False(t, (&Account{Platform: PlatformZhipu}).SupportsNativeCNResponses()) require.False(t, (&Account{Platform: PlatformOpenAI}).SupportsNativeCNResponses()) } @@ -812,7 +818,8 @@ func TestBuildOpenAIResponsesURLForPlatform(t *testing.T) { } // TestNormalizeDeepSeekResponsesRequestBody 无状态适配:强制 store=false、 -// 清除 previous_response_id;非原生 CN Responses 协议原样返回。 +// 清除 previous_response_id;携带 conversation 显式报错且不改写 body; +// 非原生 CN Responses 协议原样返回(conversation 也不拦)。 func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { t.Parallel() @@ -821,7 +828,8 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { Credentials: map[string]any{"api_protocol": APIProtocolResponses}, } body := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_123","input":"hi"}`) - normalized := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body) + normalized, err := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(normalized, "store").Bool()) require.False(t, gjson.GetBytes(normalized, "previous_response_id").Exists()) require.Equal(t, "deepseek-v4-pro", gjson.GetBytes(normalized, "model").String()) @@ -830,19 +838,23 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}, } - adaptiveNormalized := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body) + adaptiveNormalized, err := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(adaptiveNormalized, "store").Bool()) require.False(t, gjson.GetBytes(adaptiveNormalized, "previous_response_id").Exists()) // 非 responses 协议(deepseek CC 账号)原样返回 deepseekCC := &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey} - require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(deepseekCC, body))) + untouched, err := normalizeDeepSeekResponsesRequestBody(deepseekCC, body) + require.NoError(t, err) + require.Equal(t, string(body), string(untouched)) kimiResponses := &Account{ Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_protocol": APIProtocolResponses}, } - kimiNormalized := normalizeDeepSeekResponsesRequestBody(kimiResponses, body) + kimiNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiResponses, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(kimiNormalized, "store").Bool()) require.False(t, gjson.GetBytes(kimiNormalized, "previous_response_id").Exists()) @@ -850,13 +862,55 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_protocol": APIProtocolAdaptive, "account_mode": AccountModeCoding}, } - kimiCodingNormalized := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body) + kimiCodingNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(kimiCodingNormalized, "store").Bool()) require.False(t, gjson.GetBytes(kimiCodingNormalized, "previous_response_id").Exists()) // openai 账号原样返回 openai := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey} - require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(openai, body))) + untouched, err = normalizeDeepSeekResponsesRequestBody(openai, body) + require.NoError(t, err) + require.Equal(t, string(body), string(untouched)) + + // ollama cloud adaptive(原生 non-stateful /v1/responses): + // store=false + 剥离 previous_response_id。 + ollamaAdaptive := &Account{ + Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}, + } + ollamaNormalized, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, body) + require.NoError(t, err) + require.False(t, gjson.GetBytes(ollamaNormalized, "store").Bool()) + require.False(t, gjson.GetBytes(ollamaNormalized, "previous_response_id").Exists()) + + // ollama cloud + conversation:显式报错(无状态端点不支持服务端状态字段), + // body 必须保持原样——不是静默剥离。 + conversationBody := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi"}`) + rejected, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, conversationBody) + require.Error(t, err) + require.Contains(t, err.Error(), "conversation") + require.Equal(t, string(conversationBody), string(rejected), "conversation 字段不得被剥离") + + // conversation 与 previous_response_id 并存时同样报错,不做部分清洗。 + mixed := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_1","conversation":"conv_x","input":"hi"}`) + rejected, err = normalizeDeepSeekResponsesRequestBody(deepseekResponses, mixed) + require.Error(t, err) + require.Equal(t, string(mixed), string(rejected)) + + // 无 conversation 时 err 恒为 nil(存量剥离语义不受签名变化影响)。 + _, err = normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body) + require.NoError(t, err) + + // 门禁只对原生 Responses 账号生效:zhipu(无 Responses 端点)带 + // conversation 原样返回、无错误。 + zhipu := &Account{ + Platform: PlatformZhipu, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}, + } + untouched, err = normalizeDeepSeekResponsesRequestBody(zhipu, conversationBody) + require.NoError(t, err) + require.Equal(t, string(conversationBody), string(untouched)) } // TestGetAnthropicAPIKeyAuthScheme_CNProvider CN 账号可经 extra 覆写鉴权方案, diff --git a/backend/internal/service/composite_ollama_ownership_test.go b/backend/internal/service/composite_ollama_ownership_test.go new file mode 100644 index 0000000000..b960623be0 --- /dev/null +++ b/backend/internal/service/composite_ollama_ownership_test.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/model" + "github.com/stretchr/testify/require" +) + +// compositeOwnershipScopedRepo 是尊重查询契约的 fake account repo:只返回同时 +// 满足 groupID、platforms 白名单与 schedulable 的记录,语义与 +// accountRepository.ListModelAvailabilityCandidates 的 group 分支一致 +// (platforms 为空时返回空结果,组隔离由 groupID 保证,配置态由 schedulable +// 保证)。lastPlatforms 记录调用方实际传入的平台集合,供回归断言直接检查。 +type compositeOwnershipScopedRepo struct { + AccountRepository + records []compositeOwnershipScopedRecord + lastPlatforms []string +} + +type compositeOwnershipScopedRecord struct { + groupID int64 + platform string + schedulable bool + account Account +} + +func (r *compositeOwnershipScopedRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + r.lastPlatforms = append([]string(nil), platforms...) + if groupID == nil || len(platforms) == 0 { + return nil, nil + } + allowed := make(map[string]struct{}, len(platforms)) + for _, platform := range platforms { + allowed[platform] = struct{}{} + } + accounts := make([]Account, 0, len(r.records)) + for _, rec := range r.records { + if rec.groupID != *groupID || !rec.schedulable { + continue + } + if _, ok := allowed[rec.platform]; !ok { + continue + } + accounts = append(accounts, rec.account) + } + return accounts, nil +} + +func newOllamaOwnershipResolver(records ...compositeOwnershipScopedRecord) (*CompositeRouteResolver, *compositeOwnershipScopedRepo) { + repo := &compositeOwnershipScopedRepo{records: records} + svc := &GatewayService{accountRepo: repo} + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(svc.resolveCompositeModelOwnership) + return resolver, repo +} + +func mappingAccount(id int64, platform, alias, upstreamModel string) Account { + return Account{ + ID: id, + Platform: platform, + Credentials: map[string]any{ + "model_mapping": map[string]any{alias: upstreamModel}, + }, + } +} + +// 回归护栏:组内只有 ollama_cloud 账号时,ownership 候选查询必须把 +// ollama_cloud 纳入扫描平台集合(compositeOwnershipQueryPlatforms);否则仓库 +// 层按 platforms 白名单过滤会把 ollama 账号整个丢掉,显式别名再也无法被 +// Resolve 识别(detector 刻意无 ollama 分支,只能落 unmatched)。 +// 同组 schedulable=false 与其他组的账号不得混入目标平台。 +func TestResolveCompositeModelOwnershipFindsOllamaCloudAlias(t *testing.T) { + const ( + group = int64(7) + otherGroup = int64(8) + alias = "private-ollama-alias" + upstreamModel = "qwen3-coder" + ) + resolver, repo := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(166, PlatformOllamaCloud, alias, upstreamModel), + }, + // 同组但 schedulable=false:配置态查询不得纳入。 + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformDeepseek, schedulable: false, + account: mappingAccount(163, PlatformDeepseek, alias, "deepseek-v4-pro"), + }, + // 其他组的 schedulable 账号:组隔离不得纳入。 + compositeOwnershipScopedRecord{ + groupID: otherGroup, platform: PlatformDeepseek, schedulable: true, + account: mappingAccount(151, PlatformDeepseek, alias, "deepseek-v4-pro"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud, + "ownership 候选查询必须显式扫描 ollama_cloud,否则组内 ollama 账号不可见") + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccount, decision.Source) + require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform) + require.Empty(t, decision.CandidatePlatforms, "同组不可调度与其他组账号不得构成候选池") +} + +// 最高价值反向对照用例:别名本身是 detector 能识别的真实模型名 +// (MiniMax-M3 → minimax、deepseek-flash → deepseek、k3 → kimi),组内唯一 +// 可调度账号是 ollama_cloud 的显式 mapping。ownership 查询漏掉 ollama_cloud +// 时 Resolve 会回退 detector 并投到上述错误平台;补线后必须走账号目录声明 +// (Source=account,TargetPlatform=ollama_cloud),不得被 detector 冒领。 +func TestResolveCompositeModelOwnershipPrefersOllamaCloudOverDetector(t *testing.T) { + const group = int64(7) + for _, alias := range []string{"MiniMax-M3", "deepseek-flash", "k3"} { + t.Run(alias, func(t *testing.T) { + detected, ok := DetectModelPlatform(alias) + require.True(t, ok, "反向对照别名必须能被 detector 命中") + require.NotEqual(t, PlatformOllamaCloud, detected, "detector 不得直接命中 ollama_cloud") + + resolver, repo := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(166, PlatformOllamaCloud, alias, "gpt-oss:120b"), + }, + // 同组不可调度、以及本可被 detector 投中的平台账号:都不得混入。 + compositeOwnershipScopedRecord{ + groupID: group, platform: detected, schedulable: false, + account: mappingAccount(163, detected, alias, "unused"), + }, + compositeOwnershipScopedRecord{ + groupID: 8, platform: detected, schedulable: true, + account: mappingAccount(151, detected, alias, "unused"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccount, decision.Source, + "必须由账号目录声明解析,而不是 detector 回退") + require.NotEqual(t, CompositeRouteSourceDetector, decision.Source) + require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform) + require.Empty(t, decision.CandidatePlatforms) + }) + } +} + +// 强声明分层:ollama_cloud 与 anthropic 对同一公开别名都有精确 mapping 时, +// 两者同为强声明,必须构成稳定候选池(不是 detector 单平台、也不是静默丢弃 +// ollama)。缺 ollama_cloud 时池退化为 anthropic 单平台,本用例会红。 +func TestResolveCompositeModelOwnershipPoolsOllamaCloudWithStrongClaimer(t *testing.T) { + const ( + group = int64(7) + alias = "MiniMax-M3" + ) + resolver, _ := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(166, PlatformOllamaCloud, alias, "gpt-oss:120b"), + }, + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformAnthropic, schedulable: true, + account: mappingAccount(101, PlatformAnthropic, alias, "claude-sonnet-4-5"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccountPool, decision.Source) + require.Empty(t, decision.TargetPlatform, "多平台强声明不猜单平台") + require.ElementsMatch(t, []string{PlatformAnthropic, PlatformOllamaCloud}, decision.CandidatePlatforms) +} + +// 轻量不变量:ownership 候选扫描范围必须与「全部具体平台」的既有权威清单 +// (model.AllPlatforms)一致;新增平台若只加了 AllPlatforms 而漏掉 ownership, +// 本用例直接红灯,不引入任何新的 runtime registry。 +func TestCompositeOwnershipQueryPlatformsCoverConcretePlatforms(t *testing.T) { + require.ElementsMatch(t, model.AllPlatforms(), compositeOwnershipQueryPlatforms()) +} + +// schedulable=false 的 ollama_cloud 账号不构成候选,且显式别名不得靠 detector +// 兜底;其他组同别名账号同样不得混入(组隔离双向验证)。 +func TestResolveCompositeModelOwnershipSkipsUnschedulableOllamaCloud(t *testing.T) { + const alias = "private-ollama-alias" + resolver, repo := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: 7, platform: PlatformOllamaCloud, schedulable: false, + account: mappingAccount(163, PlatformOllamaCloud, alias, "qwen3-coder"), + }, + compositeOwnershipScopedRecord{ + groupID: 8, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(151, PlatformOllamaCloud, alias, "qwen3-coder"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), 7, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud) + require.False(t, decision.Matched, "不可调度与其他组的 ollama 账号不得被解析为可路由目标") + require.Empty(t, decision.TargetPlatform) +} diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index 64384abb47..6c8fad6f5f 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -149,6 +149,12 @@ func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) { // DetectModelPlatform maps common public model IDs to the concrete provider // platform used by sub2api. It intentionally returns false for ambiguous model // names so composite groups fail closed instead of guessing. +// +// ollama_cloud(与 opencode_go 同理)刻意不在本表:本函数只有模型名入参、没有 +// host 入参,而 ollama 转售的模型家族(gpt-oss / kimi-k2 / glm / deepseek / +// qwen)与上方前缀规则直接冲突(如 gpt- 已映射 openai)——在这里加 ollama +// 分支等于按名字前缀静默错投。ollama_cloud 进入 composite 只走显式 route 与 +// ownership resolver(账号目录),不要给本函数加 ollama 分支。 func DetectModelPlatform(model string) (string, bool) { normalized := strings.ToLower(strings.TrimSpace(model)) if normalized == "" { @@ -281,7 +287,7 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou func isConcreteRequestPlatform(platform string) bool { switch platform { case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, - PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return true default: return false diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index 4d7da09ff6..9377bf67ae 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -199,6 +199,41 @@ func TestDetectModelPlatform(t *testing.T) { {name: "abab unrelated namespace", model: "abab-other", ok: false}, {name: "unknown k3 alias", model: "k3-preview", ok: false}, {name: "unknown", model: "llama-4-maverick", ok: false}, + // --- 行为钉(设计决策,不是漏配)--- + // DetectModelPlatform 刻意不加 ollama 分支(无 host 入参,ollama 转售 + // gpt-oss/kimi-k2/glm/deepseek 家族与上方前缀规则直接冲突,按字面加 + // 分支 = 静默错投)。以下用例钉住 ollama_cloud 默认目录 + // (DefaultOllamaCloudModelIDs)中的典型模型名的当前返回:将来有人 + // 「顺手加 ollama 分支」时这些用例会红灯,提示先回到该决策。 + { + name: "ollama-cloud resale gpt-oss pins to openai (intentional: no ollama branch)", + model: "gpt-oss:120b", + platform: PlatformOpenAI, + ok: true, + }, + { + name: "ollama-cloud resale glm pins to zhipu (intentional: no ollama branch)", + model: "glm-5.3", + platform: PlatformZhipu, + ok: true, + }, + { + name: "ollama-cloud resale kimi pins to kimi (intentional: no ollama branch)", + model: "kimi-k2.6", + platform: PlatformKimi, + ok: true, + }, + { + name: "ollama-cloud resale deepseek pins to deepseek (intentional: no ollama branch)", + model: "deepseek-v4.1-flash", + platform: PlatformDeepseek, + ok: true, + }, + { + name: "ollama-cloud qwen stays unmatched (intentional: fail closed)", + model: "qwen3.5:397b", + ok: false, + }, } for _, tt := range tests { @@ -232,7 +267,7 @@ func TestCompositeGroupSchedulerHasAllCanonicalPlatformBuckets(t *testing.T) { platforms = append(platforms, platform) } require.ElementsMatch(t, - []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}, + []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud}, platforms, ) } @@ -243,3 +278,17 @@ func TestCompositeConcretePlatformsIncludeCNProviders(t *testing.T) { require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, platform)) } } + +// 组合路由准入:ollama_cloud 必须被视为具体请求平台,组合路由才能指向它 +// (迁移 239 已放宽 DB CHECK;代码侧缺这一条会出现「数据库允许、代码不放行」)。 +func TestCompositeConcretePlatformsIncludeOllamaCloud(t *testing.T) { + require.True(t, isConcreteRequestPlatform(PlatformOllamaCloud)) + require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, PlatformOllamaCloud)) + + route, err := compositeRouteFromInput(101, CompositeRouteInput{ + PublicModel: "qwen3-coder", + TargetPlatform: PlatformOllamaCloud, + }) + require.NoError(t, err) + require.Equal(t, PlatformOllamaCloud, route.TargetPlatform) +} diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index 883ac9f0d5..89725e5849 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -49,7 +49,9 @@ const ( PlatformDeepseek = domain.PlatformDeepseek PlatformMiniMax = domain.PlatformMiniMax PlatformOpenCodeGo = domain.PlatformOpenCodeGo - PlatformComposite = domain.PlatformComposite + // PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游。 + PlatformOllamaCloud = domain.PlatformOllamaCloud + PlatformComposite = domain.PlatformComposite // PlatformKiro is retained for unsupported-platform threshold tests and legacy // account rows. Scheduling-threshold evaluation never pauses kiro accounts. PlatformKiro = "kiro" @@ -61,6 +63,9 @@ const ( AccountModeCoding = domain.AccountModeCoding AccountModeZen = domain.AccountModeZen AccountModeGo = domain.AccountModeGo + + AccountModeOllamaLegacy = domain.AccountModeOllamaLegacy // Ollama Cloud legacy:5h / 7d 滚动窗口 + AccountModeOllamaCredits = domain.AccountModeOllamaCredits // Ollama Cloud 月度美元信用池 ) // 上游 API 协议(国产供应商):决定转发端点与格式,与接入模式正交。 @@ -85,6 +90,8 @@ const ( DefaultOpenCodeGoBaseURL = "https://opencode.ai/zen/go/v1" // OpenCode Zen:按量付费网关,模型列表为 /zen/v1/models。 DefaultOpenCodeZenBaseURL = "https://opencode.ai/zen/v1" + // Ollama Cloud:Chat Completions / Responses 共用带 /v1 的基址。 + DefaultOllamaCloudBaseURL = "https://ollama.com/v1" ) // 国产供应商 Anthropic 协议端点的默认 base_url(上游路径为 {base}/v1/messages)。 @@ -98,6 +105,8 @@ const ( // OpenCode Go Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。 DefaultOpenCodeGoAnthropicBaseURL = "https://opencode.ai/zen/go" DefaultOpenCodeZenAnthropicBaseURL = "https://opencode.ai/zen" + // Ollama Cloud Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。 + DefaultOllamaCloudAnthropicBaseURL = "https://ollama.com" ) // IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax)。 @@ -115,10 +124,15 @@ func IsOpenCodeGo(platform string) bool { return platform == PlatformOpenCodeGo } +// IsOllamaCloud 报告 platform 是否为 Ollama Cloud 多协议 API Key 网关。 +func IsOllamaCloud(platform string) bool { + return platform == PlatformOllamaCloud +} + // IsMultiProtocolAPIKeyProvider 报告 platform 是否为多协议 API Key 网关 -// (国产供应商 + OpenCode):走 OpenAI 网关、支持 adaptive 协议分流。 +// (国产供应商 + OpenCode + Ollama Cloud):走 OpenAI 网关、支持 adaptive 协议分流。 func IsMultiProtocolAPIKeyProvider(platform string) bool { - return IsCNProvider(platform) || platform == PlatformOpenCodeGo + return IsCNProvider(platform) || platform == PlatformOpenCodeGo || IsOllamaCloud(platform) } // AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。 @@ -135,11 +149,14 @@ var AllowedQuotaPlatforms = []string{ PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud, } // AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。 // openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露 // 5h/weekly 滚动窗口,纳入阈值评估。deepseek 为余额型,走余额检测而非阈值。 +// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口可等 reset;credits 型是月度美元 +// 信用池、没有窗口 reset,评估器候选恒空(见 ollamaCloudThresholdCandidates)。 var AllowedSchedulingThresholdPlatforms = []string{ PlatformOpenAI, PlatformAnthropic, @@ -148,6 +165,7 @@ var AllowedSchedulingThresholdPlatforms = []string{ PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud, } // IsAllowedQuotaPlatform 报告 s 是否为合法的 quota platform 标识。 diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 37832473c9..8c2810e395 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1428,6 +1428,16 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, for model := range mapping { modelSet[model] = struct{}{} } + } else if acc.IsOllamaCloud() { + // ollama_cloud 空 mapping:extra.allowed_models 清单即公开模型 + // 列表(空映射下公开名=出站名);无清单(deny-all)账号不贡献 + // 任何模型名,与 IsModelSupported 的运行时白名单语义一致。 + if allowed := ollamaCloudOutboundModelNames(&acc); len(allowed) > 0 { + hasAnyMapping = true + for _, model := range allowed { + modelSet[model] = struct{}{} + } + } } } @@ -1466,6 +1476,7 @@ func compositeOwnershipQueryPlatforms() []string { return []string{ PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud, } } diff --git a/backend/internal/service/model_pricing_resolver.go b/backend/internal/service/model_pricing_resolver.go index ecd3d45209..a8f6aac07e 100644 --- a/backend/internal/service/model_pricing_resolver.go +++ b/backend/internal/service/model_pricing_resolver.go @@ -143,10 +143,40 @@ func (r *ModelPricingResolver) resolveConfiguredPricing(config *ChannelModelPric return resolved } +// normalizePricingModelNameForLookup 返回模型名的第二级查价备选:剥掉最后一个 +// ":tag" 后缀(如 "deepseek-v4-flash:0731" → "deepseek-v4-flash")。ok=false 表示 +// 没有可用备选(不含 ":"、":" 在首/末位或剥后为空)。 +// +// 只作字面名 miss 后的第二级 fallback,调用方必须先完成字面查找;严禁把本函数 +// 接入 normalizeChannelPricingModelName 之类的 cache key 归一化——bedrock 的 +// canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)本身含 ":0", +// 字面名与剥 tag 名塌缩成同一 cache key 会静默互覆渠道定价。 +func normalizePricingModelNameForLookup(model string) (string, bool) { + trimmed := strings.TrimSpace(model) + idx := strings.LastIndex(trimmed, ":") + if idx <= 0 || idx == len(trimmed)-1 { + return "", false + } + return trimmed[:idx], true +} + func matchGroupModelPricing(group *Group, model string) *ChannelModelPricing { if group == nil { return nil } + if cp := matchGroupModelPricingOnce(group, model); cp != nil { + return cp + } + // 字面名(含 ":tag")未命中时按剥 tag 名再跑一轮。通配 "prefix*" 本就能 + // 前缀命中带 tag 名,仅 exact 需要补;字面优先,配置名本身带 tag(如 + // bedrock 的 "-v1:0")时字面即命中,不会走到这里。 + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + return matchGroupModelPricingOnce(group, stripped) + } + return nil +} + +func matchGroupModelPricingOnce(group *Group, model string) *ChannelModelPricing { model = normalizeChannelPricingModelName(model) var wildcard *ChannelModelPricing for i := range group.ModelPricing { @@ -187,6 +217,11 @@ func (r *ModelPricingResolver) resolveBasePricing(model string) (*ModelPricing, // // 字面名优先,保证管理员对具体变体的显式配价不被基名覆盖;非 OpenAI 模型 // normalizeKnownOpenAICodexModel 返回空串,此处天然 no-op。 +// +// 重试顺序钉死为:字面 → Codex 归一 → 剥 ":tag"。Codex 归一是官方兜底价已 +// 承认的变体名形状,优先级高于剥 tag;剥 tag 只作最后一级(ollama 的 +// /v1/models 返回名可带 tag,如 deepseek-v4-flash:0731)。字面命中时绝不剥: +// bedrock canonical key(us.anthropic.…-v1:0)本身含 ":0",字面第一步即返回。 func (r *ModelPricingResolver) lookupChannelPricingNormalized(ctx context.Context, groupID int64, model string) *ChannelModelPricing { if r.channelService == nil { return nil @@ -194,11 +229,18 @@ func (r *ModelPricingResolver) lookupChannelPricingNormalized(ctx context.Contex if pricing := r.channelService.GetChannelModelPricing(ctx, groupID, model); pricing != nil { return pricing } + // 第二级:OpenAI/Codex 归一重试(issue #5256,行为不变)。 normalized := normalizeKnownOpenAICodexModel(model) - if normalized == "" || strings.EqualFold(normalized, strings.TrimSpace(model)) { - return nil + if normalized != "" && !strings.EqualFold(normalized, strings.TrimSpace(model)) { + if pricing := r.channelService.GetChannelModelPricing(ctx, groupID, normalized); pricing != nil { + return pricing + } } - return r.channelService.GetChannelModelPricing(ctx, groupID, normalized) + // 第三级:剥 ":tag" 重试(剥后名必与字面名不同,无需再去重)。 + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + return r.channelService.GetChannelModelPricing(ctx, groupID, stripped) + } + return nil } // applyChannelOverrides 应用渠道定价覆盖 diff --git a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go new file mode 100644 index 0000000000..0566ea4f06 --- /dev/null +++ b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go @@ -0,0 +1,152 @@ +//go:build unit + +package service + +// 生产形态复现/回归:动态定价目录已加载(目录含 gpt-5.4)时,8 个 ollama 独占模型 +// 经 BillingService 两级查价的实际解析结果,逐名钉死。 +// +// 真实调用顺序(文件:行号 证据): +// - BillingService.getModelPricingAtOnce(billing_service.go:1351)先跑 +// PricingService.GetModelPricing(动态目录 + 模糊兜底,billing_service.go:1357), +// 命中即短路 fallbackPrices(billing_service.go:1366-1394);miss 才走 +// getFallbackPricing(billing_service.go:1398)。 +// - PricingService.GetModelPricing(pricing_service.go:1128)对任何 "gpt-" 前缀名 +// 进 matchOpenAIModel(pricing_service.go:1151-1153),其末端 catch-all 回落 +// pricingData[openai.DefaultTestModel] = "gpt-5.4"(pricing_service.go:1542-1547; +// internal/pkg/openai/constants.go:50)。 +// - gpt-oss 是开放权重模型、不是 OpenAI 模型:目录无其条目时,名字会被这条 +// catch-all 按 gpt-5.4 价卡($2.5/$15 per MTok)计费,而不是 fallbackPrices 的 +// ollama 价卡($0.15/$0.60 与 $0.07/$0.30,billing_service.go:848-859)。 +// +// 期望值与 TestGetModelPricing_OllamaCloudRealModelList 一致(来源 fallbackPrices +// 的 ollama 条目);差异仅在目录状态:这里模拟「动态目录已加载且含 gpt-5.4」的 +// 生产常态(openAILadderCatalogJSON 即真实目录同步形态)。 + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGetModelPricing_OllamaCloudModelsWithDynamicCatalogLoaded(t *testing.T) { + // 生产形态:动态目录已加载且含 gpt-5.4($2.5/$15 per MTok)。 + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + tests := []struct { + model string + wantInput float64 // USD per token,等于 fallbackPrices 里的 ollama 价卡 + wantOut float64 + }{ + {"gpt-oss:120b", 0.15e-6, 0.60e-6}, + {"gpt-oss:20b", 0.07e-6, 0.30e-6}, + {"gemma4:31b", 0.14e-6, 0.40e-6}, + {"mistral-large-3:675b", 0.50e-6, 1.50e-6}, + {"qwen3.5:397b", 0.60e-6, 3.60e-6}, + {"nemotron-3-super", 0.015e-6, 0.60e-6}, + {"nemotron-3-nano:30b", 0.06e-6, 0.24e-6}, + {"nemotron-3-ultra", 0.10e-6, 3.00e-6}, + } + + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err, "model %s must be priceable with the dynamic catalog loaded", tt.model) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s must bill at its ollama card, not an OpenAI family catch-all", tt.model) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s must bill at its ollama card, not an OpenAI family catch-all", tt.model) + }) + } +} + +// TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion 回归护栏:把 gpt-oss* +// 排除出 OpenAI 回退链后,真实 OpenAI 名字的解析必须不受影响 —— 目录精确命中 / +// 家族 catch-all / 静态兜底三态各钉一例(值 = 目录 gpt-5.4 卡 $2.5/$15)。 +func TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion(t *testing.T) { + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + tests := []struct { + model string + hit string + wantInput float64 + wantOut float64 + }{ + // 目录精确命中:gpt-5.4 本尊走目录价卡。 + {"gpt-5.4", "catalog-exact", 2.5e-6, 1.5e-5}, + // 目录无 gpt-4o 条目:经 OpenAI 链 catch-all 落 DefaultTestModel 目录卡 —— + // 该 catch-all 对真实 OpenAI 名必须保持可达。 + {"gpt-4o", "openai-catch-all", 2.5e-6, 1.5e-5}, + // gpt-5.5 → 业务静态 GPT-5.4 兜底价(openAIGPT54FallbackPricing,$2.5/$15)。 + {"gpt-5.5", "static-gpt54-fallback", 2.5e-6, 1.5e-5}, + } + + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err, "model %s (hit %s)", tt.model, tt.hit) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s (hit %s) input price must stay on the OpenAI chain", tt.model, tt.hit) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s (hit %s) output price must stay on the OpenAI chain", tt.model, tt.hit) + }) + } +} + +// TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace 回归护栏:gpt-oss 的 +// OpenAI 链排除只覆盖冒号命名空间(ollama 命名形态),不得误伤连字符形态。 +// +// - ollama 侧("gpt-oss:120b" / "gpt-oss:20b" / "gpt-oss:120b-cloud"):仍被排除出 +// OpenAI 回退链(PricingService 返回 nil),经 BillingService fallbackPrices 命中 +// ollama 专属价卡($0.15/$0.60 与 $0.07/$0.30 per MTok)。 +// - Antigravity 侧("gpt-oss-120b-medium",domain/constants.go 默认模型映射目标名): +// 不在排除内,恢复进 OpenAI 链的既有行为 —— 经 matchOpenAIModel 末端 catch-all +// 解析到 DefaultTestModel("gpt-5.4") 的目录卡 $2.5/$15 per MTok。收窄前该名被 +// 全局前缀排除拦下,非 Ollama 路径 fail-open 成 0 元记账。 +func TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace(t *testing.T) { + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + t.Run("ollama colon names still on ollama cards", func(t *testing.T) { + tests := []struct { + model string + wantInput float64 + wantOut float64 + }{ + {"gpt-oss:120b", 0.15e-6, 0.60e-6}, + {"gpt-oss:20b", 0.07e-6, 0.30e-6}, + {"gpt-oss:120b-cloud", 0.15e-6, 0.60e-6}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + // 排除生效:PricingService 层对冒号形态仍返回 nil。 + require.Nil(t, bs.pricingService.GetModelPricing(tt.model), + "colon-form gpt-oss name must stay excluded from the OpenAI fallback chain") + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s must bill at its ollama card", tt.model) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s must bill at its ollama card", tt.model) + }) + } + }) + + t.Run("hyphen form back on the OpenAI chain", func(t *testing.T) { + const antigravityModel = "gpt-oss-120b-medium" + // PricingService 层直接命中 OpenAI 链 catch-all 的 gpt-5.4 目录卡。 + ps := bs.pricingService.GetModelPricing(antigravityModel) + require.NotNil(t, ps, "hyphen-form name must re-enter the OpenAI fallback chain") + require.InDelta(t, 2.5e-6, ps.InputCostPerToken, 1e-12) + require.InDelta(t, 1.5e-5, ps.OutputCostPerToken, 1e-12) + + pricing, err := bs.getModelPricingAt(antigravityModel, ollamaPricingAt) + require.NoError(t, err) + require.NotNil(t, pricing) + require.InDelta(t, 2.5e-6, pricing.InputPricePerToken, 1e-12, + "antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open") + require.InDelta(t, 1.5e-5, pricing.OutputPricePerToken, 1e-12, + "antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open") + }) +} diff --git a/backend/internal/service/ollama_cloud_messages_max_tokens.go b/backend/internal/service/ollama_cloud_messages_max_tokens.go index d178488460..4bd1498930 100644 --- a/backend/internal/service/ollama_cloud_messages_max_tokens.go +++ b/backend/internal/service/ollama_cloud_messages_max_tokens.go @@ -2,8 +2,6 @@ package service import ( "strings" - - "github.com/tidwall/gjson" ) // clampOllamaCloudAnthropicMessagesMaxTokens 是 Anthropic Messages 出站 @@ -12,8 +10,8 @@ import ( // 传入本次实际选用的 Anthropic 上游 base_url(GetBaseURL 或 // GetAnthropicProtocolBaseURL,不用 GetOpenAIBaseURL——adaptive 时那是 CC/Responses // 地址),与真实出站组装一样先 TrimRight "/"(urlvalidator 与 -// nativeAnthropicTargetURL 同款归一化),仅当其为 ollama.com 且 body 中映射后出站 -// model 为 DeepSeek 系时压到 cap,否则原样返回。 +// nativeAnthropicTargetURL 同款归一化),命中 ollama.com 即按账号 cap 钳制,不看 +// 模型家族(DeepSeek 系与非 DeepSeek 模型统一 65535),否则原样返回。 func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string, body []byte) []byte { if account == nil || len(body) == 0 { return body @@ -21,8 +19,5 @@ func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string if !isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/")) { return body } - if !isDeepSeekModel(gjson.GetBytes(body, "model").String()) { - return body - } return clampOllamaCloudMaxTokens(account, body) } diff --git a/backend/internal/service/ollama_cloud_messages_max_tokens_test.go b/backend/internal/service/ollama_cloud_messages_max_tokens_test.go index 66b3e6e157..2d5bb4320c 100644 --- a/backend/internal/service/ollama_cloud_messages_max_tokens_test.go +++ b/backend/internal/service/ollama_cloud_messages_max_tokens_test.go @@ -87,14 +87,16 @@ func TestBuildUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens(t *testing.T) { require.Equal(t, int64(256000), gjson.GetBytes(wire, "max_tokens").Int()) }) - t.Run("non deepseek model untouched", func(t *testing.T) { + // D1′ 后 host 命中即钳制:非 DeepSeek 模型同样 clamp(此前该用例钉住 + // 「仅 DeepSeek 系 clamp」的旧行为,上游对 >65535 一律 400 与模型无关)。 + t.Run("non deepseek model is clamped too", func(t *testing.T) { nonDeepSeek := messagesClampBody("k3-256k", 256000) _, wire, err := svc.buildUpstreamRequest( context.Background(), c, account, nonDeepSeek, "sk-test", "api_key", "k3-256k", false, false, ) require.NoError(t, err) - require.Equal(t, int64(256000), gjson.GetBytes(wire, "max_tokens").Int()) + require.Equal(t, int64(65535), gjson.GetBytes(wire, "max_tokens").Int()) }) t.Run("at cap and extra cap zero untouched", func(t *testing.T) { @@ -229,8 +231,8 @@ func TestBuildNativeAnthropicUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens( require.Equal(t, int64(256000), gjson.GetBytes(wireBody, "max_tokens").Int()) }) - // 非 DeepSeek 模型(映射后出站 model)不变。 - t.Run("non deepseek model untouched", func(t *testing.T) { + // 非 DeepSeek 模型(映射后出站 model)按 host 判定同样 clamp(D1′)。 + t.Run("non deepseek model is clamped too", func(t *testing.T) { account := messagesClampOllamaAccount(425, PlatformDeepseek) account.Credentials["api_protocol"] = APIProtocolAnthropic nonDeepSeek := messagesClampBody("glm-4.7", 256000) @@ -240,7 +242,7 @@ func TestBuildNativeAnthropicUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens( context.Background(), c, account, nonDeepSeek, "sk-test", targetURL, ) require.NoError(t, err) - require.Equal(t, int64(256000), gjson.GetBytes(wireBody, "max_tokens").Int()) + require.Equal(t, int64(65535), gjson.GetBytes(wireBody, "max_tokens").Int()) }) } diff --git a/backend/internal/service/ollama_cloud_models.go b/backend/internal/service/ollama_cloud_models.go new file mode 100644 index 0000000000..a4e462e70d --- /dev/null +++ b/backend/internal/service/ollama_cloud_models.go @@ -0,0 +1,36 @@ +package service + +// DefaultOllamaCloudModelIDs 是 Ollama Cloud 的默认模型目录:实测 +// GET https://ollama.com/v1/models(2026-09-12,HTTP 200,20 个模型, +// owned_by 全部为 ollama,含两个带 tag 的快照名)。供分组默认模型列表、 +// composite 候选与 /v1/models 末尾兜底使用;条目均可被计费价目命中 +// (见 ollama_cloud_pricing_test.go 的逐名钉测)。 +// +// 前端同源静态表:frontend/src/composables/useModelWhitelist.ts 的 +// getModelsByPlatform 'ollama_cloud' case 必须与这里保持同一集合, +// 两侧各有测试钉住(ollama_cloud_models_test.go / useModelWhitelist.spec.ts), +// 改动任一侧须同步另一侧。 +func DefaultOllamaCloudModelIDs() []string { + return []string{ + "nemotron-3-super", + "glm-5.3", + "gpt-oss:120b", + "glm-5.3-flash", + "kimi-k2.6", + "kimi-k3", + "deepseek-v4.1-flash", + "minimax-m2.7", + "mistral-large-3:675b", + "glm-5.1", + "glm-5.2", + "gpt-oss:20b", + "qwen3.5:397b", + "kimi-k2.7-code", + "nemotron-3-nano:30b", + "minimax-m3", + "gemma4:31b", + "nemotron-3-ultra", + "deepseek-v4-flash:0731", + "deepseek-v4-pro:0813", + } +} diff --git a/backend/internal/service/ollama_cloud_models_test.go b/backend/internal/service/ollama_cloud_models_test.go new file mode 100644 index 0000000000..b2e536bbf1 --- /dev/null +++ b/backend/internal/service/ollama_cloud_models_test.go @@ -0,0 +1,73 @@ +//go:build unit + +package service + +// C15/C14/C22:ollama_cloud 默认模型清单的数据源钉测。 +// +// 权威数据:GET https://ollama.com/v1/models 实测(2026-09-12,HTTP 200, +// 20 个模型,含 deepseek-v4-flash:0731 / deepseek-v4-pro:0813 两个带 tag 快照名)。 +// +// 前端同源静态表:frontend/src/composables/useModelWhitelist.ts 的 +// getModelsByPlatform 'ollama_cloud' case 必须与 DefaultOllamaCloudModelIDs() +// 保持同一集合,两侧各有测试钉住(对侧:useModelWhitelist.spec.ts), +// 改动任一侧须同步另一侧。 + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestDefaultOllamaCloudModelIDs 钉住目录的形状:数量、去重、无 claude 串入、 +// 带 tag 快照名与各家族代表条目不得缺失。 +func TestDefaultOllamaCloudModelIDs(t *testing.T) { + ids := DefaultOllamaCloudModelIDs() + + require.Len(t, ids, 20) + + seen := make(map[string]struct{}, len(ids)) + for _, id := range ids { + require.NotEmpty(t, id) + require.NotContains(t, seen, id, "duplicate model id %q", id) + seen[id] = struct{}{} + require.NotContains(t, id, "claude", "claude 模型不得串入 ollama_cloud 目录: %q", id) + } + + for _, key := range []string{ + "deepseek-v4-flash:0731", + "deepseek-v4-pro:0813", + "gpt-oss:120b", + "gpt-oss:20b", + "glm-5.3", + "kimi-k3", + "minimax-m3", + "qwen3.5:397b", + } { + require.Contains(t, ids, key) + } +} + +// C15 验收:defaultModelsListCandidateIDs 的 ollama case 返回目录本身; +// C14/C22 验收:composite 候选包含全部 ollama 条目。 +func TestDefaultModelsListCandidateIDs_OllamaCloud(t *testing.T) { + ollama := defaultModelsListCandidateIDs(PlatformOllamaCloud) + require.Equal(t, DefaultOllamaCloudModelIDs(), ollama) + + composite := defaultModelsListCandidateIDs(PlatformComposite) + for _, id := range DefaultOllamaCloudModelIDs() { + require.Contains(t, composite, id) + } +} + +// B2-② 联动断言:目录内每个模型都必须可计费(两级查价非 nil 且单价为正), +// 防止清单与价目表漂移后出现「默认列表 ∩ 定价表 = 空」与保存期门禁打架。 +func TestDefaultOllamaCloudModelIDsAllPriceable(t *testing.T) { + bs := newTestBillingService() + for _, id := range DefaultOllamaCloudModelIDs() { + pricing, err := bs.getModelPricingAt(id, ollamaPricingAt) + require.NoError(t, err, "model %s", id) + require.NotNil(t, pricing, "model %s must be priceable", id) + require.Positive(t, pricing.InputPricePerToken, "model %s", id) + require.Positive(t, pricing.OutputPricePerToken, "model %s", id) + } +} diff --git a/backend/internal/service/ollama_cloud_platform_routing_test.go b/backend/internal/service/ollama_cloud_platform_routing_test.go new file mode 100644 index 0000000000..e8be9dd405 --- /dev/null +++ b/backend/internal/service/ollama_cloud_platform_routing_test.go @@ -0,0 +1,218 @@ +package service + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// ollamaCloudRoutingTestService 返回仅配置宽松 URL 白名单的 service,用于只验证 +// 出站 URL 组装,不发起真实请求。 +func ollamaCloudRoutingTestService() *OpenAIGatewayService { + return &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{ + Enabled: false, + AllowInsecureHTTP: true, + }}}, + } +} + +// TestOllamaCloudDefaultProtocolAndBaseURLs 覆盖 A9/A11/A13 + C30/Q2-3 + C33/Q2-4: +// ollama_cloud 属多协议网关、api_protocol 缺省为 adaptive,且 anthropic 默认 base +// 不带 /v1 而 cc/responses 带 /v1;任何情况下都不得回落到 api.openai.com。 +func TestOllamaCloudDefaultProtocolAndBaseURLs(t *testing.T) { + account := &Account{ + ID: 900, + Name: "ollama-cloud-default", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{}, + } + + require.True(t, account.IsOllamaCloud()) + require.True(t, IsOllamaCloud(PlatformOllamaCloud)) + require.True(t, IsMultiProtocolAPIKeyProvider(PlatformOllamaCloud)) + require.True(t, account.IsMultiProtocolAPIKey()) + + // A11:api_protocol 缺失时 ollama_cloud 缺省 adaptive(不是 CC)。 + require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol()) + require.True(t, account.IsAdaptiveAPIProtocol()) + + // C30/Q2-3:anthropic 默认 base 不带 /v1;cc/responses 带 /v1。 + require.Equal(t, "https://ollama.com", account.defaultCNProtocolBaseURL(APIProtocolAnthropic)) + require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolChatCompletions)) + require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolResponses)) + + // 同一结论经 adaptive 解析链(api_base_urls / base_url 均缺失)。 + require.Equal(t, "https://ollama.com", account.GetCNProtocolBaseURL(APIProtocolAnthropic)) + require.Equal(t, "https://ollama.com/v1", account.GetCNProtocolBaseURL(APIProtocolChatCompletions)) + require.Equal(t, "https://ollama.com/v1", account.GetCNProtocolBaseURL(APIProtocolResponses)) + require.Equal(t, "https://ollama.com", account.GetAnthropicProtocolBaseURL()) + + // C33/Q2-4 + S6 层 1:OpenAI 协议 base 守卫必须接受 ollama_cloud, + // 且缺省端点绝不是官方域名。 + require.Equal(t, DefaultOllamaCloudBaseURL, account.GetOpenAIBaseURL()) + require.NotEqual(t, "https://api.openai.com", account.GetOpenAIBaseURL()) + + // adaptive 下 anthropic 段没有 credentials.base_url 回退,CC 段有。 + withBase := &Account{ + ID: 901, + Name: "ollama-cloud-base-url", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://proxy.example/v1", + }, + Extra: map[string]any{}, + } + require.Equal(t, "https://proxy.example/v1", withBase.GetOpenAIBaseURL()) + require.Equal(t, "https://proxy.example/v1", withBase.GetCNProtocolBaseURL(APIProtocolChatCompletions)) + require.Equal(t, "https://ollama.com", withBase.GetCNProtocolBaseURL(APIProtocolAnthropic)) + require.Equal(t, "https://ollama.com/v1", withBase.GetCNProtocolBaseURL(APIProtocolResponses)) +} + +// TestNativeAnthropicTargetURLOllamaCloudVersionAware 覆盖 S5:nativeAnthropicTargetURL +// 改用版本感知拼接后,base 带 /v1 与不带 /v1 都得到同一个 {base}/v1/messages。 +func TestNativeAnthropicTargetURLOllamaCloudVersionAware(t *testing.T) { + svc := ollamaCloudRoutingTestService() + + cases := []struct { + name string + apiProtocol string + baseURL string + anthropicBase string + want string + }{ + { + name: "explicit anthropic base without version suffix", + apiProtocol: APIProtocolAnthropic, + baseURL: "https://ollama.com", + want: "https://ollama.com/v1/messages", + }, + { + name: "explicit anthropic base with version suffix", + apiProtocol: APIProtocolAnthropic, + baseURL: "https://ollama.com/v1", + want: "https://ollama.com/v1/messages", + }, + { + name: "explicit anthropic base trailing slash", + apiProtocol: APIProtocolAnthropic, + baseURL: "https://ollama.com/", + want: "https://ollama.com/v1/messages", + }, + { + name: "adaptive api_base_urls anthropic with version suffix", + apiProtocol: APIProtocolAdaptive, + anthropicBase: "https://ollama.com/v1", + want: "https://ollama.com/v1/messages", + }, + { + name: "adaptive api_base_urls anthropic without version suffix", + apiProtocol: APIProtocolAdaptive, + anthropicBase: "https://ollama.com", + want: "https://ollama.com/v1/messages", + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + credentials := map[string]any{ + "api_key": "sk-test", + "api_protocol": tt.apiProtocol, + } + if tt.baseURL != "" { + credentials["base_url"] = tt.baseURL + } + if tt.anthropicBase != "" { + credentials["api_base_urls"] = map[string]any{APIProtocolAnthropic: tt.anthropicBase} + } + account := &Account{ + ID: 902, + Name: "ollama-cloud-anthropic", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: credentials, + Extra: map[string]any{}, + } + + targetURL, err := svc.nativeAnthropicTargetURL(account) + require.NoError(t, err) + require.Equal(t, tt.want, targetURL) + }) + } + + // 双向钉住 buildOpenAIEndpointURL 在 messages 场景的边界行为。 + require.Equal(t, "https://ollama.com/v1/messages", buildOpenAIEndpointURL("https://ollama.com", "/v1/messages")) + require.Equal(t, "https://ollama.com/v1/messages", buildOpenAIEndpointURL("https://ollama.com/v1", "/v1/messages")) + require.Equal(t, "https://opencode.ai/zen/go/v1/messages", buildOpenAIEndpointURL("https://opencode.ai/zen/go", "/v1/messages")) + require.Equal(t, "https://opencode.ai/zen/go/v1/messages", buildOpenAIEndpointURL("https://opencode.ai/zen/go/v1", "/v1/messages")) +} + +// TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud 覆盖 C32: +// ollama_cloud 不能被 opencode 的「恒 false」复用,显式 CC 必须走 raw CC。 +func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud(t *testing.T) { + account := func(protocol string) *Account { + return &Account{ + ID: 903, + Name: "ollama-cloud-cc", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": protocol, + }, + Extra: map[string]any{}, + } + } + + require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolChatCompletions))) + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAnthropic))) + // C31 落地后 SupportsNativeCNResponses() 对 ollama 为 true:adaptive / responses + // 不再降级 raw CC,改走平台原生 /v1/responses(连锁验证见 + // TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses)。 + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAdaptive))) + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolResponses))) +} + +// TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally 覆盖 ⑨ findings B1: +// ollama_cloud 账号命中本地估算分支,返回 200 且不产生任何出站请求。 +func TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"claude-sonnet-4-5","system":"You are helpful.","messages":[{"role":"user","content":"hello"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{err: errors.New("local estimate must not hit upstream")} + svc := ollamaCloudRoutingTestService() + svc.httpUpstream = upstream + + account := &Account{ + ID: 904, + Name: "ollama-cloud-count-tokens", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{}, + } + + err := svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "claude-sonnet-4-5") + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Greater(t, gjson.Get(rec.Body.String(), "input_tokens").Int(), int64(0)) + require.Nil(t, upstream.lastReq) + require.Empty(t, upstream.requests) +} diff --git a/backend/internal/service/ollama_cloud_pricing_test.go b/backend/internal/service/ollama_cloud_pricing_test.go new file mode 100644 index 0000000000..e933af54ec --- /dev/null +++ b/backend/internal/service/ollama_cloud_pricing_test.go @@ -0,0 +1,377 @@ +//go:build unit + +package service + +// 计费批 ⑧ 前半:Ollama Cloud 模型定价数据(B2-②)+ ":tag" 模型名两级查价 +// fallback(B2-①)。 +// +// 模型清单来源:curl -s https://ollama.com/v1/models(2026-09-12 实测 HTTP 200, +// 20 个模型,owned_by 全部为 ollama)。价格来源:https://ollama.com/pricing 官方 +// 定价页(见 /tmp/ollama-pricing-data.md 换算表)。 +// +// 命中路径钉死约定: +// - "literal":字面名直接命中(fallback 表精确键 + 专属前缀/子串规则); +// - "family":既有家族规则命中(tag 透明包含于子串/前缀规则); +// - "tag-stripped":字面 miss 后按剥 tag 名第二级命中(B2-① 新增路径)。 +// +// bedrock 回归护栏:bedrock canonical key(us.anthropic.claude-sonnet-4-5-20250929-v1:0) +// 本身含 ":0",字面名必须命中字面条目,剥 tag 只能是字面 miss 后的第二级。 + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// ollamaPricingAt 固定为周一低谷(2026-08-24 12:00 UTC,DeepSeek 低谷时段), +// 使 applyModelSpecificPricingPolicyEx / deepseekPeakMultiplierAt 的输出确定。 +var ollamaPricingAt = time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC) + +// TestGetModelPricing_OllamaCloudRealModelList 覆盖 /v1/models 实测得到的全部 +// 20 个模型名:断言可定价(非 nil)且输入/输出单价均 > 0,并按上面的约定钉死 +// 每个名字的具体命中路径(期望值即该路径唯一解析到的价卡)。 +func TestGetModelPricing_OllamaCloudRealModelList(t *testing.T) { + bs := newTestBillingService() + + tests := []struct { + model string + path string + wantInput float64 // USD per token(低谷/标准档) + wantOut float64 + }{ + // --- ollama 独占 8 款(B2-② 新增,字面命中) --- + {"gpt-oss:120b", "literal", 0.15e-6, 0.60e-6}, + {"gpt-oss:20b", "literal", 0.07e-6, 0.30e-6}, + {"gemma4:31b", "literal", 0.14e-6, 0.40e-6}, + {"mistral-large-3:675b", "literal", 0.50e-6, 1.50e-6}, + {"qwen3.5:397b", "literal", 0.60e-6, 3.60e-6}, + {"nemotron-3-super", "literal", 0.015e-6, 0.60e-6}, + {"nemotron-3-nano:30b", "literal", 0.06e-6, 0.24e-6}, + {"nemotron-3-ultra", "literal", 0.10e-6, 3.00e-6}, + // --- 与别家同名、复用既有条目的 12 款(本批不改其数值) --- + {"glm-5.1", "literal", 1.4e-6, 4.4e-6}, + {"glm-5.2", "literal", 1.4e-6, 4.4e-6}, + {"glm-5.3", "literal", 1.4e-6, 4.4e-6}, + {"glm-5.3-flash", "literal", 0.15e-6, 0.5e-6}, + {"kimi-k3", "literal", 3e-6, 15e-6}, + {"kimi-k2.6", "literal", 0.95e-6, 4e-6}, + // 已知误配:kimi-k2.7-code 经 Contains("kimi-k2") 落 kimi-k2 卡, + // 与 Ollama 实收不符 —— 全局按名计费的独立议题,此处仅钉现状防漂移。 + {"kimi-k2.7-code", "family", 0.56e-6, 2.24e-6}, + {"minimax-m2.7", "literal", 0.30e-6, 1.20e-6}, + {"minimax-m3", "literal", 0.60e-6, 2.40e-6}, + {"deepseek-v4.1-flash", "family", 0.15e-6, 0.60e-6}, // HasPrefix("deepseek-") 兜底,恰好同价 + // 带 tag 名经既有子串规则命中(tag 透明包含,未剥 tag)。 + {"deepseek-v4-flash:0731", "family", 0.15e-6, 0.60e-6}, + {"deepseek-v4-pro:0813", "family", 0.66e-6, 1.98e-6}, + // --- 仓库测试里出现过的真实 "-cloud" 变体形态(前缀/子串规则一并覆盖) --- + {"gpt-oss:120b-cloud", "literal", 0.15e-6, 0.60e-6}, + {"gemma4:31b-cloud", "literal", 0.14e-6, 0.40e-6}, + {"qwen3.5:397b-cloud", "literal", 0.60e-6, 3.60e-6}, + } + + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + require.NotEmpty(t, tt.path, "hit path must be pinned explicitly") + + // 固定时点:值级断言,钉死命中路径解析到的唯一价卡。 + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err, "model %s (path %s) must be priceable", tt.model, tt.path) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s input price must match its pinned hit path (%s)", tt.model, tt.path) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s output price must match its pinned hit path (%s)", tt.model, tt.path) + + // 公开入口(无显式时点):验收口径 —— 非 nil 且输入/输出单价均 > 0。 + public, err := bs.GetModelPricing(tt.model) + require.NoError(t, err) + require.NotNil(t, public) + require.Greater(t, public.InputPricePerToken, 0.0, "model %s", tt.model) + require.Greater(t, public.OutputPricePerToken, 0.0, "model %s", tt.model) + }) + } +} + +// TestNormalizePricingModelNameForLookup 钉住剥 tag helper 的语义边界,并钉住 +// normalizeChannelPricingModelName(纯 cache key 变换)不做任何 tag 预变换。 +func TestNormalizePricingModelNameForLookup(t *testing.T) { + tests := []struct { + in string + want string + wantOK bool + wantSame string // normalizeChannelPricingModelName 的结果必须保持原样(cache key 不做变换) + }{ + {"deepseek-v4-flash:0731", "deepseek-v4-flash", true, "deepseek-v4-flash:0731"}, + {"gpt-oss:120b-cloud", "gpt-oss", true, "gpt-oss:120b-cloud"}, + {"nemotron-3-super", "", false, "nemotron-3-super"}, + {"", "", false, ""}, + {":0731", "", false, ":0731"}, // ":" 在首位,剥后为空 + {"foo:", "", false, "foo:"}, // 尾随 ":",无 tag 可剥 + {"a:b:c", "a:b", true, "a:b:c"}, // 只剥最后一个 ":" 后缀 + {"Foo:0731", "Foo", true, "foo:0731"}, + } + for _, tt := range tests { + got, ok := normalizePricingModelNameForLookup(tt.in) + require.Equal(t, tt.wantOK, ok, "input %q", tt.in) + require.Equal(t, tt.want, got, "input %q", tt.in) + // cache key 归一化禁止接入剥 tag:结果必须保留 ":"(bedrock "…-v1:0" 不塌缩)。 + require.Equal(t, tt.wantSame, normalizeChannelPricingModelName(tt.in), + "normalizeChannelPricingModelName must not transform tags (input %q)", tt.in) + } +} + +// TestGetModelPricing_LiteralTaggedKeyWinsOverStripped 字面优先:定价目录同时含 +// "foo:0" 与 "foo" 时,请求 "foo:0" 必须命中 "foo:0" 的价(不得剥成 "foo")。 +func TestGetModelPricing_LiteralTaggedKeyWinsOverStripped(t *testing.T) { + pricingSvc := newStubPricingServiceFromJSON(t, `{ + "foo:0": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}, + "foo": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 3e-06, "output_cost_per_token": 4e-06} + }`) + bs := NewBillingService(&config.Config{}, pricingSvc) + + pricing, err := bs.getModelPricingAt("foo:0", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 1e-6, pricing.InputPricePerToken, 1e-12, + "literal tagged key must win over the stripped name") + require.InDelta(t, 2e-6, pricing.OutputPricePerToken, 1e-12) +} + +// TestGetModelPricing_TagStrippedFallbackHitsBaseCard 字面 miss 且名含 tag 时, +// 按剥 tag 名完整重跑一次查找链并命中基名价卡(spec 的 qwen3-coder:0731 场景)。 +func TestGetModelPricing_TagStrippedFallbackHitsBaseCard(t *testing.T) { + pricingSvc := newStubPricingServiceFromJSON(t, `{ + "qwen3-coder": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 5e-07, "output_cost_per_token": 6e-06} + }`) + bs := NewBillingService(&config.Config{}, pricingSvc) + + pricing, err := bs.getModelPricingAt("qwen3-coder:0731", ollamaPricingAt) + require.NoError(t, err, "tagged name must fall back to the stripped base name") + require.InDelta(t, 5e-7, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, 6e-6, pricing.OutputPricePerToken, 1e-12) +} + +// TestGetModelPricing_TagStrippedFallbackStillFailClosed 两个层级都 miss 时保持 +// fail-closed(ErrModelPricingUnavailable),不得因剥 tag 引入静默零价。 +func TestGetModelPricing_TagStrippedFallbackStillFailClosed(t *testing.T) { + bs := newTestBillingService() + + _, err := bs.GetModelPricing("qwen3-coder:0731") + require.ErrorIs(t, err, ErrModelPricingUnavailable) + + _, err = bs.GetModelPricing("nemotron-3-mini:9b") // 未列出的 nemotron 型号拒绝 + require.ErrorIs(t, err, ErrModelPricingUnavailable) +} + +// TestGetModelPricing_BedrockCanonicalKeyDoubleEntry bedrock 回归:canonical key +// (含 ":0")与剥后名双 key 并存时,各命中各自条目 —— 字面优先,不做破坏性剥离。 +func TestGetModelPricing_BedrockCanonicalKeyDoubleEntry(t *testing.T) { + pricingSvc := newStubPricingServiceFromJSON(t, `{ + "us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"litellm_provider": "bedrock", "mode": "chat", + "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}, + "us.anthropic.claude-sonnet-4-5-20250929-v1": {"litellm_provider": "bedrock", "mode": "chat", + "input_cost_per_token": 3e-06, "output_cost_per_token": 4e-06} + }`) + bs := NewBillingService(&config.Config{}, pricingSvc) + + tagged, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1:0", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 1e-6, tagged.InputPricePerToken, 1e-12, + "bedrock canonical key with ':0' must hit its own entry, never the stripped one") + + bare, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 3e-6, bare.InputPricePerToken, 1e-12, + "bare bedrock name must hit its own entry") +} + +// TestGetModelPricing_BedrockFallbackFamilyUnaffected 无动态目录时,bedrock +// canonical key 经既有 Claude 家族规则命中 sonnet-4 卡,剥 tag 改动不得影响该路径。 +func TestGetModelPricing_BedrockFallbackFamilyUnaffected(t *testing.T) { + bs := newTestBillingService() + + pricing, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1:0", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 3e-6, pricing.InputPricePerToken, 1e-12) // claude-sonnet-4 卡 + require.InDelta(t, 15e-6, pricing.OutputPricePerToken, 1e-12) +} + +// TestChannelPricing_TaggedModelFallsBackToStrippedKey 渠道价路径(B2-① 第 2 条): +// 渠道只配基名、请求名带 tag 时经剥 tag 重试命中渠道价,而不是落官方兜底价。 +func TestChannelPricing_TaggedModelFallsBackToStrippedKey(t *testing.T) { + groupID := int64(888) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID}) + require.Equal(t, PricingSourceChannel, resolved.Source, + "tagged request name must reach the channel pricing configured on the bare name") + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.4e-6, resolved.BasePricing.InputPricePerToken, 1e-12) +} + +// TestChannelPricing_LiteralTaggedConfigWins 渠道价字面优先:同时配了带 tag 名与 +// 基名时,请求带 tag 名必须命中带 tag 名的显式配价。 +func TestChannelPricing_LiteralTaggedConfigWins(t *testing.T) { + groupID := int64(889) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash:0731"}, 0.9), + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID}) + require.Equal(t, PricingSourceChannel, resolved.Source) + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.9e-6, resolved.BasePricing.InputPricePerToken, 1e-12, + "explicit per-tag channel pricing must win over the stripped base name") +} + +// TestChannelPricing_TagStripMustNotMatchUnrelated 反向保护:剥 tag 后的备选名 +// 不得命中渠道里不相关的配置,未命中时落回官方兜底价。 +func TestChannelPricing_TagStripMustNotMatchUnrelated(t *testing.T) { + groupID := int64(890) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"gpt-5.4"}, 0.9), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID}) + require.NotEqual(t, PricingSourceChannel, resolved.Source, + "stripped lookup must not match an unrelated channel pricing entry") + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.15e-6, resolved.BasePricing.InputPricePerToken, 1e-12, + "should land on the official deepseek-v4-flash fallback card") +} + +// TestApplyChannelOverrides_TaggedModelInheritsLookup B2-① 第 4 条:渠道覆盖 +// applyChannelOverrides 内部走 lookupChannelPricingNormalized,自动继承剥 tag 重试。 +func TestApplyChannelOverrides_TaggedModelInheritsLookup(t *testing.T) { + groupID := int64(891) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := &ResolvedPricing{Mode: BillingModeToken, Source: PricingSourceFallback} + resolved.BasePricing = &ModelPricing{InputPricePerToken: 0.15e-6, OutputPricePerToken: 0.6e-6} + resolver.applyChannelOverrides(context.Background(), groupID, "deepseek-v4-flash:0731", resolved) + + require.Equal(t, PricingSourceChannel, resolved.Source) + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.4e-6, resolved.BasePricing.InputPricePerToken, 1e-12) +} + +// TestMatchGroupModelPricing_TaggedModelExactFallback 分组价路径(B2-① 第 3 条): +// 精确配置 miss 后按剥 tag 名再跑一轮 exact 匹配。 +func TestMatchGroupModelPricing_TaggedModelExactFallback(t *testing.T) { + group := &Group{ + ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }, + } + + cp := matchGroupModelPricing(group, "deepseek-v4-flash:0731") + require.NotNil(t, cp, "tagged request name must fall back to the exact bare-name group pricing") + require.NotNil(t, cp.InputPrice) + require.InDelta(t, 0.4e-6, *cp.InputPrice, 1e-12) +} + +// TestMatchGroupModelPricing_TaggedNilWhenUnmatched 分组价剥 tag 重试不得命中 +// 不相关配置:无任何可命中 pattern 时保持 nil。 +func TestMatchGroupModelPricing_TaggedNilWhenUnmatched(t *testing.T) { + group := &Group{ + ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"gpt-5.4"}, 0.9), + }, + } + + require.Nil(t, matchGroupModelPricing(group, "deepseek-v4-flash:0731")) +} + +// TestMatchGroupModelPricing_WildcardStillMatchesTagged 通配 "prefix*" 本就能 +// 前缀命中带 tag 名,剥 tag 改动不得破坏该路径。 +func TestMatchGroupModelPricing_WildcardStillMatchesTagged(t *testing.T) { + group := &Group{ + ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"gpt-oss:120b*"}, 0.2), + }, + } + + cp := matchGroupModelPricing(group, "gpt-oss:120b-cloud") + require.NotNil(t, cp) + require.NotNil(t, cp.InputPrice) + require.InDelta(t, 0.2e-6, *cp.InputPrice, 1e-12) +} + +// TestMatchGroupModelPricing_BedrockDoubleKey 分组价 bedrock 回归:带 ":0" 与 +// 不带的双 pattern 并存时,各自命中各自条目。 +func TestMatchGroupModelPricing_BedrockDoubleKey(t *testing.T) { + taggedEntry := tokenPricingForModels([]string{"us.anthropic.claude-sonnet-4-5-20250929-v1:0"}, 1.0) + bareEntry := tokenPricingForModels([]string{"us.anthropic.claude-sonnet-4-5-20250929-v1"}, 3.0) + group := &Group{ModelPricing: []ChannelModelPricing{taggedEntry, bareEntry}} + + tagged := matchGroupModelPricing(group, "us.anthropic.claude-sonnet-4-5-20250929-v1:0") + require.NotNil(t, tagged) + require.InDelta(t, 1e-6, *tagged.InputPrice, 1e-12) + + bare := matchGroupModelPricing(group, "us.anthropic.claude-sonnet-4-5-20250929-v1") + require.NotNil(t, bare) + require.InDelta(t, 3e-6, *bare.InputPrice, 1e-12) +} + +// TestOllamaTaggedModelPricingConsistentAcrossSources 一致性(spec 验收):同名 +// 模型在基础价 / 渠道价 / 分组价三种配置下命中同一价格档(0.15e-6 = 官方 +// deepseek-v4-flash 低谷卡)。 +func TestOllamaTaggedModelPricingConsistentAcrossSources(t *testing.T) { + const model = "deepseek-v4-flash:0731" + const tierInput = 0.15e-6 + groupID := int64(892) + bs := newTestBillingService() + + // 基础价(家族匹配) + base, err := bs.getModelPricingAt(model, ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, tierInput, base.InputPricePerToken, 1e-12) + + // 渠道价(剥 tag 命中) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.15), + }) + resolver := NewModelPricingResolver(cs, bs) + chResolved := resolver.Resolve(context.Background(), PricingInput{Model: model, GroupID: &groupID}) + require.NotNil(t, chResolved.BasePricing) + require.InDelta(t, tierInput, chResolved.BasePricing.InputPricePerToken, 1e-12) + + // 分组价(剥 tag exact 命中) + group := &Group{ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.15), + }} + gp := matchGroupModelPricing(group, model) + require.NotNil(t, gp) + require.InDelta(t, tierInput, *gp.InputPrice, 1e-12) +} + +// TestGetModelPricing_OllamaModelsPublicEntryMatchesFixed 公开入口 GetModelPricing +// (内部 timezone.Now)与 getModelPricingAt(固定时点) 在非时点敏感的 ollama 模型上 +// 解析到同一价卡。 +func TestGetModelPricing_OllamaModelsPublicEntryMatchesFixed(t *testing.T) { + bs := newTestBillingService() + + for _, model := range []string{"gpt-oss:120b", "nemotron-3-ultra", "mistral-large-3:675b"} { + fixed, err := bs.getModelPricingAt(model, ollamaPricingAt) + require.NoError(t, err, "model %s", model) + nowPricing, err := bs.GetModelPricing(model) + require.NoError(t, err, "model %s", model) + require.Equal(t, fixed.InputPricePerToken, nowPricing.InputPricePerToken, "model %s", model) + require.Equal(t, fixed.OutputPricePerToken, nowPricing.OutputPricePerToken, "model %s", model) + } +} diff --git a/backend/internal/service/ollama_cloud_scheduling_test.go b/backend/internal/service/ollama_cloud_scheduling_test.go new file mode 100644 index 0000000000..0eab300679 --- /dev/null +++ b/backend/internal/service/ollama_cloud_scheduling_test.go @@ -0,0 +1,147 @@ +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// 本文件覆盖 §11.3 ② 组(C1 + C2 + C6 + C7)与 C10:让 ollama_cloud 分组能 +// 真正调度到账号。缺任一条的表现都是静默空池(候选池按 platform 精确匹配)。 + +// C2:漏了 IsOllamaCloud() 会被 openai_account_scheduler.go 的 +// !IsOpenAICompatible() 过滤掉(filterStats: platform_mismatch)。 +func TestOllamaCloudPlatform_IsOpenAICompatible(t *testing.T) { + t.Parallel() + + acc := &Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey} + require.True(t, acc.IsOpenAICompatible(), "ollama_cloud 账号必须进入 OpenAI 网关候选池") + require.True(t, acc.IsOllamaCloud()) + + // 其他平台的既有语义不变。 + require.True(t, (&Account{Platform: PlatformOpenAI}).IsOpenAICompatible()) + require.False(t, (&Account{Platform: PlatformAnthropic}).IsOpenAICompatible()) + require.False(t, (*Account)(nil).IsOpenAICompatible()) +} + +// C6 + F2:canonical 桶必须覆盖 ollama_cloud,否则 rebuild 不写该桶、缓存永不命中。 +func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) { + t.Parallel() + + platforms := schedulerSnapshotPlatforms() + require.Len(t, platforms, 11) + require.Contains(t, platforms[:], PlatformOllamaCloud) + + seen := make(map[string]struct{}, len(platforms)) + for _, platform := range platforms { + require.NotEmpty(t, platform) + _, dup := seen[platform] + require.Falsef(t, dup, "duplicate platform in schedulerSnapshotPlatforms: %s", platform) + seen[platform] = struct{}{} + } + + // 桶数必须与平台数组长度一致:每平台 single+forced,anthropic/gemini 各多一个 mixed。 + const groupID int64 = 7701 + require.Equal(t, len(platforms)*2+2, schedulerCanonicalBucketCount()) + require.Equal(t, 24, schedulerCanonicalBucketCount()) + + buckets := schedulerCanonicalBuckets(groupID) + require.Len(t, buckets, schedulerCanonicalBucketCount()) + require.Contains(t, buckets, SchedulerBucket{GroupID: groupID, Platform: PlatformOllamaCloud, Mode: SchedulerModeSingle}) + require.Contains(t, buckets, SchedulerBucket{GroupID: groupID, Platform: PlatformOllamaCloud, Mode: SchedulerModeForced}) +} + +// C1 + C2 端到端:ollama_cloud 分组的请求必须能在候选池里选中 ollama_cloud 账号。 +// 若 C1 回退(归一为 openai),mock repo 按 platform 查询会返回空池 → +// ErrNoAvailableAccounts;若 C2 回退,候选过滤会以 platform_mismatch 排除。 +func TestOllamaCloudPlatform_EntersOpenAISchedulerCandidatePool(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + + ctx := context.Background() + groupID := int64(7702) + accounts := []Account{ + { + ID: 77021, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "ollama-key", "base_url": "https://ollama.com/v1"}, + // 运行时白名单生效后,空 mapping 且无清单的 ollama_cloud 账号是 + // deny-all(保存期门禁本就拒绝该配置),夹具必须声明清单才能入选。 + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}}, + }, + { + ID: 77022, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + }, + } + cfg := &config.Config{} + cfg.Gateway.Scheduling.LoadBatchEnabled = false + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}, + cache: &schedulerTestGatewayCache{}, + cfg: cfg, + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}), + } + + selection, decision, err := svc.SelectAccountWithSchedulerForCapability( + ctx, + &groupID, + "", + "", + "gpt-oss:120b", + nil, + OpenAIUpstreamTransportAny, + OpenAIEndpointCapabilityChatCompletions, + false, + false, + false, + PlatformOllamaCloud, + ) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotNil(t, selection.Account) + require.Equal(t, int64(77021), selection.Account.ID, "ollama_cloud 分组必须命中 ollama_cloud 账号而不是 openai 账号") + require.Equal(t, openAIAccountScheduleLayerLoadBalance, decision.Layer) + + // 反向控制:openai 分组的池里不得出现 ollama_cloud 账号(平台精确匹配)。 + openAISelection, _, err := svc.SelectAccountWithSchedulerForCapability( + ctx, + &groupID, + "", + "", + "gpt-oss:120b", + nil, + OpenAIUpstreamTransportAny, + OpenAIEndpointCapabilityChatCompletions, + false, + false, + false, + PlatformOpenAI, + ) + require.NoError(t, err) + require.NotNil(t, openAISelection) + require.NotNil(t, openAISelection.Account) + require.Equal(t, int64(77022), openAISelection.Account.ID, "openai 分组不得命中 ollama_cloud 账号") +} + +// C10:TestCredentials 的 default 分支会返回 unsupported platform → 管理端 +// 「测试凭证」对新平台必定失败。 +func TestOllamaCloudPlatform_TestCredentialsSupported(t *testing.T) { + t.Parallel() + + svc := &AccountService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{ + {ID: 77031, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}, + }}, + } + require.NoError(t, svc.TestCredentials(context.Background(), 77031)) +} diff --git a/backend/internal/service/ollama_cloud_usage.go b/backend/internal/service/ollama_cloud_usage.go index 08f1cbbcc6..5924e23bb0 100644 --- a/backend/internal/service/ollama_cloud_usage.go +++ b/backend/internal/service/ollama_cloud_usage.go @@ -13,6 +13,7 @@ import ( "math/rand/v2" "net/http" "net/url" + "slices" "strconv" "strings" "sync" @@ -39,6 +40,10 @@ const ( // floor inside the SQL due filter. OllamaCloudUsageMinFetchInterval = ollamaCloudUsageMinIntervalMinutes * time.Minute + // 决策记录:抓取目标恒为官方 settings 页,硬编码且不做可配置——保住 + // isExactOllamaCloudSettingsURL 的 host 门禁、不扩大 SSRF 面(请求发出前与 + // 重定向后都复核该 URL)。反代账号 eligible=false 是预期,见 + // IsOllamaCloudUsageAccount 注释。 ollamaCloudUsageSettingsURL = "https://ollama.com/settings" ollamaCloudUsageDefaultIntervalMinutes = 60 ollamaCloudUsageMinIntervalMinutes = 15 @@ -62,8 +67,13 @@ var ( ErrOllamaCloudUsageUnavailable = infraerrors.ServiceUnavailable( "OLLAMA_CLOUD_USAGE_UNAVAILABLE", "Ollama Cloud usage is unavailable", ) + // 文案由平台白名单(OllamaCloudUsagePlatforms)派生,白名单变化时不再漂移; + // 错误码 OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID 是对外契约,不得改名。 + ollamaCloudUsageAccountInvalidMessage = "account must be an official Ollama Cloud API key account (platform " + + strings.Join(OllamaCloudUsagePlatforms, "/") + ") using https://ollama.com" + ErrOllamaCloudUsageAccountInvalid = infraerrors.BadRequest( - "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID", "account must be an OpenAI or Anthropic API key account using https://ollama.com", + "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID", ollamaCloudUsageAccountInvalidMessage, ) ErrOllamaCloudUsageSessionRequired = infraerrors.BadRequest( "OLLAMA_CLOUD_USAGE_SESSION_REQUIRED", "an Ollama web session must be configured first", @@ -148,8 +158,22 @@ type OllamaCloudUsageSnapshot struct { // OllamaCloudUsageState is the dedicated DTO exposed to administrators. type OllamaCloudUsageState struct { - AccountID int64 `json:"account_id"` - Eligible bool `json:"eligible"` + AccountID int64 `json:"account_id"` + Eligible bool `json:"eligible"` + // EligibleReason 说明 eligible=false 的具体原因("" 表示合格): + // platform_not_eligible / wrong_account_type / unsupported_base_url, + // 供管理端区分「平台不合规 / 类型不对 / base_url 反代」。 + EligibleReason string `json:"eligible_reason,omitempty"` + // Mode 是 Ollama Cloud 双额度模式:ollama_legacy(5h/7d 滚动窗口)/ + // ollama_credits(月度美元信用池),由 GetOllamaCloudAccountMode 解析 + // credentials.account_mode,未设置或值不认识时保守默认 legacy。 + // 非 ollama_cloud 平台(含用量白名单里的 legacy 宿主平台)留空。 + Mode string `json:"mode,omitempty"` + // MonthlyCreditUSD 是 credits 模式的月度信用池分母(USD),读 + // credentials.monthly_credit_usd(建号表单录入)。凭据缺失、无法解析或 + // 非正数时为 nil——表示「无该字段」,不报错也不填假值,前端回落为只 + // 展示原始余额文本。 + MonthlyCreditUSD *float64 `json:"monthly_credit_usd,omitempty"` Configured bool `json:"configured"` AutoRefreshEnabled bool `json:"auto_refresh_enabled"` EncryptionKeyConfigured bool `json:"encryption_key_configured"` @@ -997,7 +1021,16 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState { return state } state.AccountID = account.ID - state.Eligible = IsOllamaCloudUsageAccount(account) + // mode / monthly credit 在资格判定之前填充:不合格的 ollama_cloud 账号 + // (反代 base_url、oauth 类型)同样带着额度模式与原因码下发,供管理端 + // 解释「为什么没有窗口/余额」。GetOllamaCloudAccountMode 对非 + // ollama_cloud 平台返回空串,Mode 随 omitempty 留空。 + state.Mode = account.GetOllamaCloudAccountMode() + if credit := account.GetCredentialAsFloat64("monthly_credit_usd"); credit > 0 { + state.MonthlyCreditUSD = &credit + } + state.EligibleReason = ollamaCloudUsageEligibilityReason(account) + state.Eligible = state.EligibleReason == "" if !state.Eligible { return state } @@ -1007,26 +1040,70 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState { return state } -// isOllamaCloudUsagePlatform 收敛 Ollama Cloud 用量窗口的平台白名单。官方 -// ollama.com base_url 除官方两平台外,也允许挂在经 OpenAI 网关转发的国产 -// OpenAI 兼容平台下(用户把 Ollama Cloud key 挂在 kimi/zhipu/deepseek 分组 -// 里跑托管的 glm/kimi/deepseek 模型)。repository 侧 SQL 白名单 -// (ollamaCloudUsagePlatformsSQL)是本列表的镜像,两侧必须同步修改。 -func isOllamaCloudUsagePlatform(platform string) bool { - switch platform { - case PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax: - return true - default: - return false - } +// ollamaCloudUsageLegacyPlatforms 是 platform 化之前承载官方 ollama.com +// base_url 的宿主平台(openai/anthropic 与经 OpenAI 网关转发的国产 OpenAI +// 兼容平台——用户把 Ollama Cloud key 挂在 kimi/zhipu/deepseek 等分组里跑托管 +// 模型)。存量账号迁到 platform=ollama_cloud(增量 6 存量改写)之前仍靠它进入 +// 用量链路。 +var ollamaCloudUsageLegacyPlatforms = []string{ + PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, } -func IsOllamaCloudUsageAccount(account *Account) bool { - if account == nil || account.Type != AccountTypeAPIKey || !isOllamaCloudUsagePlatform(account.Platform) { - return false +// OllamaCloudUsagePlatforms 是 Ollama Cloud 用量平台白名单的权威列表 +// (legacy 宿主平台 + platform=ollama_cloud 本体)。repository 侧 SQL 白名单 +// ollamaCloudUsagePlatformsSQL 直接由本列表派生,新增平台只改这里。 +var OllamaCloudUsagePlatforms = append(slices.Clone(ollamaCloudUsageLegacyPlatforms), PlatformOllamaCloud) + +// ollamaCloudUsageIneligible* 是 EligibleReason 的取值(D9):与 +// ollamaCloudUsageEligibilityReason 的判定顺序一一对应。 +const ( + ollamaCloudUsageIneligiblePlatform = "platform_not_eligible" + ollamaCloudUsageIneligibleAccountType = "wrong_account_type" + ollamaCloudUsageIneligibleBaseURL = "unsupported_base_url" +) + +// isOllamaCloudUsagePlatform 收敛 Ollama Cloud 用量窗口的平台白名单:新 +// platform 本体 + platform 化之前的 legacy 宿主平台。 +func isOllamaCloudUsagePlatform(platform string) bool { + return platform == PlatformOllamaCloud || slices.Contains(ollamaCloudUsageLegacyPlatforms, platform) +} + +// ollamaCloudUsageEligibilityReason 返回账号进不了用量链路的具体原因("" +// 表示三条件全部通过)。IsOllamaCloudUsageAccount 与 +// OllamaCloudUsageStateFromAccount 共用本判定,避免两份条件各自漂移。 +func ollamaCloudUsageEligibilityReason(account *Account) string { + if account == nil { + return "" + } + if !isOllamaCloudUsagePlatform(account.Platform) { + return ollamaCloudUsageIneligiblePlatform + } + if account.Type != AccountTypeAPIKey { + return ollamaCloudUsageIneligibleAccountType } baseURL, _ := account.Credentials["base_url"].(string) - return isOllamaCloudBaseURL(baseURL) + if !isOllamaCloudBaseURL(baseURL) { + return ollamaCloudUsageIneligibleBaseURL + } + return "" +} + +// IsOllamaCloudUsageAccount 报告账号是否进入 Ollama Cloud 用量链路。三个条件 +// 全部满足才为 true: +// - 平台在白名单内(platform=ollama_cloud 或 legacy 宿主平台); +// - 类型为 apikey(用量身份复用账号的官方 API key,oauth 账号没有); +// - credentials.base_url 是官方 ollama.com host(严格 https、无多余 +// path/query,见 isOllamaCloudBaseURL)。 +// +// platform=ollama_cloud 账号同样受 host 门禁约束:反代域名即使平台合规也是 +// eligible=false——这是预期行为(抓取恒打官方 settings 页,见 +// ollamaCloudUsageSettingsURL 的决策记录),不是 bug。原因码见 +// OllamaCloudUsageState.EligibleReason。 +func IsOllamaCloudUsageAccount(account *Account) bool { + if account == nil { + return false + } + return ollamaCloudUsageEligibilityReason(account) == "" } func isOllamaCloudBaseURL(raw string) bool { diff --git a/backend/internal/service/ollama_cloud_usage_test.go b/backend/internal/service/ollama_cloud_usage_test.go index 5fcfd7e407..d8857e6b48 100644 --- a/backend/internal/service/ollama_cloud_usage_test.go +++ b/backend/internal/service/ollama_cloud_usage_test.go @@ -471,6 +471,12 @@ func TestIsOllamaCloudUsageAccountStrictOfficialHost(t *testing.T) { {"https://ollama.com", PlatformKimi, true}, {"https://www.ollama.com/v1", PlatformZhipu, true}, {"https://ollama.com:443", PlatformDeepseek, true}, + // platform=ollama_cloud 本体:官方 host 通过。 + {"https://ollama.com", PlatformOllamaCloud, true}, + {"https://www.ollama.com/v1", PlatformOllamaCloud, true}, + // platform=ollama_cloud 但 base_url 是反代域名:host 门禁不变,仍不合格。 + {"https://ollama.example.test", PlatformOllamaCloud, false}, + {"https://api.ollama-cloud.test/v1", PlatformOllamaCloud, false}, // 用量窗口不随 base_url 放开到其余平台。 {"https://ollama.com", PlatformGemini, false}, {"https://ollama.com", PlatformGrok, false}, @@ -497,7 +503,7 @@ func TestIsOllamaCloudUsageAccountStrictOfficialHost(t *testing.T) { // oauth 类型账号即使平台与 base_url 都命中也不进用量窗口(仅 apikey 账号)。 func TestIsOllamaCloudUsageAccountRejectsOAuthType(t *testing.T) { - for _, platform := range []string{PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} { + for _, platform := range []string{PlatformOllamaCloud, PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} { account := ollamaUsageAccount(1) account.Platform = platform account.Type = AccountTypeOAuth @@ -505,6 +511,164 @@ func TestIsOllamaCloudUsageAccountRejectsOAuthType(t *testing.T) { } } +// OllamaCloudUsageState.EligibleReason:三种不合格各自返回对应原因码,合格时 +// 原因为空;与 IsOllamaCloudUsageAccount 判定保持一致。 +func TestOllamaCloudUsageStateEligibleReason(t *testing.T) { + tests := []struct { + name string + mutate func(account *Account) + // eligible 期望值;reason 为 "" 时断言合格且原因码为空。 + reason string + }{ + { + name: "platform 不在白名单", + mutate: func(account *Account) { account.Platform = PlatformGemini }, + reason: "platform_not_eligible", + }, + { + name: "oauth 类型", + mutate: func(account *Account) { account.Type = AccountTypeOAuth }, + reason: "wrong_account_type", + }, + { + name: "反代 base_url", + mutate: func(account *Account) { account.Credentials["base_url"] = "https://ollama.example.test" }, + reason: "unsupported_base_url", + }, + { + name: "platform=ollama_cloud + 官方 host 合格", + mutate: func(account *Account) { + account.Platform = PlatformOllamaCloud + account.Extra[OllamaCloudUsageSessionExtraKey] = "cipher:wos-session=secret" + }, + reason: "", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + account := ollamaUsageAccount(1) + account.Platform = PlatformOllamaCloud + test.mutate(account) + + state := OllamaCloudUsageStateFromAccount(account) + require.Equal(t, state.EligibleReason == "", state.Eligible) + require.Equal(t, test.reason, state.EligibleReason) + require.Equal(t, test.reason == "", IsOllamaCloudUsageAccount(account)) + if test.reason == "" { + require.True(t, state.Configured) + } + }) + } + + // nil 账号保持既有行为:空 state、不合格、无原因码。 + state := OllamaCloudUsageStateFromAccount(nil) + require.False(t, state.Eligible) + require.Empty(t, state.EligibleReason) +} + +// OllamaCloudUsageState 的双额度字段(D7):mode 由 GetOllamaCloudAccountMode +// 解析(缺省/不认识 → legacy,非 ollama_cloud 平台留空),monthly_credit_usd +// 缺失或非法时为 nil(无该字段语义,不报错不填假值)。 +func TestOllamaCloudUsageStateModeAndMonthlyCredit(t *testing.T) { + tests := []struct { + name string + credentials map[string]any + wantMode string + wantMonthlyCredit *float64 + }{ + { + name: "未设置 account_mode 默认 legacy,无月度信用池", + credentials: map[string]any{}, + wantMode: AccountModeOllamaLegacy, + }, + { + name: "显式 legacy", + credentials: map[string]any{"account_mode": AccountModeOllamaLegacy}, + wantMode: AccountModeOllamaLegacy, + }, + { + name: "credits + 月度信用池 60(JSONB 数字为 float64)", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(60)}, + wantMode: AccountModeOllamaCredits, + wantMonthlyCredit: float64Ptr(60), + }, + { + name: "月度信用池手写字符串也可解析", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": "300"}, + wantMode: AccountModeOllamaCredits, + wantMonthlyCredit: float64Ptr(300), + }, + { + name: "credits 但信用池缺失 → 只透出 mode", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "信用池为 0 / 负数 / 垃圾值 → 视为无该字段", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(0)}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "不认识的 mode 值保守回落 legacy", + credentials: map[string]any{"account_mode": "ollama_turbo"}, + wantMode: AccountModeOllamaLegacy, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + account := ollamaUsageAccount(1) + account.Platform = PlatformOllamaCloud + account.Credentials = map[string]any{"base_url": "https://ollama.com", "api_key": "key-1"} + for key, value := range test.credentials { + account.Credentials[key] = value + } + + state := OllamaCloudUsageStateFromAccount(account) + require.True(t, state.Eligible) + require.Equal(t, test.wantMode, state.Mode) + if test.wantMonthlyCredit == nil { + require.Nil(t, state.MonthlyCreditUSD) + } else { + require.NotNil(t, state.MonthlyCreditUSD) + require.InDelta(t, *test.wantMonthlyCredit, *state.MonthlyCreditUSD, 1e-9) + } + }) + } + + // 非 ollama_cloud 平台(legacy 宿主平台)mode 留空,JSON 随 omitempty 缺省。 + hostAccount := ollamaUsageAccount(2) + hostAccount.Credentials["account_mode"] = AccountModeOllamaCredits + hostState := OllamaCloudUsageStateFromAccount(hostAccount) + require.Empty(t, hostState.Mode) + + payload, err := json.Marshal(hostState) + require.NoError(t, err) + require.NotContains(t, string(payload), `"mode"`) + + // credits 账号的 JSON 形状:mode + monthly_credit_usd 均按 tag 透出。 + creditsAccount := ollamaUsageAccount(3) + creditsAccount.Platform = PlatformOllamaCloud + creditsAccount.Credentials["account_mode"] = AccountModeOllamaCredits + creditsAccount.Credentials["monthly_credit_usd"] = float64(60) + creditsState := OllamaCloudUsageStateFromAccount(creditsAccount) + payload, err = json.Marshal(creditsState) + require.NoError(t, err) + require.Contains(t, string(payload), `"mode":"ollama_credits"`) + require.Contains(t, string(payload), `"monthly_credit_usd":60`) +} + +// 错误文案由平台白名单派生(D2):platform 化后必须包含 ollama_cloud,不再 +// 残留「OpenAI or Anthropic」旧文案;错误码是对外契约,保持不变。 +func TestOllamaCloudUsageAccountInvalidMessageDerivedFromWhitelist(t *testing.T) { + message := ErrOllamaCloudUsageAccountInvalid.Error() + require.Contains(t, message, "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID") + require.Contains(t, message, "ollama_cloud") + for _, platform := range OllamaCloudUsagePlatforms { + require.Contains(t, message, platform) + } + require.NotContains(t, message, "OpenAI or Anthropic") +} + func TestNormalizeOllamaCloudUsageCookieAllowlist(t *testing.T) { normalized, err := normalizeOllamaCloudUsageCookie(" tracking=discard ; wos-session=secret ; __Secure-authjs.session-token.0=part-a ; device=discard ") require.NoError(t, err) @@ -666,7 +830,7 @@ func TestAccountServiceUpdateStripsOllamaManagedExtra(t *testing.T) { OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": OllamaCloudUsageStatusOK}, } repo := &ollamaManagedExtraUpdateRepo{account: account} - svc := NewAccountService(repo, nil) + svc := NewAccountService(repo, nil, nil) requestedExtra := map[string]any{ "note": "preserved", OllamaCloudUsageSessionExtraKey: "forged-ciphertext", diff --git a/backend/internal/service/openai_apikey_responses_probe.go b/backend/internal/service/openai_apikey_responses_probe.go index 5b2d92c69a..24a4687c9b 100644 --- a/backend/internal/service/openai_apikey_responses_probe.go +++ b/backend/internal/service/openai_apikey_responses_probe.go @@ -99,7 +99,8 @@ func selectResponsesProbeModel(account *Account) string { // ProbeOpenAIAPIKeyResponsesSupport 探测 OpenAI APIKey 账号上游是否支持 // /v1/responses 端点,并将结果持久化到 accounts.extra.openai_responses_supported。 // -// 调用时机:账号创建/更新后,且仅当 platform=openai && type=apikey 时。 +// 调用时机:账号创建/更新后,且仅当 platform=openai / 国产供应商 / ollama_cloud +// && type=apikey 时。 // // 探测策略(参见包文档 internal/pkg/openai_compat): // - 上游 404 / 405 → 端点不存在,写 false @@ -109,6 +110,8 @@ func selectResponsesProbeModel(account *Account) string { // - 网络层失败(连接错误、超时)→ 不写标记,保持 unknown // (后续请求仍按"现状即证据"默认走 Responses) // +// 例外:国产供应商与 ollama_cloud 不走网络探测,直接按协议落标(见分支内注释)。 +// // 该方法是幂等的:重复调用会以最新探测结果覆盖标记。 // // 关于失败处理:探测本身的失败不应阻塞账号创建——账号能创建/更新成功就够了, @@ -122,23 +125,45 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte if account.Type != AccountTypeAPIKey { return } - if account.IsCNProvider() { + if account.IsCNProvider() || account.Platform == PlatformOllamaCloud { // 国产 OpenAI 兼容上游默认仅支持 /v1/chat/completions。直接落标 false // 走 Chat Completions 直转,跳过网络探测。 // 例外:deepseek / kimi 的固定 responses 和 adaptive 账号使用官方原生 // Responses 端点,落标 force_responses;其余协议显式重置为 auto,避免 // 切换后残留强制模式。 + // ollama_cloud 与 CN 分支同款:C31 落地后 ollama 有原生 Responses 端点 + // (/v1/responses,non-stateful),adaptive / responses 协议直接落标 + // force_responses,无需网络探测(探测的 2xx/404 判定对它无意义); + // 显式 chat_completions 锁 CC,重置为 auto 防残留强制模式。 + // 落标失败必须结构化告警(openai_responses_probe_marker_persist_failed): + // 静默吞掉会让旧 marker 残留且无任何可观测信号,与运维预期相悖。 if account.UsesNativeCNResponses() { - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ + if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceResponses), openai_compat.ExtraKeyResponsesSupported: true, - }) + }); err != nil { + slog.Warn("openai_responses_probe_marker_persist_failed", + "account_id", account.ID, + "account_name", account.Name, + "platform", account.Platform, + "responses_mode", string(openai_compat.ResponsesSupportModeForceResponses), + "err", err, + ) + } return } - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ + if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeAuto), openai_compat.ExtraKeyResponsesSupported: false, - }) + }); err != nil { + slog.Warn("openai_responses_probe_marker_persist_failed", + "account_id", account.ID, + "account_name", account.Name, + "platform", account.Platform, + "responses_mode", string(openai_compat.ResponsesSupportModeAuto), + "err", err, + ) + } return } if account.Platform != PlatformOpenAI { diff --git a/backend/internal/service/openai_apikey_responses_probe_test.go b/backend/internal/service/openai_apikey_responses_probe_test.go index 7da1da0055..e89d4bdfe7 100644 --- a/backend/internal/service/openai_apikey_responses_probe_test.go +++ b/backend/internal/service/openai_apikey_responses_probe_test.go @@ -1,8 +1,11 @@ package service import ( + "bytes" "context" + "errors" "io" + "log/slog" "net/http" "strings" "testing" @@ -90,6 +93,107 @@ func TestProbeOpenAIAPIKeyResponsesSupportCNProviders(t *testing.T) { } } +// TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud 验证 C39:ollama_cloud 账号与 +// CN 分支同款按协议直接落标,不走网络探测(C31 后 ollama 有原生 /v1/responses, +// 探测的 2xx/404 判定对它无意义);显式 CC 重置为 auto 防残留强制模式。 +func TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud(t *testing.T) { + tests := []struct { + name string + id int64 + protocol string + wantMode string + wantSupport bool + }{ + {name: "adaptive marks force_responses", id: 221, protocol: APIProtocolAdaptive, wantMode: string(openai_compat.ResponsesSupportModeForceResponses), wantSupport: true}, + {name: "responses protocol marks force_responses", id: 222, protocol: APIProtocolResponses, wantMode: string(openai_compat.ResponsesSupportModeForceResponses), wantSupport: true}, + {name: "chat completions resets to auto", id: 223, protocol: APIProtocolChatCompletions, wantMode: string(openai_compat.ResponsesSupportModeAuto), wantSupport: false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + updateCalls := make(chan map[string]any, 1) + account := Account{ + ID: tc.id, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test", "api_protocol": tc.protocol}, + Extra: map[string]any{ + // 预置与目标相反的残留标记,验证落标会覆盖。 + openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeAuto), + openai_compat.ExtraKeyResponsesSupported: false, + }, + } + repo := &snapshotUpdateAccountRepo{ + stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}, + updateExtraCalls: updateCalls, + } + upstream := &httpUpstreamRecorder{} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream} + + svc.ProbeOpenAIAPIKeyResponsesSupport(context.Background(), account.ID) + + updates := <-updateCalls + require.Equal(t, tc.wantSupport, updates[openai_compat.ExtraKeyResponsesSupported]) + require.Equal(t, tc.wantMode, updates[openai_compat.ExtraKeyResponsesMode]) + // 不发任何网络探测请求。 + require.Nil(t, upstream.lastReq) + require.Empty(t, upstream.requests) + }) + } +} + +// failingMarkerRepo 使协议 marker 落标(UpdateExtra)返回错误,用于断言失败会产生 +// 可观测信号。 +type failingMarkerRepo struct { + stubOpenAIAccountRepo + err error +} + +func (r *failingMarkerRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error { + return r.err +} + +// TestProbeOpenAIAPIKeyResponsesSupportMarkerPersistFailureLogsWarning 评审证伪回归: +// 协议 marker 落标失败必须有可观测信号。此前 _ = UpdateExtra 把错误完全吞掉—— +// 协议更新「成功」而旧 force_responses / auto marker 静默残留,且没有任何日志。 +// 注意:ollama_cloud / CN 的请求路由以 credentials.api_protocol 为权威(探针 Extra +// 不得带偏协议决策),因此本修复锁的是可观测性,不是路由正确性。 +func TestProbeOpenAIAPIKeyResponsesSupportMarkerPersistFailureLogsWarning(t *testing.T) { + for _, tc := range []struct { + name string + protocol string + }{ + {name: "force_responses落标失败_告警", protocol: APIProtocolAdaptive}, + {name: "重置auto落标失败_告警", protocol: APIProtocolChatCompletions}, + } { + t.Run(tc.name, func(t *testing.T) { + var logs bytes.Buffer + previousLogger := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + defer slog.SetDefault(previousLogger) + + account := Account{ + ID: 231, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-marker-fail", + Credentials: map[string]any{"api_key": "sk-test", "api_protocol": tc.protocol}, + } + repo := &failingMarkerRepo{ + stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}, + err: errors.New("db write failed"), + } + svc := &AccountTestService{accountRepo: repo} + + svc.ProbeOpenAIAPIKeyResponsesSupport(context.Background(), account.ID) + + output := logs.String() + require.Contains(t, output, "openai_responses_probe_marker_persist_failed", + "UpdateExtra 失败必须产生结构化告警") + require.Contains(t, output, "account_id=231") + require.Contains(t, output, "db write failed") + }) + } +} + func TestDecideResponsesProbeSupport(t *testing.T) { fnCall := []byte(`{"output":[{"type":"reasoning"},{"type":"function_call","name":"probe_ping"}]}`) reasoningOnly := []byte(`{"output":[{"type":"reasoning"}]}`) diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index a0253a4241..da242e03ab 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -262,6 +262,10 @@ func loadCodexGroupCatalogAccounts(ctx context.Context, repo AccountRepository, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, + PlatformOllamaCloud, + // PlatformOpenCodeGo 是方案标注的同类历史漏点:同为转售型平台, + // 不进目录则 Codex 客户端同样看不到其映射模型,随本行一并补上。 + PlatformOpenCodeGo, }, false, ) diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index 087b3b8dac..5dbe8a172c 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -1114,6 +1114,8 @@ func TestBuildCodexModelsManifestForGroupLoadsAccountsOnce(t *testing.T) { require.Contains(t, repo.platforms, PlatformGrok) require.Contains(t, repo.platforms, PlatformDeepseek) require.Contains(t, repo.platforms, PlatformMiniMax) + require.Contains(t, repo.platforms, PlatformOllamaCloud) + require.Contains(t, repo.platforms, PlatformOpenCodeGo) require.NotContains(t, repo.platforms, PlatformComposite) } diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index e405bbee03..3db411e2d7 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -142,6 +142,11 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( func (s *OpenAIGatewayService) openAIChatCompletionsTargetURL(account *Account) (string, error) { baseURL := account.GetOpenAIBaseURL() if baseURL == "" { + if account.IsMultiProtocolAPIKey() { + // 多协议网关缺 base 时必须显式失败:回落官方域名会把第三方 key + // 明文发到 api.openai.com。 + return "", fmt.Errorf("account %d has no openai base url", account.ID) + } baseURL = "https://api.openai.com" } validatedURL, err := s.validateUpstreamBaseURL(baseURL) @@ -182,6 +187,11 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( userAgent string, grokCacheIdentity string, ) (*http.Response, error) { + // Ollama Cloud 请求期定价预检(raw CC 出站):未定价模型在任何上游 I/O 之前 + // 显式 400,且 400 已由 helper 写出。非 failover 错误 ⇒ 不换号、不写账号处置。 + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil { + return nil, err + } upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) upstreamReq, err := http.NewRequestWithContext(upstreamCtx, http.MethodPost, targetURL, bytes.NewReader(body)) releaseUpstreamCtx() @@ -254,10 +264,13 @@ type ccStreamScanState struct { // scanCCStream 驱动两条 CC 回退路径共享的 SSE 读循环:提取 data 行、在 [DONE] // 哨兵处停止、保留最新 usage、记录首 token 时延,并把每个解析成功的 chunk 交给 // emit 回调做各自的协议转换与写出。读错误按既有约定过滤 context 取消类噪声后 -// 记入 Warn 日志。 +// 记入 Warn 日志。account 与 upstreamModel 用于在解析成 chunk 之前对原始 SSE 行 +// 做 Ollama Cloud DeepSeek reasoning 归一化(未命中时字节级透传,语义等同不挂)。 func (s *OpenAIGatewayService) scanCCStream( c *gin.Context, resp *http.Response, + account *Account, + upstreamModel string, logPrefix string, requestID string, startTime time.Time, @@ -268,6 +281,9 @@ func (s *OpenAIGatewayService) scanCCStream( scanner := s.newUpstreamSSEScanner(resp.Body) for scanner.Scan() { line := scanner.Text() + // Ollama Cloud DeepSeek 出站:在解析成 chunk 之前把 reasoning/thinking 归一化 + // 成 reasoning_content,让协议转换器看到与官方 DeepSeek 完全一致的形态。 + line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line) payload, ok := extractOpenAISSEDataLine(line) if !ok { continue @@ -326,10 +342,14 @@ func logCCStreamMissingDoneSentinel(logPrefix, requestID string) { } // readCCUpstreamJSONResponse 读取并解析 CC 非流式 JSON 响应,失败时以调用方 -// 端点格式回写错误;成功时顺带提取 usage。 +// 端点格式回写错误;成功时顺带提取 usage。account 与 upstreamModel 用于在解析 +// 成结构体之前对原始响应体做 Ollama Cloud DeepSeek reasoning 归一化(未命中时 +// 字节级透传,语义等同不挂)。 func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( c *gin.Context, resp *http.Response, + account *Account, + upstreamModel string, writeError compatErrorWriter, ) (*apicompat.ChatCompletionsResponse, OpenAIUsage, error) { respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError) @@ -340,6 +360,11 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( return nil, OpenAIUsage{}, fmt.Errorf("read upstream body: %w", err) } + // Ollama Cloud DeepSeek 出站:在解析成结构体之前把 message/delta 里的 + // reasoning/thinking 归一化成 reasoning_content,让协议转换器看到与官方 + // DeepSeek 完全一致的形态。 + respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody) + var ccResp apicompat.ChatCompletionsResponse if err := json.Unmarshal(respBody, &ccResp); err != nil { writeError(c, http.StatusBadGateway, "api_error", "Failed to parse upstream response") diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index cd043db85d..73a8d42b81 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -359,6 +359,12 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( responsesBody = updatedBody responsesReq.ServiceTier = normalizedOpenAIServiceTierValue(gjson.GetBytes(responsesBody, "service_tier").String()) + // Ollama Cloud 原生 Responses 出站 clamp:与 /v1/responses 入站路径(Forward)同一 + // 判据(实际 Responses 上游为 ollama.com + 映射后的出站模型为 DeepSeek 系),在此 + // 转换路径(Chat Completions 入站 → Responses 出站)独立补齐,模型映射与服务层 + // 改写全部完成后、构建上游请求前最后一次改写 body。 + responsesBody = ollamaCloudClampResponsesMaxOutputTokensBody(account, upstreamModel, responsesBody) + // 5. Get access token token, _, err := s.GetAccessToken(ctx, account) if err != nil { diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index dd77e700d2..dad42d0060 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -162,7 +162,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( return nil, fmt.Errorf("sanitize Grok unsupported fields: %w", err) } } - upstreamBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamBody) + upstreamBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, upstreamBody) upstreamBody = clampOllamaCloudUpstreamMaxTokens(account, upstreamBody) logger.L().Debug("openai chat_completions raw: forwarding without protocol conversion", @@ -345,7 +345,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( } } } - line = applyOllamaCloudRawChatCompletionsSSELine(account, line) + line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line) line = stripEmptyChatToolCallIdentityFromSSELine(line) writeLine(line) @@ -517,7 +517,7 @@ func (s *OpenAIGatewayService) bufferRawChatCompletions( upstreamRequestID := firstNonEmpty(requestID, resp.Header.Get("xai-request-id")) return nil, newGrokMissingUsageFailoverError(c, account, upstreamRequestID) } - respBody = applyOllamaCloudRawChatCompletionsResponse(account, respBody) + respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody) if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) diff --git a/backend/internal/service/openai_gateway_conversation_guard_test.go b/backend/internal/service/openai_gateway_conversation_guard_test.go new file mode 100644 index 0000000000..6e7bc9e9fa --- /dev/null +++ b/backend/internal/service/openai_gateway_conversation_guard_test.go @@ -0,0 +1,125 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// conversationGuardRecorder 保留 *httptest.ResponseRecorder 的引用,以便在 Forward +// 返回后断言 client-visible 状态码与响应体。 +type conversationGuardRecorder struct { + rec *httptest.ResponseRecorder + c *gin.Context +} + +func newConversationGuardRecorder(path string, body []byte) *conversationGuardRecorder { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + return &conversationGuardRecorder{rec: rec, c: c} +} + +// TestForwardConversationFieldRejectedWithBadRequest 验证 D2/C37′ 的端到端语义: +// 原生 Responses 账号(ollama_cloud adaptive / deepseek responses)的入站 body 携带 +// conversation 时,网关显式应答 400 invalid_request_error(client-visible 状态码断 +// 言),不向上游转发、不触发账号 failover;body 不携带 conversation 时同一账号正常 +// 出站(证明 400 只由 conversation 触发,而非签名改动引入的通用错误)。 +func TestForwardConversationFieldRejectedWithBadRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`) + + t.Run("ollama_cloud adaptive gets 400 and no upstream call", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + require.Nil(t, upstream.lastReq, "conversation 请求不得出站") + require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400") + require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error") + require.Contains(t, recorder.rec.Body.String(), "conversation") + }) + + t.Run("deepseek responses gets 400 too", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformDeepseek, nil) + account.Credentials["api_protocol"] = APIProtocolResponses + + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + require.Nil(t, upstream.lastReq) + require.Equal(t, http.StatusBadRequest, recorder.rec.Code) + require.Contains(t, recorder.rec.Body.String(), "conversation") + }) + + t.Run("same account without conversation is forwarded", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + cleanBody := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","store":true,"stream":false}`) + _, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", cleanBody), account, cleanBody) + require.Error(t, err) + require.NotNil(t, upstream.lastReq) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + }) +} + +// TestForwardConversationNullTreatedAsStateless 是 conversation 门禁的兼容性回归: +// gjson 的 Exists() 对 JSON null 也返回 true,若据此判定会把「客户端把可选字段 +// 序列化成 null」这一常见形态误拒为 400。conversation: null 语义上与省略字段 +// 等价,必须按无会话依赖正常出站;非 null 值仍 400 且不出站(对照,门禁对 +// 显式会话依赖的拒绝语义不放松)。 +func TestForwardConversationNullTreatedAsStateless(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("conversation null is forwarded like an omitted field", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":null,"input":"full standalone input","stream":false}`) + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + var statelessErr *openAIResponsesStatelessFieldError + require.NotErrorAs(t, err, &statelessErr, "conversation:null 不得触发无状态字段 400") + require.NotNil(t, upstream.lastReq, "conversation:null 必须正常出站") + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + require.NotEqual(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码不得是 400") + }) + + t.Run("non-null conversation still gets 400 and no upstream call", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`) + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + var statelessErr *openAIResponsesStatelessFieldError + require.ErrorAs(t, err, &statelessErr) + require.Nil(t, upstream.lastReq, "非 null conversation 请求不得出站") + require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400") + require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error") + }) +} diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 9ece2430c8..d01338a2fc 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -264,14 +264,17 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( return fmt.Errorf("count_tokens: missing account") } - // 国产供应商与 OpenCode(全部协议,含 anthropic):一律本地估算,不发上游请求。 + // 国产供应商、OpenCode 与 Ollama Cloud(全部协议,含 anthropic):一律本地估算, + // 不发上游请求。 // 依据(2026-08 核实):三家的 Anthropic 兼容层均未提供 // /v1/messages/count_tokens——DeepSeek 官方 anthropic_api 文档无此端点 // (且注明 anthropic-version 头被忽略),聚合网关 OpenModel 明确标注 // count_tokens 为 "Anthropic only",Kimi/智谱亦无任何文档承诺。转发上游 // 只会常态 404,且错误还会流入账号处置逻辑误伤整账号调度;Claude Code // 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。 - if account.IsCNProvider() || account.IsOpenCodeGo() { + // Ollama Cloud 同因:其 Anthropic 兼容层同样未提供该端点(上游只有 + // /v1/responses/input_tokens),转发同样只会得到 404。 + if account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud() { estimated, err := estimateAnthropicCountTokensLocally(body) if err != nil { writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 7f899d2c34..0630fe0ab4 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -633,8 +633,13 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // ollama.com 以 400 拒绝)。在 `!isCodexCLI` 归一化块之后独立调用:非 Codex 时 // 位于平台字段归一化之后,不跳过原有平台 switch(patch 按追加顺序应用,set 在 // 先前的 delete/set 之后生效);Codex 请求不做归一化,直接按 body 现值判定。 - if clampedCap, ok := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body); ok { + // 生效值来自 max_tokens(无 max_output_tokens 的非 openai 平台)时, + // markPatchDelete("max_tokens") 与第 601 行一样按追加顺序在 set 之后应用。 + if clampedCap, ok, sourceField := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body); ok { markPatchSet("max_output_tokens", clampedCap) + if sourceField == "max_tokens" { + markPatchDelete("max_tokens") + } } if wsDecision.Transport != OpenAIUpstreamTransportResponsesWebsocketV2 && !account.IsOpenAIApiKey() && gjson.GetBytes(body, "previous_response_id").Exists() { @@ -1364,6 +1369,18 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool { return false } } + if account.IsOllamaCloud() { + // Ollama Cloud 无 protocol_rules:显式 CC 锁 CC,adaptive / responses + // 走平台原生 Responses 端点(探针 Extra 不得把协议决策带偏)。 + switch account.GetAPIProtocol() { + case APIProtocolChatCompletions: + return true + case APIProtocolAdaptive, APIProtocolResponses: + return !account.SupportsNativeCNResponses() + default: + return false + } + } return !openai_compat.ShouldUseResponsesAPI(account.Extra) } @@ -1387,6 +1404,11 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. baseURL = account.GetCNProtocolBaseURL(APIProtocolResponses) } if baseURL == "" { + if account.IsMultiProtocolAPIKey() { + // 多协议网关缺 base 时必须显式失败:回落官方域名会把第三方 key + // 明文发到 api.openai.com。 + return nil, fmt.Errorf("account %d has no openai responses base url", account.ID) + } targetURL = openaiPlatformAPIURL } else { validatedURL, err := s.validateUpstreamBaseURL(baseURL) @@ -1400,9 +1422,22 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) - // DeepSeek / Kimi 原生 Responses 端点为无状态实现:强制 store=false、清除 - // previous_response_id,避免携带状态字段被上游拒绝。 - body = normalizeDeepSeekResponsesRequestBody(account, body) + // DeepSeek / Kimi / Ollama Cloud 原生 Responses 端点为无状态实现:强制 + // store=false、清除 previous_response_id;携带 conversation 时显式 400。 + body, err := normalizeDeepSeekResponsesRequestBody(account, body) + if err != nil { + var statelessErr *openAIResponsesStatelessFieldError + if errors.As(err, &statelessErr) { + respondOpenAIStatelessFieldError(c, statelessErr) + } + return nil, err + } + + // Ollama Cloud 请求期定价预检:未定价模型在构造上游请求(即任何上游 I/O)之前 + // 显式 400,且 400 已由 helper 写出。非 UpstreamFailoverError ⇒ 不换号、不写账号处置。 + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil { + return nil, err + } req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body)) if err != nil { diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 6b9300fa59..cac383b6ab 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -331,6 +331,12 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( } } + // Ollama Cloud 原生 Responses 出站 clamp:与 /v1/responses 入站路径(Forward)同一 + // 判据(实际 Responses 上游为 ollama.com + 映射后的出站模型为 DeepSeek 系),在此 + // 转换路径(Anthropic Messages 入站 → Responses 出站)独立补齐,模型映射与服务层 + // 改写全部完成后、构建上游请求前最后一次改写 body。 + responsesBody = ollamaCloudClampResponsesMaxOutputTokensBody(account, upstreamModel, responsesBody) + // 5. Get access token token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index d863d6d484..e9356b58bb 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -139,11 +139,10 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin if err != nil { return "", fmt.Errorf("invalid base_url: %w", err) } - if account.IsOpenCodeGo() { - // OpenCode Go 的 Chat Completions base 带 /v1;用版本感知拼接避免 /v1/v1/messages。 - return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil - } - return strings.TrimRight(validatedURL, "/") + "/v1/messages", nil + // 版本感知拼接:base 已带 /v1 时不再追加,避免拼出 /v1/v1/messages + //(OpenCode Go 的 Chat Completions base 带 /v1,Ollama Cloud 的 anthropic + // 默认 base 不带)。 + return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil } func resolveOpenCodeGoMappedModel(account *Account, body []byte, defaultMappedModel string) string { @@ -180,6 +179,13 @@ func (s *OpenAIGatewayService) buildNativeAnthropicUpstreamRequest( // 地址而非 CC/Responses 地址),详见 helper 注释。 body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetAnthropicProtocolBaseURL(), body) + // Ollama Cloud 请求期定价预检(api_protocol=anthropic 的独立构造器,覆盖 + // messages / responses / chat_completions 三条 anthropic 原生直通入站):未定价 + // 模型在任何上游 I/O 之前显式 400,且 400 已由 helper 写出。 + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil { + return nil, nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { return nil, nil, err diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index a7aad11948..ba2bf12d36 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -100,6 +100,13 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( // so the converted Chat Completions body never contains one and the policy // would always be a no-op on this path. + // Ollama Cloud → DeepSeek 出站(chatReq.Model 已是模型映射后的 upstreamModel): + // 与 raw 路径同序——先归一化 request(历史 assistant 消息 + // reasoning_content → reasoning)、再 clamp max_tokens(>65535 → 65535)。 + // 官方 DeepSeek/glm 等未命中时字节级透传。 + chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody) + chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody) + logger.L().Debug("openai messages: forwarding via raw chat completions", zap.Int64("account_id", account.ID), zap.String("original_model", originalModel), @@ -135,14 +142,15 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( // 5. Convert response if clientStream { - return s.streamChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.streamChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } - return s.bufferChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.bufferChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( c *gin.Context, resp *http.Response, + account *Account, originalModel string, billingModel string, upstreamModel string, @@ -151,7 +159,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( startTime time.Time, ) (*OpenAIForwardResult, error) { requestID := resp.Header.Get("x-request-id") - ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeAnthropicError) + ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeAnthropicError) if err != nil { return nil, err } @@ -180,6 +188,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( c *gin.Context, resp *http.Response, + account *Account, originalModel string, billingModel string, upstreamModel string, @@ -217,7 +226,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( } } - scan := s.scanCCStream(c, resp, "openai messages chat fallback", requestID, startTime, emitChunk) + scan := s.scanCCStream(c, resp, account, upstreamModel, "openai messages chat fallback", requestID, startTime, emitChunk) usage := scan.Usage if scan.Err != nil { diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go b/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go new file mode 100644 index 0000000000..d81f3c2652 --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go @@ -0,0 +1,149 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// runOllamaMessagesChatFallback 直接走 /v1/messages → raw CC 降级桥 +// forwardAnthropicViaRawChatCompletions(与 messages 桥既有测试同风格,直接调桥函数)。 +func runOllamaMessagesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + } + upstreamResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{contentType}, + "x-request-id": []string{"rid_ollama_messages_fallback"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + upstream := &httpUpstreamRecorder{resp: upstreamResp} + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + result, err := svc.forwardAnthropicViaRawChatCompletions(context.Background(), c, account, body, "") + require.NoError(t, err) + require.NotNil(t, result) + return rec, upstream +} + +func TestMessagesChatFallback_OllamaDeepSeek_ClampMaxTokens(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 701) + + t.Run("256000 clamps to 65535", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) + + t.Run("1000 stays 1000", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) +} + +// TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧 +// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content +// 在归一化之后产出完全相同的 thinking 输出(同一转换路径跑多个输入对比)。 +func TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 702) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + + run := func(reasoningField string) string { + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`, + "", + "data: [DONE]", + "", + }, "\n") + rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamBody, true) + return rec.Body.String() + } + + baseline := run(`"reasoning_content":"abc"`) + for _, tc := range []struct { + name string + field string + }{ + {name: "delta.reasoning alias", field: `"reasoning":"abc"`}, + {name: "delta.thinking alias", field: `"thinking":"abc"`}, + } { + t.Run(tc.name, func(t *testing.T) { + out := run(tc.field) + require.Equal(t, baseline, out, "归一化后输出必须与 reasoning_content 基线完全一致") + require.Contains(t, out, "event: content_block_start") + require.Contains(t, out, `"type":"thinking"`) + require.Contains(t, out, `"thinking":"abc"`) + require.Contains(t, out, `"type":"text"`) + require.Contains(t, out, `"text":"final answer"`) + }) + } +} + +func TestMessagesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 703) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "thinking", gjson.Get(rec.Body.String(), "content.0.type").String()) + require.Equal(t, "abc", gjson.Get(rec.Body.String(), "content.0.thinking").String()) + require.Equal(t, "text", gjson.Get(rec.Body.String(), "content.1.type").String()) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.1.text").String()) +} + +func TestMessagesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) { + official := officialDeepSeekTestAccount(704) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + // thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃, + // 输出不出现 thinking 块(与不挂钩子的原始路径行为一致)。 + upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaMessagesChatFallback(t, official, body, upstreamJSON, false) + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.NotContains(t, rec.Body.String(), `"type":"thinking"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String()) +} + +// TestMessagesChatFallback_OllamaGLM_ClampsMaxTokens 验证 D1′ 后非 DeepSeek 模型 +// (glm-5.3-flash)在 ollama host 上同样被 clamp(此前 max_tokens 透传 256000 会被 +// 上游 400);reasoning 钩子仍按 isOllamaCloudDeepSeekUpstream 判定,非 DeepSeek +// 模型不做归一化,输出不出现 thinking 块。 +func TestMessagesChatFallback_OllamaGLM_ClampsMaxTokens(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 705) + body := []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.NotContains(t, rec.Body.String(), `"type":"thinking"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String()) +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go b/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go new file mode 100644 index 0000000000..6effea1a0d --- /dev/null +++ b/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go @@ -0,0 +1,169 @@ +//go:build unit + +package service + +// S1(计费候选过滤纳入 ollama_cloud)与定价缺失兜底路径的回归测试。 +// +// 关键顺序约束的实证:S1 只在「定价已就位」的前提下才安全——若过滤把候选滤空 +// 而定价缺失,会从误计变全零计费。本文件用真实 fallbackPrices(含 ollama 价卡) +// 证明:ollama 真实模型名(不含 claude-*)永不被过滤,候选不会滤空。 +// +// 未定价的主门在请求期定价预检(openai_gateway_ollama_cloud_pricing_preflight.go, +// 上游 I/O 之前 400);记账阶段的零成本落账 + 告警是预检漏放的兜底观测,本文件 +// 一并钉住该兜底不被回归吃掉。 + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestFilterCNProviderBillingModelCandidates_OllamaCloud(t *testing.T) { + svc := &OpenAIGatewayService{} // resolver 为 nil → 无显式分组/渠道定价 + apiKey := &APIKey{Group: &Group{ID: 1, Platform: PlatformOllamaCloud}} + ollamaAccount := &Account{ID: 4, Platform: PlatformOllamaCloud} + + // claude-* 被移除,ollama 真实模型名保留 → 候选不会滤空。 + filtered := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey, + []string{"claude-sonnet-4-5", "gpt-oss:120b-cloud", "qwen3.5:397b"}) + require.Equal(t, []string{"gpt-oss:120b-cloud", "qwen3.5:397b"}, filtered, + "ollama 真实模型名必须保留,只有 claude-* 被过滤") + + // 全 claude 候选才会被清空(上层走 B2-④ 显式拒绝,而非误计 Anthropic 价)。 + allClaude := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey, + []string{"claude-sonnet-4-5", "claude-opus-4-1"}) + require.Empty(t, allClaude) + + // 未定价的非 claude 名也不过滤(过滤只针对 claude-*,不查价)。 + unpriced := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey, + []string{"totally-unpriced-model"}) + require.Equal(t, []string{"totally-unpriced-model"}, unpriced) + + // 既有豁免语义回归:运营者显式配置 claude 渠道价时 claude 名保留。 + const groupID = int64(778) + svcWithChannel := &OpenAIGatewayService{billingService: NewBillingService(nil, nil)} + svcWithChannel.channelService = newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"claude-sonnet-4-5"}, 3.0), + }) + svcWithChannel.resolver = NewModelPricingResolver(svcWithChannel.channelService, svcWithChannel.billingService) + apiKeyWithGroup := &APIKey{Group: &Group{ID: groupID, Platform: PlatformOllamaCloud}} + kept := svcWithChannel.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKeyWithGroup, + []string{"claude-sonnet-4-5", "gpt-oss:120b-cloud"}) + require.Equal(t, []string{"claude-sonnet-4-5", "gpt-oss:120b-cloud"}, kept, + "显式渠道定价的 claude-* 候选必须保留(既有豁免语义)") +} + +// 请求期定价预检(openai_gateway_ollama_cloud_pricing_preflight.go)成为 ollama_cloud +// 未定价模型的主门之后,记账阶段回到全平台统一的 fail-open:定价缺失 → 零成本落账 +// + `openai_usage.pricing_missing_record_zero_cost` 告警。原 B2-④ 在记账阶段显式拒绝 +// 的用例改写为「兜底观测路径保持可用」的回归:拒绝阶段(异步)连 usage 记录都不写, +// 比零成本记录更难发现,且会吃掉放量观察所依赖的告警。 +func TestOpenAIGatewayRecordUsage_OllamaCloudUnpricedModelZeroCostObserved(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "resp_ollama_unpriced", + Usage: OpenAIUsage{ + InputTokens: 1_000_000, + OutputTokens: 0, + }, + Model: "totally-unpriced-model", + Duration: time.Second, + }, + APIKey: &APIKey{ID: 1}, + User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOllamaCloud}, + }) + require.NoError(t, err, "记账阶段不再拒绝:未定价模型回退零成本落账(主门在请求期预检)") + require.Equal(t, 1, usageRepo.calls, "零成本记录必须落账,作为 pricing_missing_record_zero_cost 告警的观测依据") + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, 0.0, usageRepo.lastLog.ActualCost) +} + +// claude-* 请求打到 ollama_cloud:候选被 S1 滤空 → ErrModelPricingUnavailable → +// 与其他平台一致的零成本落账。请求期该模型若未定价会先被预检 400(不发上游); +// 记账阶段不再有第二条拒绝路径。 +func TestOpenAIGatewayRecordUsage_OllamaCloudClaudeNameZeroCostObserved(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "resp_ollama_claude_name", + Usage: OpenAIUsage{ + InputTokens: 1_000_000, + OutputTokens: 0, + }, + Model: "claude-sonnet-4-5", + Duration: time.Second, + }, + APIKey: &APIKey{ID: 1}, + User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOllamaCloud}, + }) + require.NoError(t, err) + require.Equal(t, 1, usageRepo.calls) + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, 0.0, usageRepo.lastLog.ActualCost) +} + +// 已定价模型(真实 :tag 请求形态)→ 正常落账且 actual_cost > 0: +// 证明 S1 过滤 + B2-① tag fallback + B2-② 价卡组合后,ollama 正常请求计费完整。 +func TestOpenAIGatewayRecordUsage_OllamaCloudPricedModelBilledPositive(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "resp_ollama_priced", + Usage: OpenAIUsage{ + InputTokens: 1_000_000, + OutputTokens: 0, + }, + Model: "gpt-oss:120b-cloud", + Duration: time.Second, + }, + APIKey: &APIKey{ID: 1}, + User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOllamaCloud}, + }) + require.NoError(t, err) + require.Equal(t, 1, usageRepo.calls) + require.NotNil(t, usageRepo.lastLog) + require.Greater(t, usageRepo.lastLog.ActualCost, 0.0, + "gpt-oss:120b-cloud 经 :tag fallback 命中 ollama 价卡,actual_cost 必须为正") +} + +// 只收窄 ollama_cloud 的回归:其它平台的定价缺失保持既有 fail-open +// (零成本落账 + Warn),不得被本批改动波及。 +func TestOpenAIGatewayRecordUsage_NonOllamaPlatformZeroCostFallbackPreserved(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "resp_openai_unpriced_zero_cost", + Usage: OpenAIUsage{ + InputTokens: 1_000_000, + OutputTokens: 0, + }, + Model: "totally-unpriced-model", + Duration: time.Second, + }, + APIKey: &APIKey{ID: 1}, + User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOpenAI}, + }) + require.NoError(t, err, "非 ollama 平台的定价缺失必须保持既有零成本落账行为") + require.Equal(t, 1, usageRepo.calls) + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, 0.0, usageRepo.lastLog.ActualCost) +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go index 4fd1c317b6..8ac5d7b838 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go @@ -4,7 +4,6 @@ import ( "strconv" "strings" - "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" "github.com/tidwall/gjson" "github.com/tidwall/sjson" ) @@ -13,58 +12,40 @@ import ( // 而 DeepSeek/OpenAI 客户端只认 reasoning_content。仅在 raw CC 直转路径上做 wire JSON // 双向补齐,不改 CC↔Responses / Anthropic / Grok 桥。 -func isOllamaCloudRawChatCompletionsAccount(account *Account) bool { - if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeAPIKey { +// isOllamaCloudDeepSeekUpstream 判断本次出站是否命中 Ollama Cloud 上托管的 +// DeepSeek 模型:出站 base_url 是 Ollama Cloud(GetOpenAIBaseURL,与 +// clampOllamaCloudUpstreamMaxTokens 的取值一致)且映射后的出站模型是 DeepSeek 系。 +// 不看 platform / account.Type / responses-mode,不读 usage extra;同一分组内 +// 官方 DeepSeek 账号(api.deepseek.com)不命中,保持字节级透传。后续其它出站 +// 路径复用同一判定。nil account / 空模型返回 false。 +func isOllamaCloudDeepSeekUpstream(account *Account, upstreamModel string) bool { + if account == nil { return false } - mode, _ := account.Extra[openai_compat.ExtraKeyResponsesMode].(string) - if openai_compat.NormalizeResponsesSupportMode(mode) != openai_compat.ResponsesSupportModeForceChatCompletions { + if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) { return false } - if accountHasOllamaCloudUsageExtra(account) { - return true - } - if account.Credentials == nil { - return false - } - baseURL, _ := account.Credentials["base_url"].(string) - return isOllamaCloudBaseURL(baseURL) -} - -func accountHasOllamaCloudUsageExtra(account *Account) bool { - if account == nil || account.Extra == nil { - return false - } - for _, key := range []string{ - OllamaCloudUsageSessionExtraKey, - OllamaCloudUsageAutoRefreshExtraKey, - OllamaCloudUsageSnapshotExtraKey, - } { - if _, ok := account.Extra[key]; ok { - return true - } - } - return false + return isDeepSeekModel(upstreamModel) } // applyOllamaCloudRawChatCompletionsRequest 只做 Ollama Cloud reasoning 归一化; // max_tokens clamp 已解耦到独立钩子 clampOllamaCloudUpstreamMaxTokens,由出站方依次调用。 -func applyOllamaCloudRawChatCompletionsRequest(account *Account, body []byte) []byte { - if !isOllamaCloudRawChatCompletionsAccount(account) || len(body) == 0 { +func applyOllamaCloudRawChatCompletionsRequest(account *Account, upstreamModel string, body []byte) []byte { + if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || len(body) == 0 { return body } return normalizeOllamaCloudChatCompletionsRequest(body) } -func applyOllamaCloudRawChatCompletionsResponse(account *Account, body []byte) []byte { - if !isOllamaCloudRawChatCompletionsAccount(account) || len(body) == 0 { +func applyOllamaCloudRawChatCompletionsResponse(account *Account, upstreamModel string, body []byte) []byte { + if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || len(body) == 0 { return body } return normalizeOllamaCloudChatCompletionsResponseJSON(body) } -func applyOllamaCloudRawChatCompletionsSSELine(account *Account, line string) string { - if !isOllamaCloudRawChatCompletionsAccount(account) || line == "" { +func applyOllamaCloudRawChatCompletionsSSELine(account *Account, upstreamModel string, line string) string { + if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || line == "" { return line } return normalizeOllamaCloudChatCompletionsSSELine(line) diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go index ba8bdf714c..2c36d3c973 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go @@ -33,61 +33,9 @@ func ollamaCloudRawChatCompletionsTestAccount() *Account { } } -func TestIsOllamaCloudRawChatCompletionsAccount(t *testing.T) { - t.Parallel() - - t.Run("ollama.com + force_chat_completions", func(t *testing.T) { - t.Parallel() - require.True(t, isOllamaCloudRawChatCompletionsAccount(ollamaCloudRawChatCompletionsTestAccount())) - }) - - t.Run("extra usage signal without ollama host", func(t *testing.T) { - t.Parallel() - account := rawChatCompletionsTestAccount() - account.Credentials["base_url"] = "https://example.invalid/v1" - account.Extra = map[string]any{ - openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), - OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": "ok"}, - } - require.True(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("official DeepSeek", func(t *testing.T) { - t.Parallel() - account := rawChatCompletionsTestAccount() - account.Name = "DeepSeek" - account.Credentials["base_url"] = "https://api.deepseek.com" - account.Extra = map[string]any{ - openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), - } - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("OpenCode Go extra", func(t *testing.T) { - t.Parallel() - account := rawChatCompletionsTestAccount() - account.Credentials["base_url"] = "https://opencode.ai/zen/go/v1" - account.Extra = map[string]any{ - openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), - "opencode_go_usage_auto_refresh": true, - } - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("ollama.com without force_chat_completions", func(t *testing.T) { - t.Parallel() - account := ollamaCloudRawChatCompletionsTestAccount() - account.Extra = nil - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("anthropic ollama.com", func(t *testing.T) { - t.Parallel() - account := ollamaCloudRawChatCompletionsTestAccount() - account.Platform = PlatformAnthropic - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) -} +// TestIsOllamaCloudRawChatCompletionsAccount 已随谓词删除:reasoning 修复把 CC 钩子 +// 换成按 host + 模型判定的 isOllamaCloudDeepSeekUpstream(见下方同名测试),D1′ 又 +// 移除了 clamp 侧最后一个引用,平台 + responses_mode 双门禁判定退出仓库。 func TestNormalizeOllamaCloudChatCompletionsResponseJSON(t *testing.T) { t.Parallel() @@ -174,9 +122,11 @@ func TestApplyOllamaCloudRawChatCompletionsLeavesForeignAccountsUnchanged(t *tes } for _, account := range []*Account{official, opencode} { - require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, reqBody)) - require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, respBody)) - require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, sseLine)) + // 出站 base_url 都不是 ollama.com,即使模型是 DeepSeek 系、即使带残留 + // usage extra,reasoning 归一化门控不命中,字节级不变。 + require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, "deepseek-v4-flash", reqBody)) + require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, "deepseek-v4-flash", respBody)) + require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, "deepseek-v4-flash", sseLine)) } } @@ -267,3 +217,77 @@ func TestForwardAsRawChatCompletions_OllamaCloudThinkingAliasNonStreaming(t *tes require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "choices.0.message.content").String()) require.Equal(t, int64(4), gjson.Get(rec.Body.String(), "usage.completion_tokens_details.reasoning_tokens").Int()) } + +// TestIsOllamaCloudDeepSeekUpstream 验证唯一判据:出站 base_url 是 Ollama Cloud && +// 出站模型是 DeepSeek 系,不看 platform / account.Type / responses-mode / usage extra。 +func TestIsOllamaCloudDeepSeekUpstream(t *testing.T) { + t.Parallel() + + t.Run("ollama.com + deepseek model regardless of platform", func(t *testing.T) { + t.Parallel() + for _, platform := range []string{PlatformDeepseek, PlatformZhipu, PlatformOpenAI} { + require.True(t, isOllamaCloudDeepSeekUpstream(ollamaUpstreamTestAccount(platform, 410), "deepseek-v4-flash"), + "platform %s should be recognized", platform) + } + }) + + t.Run("ollama.com + non-deepseek model", func(t *testing.T) { + t.Parallel() + require.False(t, isOllamaCloudDeepSeekUpstream(ollamaUpstreamTestAccount(PlatformDeepseek, 411), "glm-5.3-flash")) + }) + + t.Run("official deepseek upstream is untouched", func(t *testing.T) { + t.Parallel() + require.False(t, isOllamaCloudDeepSeekUpstream(officialDeepSeekTestAccount(412), "deepseek-v4-flash")) + }) + + t.Run("nil account", func(t *testing.T) { + t.Parallel() + require.False(t, isOllamaCloudDeepSeekUpstream(nil, "deepseek-v4-flash")) + }) +} + +// TestApplyOllamaCloudRawChatCompletionsByUpstream 验证三个 apply* 包装函数按唯一 +// 判据(出站 base_url 是 Ollama Cloud && 出站模型是 DeepSeek 系)生效,不看 +// platform / account.Type / responses-mode / usage extra;官方 DeepSeek 字节级不变。 +func TestApplyOllamaCloudRawChatCompletionsByUpstream(t *testing.T) { + t.Parallel() + + reqBody := []byte(`{"messages":[{"role":"assistant","reasoning_content":"prev","content":""}]}`) + respBody := []byte(`{"choices":[{"delta":{"reasoning":"abc"}}]}`) + sseLine := `data: {"choices":[{"delta":{"reasoning":"abc"}}]}` + + t.Run("deepseek platform ollama account + deepseek model is normalized", func(t *testing.T) { + t.Parallel() + account := ollamaUpstreamTestAccount(PlatformDeepseek, 401) + normalizedReq := applyOllamaCloudRawChatCompletionsRequest(account, "deepseek-v4-flash", reqBody) + require.Equal(t, "prev", gjson.GetBytes(normalizedReq, "messages.0.reasoning").String()) + require.Equal(t, "prev", gjson.GetBytes(normalizedReq, "messages.0.reasoning_content").String()) + + normalizedResp := applyOllamaCloudRawChatCompletionsResponse(account, "deepseek-v4-flash", respBody) + require.Equal(t, "abc", gjson.GetBytes(normalizedResp, "choices.0.delta.reasoning").String()) + require.Equal(t, "abc", gjson.GetBytes(normalizedResp, "choices.0.delta.reasoning_content").String()) + + normalizedLine := applyOllamaCloudRawChatCompletionsSSELine(account, "deepseek-v4-flash", sseLine) + require.True(t, strings.HasPrefix(normalizedLine, "data: ")) + payload := strings.TrimPrefix(normalizedLine, "data: ") + require.Equal(t, "abc", gjson.Get(payload, "choices.0.delta.reasoning").String()) + require.Equal(t, "abc", gjson.Get(payload, "choices.0.delta.reasoning_content").String()) + }) + + t.Run("official deepseek account is byte-identical", func(t *testing.T) { + t.Parallel() + official := officialDeepSeekTestAccount(402) + require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(official, "deepseek-v4-flash", reqBody)) + require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(official, "deepseek-v4-flash", respBody)) + require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(official, "deepseek-v4-flash", sseLine)) + }) + + t.Run("ollama account with non-deepseek model is byte-identical", func(t *testing.T) { + t.Parallel() + account := ollamaUpstreamTestAccount(PlatformDeepseek, 403) + require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, "glm-5.3-flash", reqBody)) + require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, "glm-5.3-flash", respBody)) + require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, "glm-5.3-flash", sseLine)) + }) +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go index 4c69a32b23..a30e39b77e 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go @@ -22,9 +22,8 @@ const ollamaCloudDefaultMaxTokensCap = 65535 // /v1/responses 降级 forwardResponsesViaRawChatCompletions 共用)的独立 token 钩子, // 与 reasoning 钩子解耦:只看本次请求实际选用的 CC 上游 base_url(GetOpenAIBaseURL, // 与 openAIChatCompletionsTargetURL 的取值一致)是否 ollama.com,不读 usage extra。 -// DeepSeek 系模型(用模型映射后的真实出站 model,body 中 model 已改写)任意平台均 -// clamp;非 DeepSeek 模型仅保留既有 openai 平台 Ollama 账号(force_chat_completions -// 判定)的 clamp,不扩展到其它平台。 +// host 命中即按账号 cap 钳制,不看模型家族(DeepSeek 系与非 DeepSeek 模型统一 +// 65535;Ollama Cloud 对 >65535 的输出预算一律 400,与模型无关)。 func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte { if account == nil || len(body) == 0 { return body @@ -32,9 +31,6 @@ func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte { if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) { return body } - if !isDeepSeekModel(gjson.GetBytes(body, "model").String()) && !isOllamaCloudRawChatCompletionsAccount(account) { - return body - } return clampOllamaCloudMaxTokens(account, body) } @@ -51,26 +47,55 @@ func ollamaCloudResponsesUpstreamBaseURL(account *Account) string { // ollamaCloudResponsesMaxOutputTokensClamp 是原生 /v1/responses 路径的 clamp:在 // 平台字段归一化之后独立调用,不改写原有的 max_output_tokens 平台 switch。判定: // 实际 Responses 上游(ollamaCloudResponsesUpstreamBaseURL)为 ollama.com 的 -// APIKey 账号 + 映射后的出站模型是 DeepSeek 系;openai 平台 max_tokens 刚被归一化 -// patch 到 max_output_tokens 时取 max_tokens 为生效值。未命中返回 ok=false。 +// APIKey 账号即钳制,不按模型家族过滤(DeepSeek 系与非 DeepSeek 模型统一 +// 65535;upstreamModel 保留入参供后续分模型 cap 表使用);body 无 +// max_output_tokens 时回退读 max_tokens 为生效值(不限定平台——客户端按 Chat +// Completions 习惯只发 max_tokens 时,任何平台的 ollama 命中判据都要 clamp)。 +// 返回 (cap, ok, sourceField),sourceField 为生效字段名("max_tokens" / ""), +// 供调用方在值来自 max_tokens 时清除残留的 max_tokens。未命中返回 ok=false。 // 实测:ollama.com/v1/responses max_output_tokens=256000 被上游以 "max_tokens -// (256000) exceeds model's maximum output tokens (65536)" 400 拒绝(DeepSeek 模型)。 -func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool) { - if account == nil || account.Type != AccountTypeAPIKey || !isDeepSeekModel(upstreamModel) { - return 0, false +// (256000) exceeds model's maximum output tokens (65536)" 400 拒绝。 +func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool, string) { + if account == nil || account.Type != AccountTypeAPIKey { + return 0, false, "" } if !isOllamaCloudBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) { - return 0, false + return 0, false, "" } value := gjson.GetBytes(body, "max_output_tokens") - if !value.Exists() && account.Platform == PlatformOpenAI { - value = gjson.GetBytes(body, "max_tokens") + sourceField := "" + if !value.Exists() { + if fallback := gjson.GetBytes(body, "max_tokens"); fallback.Exists() { + value = fallback + sourceField = "max_tokens" + } } cap := ollamaCloudMaxTokensCap(account) if cap <= 0 || !value.Exists() || value.Type != gjson.Number || value.Int() <= cap { - return 0, false + return 0, false, "" } - return cap, true + return cap, true, sourceField +} + +// ollamaCloudClampResponsesMaxOutputTokensBody 是原生 /v1/responses 出站 body 的 +// 字节级 clamp 应用(供 CC→Responses、Messages→Responses 转换路径使用):命中 +// ollama.com + DeepSeek 时把 max_output_tokens 改写为 cap,生效值来自 max_tokens 时 +// 一并清除残留的 max_tokens。未命中或改写失败时原样返回。 +func ollamaCloudClampResponsesMaxOutputTokensBody(account *Account, upstreamModel string, body []byte) []byte { + cap, ok, sourceField := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body) + if !ok { + return body + } + out, err := sjson.SetBytes(body, "max_output_tokens", cap) + if err != nil { + return body + } + if sourceField == "max_tokens" { + if stripped, err := sjson.DeleteBytes(out, "max_tokens"); err == nil { + out = stripped + } + } + return out } // ollamaCloudMaxTokensCap 返回账号配置的 max_tokens 上限。账号为 nil 或 extra 中 diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go index f818c37973..2940634737 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go @@ -140,9 +140,10 @@ func TestOllamaCloudMaxTokensCap(t *testing.T) { func TestApplyOllamaCloudRawChatCompletionsRequestClampsMaxTokens(t *testing.T) { body := []byte(`{"model":"deepseek-chat","max_tokens":100000}`) - // Ollama Cloud 账号:reasoning 钩子不再 clamp,字节级原样。 + // Ollama Cloud 账号:reasoning 钩子命中(ollama.com + deepseek-chat),但 body + // 无可归一化的 reasoning 结构,字节级原样;max_tokens 不再由 reasoning 钩子 clamp。 ollama := ollamaCloudRawChatCompletionsTestAccount() - require.Equal(t, string(body), string(applyOllamaCloudRawChatCompletionsRequest(ollama, body))) + require.Equal(t, string(body), string(applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", body))) // 独立 token 钩子接续 clamp 到既有默认 cap。 require.JSONEq(t, `{"model":"deepseek-chat","max_tokens":65535}`, string(clampOllamaCloudUpstreamMaxTokens(ollama, body))) @@ -153,20 +154,21 @@ func TestApplyOllamaCloudRawChatCompletionsRequestClampsMaxTokens(t *testing.T) official.Extra = map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), } - require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(official, body)) + require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(official, "deepseek-chat", body)) require.Equal(t, string(body), string(clampOllamaCloudUpstreamMaxTokens(official, body))) - // ollama.com 但无 force_chat_completions:reasoning 钩子不生效;独立钩子按 - // DeepSeek 系模型判定仍 clamp(DeepSeek 覆盖不依赖 responses_mode extra)。 + // ollama.com 但无 force_chat_completions:reasoning 钩子按新判据命中(判定不看 + // responses-mode),body 无可归一化内容故仍字节不变;独立钩子按 DeepSeek 系模型 + // 判定仍 clamp(DeepSeek 覆盖不依赖 responses_mode extra)。 noForce := ollamaCloudRawChatCompletionsTestAccount() noForce.Extra = nil - require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(noForce, body)) + require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(noForce, "deepseek-chat", body)) require.JSONEq(t, `{"model":"deepseek-chat","max_tokens":65535}`, string(clampOllamaCloudUpstreamMaxTokens(noForce, body))) // 空 body → 原样返回。 - require.Equal(t, []byte(nil), applyOllamaCloudRawChatCompletionsRequest(ollama, nil)) - require.Equal(t, []byte{}, applyOllamaCloudRawChatCompletionsRequest(ollama, []byte{})) + require.Equal(t, []byte(nil), applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", nil)) + require.Equal(t, []byte{}, applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", []byte{})) } // ollamaUpstreamTestAccount 构造挂在实际 ollama.com 上游的 APIKey 账号。平台标签 @@ -228,18 +230,27 @@ func TestClampOllamaCloudUpstreamMaxTokens(t *testing.T) { want: `{"model":"deepseek-v4-flash","max_completion_tokens":65535}`, }, { - // 新增范围只限 DeepSeek 系模型:kimi/zhipu 平台挂 ollama.com 跑非 - // DeepSeek 模型的请求保持不变。 - name: "kimi platform non-deepseek model untouched", + // D1′ 后 host 命中即钳制、不按模型家族过滤:kimi/zhipu 平台挂 + // ollama.com 跑非 DeepSeek 模型同样被 clamp(上游对 >65535 一律 400, + // 与模型无关;这些用例此前钉住的是「仅 DeepSeek 系 clamp」的旧行为)。 + name: "kimi platform non-deepseek model is clamped", account: ollamaUpstreamTestAccount(PlatformKimi, 302), body: `{"model":"k3-256k","max_tokens":256000}`, - want: `{"model":"k3-256k","max_tokens":256000}`, + want: `{"model":"k3-256k","max_tokens":65535}`, }, { - name: "zhipu platform non-deepseek model untouched", + name: "zhipu platform non-deepseek model is clamped", account: ollamaUpstreamTestAccount(PlatformZhipu, 302), body: `{"model":"glm-4.7","max_tokens":256000}`, - want: `{"model":"glm-4.7","max_tokens":256000}`, + want: `{"model":"glm-4.7","max_tokens":65535}`, + }, + { + // platform=ollama_cloud + 非 DeepSeek 模型(真实名形态含 tag): + // D1′ 的目标场景,此前不 clamp 会被上游 400。 + name: "ollama_cloud platform non-deepseek tagged model is clamped", + account: ollamaUpstreamTestAccount(PlatformOllamaCloud, 306), + body: `{"model":"gpt-oss:120b-cloud","max_tokens":256000}`, + want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`, }, { // 既有 openai 平台 Ollama 账号对 DeepSeek 模型的 clamp 幂等保持。 @@ -249,23 +260,24 @@ func TestClampOllamaCloudUpstreamMaxTokens(t *testing.T) { want: `{"model":"deepseek-v4-flash","max_tokens":65535}`, }, { - // 既有 openai 平台 Ollama(真实 ollama.com + force_chat_completions)对 - // 非 DeepSeek 模型的 clamp 保留。 - name: "openai platform ollama.com non-deepseek model keeps legacy clamp", + // 既有 openai 平台 Ollama(真实 ollama.com)对非 DeepSeek 模型的 clamp + // 保持(现按 host 判定命中,不再依赖 force_chat_completions extra)。 + name: "openai platform ollama.com non-deepseek model keeps clamp", account: ollamaCloudRawChatCompletionsTestAccount(), body: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`, want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`, }, { - // 非 DeepSeek 模型不扩展到其它平台。 - name: "openai platform ollama.com non-deepseek model without force_cc untouched", + // 非 DeepSeek 模型不再豁免:openai 平台 + 无 force_cc extra 同样按 + // host 判定 clamp(旧行为「无 force_cc 不 clamp」已随 D1′ 移除)。 + name: "openai platform ollama.com non-deepseek model without force_cc is clamped", account: func() *Account { account := ollamaUpstreamTestAccount(PlatformOpenAI, 303) account.Extra = nil return account }(), body: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`, - want: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`, + want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`, }, { // 残留 usage extra 不得把非 Ollama host 变成 Ollama(旧 reasoning 钩子内的 @@ -397,6 +409,17 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokens(t *testing.T) { require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) }) + // D1′:原生 Responses 路径不再按模型家族过滤,非 DeepSeek 模型同样 clamp。 + t.Run("non-deepseek model on native responses is clamped", func(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformOllamaCloud, 338) + account.Credentials["api_protocol"] = APIProtocolResponses + nonDeepSeekBody := []byte(`{"model":"gpt-oss:120b-cloud","input":"Reply with exactly OK and nothing else.","max_output_tokens":256000,"stream":false}`) + upstream, err := run(account, nonDeepSeekBody) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + t.Run("official deepseek with leftover usage extra is untouched", func(t *testing.T) { account := officialDeepSeekTestAccount(333) account.Credentials["api_protocol"] = APIProtocolResponses @@ -551,3 +574,188 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokensForCodexClients(t *test }) } } + +// TestForwardResponses_DeepseekOllamaCloudClampsClientMaxTokensFallback 覆盖问题 1: +// 原生 /v1/responses 入站只带 max_tokens(无 max_output_tokens)的 deepseek 平台 +// ollama 账号,clamp 判据不限定平台——出站 patch 为 max_output_tokens=cap,并清除 +// 残留的 max_tokens。 +func TestForwardResponses_DeepseekOllamaCloudClampsClientMaxTokensFallback(t *testing.T) { + gin.SetMode(gin.TestMode) + + newAccount := func(id int64) *Account { + account := ollamaUpstreamTestAccount(PlatformDeepseek, id) + account.Credentials["api_protocol"] = APIProtocolResponses + return account + } + run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body) + return upstream, err + } + + t.Run("max_tokens above cap is clamped and removed", func(t *testing.T) { + account := newAccount(351) + body := []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + require.False(t, gjson.GetBytes(upstream.lastBody, "max_tokens").Exists()) + }) + + t.Run("max_tokens at or below cap is not rewritten", func(t *testing.T) { + account := newAccount(352) + body := []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":1000,"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "max_output_tokens").Exists()) + // 既有行为:非 openai 平台只发 max_tokens(≤cap)时残留 max_tokens,本次不处理。 + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int()) + }) +} + +// TestForwardAsChatCompletions_DeepseekOllamaCloudClampsMaxOutputTokens 覆盖问题 2 的 +// CC 入站路径:/v1/chat/completions 入站、账号出站协议为原生 Responses 时,转换生成的 +// max_output_tokens 在发出前被 clamp;≤cap 保持转换后的原值。 +func TestForwardAsChatCompletions_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing.T) { + gin.SetMode(gin.TestMode) + + newAccount := func(id int64) *Account { + account := ollamaUpstreamTestAccount(PlatformDeepseek, id) + account.Credentials["api_protocol"] = APIProtocolResponses + return account + } + run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.ForwardAsChatCompletions(context.Background(), adaptiveProtocolTestContext("/v1/chat/completions", body), account, body, "", "") + return upstream, err + } + + t.Run("max_tokens above cap is clamped", func(t *testing.T) { + account := newAccount(361) + body := []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, "deepseek-chat", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + + t.Run("max_tokens at or below cap is preserved", func(t *testing.T) { + account := newAccount(362) + body := []byte(`{"model":"deepseek-chat","max_tokens":1000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) +} + +// TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens 覆盖问题 2 的 +// Messages 入站路径:/v1/messages 入站、账号出站协议为原生 Responses 时,转换生成的 +// max_output_tokens 在发出前被 clamp;≤cap 保持转换后的原值。 +func TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing.T) { + gin.SetMode(gin.TestMode) + + newAccount := func(id int64) *Account { + account := ollamaUpstreamTestAccount(PlatformDeepseek, id) + account.Credentials["api_protocol"] = APIProtocolResponses + return account + } + run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.ForwardAsAnthropic(context.Background(), adaptiveProtocolTestContext("/v1/messages", body), account, body, "", "") + return upstream, err + } + + t.Run("max_tokens above cap is clamped", func(t *testing.T) { + account := newAccount(371) + body := []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, "deepseek-chat", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + + t.Run("max_tokens at or below cap is preserved", func(t *testing.T) { + account := newAccount(372) + body := []byte(`{"model":"deepseek-chat","max_tokens":1000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) +} + +// TestResponsesPathNotClampedForOfficialDeepseek 对照用例(问题 1/2):官方 +// deepseek(api.deepseek.com)的账号同一判据不命中——三个出站入口的出站 body 保持 +// 256000、不做任何改写。(D1′ 后非 DeepSeek 模型在 ollama host 上同样 clamp, +// 对照只保留非 Ollama 上游场景;非 DeepSeek 的 clamp 断言见 +// TestForwardResponsesClampsOllamaCloudMaxOutputTokens 与 raw CC 表驱动用例。) +func TestResponsesPathNotClampedForOfficialDeepseek(t *testing.T) { + gin.SetMode(gin.TestMode) + + type entry struct { + name string + path string + body []byte + forward func(*OpenAIGatewayService, *gin.Context, *Account, []byte) error + } + entries := []entry{ + { + name: "responses ingress", + path: "/v1/responses", + body: []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`), + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.Forward(context.Background(), c, account, body) + return err + }, + }, + { + name: "chat completions ingress", + path: "/v1/chat/completions", + body: []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`), + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + return err + }, + }, + { + name: "messages ingress", + path: "/v1/messages", + body: []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`), + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + return err + }, + }, + } + + run := func(account *Account, e entry) *httpUpstreamRecorder { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + err := e.forward(svc, adaptiveProtocolTestContext(e.path, e.body), account, e.body) + require.Error(t, err) + return upstream + } + + t.Run("official deepseek keeps 256000", func(t *testing.T) { + account := officialDeepSeekTestAccount(381) + account.Credentials["api_protocol"] = APIProtocolResponses + for _, e := range entries { + t.Run(e.name, func(t *testing.T) { + upstream := run(account, e) + require.Equal(t, "https://api.deepseek.com/responses", upstream.lastReq.URL.String()) + // 原生 Responses 入站只发 max_tokens 时保持原样(无 max_output_tokens); + // 转换路径经转换器生成 max_output_tokens=256000,均不做 clamp。 + if out := gjson.GetBytes(upstream.lastBody, "max_output_tokens"); out.Exists() { + require.Equal(t, int64(256000), out.Int()) + } else { + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int()) + } + }) + } + }) +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go new file mode 100644 index 0000000000..9c23e5cab9 --- /dev/null +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -0,0 +1,126 @@ +package service + +// 请求期 ollama_cloud 定价预检:在上游 I/O 之前拒绝无价可循的出站模型(客户端 +// 得到 400),取代曾在 RecordUsage 成本计算里执行的异步阶段拒绝。异步阶段的拒绝 +// 位置是错的——那时上游已被调用、响应已写给客户端(各 handler 先 Forward,再把 +// RecordUsage 投递给后台 worker,其错误只在闭包里打日志),拒绝只会让 usage 整条 +// 不落账,形成「请求成功但不计费」的静默漏损。 +// +// 挂点(合计覆盖 ollama_cloud 的全部 HTTP 出站): +// - buildUpstreamRequest 原生 Responses 出站;三条入站路径的转换分支都经过它 +// - sendCCUpstreamRequest raw CC 出站;三条入站路径的回退分支都经过它 +// - buildNativeAnthropicUpstreamRequest api_protocol=anthropic 的独立构造器 +// +// 判定与计费同源:复用 RecordUsage → CalculateCostUnified → ModelPricingResolver +// 的同一条解析链(Group → Channel → LiteLLM → Fallback)。无价判定取 +// calculateTokenCost 的失败条件(token 模式下 GetIntervalPricing 无价可取);按次 / +// 图片 / 视频模式走 calculatePerRequestCost,从不因缺价报错,因此不视为未定价—— +// 预检绝不会比计费更严格,「只有渠道价 / 分组价」的合法流量不会被误拒。 +// +// 预检是主门;未定价请求被放行(理论上仅剩 body 无模型名等无法判定的形态)时, +// 计费侧回退到既有的零成本落账 + `openai_usage.pricing_missing_record_zero_cost` +// 告警路径——那条告警是放量观察断言的观测依据,不能被本门禁遮蔽。 + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// openAIOllamaCloudUnpricedModelError 标记 ollama_cloud 出站模型名在计费同一条 +// 解析链上无价可循。网关必须把它应答为 400 invalid_request_error,不得向上游转发, +// 也不得触发账号 failover。 +type openAIOllamaCloudUnpricedModelError struct { + model string +} + +func (e *openAIOllamaCloudUnpricedModelError) Error() string { + return fmt.Sprintf( + "model %q has no pricing configured and cannot be billed: configure model pricing (base, group or channel) or adjust the account model_mapping/allowed_models", + e.model, + ) +} + +// respondOpenAIOllamaCloudUnpricedModelError 按 respondOpenAIStatelessFieldError 的 +// 先例由服务层直接写出 400 invalid_request_error。写前 MarkResponseCommitted 与 +// cyber_policy / grok content 拒绝同款:handler 侧 ensureForwardErrorResponse / +// ensureAnthropicErrorResponse 检测到响应已提交便不再追加 fallback 错误;返回的 +// 错误非 UpstreamFailoverError——不换号、不写账号处置。 +func respondOpenAIOllamaCloudUnpricedModelError(c *gin.Context, err *openAIOllamaCloudUnpricedModelError) { + setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "") + MarkResponseCommitted(c) + c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ + "type": "invalid_request_error", + "message": err.Error(), + }}) +} + +// ollamaCloudBillingGroupFromContext 取认证中间件放入 ctx 的计费分组(与利润门 D +// 同一口径:计费永远按 apiKey 自身分组),用于分组/渠道定价查找。ctx 无有效分组 +// (内部调用、直接构造 service 的单测)时返回 nil——等价于计费在无分组输入下的 +// 解析行为,不会让预检更严格。 +func ollamaCloudBillingGroupFromContext(ctx context.Context) *Group { + if ctx == nil { + return nil + } + group, _ := ctx.Value(ctxkey.Group).(*Group) + if IsGroupContextValid(group) { + return group + } + return nil +} + +// ollamaCloudModelUnpricedForBilling 报告模型在计费的解析链上是否无价可循。 +// s.resolver 为 nil 时恒返回 false(放行):生产 wire 必然注入 resolver,直接构造 +// struct 的单测与内部调用不应被门禁拦截(与 resolveOpenAIChannelPricing 的 nil 守卫 +// 同一取舍)。 +func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Context, model string) bool { + if s == nil || s.resolver == nil { + return false + } + group := ollamaCloudBillingGroupFromContext(ctx) + var groupID *int64 + if group != nil { + gid := group.ID + groupID = &gid + } + resolved := s.resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group}) + if resolved == nil { + return true + } + // 与 CalculateCostUnified 的模式分发一致:按次/图片/视频模式由 + // calculatePerRequestCost 计价,缺价只会得到 0 而不会报错;只有 token 模式 + // 会在 GetIntervalPricing 无价可取时以 ErrModelPricingUnavailable 失败。 + if resolved.Mode != BillingModeToken { + return false + } + // 定价上下文取 1 token(最低档):GetIntervalPricing 返回 nil 与否只取决于 + // BasePricing 是否存在,与上下文档位无关,与 calculateTokenCost 的失败条件 + // 完全同一条链。 + return s.resolver.GetIntervalPricing(resolved, 1) == nil +} + +// enforceOllamaCloudRequestPricingPreflight 在上游 I/O 之前对 ollama_cloud 出站做 +// 定价预检。未定价时写出 400 并返回类型化错误,调用方原样 `return nil, err` 即可 +// 终止本次出站(构造的请求不会发出,上游零调用)。非 ollama_cloud 账号、出站 +// body 缺模型名(无法判定,交由计费侧零成本告警观测)一律放行。 +func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.Context, c *gin.Context, account *Account, body []byte) error { + if account == nil || !account.IsOllamaCloud() { + return nil + } + model := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + if model == "" { + return nil + } + if !s.ollamaCloudModelUnpricedForBilling(ctx, model) { + return nil + } + err := &openAIOllamaCloudUnpricedModelError{model: model} + respondOpenAIOllamaCloudUnpricedModelError(c, err) + return err +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go new file mode 100644 index 0000000000..6086fadede --- /dev/null +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go @@ -0,0 +1,230 @@ +//go:build unit + +package service + +// 请求期 ollama_cloud 定价预检的回归测试(上游 I/O 之前 400)。 +// +// 最重要的验收断言是「上游零调用 + 不 failover / 不写账号处置」:未定价请求必须在 +// 构造上游请求之前被终止,客户端拿到 400 invalid_request_error,而不是像旧的异步 +// 阶段拒绝那样——上游已被调用、响应已写给客户端之后才在记账阶段丢弃 usage。 + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// newPricingPreflightTestService 构造带真实定价解析链(fallbackPrices 价卡 + +// 可选渠道定价)的网关服务,供预检测试复用。 +func newPricingPreflightTestService(upstream *httpUpstreamRecorder, groupID int64, channelPricings []ChannelModelPricing) *OpenAIGatewayService { + bs := NewBillingService(nil, nil) + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + billingService: bs, + resolver: NewModelPricingResolver(nil, bs), + } + if len(channelPricings) > 0 { + svc.channelService = newChannelServiceWithPricings(groupID, channelPricings) + svc.resolver = NewModelPricingResolver(svc.channelService, bs) + } + return svc +} + +// pricingPreflightGroup 构造通过 IsGroupContextValid 的认证分组(ctxkey.Group 载体)。 +func pricingPreflightGroup(id int64, modelPricing ...ChannelModelPricing) *Group { + return &Group{ + ID: id, + Platform: PlatformOllamaCloud, + Status: StatusActive, + Hydrated: true, + ModelPricing: modelPricing, + } +} + +func pricingPreflightContext(path string, body []byte, group *Group) (*gin.Context, *httptest.ResponseRecorder, context.Context) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + ctx := context.Background() + if group != nil { + ctx = context.WithValue(ctx, ctxkey.Group, group) + } + return c, rec, ctx +} + +// assertPricingPreflightRejected 汇总预检拒绝路径的共同断言:上游零调用(最重要)、 +// 客户端可见 400 invalid_request_error、响应已提交标记(handler 不追加 fallback)、 +// 返回类型化错误且非 UpstreamFailoverError(不换号、不写账号处置)。 +func assertPricingPreflightRejected(t *testing.T, c *gin.Context, upstream *httpUpstreamRecorder, rec *httptest.ResponseRecorder, err error, wantModel string) { + t.Helper() + + require.Nil(t, upstream.lastReq, "未定价请求不得发起任何上游调用(核心验收断言)") + require.Nil(t, upstream.lastBody) + require.Equal(t, http.StatusBadRequest, rec.Code, "client-visible 状态码必须是 400") + require.Equal(t, "invalid_request_error", gjson.Get(rec.Body.String(), "error.type").String()) + require.Contains(t, rec.Body.String(), wantModel, "错误体必须点名未定价模型") + require.True(t, IsResponseCommitted(c), "响应已提交标记必须置位(handler 不再追加 fallback 错误)") + + var unpricedErr *openAIOllamaCloudUnpricedModelError + require.ErrorAs(t, err, &unpricedErr, "必须是预检类型化错误") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "预检错误不得是 failover 错误") +} + +// TestOllamaCloudPricingPreflight_RejectsUnpricedBeforeUpstream 主验收:原生 +// Responses 出站(buildUpstreamRequest 挂点)上,未定价模型在发起上游请求之前被 +// 400 终止。 +func TestOllamaCloudPricingPreflight_RejectsUnpricedBeforeUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"totally-unpriced-model","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, account, body) + assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") +} + +// TestOllamaCloudPricingPreflight_BasePricedModelPasses 基础价(fallbackPrices 命中) +// 的模型必须正常出站——预检只拒无价可循的名字。 +func TestOllamaCloudPricingPreflight_BasePricedModelPasses(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, account, body) + require.NotNil(t, upstream.lastReq, "已定价模型不得被预检拦截") + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.Error(t, err) // upstream 被Recorder 短路,错误来自传输层,与预检无关 +} + +// TestOllamaCloudPricingPreflight_ChannelOnlyPricedModelPasses 「判定与计费同源」的 +// 关键用例:模型只在渠道定价里配置、不在基础价里 → 计费能算出成本,预检不得拒绝。 +func TestOllamaCloudPricingPreflight_ChannelOnlyPricedModelPasses(t *testing.T) { + gin.SetMode(gin.TestMode) + + const groupID = int64(777) + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := newPricingPreflightTestService(upstream, groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"channel-only-model"}, 3.0), + }) + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"channel-only-model","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, pricingPreflightGroup(groupID)) + _, err := svc.Forward(ctx, c, account, body) + require.NotNil(t, upstream.lastReq, "只有渠道价的模型不得被预检误拒(预检不得比计费更严格)") + require.Equal(t, "channel-only-model", gjson.GetBytes(upstream.lastBody, "model").String()) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.Error(t, err) // upstream 短路错误,与预检无关 +} + +// TestOllamaCloudModelUnpricedForBilling_MatchesBillingChain 钉住判定函数与计费 +// 解析链(Group → Channel → LiteLLM → Fallback)的同源矩阵。 +func TestOllamaCloudModelUnpricedForBilling_MatchesBillingChain(t *testing.T) { + const groupID = int64(778) + bs := NewBillingService(nil, nil) + channelSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"channel-only-model"}, 3.0), + { + Platform: PlatformOpenAI, + Models: []string{"per-request-only-model"}, + BillingMode: BillingModePerRequest, + PerRequestPrice: f64p(0.5), + }, + }) + svc := &OpenAIGatewayService{ + billingService: bs, + channelService: channelSvc, + resolver: NewModelPricingResolver(channelSvc, bs), + } + // resolver 缺失(直接构造 service 的场景)恒放行。 + require.False(t, (&OpenAIGatewayService{}).ollamaCloudModelUnpricedForBilling(context.Background(), "totally-unpriced-model")) + + withGroup := context.WithValue(context.Background(), ctxkey.Group, pricingPreflightGroup(groupID)) + + // 基础价命中(fallbackPrices ollama 价卡,含 :tag 两级 fallback)。 + require.False(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "gpt-oss:120b-cloud")) + // 全链未命中。 + require.True(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "totally-unpriced-model")) + // 只有渠道价(token 模式):带认证分组 → 有价;不带分组 → 计费同样看不到渠道价。 + require.False(t, svc.ollamaCloudModelUnpricedForBilling(withGroup, "channel-only-model")) + require.True(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "channel-only-model")) + // 渠道按次模式:calculatePerRequestCost 从不因缺价报错 → 永不判无价。 + require.False(t, svc.ollamaCloudModelUnpricedForBilling(withGroup, "per-request-only-model")) + // 分组价卡命中。 + groupWithPricing := pricingPreflightGroup(groupID, tokenPricingForModels([]string{"group-priced-model"}, 2.0)) + groupCtx := context.WithValue(context.Background(), ctxkey.Group, groupWithPricing) + require.False(t, svc.ollamaCloudModelUnpricedForBilling(groupCtx, "group-priced-model")) +} + +// TestOllamaCloudPricingPreflight_RawCCPathRejectsUnpriced raw CC 出站挂点 +// (sendCCUpstreamRequest):显式 api_protocol=chat_completions 的 ollama 账号, +// 未定价模型在发送前 400、上游零调用。 +func TestOllamaCloudPricingPreflight_RawCCPathRejectsUnpriced(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := &Account{ + ID: 907, + Name: "ollama-cloud-cc", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": APIProtocolChatCompletions, + "base_url": "https://ollama.com", + }, + } + + body := []byte(`{"model":"totally-unpriced-model","messages":[{"role":"user","content":"hi"}],"stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/chat/completions", body, nil) + _, err := svc.forwardAsRawChatCompletions(ctx, c, account, body, "") + assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") +} + +// TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced 第三挂点 +// (buildNativeAnthropicUpstreamRequest):api_protocol=anthropic 的 ollama 账号走 +// 独立构造器,未定价模型同样必须在任何上游 I/O 之前 400。 +func TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := &Account{ + ID: 908, + Name: "ollama-cloud-anthropic", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": APIProtocolAnthropic, + "base_url": "https://ollama.com", + }, + } + + body := []byte(`{"model":"totally-unpriced-model","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/messages", body, nil) + _, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "") + assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") +} diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index dd8f390079..18bbf6d809 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -601,12 +601,24 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( return nil, err } targetURL = buildOpenAIResponsesURLForPlatform(account.Platform, validatedURL) + } else if account.IsMultiProtocolAPIKey() { + // 多协议网关缺 base 时必须显式失败:targetURL 初值即官方域名, + // 回落它会把第三方 key 明文发到 api.openai.com。 + return nil, fmt.Errorf("account %d has no openai responses base url", account.ID) } } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) - // DeepSeek / Kimi 原生 Responses 端点为无状态实现(见 normalizeDeepSeekResponsesRequestBody)。 - body = normalizeDeepSeekResponsesRequestBody(account, body) + // DeepSeek / Kimi / Ollama Cloud 原生 Responses 端点为无状态实现 + // (见 normalizeDeepSeekResponsesRequestBody);conversation 显式 400。 + body, normalizeErr := normalizeDeepSeekResponsesRequestBody(account, body) + if normalizeErr != nil { + var statelessErr *openAIResponsesStatelessFieldError + if errors.As(normalizeErr, &statelessErr) { + respondOpenAIStatelessFieldError(c, statelessErr) + } + return nil, normalizeErr + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index e26197ed1e..9ed0924658 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -127,21 +127,65 @@ func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body m } // normalizeDeepSeekResponsesRequestBody 适配无状态 CN Responses 端点: -// 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi 官方 -// Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。 +// 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi / Ollama Cloud +// 官方 Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。 // 非原生 Responses 协议账号原样返回。 -func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) []byte { +// +// 请求体携带非 null 的 conversation 时返回 *openAIResponsesStatelessFieldError +// 且不改写 body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法 +// 不存在。依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离 +// 等于静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整 +// input 的 non-stream 用法被误伤;出现真实此类客户端时按平台/账号开关显式 +// 放行,不得回退静默剥离。 +// +// 判定用 Type != gjson.Null 而非 Exists():gjson 对 JSON null 也返回 +// Exists()==true(Raw 非空),而 conversation: null 语义上与「省略该字段」等价 +// (很多客户端会把可选字段序列化成 null),必须按无会话依赖正常出站。 +func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byte, error) { if account == nil || !account.UsesNativeCNResponses() { - return body + return body, nil + } + if gjson.GetBytes(body, "conversation").Type != gjson.Null { + return body, &openAIResponsesStatelessFieldError{field: "conversation"} } normalized, err := sjson.SetBytes(body, "store", false) if err != nil { - return body + return body, fmt.Errorf("force responses store=false: %w", err) } if stripped, err := sjson.DeleteBytes(normalized, "previous_response_id"); err == nil { normalized = stripped } - return normalized + return normalized, nil +} + +// openAIResponsesStatelessFieldError 标记请求体携带无状态 Responses 端点不支持 +// 的服务端状态字段(如 conversation)。网关必须把它应答为 400 +// invalid_request_error,不得向上游转发,也不得触发账号 failover。 +type openAIResponsesStatelessFieldError struct { + field string +} + +func (e *openAIResponsesStatelessFieldError) Error() string { + return fmt.Sprintf( + "%s is not supported on this stateless /responses endpoint: omit it and send the full input with store=false", + e.field, + ) +} + +// respondOpenAIStatelessFieldError 按 stripOpenAIResponsesInputNamespaces 的先例 +// 把无状态端点不支持的字段应答为 400 invalid_request_error(由服务层写出响应, +// handler 侧 ensureForwardErrorResponse 检测到响应已提交便不再追加 fallback)。 +// 写前 MarkResponseCommitted 与 cyber_policy / grok content 拒绝及 ollama_cloud +// 定价预检 400 同款:本 400 的错误消息("%s is not supported ...")不在 +// openAIForwardErrorAlreadyCommunicated 识别的消息前缀里,不置位的话 handler 会因 +// Writer 已写出而向 JSON body 尾部追加 SSE 终止帧,污染响应体。 +func respondOpenAIStatelessFieldError(c *gin.Context, statelessErr *openAIResponsesStatelessFieldError) { + setOpsUpstreamError(c, http.StatusBadRequest, statelessErr.Error(), "") + MarkResponseCommitted(c) + c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ + "type": "invalid_request_error", + "message": statelessErr.Error(), + }}) } func trimOpenAIEncryptedReasoningItems(reqBody map[string]any) bool { diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index 67d3e2b4e7..15cd680239 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -89,6 +89,9 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( } // /v1/responses 降级到 raw CC 的出站与 forwardAsRawChatCompletions 共用同一个 // 独立 Ollama Cloud token 钩子;chatReq.Model 已是模型映射后的 upstreamModel。 + // reasoning 归一化与 raw 路径同序:先归一化 request(历史 assistant 消息的 + // reasoning_content → reasoning)再 clamp max_tokens。 + chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody) chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody) // Keep the final outbound tier for usage-time reconciliation. A policy // filter that removes the field therefore leaves this nil. @@ -123,14 +126,15 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( } if clientStream { - return s.streamChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.streamChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } - return s.bufferChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.bufferChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( c *gin.Context, resp *http.Response, + account *Account, originalModel string, customTools map[string]bool, functionTools map[string]bool, @@ -143,7 +147,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( startTime time.Time, ) (*OpenAIForwardResult, error) { requestID := resp.Header.Get("x-request-id") - ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeOpenAIResponsesFallbackError) + ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeOpenAIResponsesFallbackError) if err != nil { return nil, err } @@ -173,6 +177,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( c *gin.Context, resp *http.Response, + account *Account, originalModel string, customTools map[string]bool, functionTools map[string]bool, @@ -220,7 +225,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( c.Writer.Flush() } - scan := s.scanCCStream(c, resp, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) { + scan := s.scanCCStream(c, resp, account, upstreamModel, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) { events := apicompat.ChatCompletionsChunkToResponsesEvents(chunk, state) s.cacheReasoningItemsFromEvents(events) writeEvents(events) diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go b/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go new file mode 100644 index 0000000000..4991873d85 --- /dev/null +++ b/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go @@ -0,0 +1,151 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// runOllamaResponsesChatFallback 直接走 /v1/responses → raw CC 降级桥 +// forwardResponsesViaRawChatCompletions(与 raw 路径测试同风格,直接调桥函数)。 +func runOllamaResponsesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + } + upstreamResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{contentType}, + "x-request-id": []string{"rid_ollama_responses_fallback"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + upstream := &httpUpstreamRecorder{resp: upstreamResp} + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + result, err := svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + return rec, upstream +} + +func TestResponsesChatFallback_OllamaDeepSeek_ClampMaxOutputTokens(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 601) + + t.Run("256000 clamps to 65535", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":256000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) + + t.Run("1000 stays 1000", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) +} + +// TestResponsesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧 +// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content +// 在归一化之后产出完全相同的 reasoning 输出(同一转换路径跑多个输入对比)。 +// normalizeStreamIDs 抹平响应里每次运行随机生成的 item id 与 created_at 时间戳, +// 使两条输入路径的 SSE 输出可做语义级字节比较。 +var normalizeStreamIDs = regexp.MustCompile(`("item_[0-9a-f]+"|"created_at":[0-9]+)`) + +func TestResponsesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 602) + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":true}`) + + run := func(reasoningField string) string { + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`, + "", + "data: [DONE]", + "", + }, "\n") + rec, _ := runOllamaResponsesChatFallback(t, account, body, upstreamBody, true) + return normalizeStreamIDs.ReplaceAllString(rec.Body.String(), `"item_x"`) + } + + baseline := run(`"reasoning_content":"abc"`) + require.Contains(t, baseline, "response.reasoning_summary_text.delta") + require.Contains(t, baseline, `"delta":"abc"`) + require.Contains(t, baseline, `"delta":"final answer"`) + for _, tc := range []struct { + name string + field string + }{ + {name: "delta.reasoning alias", field: `"reasoning":"abc"`}, + {name: "delta.thinking alias", field: `"thinking":"abc"`}, + } { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, baseline, run(tc.field), "归一化后输出必须与 reasoning_content 基线完全一致") + }) + } +} + +func TestResponsesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 603) + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, _ := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "reasoning", gjson.Get(rec.Body.String(), "output.0.type").String()) + require.Equal(t, "abc", gjson.Get(rec.Body.String(), "output.0.summary.0.text").String()) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.1.content.0.text").String()) +} + +func TestResponsesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) { + official := officialDeepSeekTestAccount(604) + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":256000,"stream":false}`) + // thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃, + // 输出不出现 reasoning item(与不挂钩子的原始路径行为一致)。 + upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaResponsesChatFallback(t, official, body, upstreamJSON, false) + // 请求侧不被 clamp:max_completion_tokens 保持 256000。 + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + // 响应侧不归一化:输出只有 message item,没有 reasoning item。 + require.NotContains(t, rec.Body.String(), `"type":"reasoning"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) +} + +// TestResponsesChatFallback_OllamaGLM_ClampsMaxTokens 验证 D1′ 后非 DeepSeek 模型 +// (glm-5.3-flash)在 ollama host 的 Responses→CC 降级桥上同样被 clamp;reasoning +// 钩子仍按模型判定,非 DeepSeek 模型不做归一化。 +func TestResponsesChatFallback_OllamaGLM_ClampsMaxTokens(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 605) + body := []byte(`{"model":"glm-5.3-flash","input":"hello","max_output_tokens":256000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.NotContains(t, rec.Body.String(), `"type":"reasoning"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) +} diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index c32f143b97..751918d45e 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -288,11 +288,13 @@ func (s *OpenAIGatewayService) SelectAccountForTokenCount( // NormalizeOpenAICompatiblePlatform 保留 grok 与国产 OpenAI 兼容供应商(kimi/zhipu/ // deepseek)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配: // kimi 分组请求只命中 kimi 账号,语义与 openai/grok 一致。 +// Ollama Cloud 同样必须保留原值:归一为 openai 会让 ollama_cloud 分组去查 +// openai 候选桶,表现为静默空池。 // (upstream 曾将本函数改为未导出 normalizeOpenAICompatiblePlatform,本分支的 // handler 调度入口仍需导出,保持导出名。) func NormalizeOpenAICompatiblePlatform(platform string) string { switch platform { - case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return platform default: return PlatformOpenAI diff --git a/backend/internal/service/openai_gateway_stateless_field_error_test.go b/backend/internal/service/openai_gateway_stateless_field_error_test.go new file mode 100644 index 0000000000..c5fe678fcf --- /dev/null +++ b/backend/internal/service/openai_gateway_stateless_field_error_test.go @@ -0,0 +1,114 @@ +//go:build unit + +package service + +// conversation 400 响应体洁净度回归。 +// +// respondOpenAIStatelessFieldError 由服务层直接写出 400 invalid_request_error,但 +// 其错误消息("conversation is not supported ...")不在 handler 侧 +// openAIForwardErrorAlreadyCommunicated 识别的两条消息前缀内:不置位 +// ResponseCommitted 的话,Forward 返回错误后 handler 走 ensureForwardErrorResponse, +// 因 Writer.Written() 已为 true 而向完整 400 JSON body 尾部追加 SSE 终止帧 +// (responses 入站追加 response.failed),body 变脏、JSON 不完整。 +// 修复:写前 MarkResponseCommitted(同 cyber_policy / grok 与 ollama_cloud 定价 +// 预检 400 的既有先例),handler 检测到响应已提交便不再追加。 + +import ( + "errors" + "net/http" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func TestConversationStatelessFieldError400BodyStaysClean(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + // adaptive 协议 → UsesNativeCNResponses 为真,normalizeDeepSeekResponsesRequestBody 生效。 + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","store":true,"stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, account, body) + + require.Error(t, err) + require.Nil(t, upstream.lastReq, "conversation 400 必须发生在任何上游 I/O 之前") + require.Equal(t, http.StatusBadRequest, rec.Code) + + raw := rec.Body.String() + require.Equal(t, "invalid_request_error", gjson.Get(raw, "error.type").String()) + require.Contains(t, raw, "conversation is not supported") + + // body 洁净度(核心验收断言):服务层写出的 400 不得被追加任何 SSE 帧。 + require.NotContains(t, raw, "response.failed", "400 JSON body 不得被追加 response.failed SSE 帧") + require.NotContains(t, raw, "data:", "400 JSON body 不得被追加任何 SSE 帧") + require.NotContains(t, raw, "Upstream request failed", "handler fallback 错误不得混入 400 body") + require.True(t, gjson.Parse(raw).IsObject(), "400 body 必须是单个完整 JSON 对象") + + // 机制断言:响应已提交标记必须置位 —— ensureForwardErrorResponse 的第一道检查 + // 读它,置位即跳过追加 fallback(与定价预检 400 的验收口径一致)。 + require.True(t, IsResponseCommitted(c), "ResponseCommitted 必须置位,handler 才不会追加 fallback 错误") +} + +// 三入站路径覆盖:conversation 是 Responses 协议字段,只有 Responses 入站能携带。 +// CC / Messages 入站的转换分支构造全新的 Responses body(协议里不存在该字段, +// 转换不会透传未知键),因此不会触发该 400 —— 这里用真实转换路径实证,而非假定: +// 强制原生 Responses 出站后,CC / Messages 各自转换出的 outbound body 均无 +// conversation,请求正常走到上游(不存在 400 短路);Responses 入站为对照组, +// 同字段直接 400。 +func TestConversationStateless400OnlyReachableFromResponsesIngress(t *testing.T) { + gin.SetMode(gin.TestMode) + + newForcedResponsesAccount := func() *Account { + account := adaptiveProtocolTestAccount(PlatformDeepseek, nil) + account.Credentials["api_protocol"] = APIProtocolResponses + account.Credentials["base_url"] = "http://responses.example" + return account + } + + // CC / Messages 入站:conversation 被转换丢弃,请求照常出站。 + for _, tc := range cnProtocolIngressCases() { + if tc.name == "responses" { + continue + } + t.Run(tc.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + // 向入站 body 硬塞 conversation(客户端异常/恶意形态)。 + body, err := sjson.SetBytes(tc.body, "conversation", "conv_x") + require.NoError(t, err) + + forwardErr := tc.forward(svc, adaptiveProtocolTestContext(tc.path, body), newForcedResponsesAccount(), body) + + // 到达上游(transport 短路错误)= 未被 conversation 400 拦截。 + var statelessErr *openAIResponsesStatelessFieldError + require.False(t, errors.As(forwardErr, &statelessErr), + "%s 入站不得触发 conversation 400", tc.name) + require.NotNil(t, upstream.lastReq, "%s 入站必须照常出站", tc.name) + require.False(t, gjson.GetBytes(upstream.lastBody, "conversation").Exists(), + "%s 入站转换出的 Responses body 不得携带 conversation 字段(即该入站永远到不了这个 400)", tc.name) + }) + } + + // Responses 入站(对照):conversation 直达 normalize,显式 400。 + t.Run("responses", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + body := []byte(`{"model":"deepseek-v4.1-flash","conversation":"conv_x","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, newForcedResponsesAccount(), body) + + var statelessErr *openAIResponsesStatelessFieldError + require.ErrorAs(t, err, &statelessErr) + require.Nil(t, upstream.lastReq) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.True(t, IsResponseCommitted(c)) + }) +} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index cb0802b95f..712a45fda6 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -150,6 +150,72 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie } } +// 运营 preflight SQL(B2-④,上线/放量前人工执行;是一次性运营检查,不是迁移, +// 不要放进 migrations/)。用于在放量前扫出「保存期门禁(B2-③)生效前就已存在、 +// 或绕过门禁写入」的无价 ollama_cloud 账号;三条都期望 0 行,均为可直接执行的 +// 完整语句,在【业务主库】accounts 表跑;命中处置与存量盘点(第 0 条)见完整 +// 迁移手册(运营文档)。已定价模型集合(22 名)取自 billing_service.go +// fallbackPrices 的 ollama 条目:18 条字面名 + 家族兜底可计费的 +// kimi-k2.7-code / deepseek-v4.1-flash;查询里 regexp_replace 剥 :tag 的二级 +// 比对与两级查价同源。 +// +// -- 1) model_mapping 目标值必须全部有价;期望 0 行(命中先甄别家族兜底 +// -- 误报,再补价或改 mapping) +// WITH priced(model) AS (VALUES +// ('nemotron-3-super'),('glm-5.3'),('gpt-oss:120b'),('glm-5.3-flash'), +// ('kimi-k2.6'),('kimi-k3'),('deepseek-v4.1-flash'),('minimax-m2.7'), +// ('mistral-large-3:675b'),('glm-5.1'),('glm-5.2'),('gpt-oss:20b'), +// ('qwen3.5:397b'),('kimi-k2.7-code'),('nemotron-3-nano:30b'),('minimax-m3'), +// ('gemma4:31b'),('nemotron-3-ultra'),('deepseek-v4-flash:0731'), +// ('deepseek-v4-pro:0813'),('deepseek-v4-flash'),('deepseek-v4-pro')) +// SELECT a.id, a.name, kv.key AS source_model, kv.value AS target_model +// FROM accounts a, +// jsonb_each_text(COALESCE(a.credentials->'model_mapping','{}'::jsonb)) AS kv +// WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud' +// AND btrim(kv.value) <> '' +// AND lower(btrim(kv.value)) NOT IN (SELECT model FROM priced) +// AND lower(regexp_replace(btrim(kv.value), ':.*$', '')) NOT IN (SELECT model FROM priced); +// +// -- 1b) extra.allowed_models 清单值必须全部有价(清单存 accounts.extra,不在 +// -- credentials;与 model_mapping 是同地位的两条可出站来源);期望 0 行 +// WITH priced(model) AS (VALUES +// ('nemotron-3-super'),('glm-5.3'),('gpt-oss:120b'),('glm-5.3-flash'), +// ('kimi-k2.6'),('kimi-k3'),('deepseek-v4.1-flash'),('minimax-m2.7'), +// ('mistral-large-3:675b'),('glm-5.1'),('glm-5.2'),('gpt-oss:20b'), +// ('qwen3.5:397b'),('kimi-k2.7-code'),('nemotron-3-nano:30b'),('minimax-m3'), +// ('gemma4:31b'),('nemotron-3-ultra'),('deepseek-v4-flash:0731'), +// ('deepseek-v4-pro:0813'),('deepseek-v4-flash'),('deepseek-v4-pro')) +// SELECT a.id, a.name, btrim(m.value) AS allowed_model +// FROM accounts a, jsonb_array_elements_text(a.extra->'allowed_models') AS m +// WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud' +// AND jsonb_typeof(a.extra->'allowed_models') = 'array' +// AND btrim(m.value) <> '' +// AND lower(btrim(m.value)) NOT IN (SELECT model FROM priced) +// AND lower(regexp_replace(btrim(m.value), ':.*$', '')) NOT IN (SELECT model FROM priced); +// +// -- 2) 空 mapping 账号必须有「有效清单」(非空字符串数组);期望 0 行 +// -- (空 mapping + 合法清单是合规形态,不算命中;此处命中的是既无 mapping +// -- 又无有效清单的账号——运行时 deny-all,需补 allowed_models/mapping 或下线) +// SELECT a.id, a.name, a.status, a.schedulable, +// CASE WHEN NOT (a.extra ? 'allowed_models') THEN 'no_allowed_models_key' +// WHEN jsonb_typeof(a.extra->'allowed_models') <> 'array' THEN 'allowed_models_not_array' +// WHEN NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(a.extra->'allowed_models') +// WHERE btrim(value) <> '') THEN 'allowed_models_empty' +// END AS reason +// FROM accounts a +// WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud' +// AND COALESCE(a.credentials->'model_mapping','{}'::jsonb) = '{}'::jsonb +// AND (NOT (a.extra ? 'allowed_models') +// OR jsonb_typeof(a.extra->'allowed_models') <> 'array' +// OR NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(a.extra->'allowed_models') +// WHERE btrim(value) <> '')); +// +// 上线后观察断言:日志中 `openai_usage.pricing_missing_record_zero_cost` 出现 +// 次数必须为 0(出现即回滚放量)。定价门禁已前移到上游 I/O 之前的请求期预检 +// (openai_gateway_ollama_cloud_pricing_preflight.go,未定价直接 400,不发上游); +// 记账阶段不再拒绝——这里只保留零成本落账 + 本告警作为「预检漏放」的兜底观测, +// 两者不互相遮蔽:告警出现即说明有请求绕过了预检,需要排查而不是靠记账阶段补拒。 +// // RecordUsage records usage and deducts balance func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRecordUsageInput) error { if input == nil { @@ -254,6 +320,11 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec if !isUsagePricingUnavailableError(err) { return err } + // 定价缺失回到既有的全平台 fail-open 设计:零成本落账 + Warn 告警。 + // ollama_cloud 的请求期拒绝已前移到上游 I/O 之前的定价预检(见 + // openai_gateway_ollama_cloud_pricing_preflight.go);记账阶段拒绝会在 + // 上游已调用、响应已写给客户端之后连 usage 记录一起丢掉,比零成本记录 + // 更难发现,故不再在此拒绝——本告警是「预检漏放」的观测依据。 logger.L().With( zap.String("component", "service.openai_gateway"), zap.Strings("billing_models", billingModels), @@ -921,19 +992,22 @@ func groupMediaPricingLooksIncomplete(group *Group) bool { group.VideoPrice480P == nil && group.VideoPrice720P == nil && group.VideoPrice1080P == nil } -// filterCNProviderBillingModelCandidates 过滤国产供应商(kimi/zhipu/deepseek) -// 账号的计费候选模型名:claude-* 候选仅在运营者显式配置了分组/渠道定价时保留。 +// filterCNProviderBillingModelCandidates 过滤 CN/类 CN 平台(kimi/zhipu/deepseek/ +// opencode_go/ollama_cloud)账号的计费候选模型名:claude-* 候选仅在运营者显式 +// 配置了分组/渠道定价时保留。 // // 背景:候选链的兜底候选含客户端请求的原始模型名。CN 上游的 Anthropic 兼容端点 // 接受 claude-* 模型名但从不真正服务 Claude 模型;若放行,目录里的 Claude 价卡 // 与 getFallbackPricing 的 "claude"→Sonnet 统一兜底会把 CN 流量按 Claude 原价 // (数倍~数十倍)静默误计,且 usage 日志显示的正是 claude-* 名,无从察觉。 +// ollama_cloud 同理:它服务的是自家托管模型(qwen3.5/gpt-oss/nemotron 等), +// 请求里的 claude-* 名不会真的被 Claude 服务,放行即按 Anthropic 价误计。 // 候选全部落空时走既有的零成本+告警路径(openai_usage.pricing_missing_record_ -// zero_cost),与定价层「未知型号不回退以避免误计价」的既有设计意图一致; -// 运营者的修复手段是配置账号级 model_mapping(映射到已定价的 CN 模型)或 -// 分组/渠道显式定价。 +// zero_cost;ollama_cloud 已由 B2-④ 收窄为显式拒绝),与定价层「未知型号不回退 +// 以避免误计价」的既有设计意图一致;运营者的修复手段是配置账号级 model_mapping +// (映射到已定价的 CN/ollama 模型)或分组/渠道显式定价。 func (s *OpenAIGatewayService) filterCNProviderBillingModelCandidates(ctx context.Context, account *Account, apiKey *APIKey, candidates []string) []string { - if account == nil || (!account.IsCNProvider() && !account.IsOpenCodeGo()) { + if account == nil || (!account.IsCNProvider() && !account.IsOpenCodeGo() && !account.IsOllamaCloud()) { return candidates } out := make([]string, 0, len(candidates)) diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index 701526252b..f33e4ef1a3 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1148,7 +1148,13 @@ func (s *PricingService) GetModelPricing(modelName string) *LiteLLMModelPricing } // 5. OpenAI 模型回退策略 - if strings.HasPrefix(lookupCandidates[0], "gpt-") { + // gpt-oss: 是开放权重模型(ollama cloud 等托管),不属于 OpenAI 模型家族: + // 不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把它落到 + // DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计。 + // 返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 专属价卡。 + // 排除只收窄到 "gpt-oss:"(冒号命名空间,ollama 命名形态);连字符形态如 + // Antigravity 的 "gpt-oss-120b-medium" 不在排除内,保持进 OpenAI 链的既有行为。 + if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.HasPrefix(lookupCandidates[0], "gpt-oss:") { return s.matchOpenAIModel(lookupCandidates[0]) } diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 4158d0559c..922b891f25 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -987,10 +987,10 @@ func (s *RateLimitService) handle403(ctx context.Context, account *Account, upst s.handleCNProviderConcurrencyLimit403(ctx, account) return true } - // 国产供应商与 openai 同口径:HTML 403(CDN/代理拦截页)不构成账号失效证据, - // 且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个坏请求/ - // 一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。 - if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() { + // 国产供应商、openai 与 ollama_cloud 同口径:HTML 403(CDN/代理拦截页)不构成账号 + // 失效证据,且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个 + // 坏请求/一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。 + if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() || account.IsOllamaCloud() { return s.handleOpenAI403(ctx, account, upstreamMsg, responseBody) } // 非 Antigravity 平台:保持原有行为 diff --git a/backend/internal/service/ratelimit_service_403_html_test.go b/backend/internal/service/ratelimit_service_403_html_test.go index 5c8f782598..039a60c269 100644 --- a/backend/internal/service/ratelimit_service_403_html_test.go +++ b/backend/internal/service/ratelimit_service_403_html_test.go @@ -151,6 +151,20 @@ func TestHandleUpstreamError_HTML403OnOtherPlatformsUnchanged(t *testing.T) { } } +// ollama_cloud 迁到独立 platform 后必须继续命中 HTML 403 豁免:与 openai/ +// 国产/opencode_go 同为多协议 API Key 网关,链路级 403 同样不构成账号失效 +// 证据;漏加会在迁移后掉进默认 SetError 永久禁号路径。 +func TestHandleUpstreamError_OllamaCloudHTML403DoesNotPenalizeAccount(t *testing.T) { + h := newOpenAI403TestHarness(t, 507, 1) + h.account.Platform = PlatformOllamaCloud + h.account.Type = AccountTypeAPIKey + + shouldDisable := h.handle(openAI403HTMLBody) + + require.False(t, shouldDisable, "ollama_cloud 的 HTML 403 不得判定账号应下线") + h.requireNoAccountPenalty(t) +} + func TestIsHTMLResponse(t *testing.T) { cases := []struct { name string diff --git a/backend/internal/service/ratelimit_service_scheduling_threshold_test.go b/backend/internal/service/ratelimit_service_scheduling_threshold_test.go index 2af50086ae..fc3154e76f 100644 --- a/backend/internal/service/ratelimit_service_scheduling_threshold_test.go +++ b/backend/internal/service/ratelimit_service_scheduling_threshold_test.go @@ -228,3 +228,81 @@ func TestRateLimitService_ApplyAccountSchedulingThreshold_UnsupportedPlatformDoe require.Nil(t, account.TempUnschedulableUntil) require.Empty(t, account.TempUnschedulableReason) } + +func TestRateLimitService_ApplyAccountSchedulingThreshold_OllamaCloudLegacySetsTempUnschedulable(t *testing.T) { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + + settingsRepo := newMockSettingRepo() + settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"ollama_cloud":80}` + + accountRepo := &rateLimitAccountRepoStub{} + rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil) + rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{})) + + until := time.Now().UTC().Add(2 * time.Hour) + account := &Account{ + ID: 3001, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "account_mode": "ollama_legacy", + }, + Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(95, until), + "seven_day": ollamaCloudUsageWindowFixture(40, until.Add(5*24*time.Hour)), + }), + } + + blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account) + + require.True(t, blocked) + require.Equal(t, 1, accountRepo.tempCalls) + require.NotNil(t, account.TempUnschedulableUntil) + require.WithinDuration(t, until, *account.TempUnschedulableUntil, time.Second) + require.True(t, IsAccountSchedulingThresholdReason(accountRepo.lastTempReason)) + + var payload map[string]any + require.NoError(t, json.Unmarshal([]byte(accountRepo.lastTempReason), &payload)) + require.Equal(t, PlatformOllamaCloud, payload["platform"]) + require.Equal(t, "5h", payload["window"]) + require.Equal(t, float64(80), payload["threshold_percent"]) + require.Equal(t, float64(95), payload["used_percent"]) +} + +func TestRateLimitService_ApplyAccountSchedulingThreshold_OllamaCloudCreditsDoesNotBlock(t *testing.T) { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + + settingsRepo := newMockSettingRepo() + settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"ollama_cloud":80}` + + accountRepo := &rateLimitAccountRepoStub{} + rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil) + rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{})) + + until := time.Now().UTC().Add(2 * time.Hour) + account := &Account{ + ID: 3002, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "account_mode": "ollama_credits", + }, + Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(100, until), + "seven_day": ollamaCloudUsageWindowFixture(100, until.Add(5*24*time.Hour)), + }), + } + + blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account) + + require.False(t, blocked) + require.Equal(t, 0, accountRepo.tempCalls) + require.Nil(t, account.TempUnschedulableUntil) + require.Empty(t, account.TempUnschedulableReason) +} diff --git a/backend/internal/service/scheduler_snapshot_bulk_event_test.go b/backend/internal/service/scheduler_snapshot_bulk_event_test.go index 17bfec7c9f..49feb5aacb 100644 --- a/backend/internal/service/scheduler_snapshot_bulk_event_test.go +++ b/backend/internal/service/scheduler_snapshot_bulk_event_test.go @@ -115,7 +115,7 @@ func TestSchedulerBulkAccountEventScopesOpenAIRebuildToFreshPlatform(t *testing. } func TestSchedulerBulkAccountEventScopesCNRebuildToFreshPlatform(t *testing.T) { - for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} { t.Run(platform, func(t *testing.T) { cache := newBulkEventSnapshotCache() repo := newBulkEventAccountRepo(&Account{ID: 1, Platform: platform, GroupIDs: []int64{12}}) diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 14d43f0c87..31caa57fce 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -609,7 +609,7 @@ func (s *SchedulerSnapshotService) handleBulkAccountEvent(ctx context.Context, p } accountGroupIDs := s.normalizeGroupIDs(account.GroupIDs) switch account.Platform { - case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: addPlatformGroups(account.Platform, accountGroupIDs) case PlatformAntigravity: // 批量更新可能刚关闭 mixed_scheduling,仍需清理两个兼容平台的旧快照。 @@ -824,8 +824,11 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account return s.rebuildBuckets(ctx, buckets, reason) } -func schedulerSnapshotPlatforms() [10]string { - return [10]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} +// schedulerSnapshotPlatforms 是 canonical 桶覆盖的平台全集:新增 concrete +// platform 必须同时扩展本数组与 scheduler_snapshot 的批量变更 switch(否则 +// 桶不在 canonical 集里、rebuild 不覆盖 → 缓存永不命中)。 +func schedulerSnapshotPlatforms() [11]string { + return [11]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} } // 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。 diff --git a/backend/internal/service/setting_service_platform_threshold_test.go b/backend/internal/service/setting_service_platform_threshold_test.go index 3e4543e0e0..b8281cd6db 100644 --- a/backend/internal/service/setting_service_platform_threshold_test.go +++ b/backend/internal/service/setting_service_platform_threshold_test.go @@ -169,3 +169,31 @@ func TestGetAccountSchedulingThresholds_NilRepoReturnsDefaults(t *testing.T) { PlatformGrok: 100, }, got) } + +func TestValidateAndNormalizeAccountSchedulingThresholds_AcceptsOllamaCloud(t *testing.T) { + normalized, err := validateAndNormalizeAccountSchedulingThresholds(map[string]int{ + PlatformOllamaCloud: 80, + }) + require.NoError(t, err) + require.Equal(t, 80, normalized[PlatformOllamaCloud]) +} + +func TestAccountSchedulingThresholds_OllamaCloudRoundTrip(t *testing.T) { + svc := newSettingServiceForPlatformThresholdTest(nil) + + // A6 验收的服务层等价路径:PUT account_scheduling_thresholds {"ollama_cloud":80} + // 必须被接受并回读 —— 白名单未纳入 ollama_cloud 时这里被 + // validateAndNormalizeAccountSchedulingThresholds 拒为 unknown platform(400)。 + err := svc.UpdateSettings(context.Background(), &SystemSettings{ + AccountSchedulingThresholds: map[string]int{ + PlatformOllamaCloud: 80, + }, + }) + require.NoError(t, err) + + stored := svc.settingRepo.(*mockSettingRepo).data[SettingKeyAccountSchedulingThresholds] + require.Contains(t, stored, `"ollama_cloud":80`) + + cached := svc.GetAccountSchedulingThresholds(context.Background()) + require.Equal(t, 80, cached[PlatformOllamaCloud]) +} diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index 97603793e5..1f3253a5b8 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -626,7 +626,9 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "missing_api_key", 0) } baseURL := account.GetCredential("base_url") - if account.IsCNProvider() && account.IsAdaptiveAPIProtocol() { + // 多协议 adaptive 账号(CN 供应商 / ollama_cloud)的探测 base 与出站 + // base 同源:优先读 api_base_urls 分协议地址,而不是 legacy credentials.base_url。 + if (account.IsCNProvider() || account.IsOllamaCloud()) && account.IsAdaptiveAPIProtocol() { baseURL = account.GetCNProtocolBaseURL(APIProtocolChatCompletions) } if account.Platform == PlatformOpenAI { @@ -1013,7 +1015,8 @@ func IsUpstreamBillingProbeIdentity(platform, accountType string) bool { } switch platform { case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok, - PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud: return true default: return false @@ -1034,9 +1037,11 @@ func isUpstreamBillingProbeAccount(account *Account) bool { // relays (the only targets that can answer /v1/sub2api/billing) always do // probe. OpenAI-platform accounts never reach this check: they keep the // upstream-official behavior of probing api.openai.com. -// ollama.com is a first-class configuration here (Ollama Cloud accounts are -// platform openai/anthropic with base_url https://ollama.com/v1), and it is -// an official provider API just like the rest, so it belongs on this list. +// ollama.com is a first-class configuration here (it is the official Ollama +// Cloud API base: platform ollama_cloud accounts use https://ollama.com/v1, +// and legacy openai/anthropic-platform accounts may still point at the same +// host), and it is an official provider API just like the rest, so it belongs +// on this list. // CN provider domains (moonshot.cn / kimi.com / bigmodel.cn / deepseek.com) // serve the same role: official APIs that can never host /v1/sub2api/billing, // so their accounts short-circuit to "unsupported" without a request. diff --git a/backend/internal/service/upstream_billing_probe_test.go b/backend/internal/service/upstream_billing_probe_test.go index 9a5f774f4f..ccd1cb7d62 100644 --- a/backend/internal/service/upstream_billing_probe_test.go +++ b/backend/internal/service/upstream_billing_probe_test.go @@ -372,6 +372,40 @@ func TestUpstreamBillingProbeAdaptiveCNUsesChatProtocolBaseURL(t *testing.T) { require.Equal(t, "https://chat-relay.example/v1/sub2api/billing", upstream.lastReq.URL.String()) } +// Scenario: ollama_cloud adaptive 账号配置 api_base_urls[chat_completions] 时, +// 探测 base 与出站 base 同源(读分协议地址,而非 legacy credentials.base_url)。 +func TestUpstreamBillingProbeAdaptiveOllamaCloudUsesChatProtocolBaseURL(t *testing.T) { + account := &Account{ + ID: 19, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-sensitive", + "api_protocol": APIProtocolAdaptive, + "base_url": "https://legacy-relay.example/v1", + "api_base_urls": map[string]any{ + APIProtocolChatCompletions: "https://chat.example/v1", + }, + }, + Extra: map[string]any{UpstreamBillingProbeEnabledExtraKey: true}, + } + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: upstreamBillingProbeValidBody(), + }} + svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{}) + + snapshot, err := svc.ProbeAccount(context.Background(), account.ID) + + require.NoError(t, err) + require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status) + require.Equal(t, "https://chat.example/v1/sub2api/billing", upstream.lastReq.URL.String()) +} + func TestUpstreamBillingProbeSyncsResolvedRateForAllAPIKeyPlatforms(t *testing.T) { for _, platform := range []string{ PlatformOpenAI, diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 23ae22fa5d..16c831ed28 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -625,7 +625,7 @@ func upstreamModelRegistryBaseURL(account *Account) string { return "" } switch { - case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo(): + case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud(): return account.GetOpenAIFormatBaseURL() case account.IsGrok(): return account.GetGrokBaseURL() @@ -687,6 +687,12 @@ func matchModelsDevProviderByKnownHost(registry map[string]modelsDevProvider, ac providerID = "openai" case "opencode.ai": providerID = "opencode-go" + case "ollama.com": + // 实测 models.dev registry(api.json):provider ID 是 `ollama-cloud` + // (不是 "ollama"),且其 api 字段为 https://ollama.com/v1 —— 常规 + // base 走上方 API-URL 匹配即可命中;本 case 兜底 registry 形态漂移 + // (api 字段缺失/变更)或非常规路径形式,避免官方 host 静默丢元数据。 + providerID = "ollama-cloud" default: return modelsDevProvider{}, false } @@ -792,9 +798,9 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc return s.buildAntigravityAPIKeyModelsRequest(ctx, account) case account.IsGrok(): return s.buildGrokUpstreamModelsRequest(ctx, account) - case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo(): - // 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go - // 复用 OpenAI /v1/models 探测。 + case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud(): + // 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与 + // Ollama Cloud 复用 OpenAI /v1/models 探测。 return s.buildOpenAIUpstreamModelsRequest(ctx, account) case account.IsGemini(): return s.buildGeminiUpstreamModelsRequest(ctx, account) diff --git a/backend/internal/service/upstream_models_test.go b/backend/internal/service/upstream_models_test.go index e0e9f263ec..016e87f76b 100644 --- a/backend/internal/service/upstream_models_test.go +++ b/backend/internal/service/upstream_models_test.go @@ -929,6 +929,50 @@ func TestMatchModelsDevProviderFallsBackToOpenAIProviderWithoutAPIField(t *testi require.Equal(t, "opencode", provider.ID) } +// Scenario: ollama.com 账号的模型 registry 元数据能匹配到 models.dev 的 +// ollama-cloud provider(实测 provider ID 为 `ollama-cloud`,非 "ollama")。 +// registry 带 api 字段(当前真实形态 https://ollama.com/v1)时走 API-URL +// 匹配;api 字段缺失(registry 形态漂移)时 known-host 兜底仍命中; +// 反代 host 不继承官方 provider,避免跨厂商错误归因。 +func TestMatchModelsDevProviderOllamaCloud(t *testing.T) { + t.Parallel() + + newRegistry := func(withAPI bool) map[string]modelsDevProvider { + provider := modelsDevProvider{ + ID: "ollama-cloud", + Name: "Ollama Cloud", + Models: map[string]modelsDevModel{ + "gpt-oss:120b": {ID: "gpt-oss:120b", Name: "GPT-OSS 120B"}, + }, + } + if withAPI { + provider.API = "https://ollama.com/v1" + } + return map[string]modelsDevProvider{"ollama-cloud": provider} + } + + // registry 带 api 字段:API-URL 匹配直接命中。 + for _, baseURL := range []string{ + "https://ollama.com/v1", + "https://ollama.com", + } { + provider, ok := matchModelsDevProvider(newRegistry(true), baseURL) + require.True(t, ok, baseURL) + require.Equal(t, "ollama-cloud", provider.ID, baseURL) + require.Contains(t, provider.Models, "gpt-oss:120b", baseURL) + } + + // registry api 字段缺失(形态漂移):known-host 兜底命中官方 host。 + provider, ok := matchModelsDevProvider(newRegistry(false), "https://ollama.com/v1") + require.True(t, ok) + require.Equal(t, "ollama-cloud", provider.ID) + require.Contains(t, provider.Models, "gpt-oss:120b") + + // 反代/自定义 host 不命中:同前缀名字不得跨厂商归因到 ollama-cloud。 + _, ok = matchModelsDevProvider(newRegistry(true), "https://relay.example.com/v1") + require.False(t, ok, "custom hosts must not inherit the official ollama-cloud provider by name") +} + // Scenario: 官方 OpenAI ID-only /models + 无 api 字段的 models.dev openai 条目仍能补齐并落库。 func TestSyncUpstreamModelCatalogEnrichesOfficialOpenAIHostWithoutRegistryAPIField(t *testing.T) { upstream := &httpUpstreamRecorder{responses: []*http.Response{ diff --git a/backend/migrations/239_ollama_cloud_platform.sql b/backend/migrations/239_ollama_cloud_platform.sql new file mode 100644 index 0000000000..2aada9bd09 --- /dev/null +++ b/backend/migrations/239_ollama_cloud_platform.sql @@ -0,0 +1,67 @@ +-- Add Ollama Cloud as a first-class platform. +-- +-- 1. user_platform_quotas.platform CHECK +-- 2. composite_model_routes.target_platform CHECK +-- 3. channel_monitors / channel_monitor_request_templates provider CHECK +-- +-- Runs after 238_opencode_go_platform.sql. DROP ... IF EXISTS + 幂等守卫保证可重入; +-- 新约束是 238 的超集,必须同时保留 MiniMax 与 OpenCode Go。 +-- 零 DML 回填:与 157/224/237/238 一致,只放宽约束,不写任何 DML。 + +ALTER TABLE user_platform_quotas + DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; + +ALTER TABLE user_platform_quotas + ADD CONSTRAINT user_platform_quotas_platform_check + CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + +ALTER TABLE composite_model_routes + DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check; + +ALTER TABLE composite_model_routes + ADD CONSTRAINT composite_model_routes_target_platform_check + CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + +DO $$ +DECLARE + monitor_constraint_def TEXT; + template_constraint_def TEXT; +BEGIN + SELECT pg_get_constraintdef(c.oid) + INTO monitor_constraint_def + FROM pg_constraint c + JOIN pg_class t ON t.oid = c.conrelid + WHERE t.relname = 'channel_monitors' + AND c.conname = 'channel_monitors_provider_check'; + + IF monitor_constraint_def IS NULL OR position('ollama_cloud' IN monitor_constraint_def) = 0 THEN + ALTER TABLE channel_monitors + DROP CONSTRAINT IF EXISTS channel_monitors_provider_check; + ALTER TABLE channel_monitors + ADD CONSTRAINT channel_monitors_provider_check + CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', + 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + END IF; + + SELECT pg_get_constraintdef(c.oid) + INTO template_constraint_def + FROM pg_constraint c + JOIN pg_class t ON t.oid = c.conrelid + WHERE t.relname = 'channel_monitor_request_templates' + AND c.conname = 'channel_monitor_request_templates_provider_check'; + + IF template_constraint_def IS NULL OR position('ollama_cloud' IN template_constraint_def) = 0 THEN + ALTER TABLE channel_monitor_request_templates + DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check; + ALTER TABLE channel_monitor_request_templates + ADD CONSTRAINT channel_monitor_request_templates_provider_check + CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', + 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + END IF; +END $$; diff --git a/backend/migrations/ollama_cloud_platform_migration_test.go b/backend/migrations/ollama_cloud_platform_migration_test.go new file mode 100644 index 0000000000..ab5362f775 --- /dev/null +++ b/backend/migrations/ollama_cloud_platform_migration_test.go @@ -0,0 +1,30 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOllamaCloudPlatformMigration(t *testing.T) { + content, err := FS.ReadFile("239_ollama_cloud_platform.sql") + require.NoError(t, err) + + sql := strings.Join(strings.Fields(string(content)), " ") + require.Contains(t, sql, "user_platform_quotas_platform_check") + require.Contains(t, sql, "composite_model_routes_target_platform_check") + require.Contains(t, sql, "channel_monitors_provider_check") + require.Contains(t, sql, "channel_monitor_request_templates_provider_check") + require.Contains(t, sql, "'ollama_cloud'") + require.Contains(t, sql, "'minimax'") + require.Contains(t, sql, "'opencode_go'") + require.Contains(t, sql, "position('ollama_cloud' IN monitor_constraint_def) = 0") + require.Contains(t, sql, "position('ollama_cloud' IN template_constraint_def) = 0") + require.Contains(t, sql, + "CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") + require.Contains(t, sql, + "CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") + require.Contains(t, sql, + "CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") +} diff --git a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts index deeb758250..67ae218e47 100644 --- a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts +++ b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts @@ -5,18 +5,15 @@ import { buildAuthSourceDefaultsState, normalizePlatformQuotasMap, sanitizePlatformQuotasMap, + QUOTA_PLATFORMS, type UpdateSettingsRequest, type DefaultPlatformQuotasMap, } from "@/api/admin/settings"; -/** 全 null 的 5 平台 map,用于断言归一化默认值 */ -const allNullQuotas: DefaultPlatformQuotasMap = { - anthropic: { daily: null, weekly: null, monthly: null }, - openai: { daily: null, weekly: null, monthly: null }, - gemini: { daily: null, weekly: null, monthly: null }, - antigravity: { daily: null, weekly: null, monthly: null }, - grok: { daily: null, weekly: null, monthly: null }, -} +/** 全 null 的全平台 map,用于断言归一化默认值 */ +const allNullQuotas: DefaultPlatformQuotasMap = Object.fromEntries( + QUOTA_PLATFORMS.map((p) => [p, { daily: null, weekly: null, monthly: null }] as const), +); describe("admin settings auth source defaults helpers", () => { it("builds auth source defaults state from flat settings fields", () => { @@ -240,14 +237,47 @@ describe("normalizePlatformQuotasMap", () => { expect(result.grok).toEqual({ daily: null, weekly: null, monthly: null }); }); - it("无参数时返回全 5 平台全 null", () => { + it("无参数时返回全平台(对齐后端 AllowedQuotaPlatforms)全 null", () => { const result = normalizePlatformQuotasMap(); - expect(Object.keys(result)).toHaveLength(5); + expect(Object.keys(result)).toHaveLength(QUOTA_PLATFORMS.length); for (const v of Object.values(result)) { expect(v).toEqual({ daily: null, weekly: null, monthly: null }); } }); + it("预置 ollama_cloud 配额在 normalize 后保留(不再被旧 5 平台列表丢弃)", () => { + const result = normalizePlatformQuotasMap({ + ollama_cloud: { daily: 3, weekly: 30, monthly: 300 }, + kimi: { daily: 1, weekly: null, monthly: null }, + zhipu: { daily: null, weekly: 2, monthly: null }, + deepseek: { daily: null, weekly: null, monthly: 4 }, + minimax: { daily: 0.5, weekly: null, monthly: null }, + opencode_go: { daily: null, weekly: null, monthly: null }, + }); + expect(result.ollama_cloud).toEqual({ daily: 3, weekly: 30, monthly: 300 }); + expect(result.kimi).toEqual({ daily: 1, weekly: null, monthly: null }); + expect(result.zhipu).toEqual({ daily: null, weekly: 2, monthly: null }); + expect(result.deepseek).toEqual({ daily: null, weekly: null, monthly: 4 }); + expect(result.minimax).toEqual({ daily: 0.5, weekly: null, monthly: null }); + expect(result.opencode_go).toEqual({ daily: null, weekly: null, monthly: null }); + }); + + it("保留未知平台 key(后端新加、前端未收录)", () => { + const result = normalizePlatformQuotasMap({ + anthropic: { daily: 5, weekly: null, monthly: null }, + some_future_platform: { daily: 7, weekly: 8, monthly: 9 }, + } as DefaultPlatformQuotasMap); + expect(result.some_future_platform).toEqual({ daily: 7, weekly: 8, monthly: 9 }); + expect(result.anthropic).toEqual({ daily: 5, weekly: null, monthly: null }); + }); + + it("未知平台的非 number 值归一化为 null", () => { + const result = normalizePlatformQuotasMap({ + some_future_platform: { daily: "50" as unknown as number, weekly: undefined as unknown as number, monthly: null }, + } as DefaultPlatformQuotasMap); + expect(result.some_future_platform).toEqual({ daily: null, weekly: null, monthly: null }); + }); + it("非 number 类型的值归一化为 null", () => { const result = normalizePlatformQuotasMap({ anthropic: { daily: "50" as unknown as number, weekly: undefined as unknown as number, monthly: null }, @@ -288,9 +318,23 @@ describe("sanitizePlatformQuotasMap", () => { expect(result.gemini?.weekly).toBe(null); }); + it("预置 ollama_cloud 配额清洗后保留(提交 payload 不再丢行)", () => { + const result = sanitizePlatformQuotasMap({ + ollama_cloud: { daily: 3, weekly: 0, monthly: null }, + }); + expect(result.ollama_cloud).toEqual({ daily: 3, weekly: 0, monthly: null }); + }); + + it("保留未知平台 key 且同样清洗其值", () => { + const result = sanitizePlatformQuotasMap({ + some_future_platform: { daily: 7, weekly: -3, monthly: "x" as unknown as number }, + } as DefaultPlatformQuotasMap); + expect(result.some_future_platform).toEqual({ daily: 7, weekly: null, monthly: null }); + }); + it("缺失平台填充为全 null", () => { const result = sanitizePlatformQuotasMap({}); - expect(Object.keys(result)).toHaveLength(5); + expect(Object.keys(result)).toHaveLength(QUOTA_PLATFORMS.length); for (const v of Object.values(result)) { expect(v).toEqual({ daily: null, weekly: null, monthly: null }); } diff --git a/frontend/src/api/admin/channelMonitor.ts b/frontend/src/api/admin/channelMonitor.ts index 7ddd5697e5..6ac25d15ec 100644 --- a/frontend/src/api/admin/channelMonitor.ts +++ b/frontend/src/api/admin/channelMonitor.ts @@ -16,6 +16,7 @@ export type Provider = | 'deepseek' | 'minimax' | 'opencode_go' + | 'ollama_cloud' export type MonitorStatus = 'operational' | 'degraded' | 'failed' | 'error' export type BodyOverrideMode = 'off' | 'merge' | 'replace' export type APIMode = 'chat_completions' | 'responses' diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 4c8c06a7a3..967329e64d 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -17,7 +17,26 @@ export interface DefaultSubscriptionSetting { } // ── 平台限额类型 ────────────────────────────────────────────────── -export type PlatformType = "anthropic" | "openai" | "gemini" | "antigravity" | "grok" + +// 配额平台镜像:与后端 service.AllowedQuotaPlatforms 保持一致(单一权威来源: +// backend/internal/service/domain_constants.go)。后端对 default_platform_quotas +// 与用户平台配额均为整体替换语义:这份列表缺一个平台,保存时就会静默丢弃 +// 该平台的配额行(缺行等价于不限额 → 限额 fail-open)。新增平台必须同步此列表。 +export const QUOTA_PLATFORMS = [ + "anthropic", + "openai", + "gemini", + "antigravity", + "grok", + "kimi", + "zhipu", + "deepseek", + "minimax", + "opencode_go", + "ollama_cloud", +] as const + +export type PlatformType = (typeof QUOTA_PLATFORMS)[number] export type QuotaWindowType = "daily" | "weekly" | "monthly" /** 单平台三档限额;null = 不限制,undefined = 未填(等价 null) */ @@ -27,10 +46,13 @@ export interface PlatformQuotaLimits { monthly: number | null } -/** 全平台默认限额 map(key = PlatformType) */ -export type DefaultPlatformQuotasMap = Partial> - -const PLATFORMS: PlatformType[] = ["anthropic", "openai", "gemini", "antigravity", "grok"] +/** + * 全平台默认限额 map(key = PlatformType)。 + * 可能额外含后端新加、前端尚未收录的平台 key:整体替换语义下 normalize/sanitize + * 必须原样保留这些 key,否则一次保存就会静默删除该平台的默认配额。 + */ +export type DefaultPlatformQuotasMap = Partial> & + Record export type SchedulingThresholdPlatformType = | "openai" @@ -40,11 +62,13 @@ export type SchedulingThresholdPlatformType = | "zhipu" | "minimax" | "opencode_go" + | "ollama_cloud" export type AccountSchedulingThresholdsMap = Record // 与后端 AllowedSchedulingThresholdPlatforms 保持一致(deepseek 为余额型, -// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口)。 +// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口; +// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口,credits 型月度信用池无窗口不停调)。 export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] = [ "openai", "anthropic", @@ -53,6 +77,7 @@ export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] = "zhipu", "minimax", "opencode_go", + "ollama_cloud", ] export function normalizeAccountSchedulingThresholdsMap( @@ -74,27 +99,45 @@ export function sanitizeAccountSchedulingThresholdsMap( return normalizeAccountSchedulingThresholdsMap(input) } -/** 归一化为全 4 平台 × 3 窗口(缺失填 null),供模板非空绑定 */ +/** 归一化为全平台 × 3 窗口(缺失填 null),供模板非空绑定;保留输入中的未知平台 key */ export function normalizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap { + const normalizeOne = (src?: PlatformQuotaLimits): PlatformQuotaLimits => ({ + daily: typeof src?.daily === "number" ? src.daily : null, + weekly: typeof src?.weekly === "number" ? src.weekly : null, + monthly: typeof src?.monthly === "number" ? src.monthly : null, + }) const result: DefaultPlatformQuotasMap = {} - for (const p of PLATFORMS) { - const src = input?.[p] - result[p] = { - daily: typeof src?.daily === "number" ? src.daily : null, - weekly: typeof src?.weekly === "number" ? src.weekly : null, - monthly: typeof src?.monthly === "number" ? src.monthly : null, + for (const p of QUOTA_PLATFORMS) { + result[p] = normalizeOne(input?.[p]) + } + // 稳健性护栏:后端新加、前端尚未收录的平台 key 原样保留(整体替换语义下 + // 丢弃 = 静默删除该平台的默认配额)。 + if (input) { + for (const [key, value] of Object.entries(input)) { + if (!(QUOTA_PLATFORMS as readonly string[]).includes(key)) { + result[key] = normalizeOne(value) + } } } return result } -/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全 4 平台嵌套 map */ +/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全平台嵌套 map;保留未知平台 key */ export function sanitizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap { const clean = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null) + const sanitizeOne = (src?: PlatformQuotaLimits): PlatformQuotaLimits => ({ + daily: clean(src?.daily), weekly: clean(src?.weekly), monthly: clean(src?.monthly), + }) const result: DefaultPlatformQuotasMap = {} - for (const p of PLATFORMS) { - const src = input?.[p] - result[p] = { daily: clean(src?.daily), weekly: clean(src?.weekly), monthly: clean(src?.monthly) } + for (const p of QUOTA_PLATFORMS) { + result[p] = sanitizeOne(input?.[p]) + } + if (input) { + for (const [key, value] of Object.entries(input)) { + if (!(QUOTA_PLATFORMS as readonly string[]).includes(key)) { + result[key] = sanitizeOne(value) + } + } } return result } diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts index 738e0531c1..be05db89c5 100644 --- a/frontend/src/api/admin/users.ts +++ b/frontend/src/api/admin/users.ts @@ -5,6 +5,7 @@ import { apiClient } from '../client' import type { AdminUser, UpdateUserRequest, PaginatedResponse, ApiKey } from '@/types' +import type { PlatformType } from './settings' export interface AdminBindAuthIdentityChannelRequest { channel: string @@ -330,7 +331,9 @@ export async function bindUserAuthIdentity( /** * Platform quota types */ -export type PlatformQuotaPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' +// 与后端 AllowedQuotaPlatforms 对齐;单一来源为 settings.ts 的 QUOTA_PLATFORMS +// (后端用户平台配额 PUT 是整体替换语义,前端列表缺平台 = 保存即静默删行)。 +export type PlatformQuotaPlatform = PlatformType export type PlatformQuotaWindow = 'daily' | 'weekly' | 'monthly' export interface PlatformQuotaItem { diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 72a92dd865..00ec32a4b3 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -576,8 +576,11 @@
+ @@ -639,7 +642,7 @@
-
@@ -723,6 +726,10 @@ let visibilityObserver: IntersectionObserver | null = null const showUsageWindows = computed(() => { // Gemini: we can always compute local usage windows from DB logs (simulated quotas). if (props.account.platform === 'gemini') return true + // Ollama Cloud(apikey):不进本根分支——由下方 apikey 根分支渲染 + // OllamaCloudUsageCell(数据随账号 payload 下发 + 专用刷新端点,还带 + // today-stats 行)。eligibility 由后端下发的 ollama_cloud_usage.eligible 决定。 + if (props.account.platform === 'ollama_cloud' && props.account.type === 'apikey') return false // CN providers: apikey 账号也有滚动用量窗口(coding plan)或余额(payg), // 由 CNProviderQuotaCell / CNProviderBalanceCell 自行探测与展示。 if ( @@ -753,6 +760,9 @@ const shouldFetchUsage = computed(() => { if (props.account.platform === 'openai') { return props.account.type === 'oauth' } + // ollama_cloud 与 CN 平台同构:/usage API 对 apikey 账号一律拒绝(后端只 + // 支持 oauth/setup-token 查询);Ollama Cloud 用量数据随账号 payload 下发、 + // 由 OllamaCloudUsageCell 专用刷新端点更新——不拉取通用 /usage。 return false }) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 54a6b2331f..798a9314ec 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -228,6 +228,19 @@ OpenCode + @@ -532,6 +545,94 @@ + +
+ +
+ + +
+ +
+ + +
+ + +
+
+
+
@@ -3958,6 +4059,7 @@ import { type CnNativeApiProtocol, type CnProviderPlatform, type HeaderOverrideRow, + type OllamaCloudAccountMode, type OpenCodeAccountMode, type OpenCodeGoProtocolRule } from '@/components/account/credentialsBuilder' @@ -4156,6 +4258,10 @@ const upstreamBillingAutoProbeEnabled = ref(true) // ── 国产供应商(Kimi / Zhipu / DeepSeek)账号类型、API 协议与端点 ── const accountMode = ref('payg') const openCodeAccountMode = ref('zen') +// Ollama Cloud 双额度模式:legacy(5h/7d 滚动窗口)/ credits(月度美元信用池)。 +const ollamaAccountMode = ref('ollama_legacy') +// credits 模式的月度信用额度录入(USD);提交时解析,仅 credits 模式写入凭据。 +const ollamaMonthlyCreditUsdInput = ref('60') // API 协议决定转发端点与格式:cc=现有转换链,anthropic=原生直通(Claude Code), // responses=deepseek / kimi 原生 Responses 端点(Codex)。与账号类型正交。 const apiProtocol = ref('adaptive') @@ -4172,7 +4278,7 @@ const adaptiveBaseUrls = ref>({ }) const isCNPlatform = computed(() => isCNProviderPlatform(form.platform)) const isOpenCodeGoPlatform = computed(() => form.platform === 'opencode_go') -const isMultiProtocolPlatform = computed(() => isCNPlatform.value || isOpenCodeGoPlatform.value) +const isMultiProtocolPlatform = computed(() => isCNPlatform.value || isOpenCodeGoPlatform.value || form.platform === 'ollama_cloud') function currentOpenCodeOrCNMode(): CnAccountMode | OpenCodeAccountMode { return isOpenCodeGoPlatform.value ? openCodeAccountMode.value : accountMode.value } @@ -4184,8 +4290,9 @@ const cnPresetPlatform = computed(() => { } return 'kimi' }) -const adaptivePresetPlatform = computed(() => { +const adaptivePresetPlatform = computed(() => { if (form.platform === 'opencode_go') return 'opencode_go' + if (form.platform === 'ollama_cloud') return 'ollama_cloud' return cnPresetPlatform.value }) // 当前平台可选的协议档(responses 仅 deepseek / kimi)。 @@ -4210,7 +4317,7 @@ const cnAdaptiveProtocolOptions = computed { return 'border-rose-500 bg-rose-50 dark:bg-rose-900/20' case 'opencode_go': return 'border-amber-500 bg-amber-50 dark:bg-amber-900/20' + case 'ollama_cloud': + return 'border-stone-500 bg-stone-50 dark:bg-stone-900/20' default: return 'border-primary-500 bg-primary-50 dark:bg-primary-900/20' } @@ -4244,6 +4353,8 @@ const cnAccentIconClass = computed(() => { return 'bg-rose-500 text-white' case 'opencode_go': return 'bg-amber-500 text-white' + case 'ollama_cloud': + return 'bg-stone-500 text-white' default: return 'bg-primary-500 text-white' } @@ -4271,6 +4382,17 @@ function selectOpenCodeGoPlatform() { resetAdaptiveBaseUrls('opencode_go', openCodeAccountMode.value) openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultOpenCodeProtocolRules(openCodeAccountMode.value)) } +// 切换到 Ollama Cloud:强制 apikey 类型,账号模式回落 legacy,协议回落 adaptive, +// 端点重置为平台默认(ollama 的 base url 预设不区分账号模式,mode 参数仅为满足签名)。 +function selectOllamaCloudPlatform() { + form.platform = 'ollama_cloud' + form.type = 'apikey' + accountCategory.value = 'apikey' + apiProtocol.value = 'adaptive' + ollamaAccountMode.value = 'ollama_legacy' + apiKeyBaseUrl.value = defaultCNBaseUrl('ollama_cloud', accountMode.value, 'adaptive') + resetAdaptiveBaseUrls('ollama_cloud', accountMode.value) +} // 账号类型 / 协议变更时同步默认 base url。 watch(openCodeAccountMode, (mode, previousMode) => { if (!isOpenCodeGoPlatform.value) return @@ -5309,6 +5431,8 @@ const resetForm = () => { addMethod.value = 'oauth' accountMode.value = 'payg' openCodeAccountMode.value = 'zen' + ollamaAccountMode.value = 'ollama_legacy' + ollamaMonthlyCreditUsdInput.value = '60' apiProtocol.value = 'adaptive' openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultOpenCodeProtocolRules('zen')) adaptiveBaseUrls.value = { chat_completions: '', anthropic: '', responses: '' } @@ -5782,11 +5906,22 @@ const handleSubmit = async () => { credentials.tier_id = geminiTierAIStudio.value } - // 国产供应商:账号模式 + 协议 + 对应端点写入凭据;后端按 account_mode 路由 - // 额度/余额探测,按 api_protocol 路由转发端点与格式。注意 CN apikey 走本函数 - // 的通用路径(直接 doCreateAccount),不经过 createAccountAndFinish。 - if (isCNProviderPlatform(form.platform) || form.platform === 'opencode_go') { - credentials.account_mode = form.platform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value + // 国产供应商 / OpenCode / Ollama Cloud:账号模式 + 协议 + 对应端点写入凭据;后端按 + // account_mode 路由额度/余额探测,按 api_protocol 路由转发端点与格式。注意这些 apikey + // 平台走本函数的通用路径(直接 doCreateAccount),不经过 createAccountAndFinish。 + if (isCNProviderPlatform(form.platform) || form.platform === 'opencode_go' || form.platform === 'ollama_cloud') { + if (form.platform === 'ollama_cloud') { + // Ollama Cloud 双额度模式:credits 需同时录入月度信用额度(USD)作为分母。 + credentials.account_mode = ollamaAccountMode.value + if (ollamaAccountMode.value === 'ollama_credits') { + const monthlyCreditUsd = Number.parseFloat(ollamaMonthlyCreditUsdInput.value) + if (Number.isFinite(monthlyCreditUsd) && monthlyCreditUsd > 0) { + credentials.monthly_credit_usd = monthlyCreditUsd + } + } + } else { + credentials.account_mode = form.platform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value + } credentials.api_protocol = apiProtocol.value if (apiProtocol.value === 'adaptive') { const defaults = defaultCNAdaptiveBaseUrls( diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index 5f359ccca1..eeef65c187 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -210,7 +210,10 @@ const upstreamSyncPlatforms = new Set([ 'zhipu', 'deepseek', 'minimax', - 'opencode_go' + 'opencode_go', + // ollama_cloud:后端探测路径已就绪(upstream_models.go 的 IsOllamaCloud 谓词), + // 打开真实 /v1/models 上游同步。 + 'ollama_cloud' ]) const canSyncUpstream = computed(() => { if (props.accountId) { diff --git a/frontend/src/components/account/OllamaCloudUsageCell.vue b/frontend/src/components/account/OllamaCloudUsageCell.vue index 17c09050c0..9935f0a94b 100644 --- a/frontend/src/components/account/OllamaCloudUsageCell.vue +++ b/frontend/src/components/account/OllamaCloudUsageCell.vue @@ -4,22 +4,50 @@ class="min-w-0 max-w-full space-y-1" data-testid="ollama-cloud-usage-cell" > + + + - +
+ {{ balanceLabel }} +
+ +
+ {{ snapshotTimeLabel }} +
+ + {{ eligibleReasonLabel }} - @@ -62,6 +97,44 @@ const { t } = useI18n() const state = ref(props.account.ollama_cloud_usage) const refreshing = ref(false) const snapshot = computed(() => state.value?.snapshot) +const isCredits = computed(() => state.value?.mode === 'ollama_credits') + +// balance 是官方文本(如 "$12.00"),派生池进度需要数值:剥掉货币符号与 +// 千分位后 parseFloat;解析不了返回 null(回落为只显示原始文本)。 +const balanceNumber = computed(() => { + const raw = snapshot.value?.data?.balance + if (!raw) return null + const parsed = Number.parseFloat(raw.replace(/[^0-9.]/g, '')) + return Number.isFinite(parsed) ? parsed : null +}) + +// credits 模式的月度信用池已用百分比:(pool - balance) / pool,clamp 0-100。 +const creditsPoolUtilization = computed(() => { + const pool = state.value?.monthly_credit_usd + if (!isCredits.value || !pool || pool <= 0 || balanceNumber.value === null) return null + const used = ((pool - balanceNumber.value) / pool) * 100 + return Math.min(Math.max(used, 0), 100) +}) + +const balanceText = computed(() => snapshot.value?.data?.balance ?? '') +const balanceLabel = computed(() => { + const prefix = `${t('admin.accounts.ollamaCloud.balance')}: ${balanceText.value}` + const pool = state.value?.monthly_credit_usd + return isCredits.value && pool && pool > 0 ? `${prefix} / $${pool}` : prefix +}) + +const eligibleReasonLabel = computed(() => { + const reason = state.value?.eligible_reason + return reason ? t(`admin.accounts.ollamaCloud.eligibleReason.${reason}`) : '' +}) + +const snapshotTimeLabel = computed(() => { + const raw = snapshot.value?.fetched_at + if (!raw) return '' + const date = new Date(raw) + const formatted = Number.isNaN(date.getTime()) ? raw : date.toLocaleString() + return `${t('admin.accounts.ollamaCloud.updatedAt')}: ${formatted}` +}) watch(() => props.account.ollama_cloud_usage, (next) => { state.value = next diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index 954b6e15ec..9c11cae962 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -240,6 +240,81 @@ describe('AccountUsageCell', () => { expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(false) }) + // ollama_cloud 本体平台:eligible 由后端下发,api key 账号走通用 apikey 根 + // 分支(OllamaCloudUsageCell + today-stats),不进滚动用量窗口根分支,也不 + // 拉取通用 /usage(后端对 apikey 账号一律拒绝)。 + it('ollama_cloud apikey eligible 渲染 OllamaCloudUsageCell 且不经 /usage 拉取', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9100, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: makeOllamaUsage(9100) + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(true) + expect(wrapper.find('[data-test="cn-quota-cell"]').exists()).toBe(false) + expect(wrapper.find('[data-test="cn-balance-cell"]').exists()).toBe(false) + expect(getUsage).not.toHaveBeenCalled() + }) + + it('ollama_cloud apikey 账号(无 ollama_cloud_usage)渲染占位而非 CN quota 格', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9101, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: undefined + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(false) + expect(wrapper.find('[data-test="cn-quota-cell"]').exists()).toBe(false) + expect(wrapper.find('[data-test="cn-balance-cell"]').exists()).toBe(false) + expect(getUsage).not.toHaveBeenCalled() + }) + + // 不合格(如反代 base_url):后端也下发 state(带 eligible_reason),cell + // 照常挂载以展示可解释提示,而不是空白占位。 + it('ollama_cloud apikey 账号(eligible=false)仍渲染 OllamaCloudUsageCell 展示原因', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9102, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: makeOllamaUsage(9102, { + eligible: false, + eligible_reason: 'unsupported_base_url' + }) + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(true) + expect(getUsage).not.toHaveBeenCalled() + }) + it('Antigravity 图片用量会聚合新旧 image 模型', async () => { getUsage.mockResolvedValue({ antigravity_quota: { diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index f9cf78675a..02c1dd9d3b 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -712,3 +712,124 @@ describe('CreateAccountModal OpenAI long-context billing', () => { expect(createOpenAICodexPATMock.mock.calls[0]?.[0]?.extra?.openai_long_context_billing_enabled).toBe(false) }) }) + +describe('CreateAccountModal Ollama Cloud protocol and quota mode', () => { + beforeEach(() => { + createAccountMock.mockReset().mockResolvedValue({ id: 42, platform: 'ollama_cloud', type: 'apikey' }) + }) + + afterEach(() => { + vi.clearAllMocks() + }) + + async function selectOllamaCloudPlatform(wrapper: ReturnType) { + await selectButtonByText(wrapper, 'Ollama') + } + + it('shows the protocol selector with adaptive defaults when Ollama Cloud is selected', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + + // 协议选择器出现且默认 adaptive(adaptive 区渲染三个原生端点输入框) + expect(wrapper.findAll('button').some((b) => b.text().includes('admin.accounts.cnProviders.apiProtocol.adaptive'))).toBe(true) + expect(wrapper.find('[data-testid="cn-adaptive-base-url-chat_completions"]').exists()).toBe(true) + expect((wrapper.get('[data-testid="cn-adaptive-base-url-chat_completions"]').element as HTMLInputElement).value).toBe('https://ollama.com/v1') + // anthropic 端点预设不带 /v1(/v1/v1 静默 404 坑) + const anthropicUrl = (wrapper.get('[data-testid="cn-adaptive-base-url-anthropic"]').element as HTMLInputElement).value + expect(anthropicUrl).toBe('https://ollama.com') + expect(anthropicUrl.includes('/v1')).toBe(false) + expect((wrapper.get('[data-testid="cn-adaptive-base-url-responses"]').element as HTMLInputElement).value).toBe('https://ollama.com/v1') + }) + + it('submits adaptive ollama_cloud credentials with api_protocol and api_base_urls', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama cloud') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_legacy', + api_protocol: 'adaptive', + base_url: 'https://ollama.com/v1', + api_base_urls: { + chat_completions: 'https://ollama.com/v1', + anthropic: 'https://ollama.com', + responses: 'https://ollama.com/v1' + } + }) + expect('monthly_credit_usd' in credentials).toBe(false) + }) + + it('prefills the locked anthropic protocol endpoint without the /v1 suffix', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.cnProviders.apiProtocol.anthropic') + + const baseUrlInput = wrapper + .findAll('form#create-account-form input[type="text"]') + .map((input) => input.element as HTMLInputElement) + .find((input) => input.value.startsWith('https://ollama.com')) + expect(baseUrlInput).toBeDefined() + expect(baseUrlInput?.value).toBe('https://ollama.com') + expect(baseUrlInput?.value.includes('/v1')).toBe(false) + }) + + it('submits ollama_credits mode with the monthly credit amount', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.ollamaCloud.accountMode.credits') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama credits') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_credits', + api_protocol: 'adaptive', + monthly_credit_usd: 60 + }) + }) + + it('applies the 300 USD quick preset to the monthly credit input', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.ollamaCloud.accountMode.credits') + await wrapper.get('[data-testid="ollama-credit-preset-300"]').trigger('click') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama credits 300') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_credits', + monthly_credit_usd: 300 + }) + }) + + it('submits a locked protocol with the legacy mode and no credit field', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.cnProviders.apiProtocol.chatCompletions') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama cc') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_legacy', + api_protocol: 'chat_completions', + base_url: 'https://ollama.com/v1' + }) + expect('monthly_credit_usd' in credentials).toBe(false) + expect('api_base_urls' in credentials).toBe(false) + }) +}) diff --git a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts index e38f3d3729..49febab9a8 100644 --- a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts @@ -27,6 +27,7 @@ vi.mock('vue-i18n', async () => { const usageState = (): OllamaCloudUsageState => ({ account_id: 7, eligible: true, + mode: 'ollama_legacy', configured: true, auto_refresh_enabled: false, encryption_key_configured: true, @@ -104,8 +105,55 @@ describe('OllamaCloudUsageCell', () => { expect(query.classes()).toEqual(expect.arrayContaining(['text-blue-600', 'hover:bg-blue-50'])) expect(query.text()).toContain('admin.accounts.usageWindow.activeQuery') expect(wrapper.text()).not.toContain('max') - expect(wrapper.text()).not.toContain('$0') expect(wrapper.text()).not.toContain('gpt-oss:120b-cloud') + // legacy 模式追加 balance 文本(不含信用池分母)。 + const balance = wrapper.get('[data-testid="ollama-cloud-balance"]') + expect(balance.text()).toBe('admin.accounts.ollamaCloud.balance: $0') + }) + + it('renders legacy 5h/7d window bars and skips the pool bar', () => { + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account() } }) + + expect(wrapper.find('[data-testid="ollama-cloud-monthly-pool"]').exists()).toBe(false) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars.map(bar => bar.props('label'))).toEqual(['5h', '7d']) + expect(wrapper.find('[data-testid="ollama-cloud-snapshot-time"]').exists()).toBe(false) + }) + + it('renders the monthly pool bar for credits mode instead of window bars', () => { + const state = usageState() + state.mode = 'ollama_credits' + state.monthly_credit_usd = 60 + state.snapshot!.data!.balance = '$12.00' + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + expect(wrapper.find('[data-testid="ollama-cloud-five-hour"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ollama-cloud-seven-day"]').exists()).toBe(false) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars).toHaveLength(1) + expect(bars[0].props()).toMatchObject({ + // (60 - 12) / 60 = 80% + label: 'admin.accounts.ollamaCloud.monthlyPoolShort', + utilization: 80, + color: 'amber' + }) + expect(wrapper.get('[data-testid="ollama-cloud-balance"]').text()) + .toBe('admin.accounts.ollamaCloud.balance: $12.00 / $60') + expect(wrapper.get('[data-testid="ollama-cloud-snapshot-time"]').text()) + .toContain('admin.accounts.ollamaCloud.updatedAt') + }) + + it('falls back to the raw balance text when the credits pool is missing', () => { + const state = usageState() + state.mode = 'ollama_credits' + state.snapshot!.data!.balance = '$12.00' + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + expect(wrapper.find('[data-testid="ollama-cloud-monthly-pool"]').exists()).toBe(false) + expect(wrapper.get('[data-testid="ollama-cloud-balance"]').text()) + .toBe('admin.accounts.ollamaCloud.balance: $12.00') }) it('reacts to an account snapshot update', async () => { @@ -140,4 +188,27 @@ describe('OllamaCloudUsageCell', () => { expect(wrapper.find('[data-testid="ollama-cloud-usage-query"]').exists()).toBe(false) }) + + it('explains an ineligible account via the backend reason code', () => { + const state = usageState() + state.eligible = false + state.eligible_reason = 'unsupported_base_url' + state.snapshot = undefined + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + const hint = wrapper.get('[data-testid="ollama-cloud-usage-ineligible"]') + expect(hint.text()).toBe('admin.accounts.ollamaCloud.eligibleReason.unsupported_base_url') + expect(hint.attributes('title')).toBe('admin.accounts.ollamaCloud.eligibleReason.unsupported_base_url') + }) + + it('keeps the dash placeholder when no state is available', () => { + const wrapper = mount(OllamaCloudUsageCell, { + props: { account: account(null as unknown as OllamaCloudUsageState) } + }) + + expect(wrapper.find('[data-testid="ollama-cloud-usage-ineligible"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ollama-cloud-usage-cell"]').exists()).toBe(false) + expect(wrapper.get('span').classes()).toContain('text-sm') + }) }) diff --git a/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts b/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts index caadfa3fa9..6a390c8c39 100644 --- a/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts +++ b/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { cnSupportsNativeResponses, defaultCNAdaptiveBaseUrls } from '../credentialsBuilder' +import { cnSupportsNativeResponses, defaultCNAdaptiveBaseUrls, defaultCNBaseUrl, isMultiProtocolApiKeyPlatform } from '../credentialsBuilder' describe('cnSupportsNativeResponses', () => { it('is true for DeepSeek, Kimi, and MiniMax', () => { @@ -57,3 +57,38 @@ describe('defaultCNAdaptiveBaseUrls', () => { expect(defaultCNAdaptiveBaseUrls('minimax', 'coding')).toEqual(expected) }) }) + +describe('ollama_cloud base url presets (E11 + E12)', () => { + it('advertises native responses support', () => { + expect(cnSupportsNativeResponses('ollama_cloud')).toBe(true) + }) + + it('is recognized as a multi-protocol apikey platform', () => { + expect(isMultiProtocolApiKeyPlatform('ollama_cloud')).toBe(true) + }) + + // anthropic 预设不带 /v1:出站由后端拼 /v1/messages,预设带 /v1 会拼成 + // /v1/v1/messages 静默 404(本分支早前修过的真实缺陷)。 + it.each([ + ['anthropic', 'https://ollama.com'], + ['chat_completions', 'https://ollama.com/v1'], + ['responses', 'https://ollama.com/v1'] + ])('resolves the %s preset without depending on account mode', (protocol, expected) => { + expect(defaultCNBaseUrl('ollama_cloud', 'payg', protocol)).toBe(expected) + expect(defaultCNBaseUrl('ollama_cloud', 'coding', protocol)).toBe(expected) + }) + + it('keeps the anthropic preset free of the /v1 suffix', () => { + const anthropicPreset = defaultCNBaseUrl('ollama_cloud', 'payg', 'anthropic') + expect(anthropicPreset).toBe('https://ollama.com') + expect(anthropicPreset.includes('/v1')).toBe(false) + }) + + it('fills all three native endpoints for adaptive mode', () => { + expect(defaultCNAdaptiveBaseUrls('ollama_cloud', 'payg')).toEqual({ + chat_completions: 'https://ollama.com/v1', + anthropic: 'https://ollama.com', + responses: 'https://ollama.com/v1' + }) + }) +}) diff --git a/frontend/src/components/account/credentialsBuilder.ts b/frontend/src/components/account/credentialsBuilder.ts index 09fc1896c9..60a35c28f1 100644 --- a/frontend/src/components/account/credentialsBuilder.ts +++ b/frontend/src/components/account/credentialsBuilder.ts @@ -260,6 +260,7 @@ export const GROK_BASE_URL_PRESETS: GrokBaseUrlPreset[] = [ export type CnAccountMode = 'payg' | 'coding' export type OpenCodeAccountMode = 'zen' | 'go' +export type OllamaCloudAccountMode = 'ollama_legacy' | 'ollama_credits' export type CnProviderPlatform = 'kimi' | 'zhipu' | 'deepseek' | 'minimax' /** deepseek / kimi / minimax 支持原生 responses;adaptive 会按入站协议选择原生端点。 */ @@ -270,9 +271,9 @@ export function isCNProviderPlatform(platform: string): platform is CnProviderPl return platform === 'kimi' || platform === 'zhipu' || platform === 'deepseek' || platform === 'minimax' } -/** DeepSeek、Kimi 与 MiniMax 提供原生 Responses 端点。 */ +/** DeepSeek、Kimi 与 MiniMax 提供原生 Responses 端点;Ollama Cloud 自适应支持 /v1/responses。 */ export function cnSupportsNativeResponses(platform: string): boolean { - return platform === 'deepseek' || platform === 'kimi' || platform === 'minimax' || platform === 'opencode_go' + return platform === 'deepseek' || platform === 'kimi' || platform === 'minimax' || platform === 'opencode_go' || platform === 'ollama_cloud' } export const OPENCODE_GO_BASE_URL = 'https://opencode.ai/zen/go/v1' @@ -280,6 +281,12 @@ export const OPENCODE_GO_ANTHROPIC_BASE_URL = 'https://opencode.ai/zen/go' export const OPENCODE_ZEN_BASE_URL = 'https://opencode.ai/zen/v1' export const OPENCODE_ZEN_ANTHROPIC_BASE_URL = 'https://opencode.ai/zen' +// Ollama Cloud 默认端点(与后端 service/domain_constants.go 的 DefaultOllamaCloudBaseURL / +// DefaultOllamaCloudAnthropicBaseURL 一字不差)。anthropic 档不带 /v1:后端按协议拼接 +// /v1/messages,预设若带 /v1 会拼出 /v1/v1/messages 静默 404。 +export const OLLAMA_BASE_URL = 'https://ollama.com/v1' +export const OLLAMA_ANTHROPIC_BASE_URL = 'https://ollama.com' + export function isOpenCodeGoPlatform(platform: string): boolean { return platform === 'opencode_go' } @@ -358,7 +365,7 @@ export function applyOpenCodeGoProtocolRules( } export function isMultiProtocolApiKeyPlatform(platform: string): boolean { - return platform === 'kimi' || platform === 'zhipu' || platform === 'deepseek' || platform === 'minimax' || platform === 'opencode_go' + return platform === 'kimi' || platform === 'zhipu' || platform === 'deepseek' || platform === 'minimax' || platform === 'opencode_go' || platform === 'ollama_cloud' } export interface CnBaseUrlPreset { @@ -424,6 +431,8 @@ export function defaultCNBaseUrl( return 'https://api.minimaxi.com/anthropic' case 'opencode_go': return mode === 'zen' ? OPENCODE_ZEN_ANTHROPIC_BASE_URL : OPENCODE_GO_ANTHROPIC_BASE_URL + case 'ollama_cloud': + return OLLAMA_ANTHROPIC_BASE_URL default: return '' } @@ -442,6 +451,8 @@ export function defaultCNBaseUrl( return 'https://api.minimaxi.com/v1' case 'opencode_go': return mode === 'zen' ? OPENCODE_ZEN_BASE_URL : OPENCODE_GO_BASE_URL + case 'ollama_cloud': + return OLLAMA_BASE_URL default: return '' } @@ -449,7 +460,7 @@ export function defaultCNBaseUrl( /** 返回自适应模式下需要配置的原生协议及其默认端点。 */ export function defaultCNAdaptiveBaseUrls( - platform: CnProviderPlatform | 'opencode_go', + platform: CnProviderPlatform | 'opencode_go' | 'ollama_cloud', mode: CnAccountMode | OpenCodeAccountMode ): Record { return { diff --git a/frontend/src/components/admin/monitor/MonitorFiltersBar.vue b/frontend/src/components/admin/monitor/MonitorFiltersBar.vue index c489738eef..46cfdedd85 100644 --- a/frontend/src/components/admin/monitor/MonitorFiltersBar.vue +++ b/frontend/src/components/admin/monitor/MonitorFiltersBar.vue @@ -77,6 +77,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, } from '@/constants/channelMonitor' defineProps<{ @@ -108,6 +109,7 @@ const providerFilterOptions = computed(() => [ { value: PROVIDER_DEEPSEEK, label: t('monitorCommon.providers.deepseek') }, { value: PROVIDER_MINIMAX, label: t('monitorCommon.providers.minimax') }, { value: PROVIDER_OPENCODE_GO, label: t('monitorCommon.providers.opencode_go') }, + { value: PROVIDER_OLLAMA_CLOUD, label: t('monitorCommon.providers.ollama_cloud') }, ]) const enabledFilterOptions = computed(() => [ diff --git a/frontend/src/components/admin/monitor/MonitorFormDialog.vue b/frontend/src/components/admin/monitor/MonitorFormDialog.vue index 3ec29f0dcb..cdef6fd638 100644 --- a/frontend/src/components/admin/monitor/MonitorFormDialog.vue +++ b/frontend/src/components/admin/monitor/MonitorFormDialog.vue @@ -271,6 +271,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, API_MODE_CHAT_COMPLETIONS, API_MODE_RESPONSES, CHECK_MODE_PROBE, @@ -283,6 +284,7 @@ import { DEFAULT_DEEPSEEK_ENDPOINT, DEFAULT_MINIMAX_ENDPOINT, DEFAULT_OPENCODE_GO_ENDPOINT, + DEFAULT_OLLAMA_CLOUD_ENDPOINT, DEFAULT_INTERVAL_SECONDS, } from '@/constants/channelMonitor' @@ -479,6 +481,7 @@ const providerOptions = computed(() => [ { value: PROVIDER_DEEPSEEK, label: t('monitorCommon.providers.deepseek') }, { value: PROVIDER_MINIMAX, label: t('monitorCommon.providers.minimax') }, { value: PROVIDER_OPENCODE_GO, label: t('monitorCommon.providers.opencode_go') }, + { value: PROVIDER_OLLAMA_CLOUD, label: t('monitorCommon.providers.ollama_cloud') }, ]) // 国产 provider 预填的官方 endpoint(仅探活侧;配额模式 endpoint 可留空)。 @@ -488,6 +491,7 @@ const PROVIDER_DEFAULT_ENDPOINTS: Partial> = { [PROVIDER_DEEPSEEK]: DEFAULT_DEEPSEEK_ENDPOINT, [PROVIDER_MINIMAX]: DEFAULT_MINIMAX_ENDPOINT, [PROVIDER_OPENCODE_GO]: DEFAULT_OPENCODE_GO_ENDPOINT, + [PROVIDER_OLLAMA_CLOUD]: DEFAULT_OLLAMA_CLOUD_ENDPOINT, } interface CheckModeOption { diff --git a/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue b/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue index 546568d4fe..720a0b80e1 100644 --- a/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue +++ b/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue @@ -255,6 +255,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, PROVIDERS, API_MODE_CHAT_COMPLETIONS, API_MODE_RESPONSES, @@ -282,6 +283,7 @@ const providerTabs = computed<{ value: Provider; label: string }[]>(() => [ { value: PROVIDER_DEEPSEEK, label: t('monitorCommon.providers.deepseek') }, { value: PROVIDER_MINIMAX, label: t('monitorCommon.providers.minimax') }, { value: PROVIDER_OPENCODE_GO, label: t('monitorCommon.providers.opencode_go') }, + { value: PROVIDER_OLLAMA_CLOUD, label: t('monitorCommon.providers.ollama_cloud') }, ]) const activeProvider = ref(PROVIDER_ANTHROPIC) diff --git a/frontend/src/components/admin/user/UserPlatformQuotaModal.vue b/frontend/src/components/admin/user/UserPlatformQuotaModal.vue index 536f9a8424..8ffe8a66fc 100644 --- a/frontend/src/components/admin/user/UserPlatformQuotaModal.vue +++ b/frontend/src/components/admin/user/UserPlatformQuotaModal.vue @@ -119,6 +119,7 @@ import { ref, reactive, watch, computed } from 'vue' import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' import { adminAPI } from '@/api/admin' +import { QUOTA_PLATFORMS } from '@/api/admin/settings' import type { AdminUser, PlatformQuotaItem, PlatformQuotaPlatform, PlatformQuotaWindow } from '@/types' import BaseDialog from '@/components/common/BaseDialog.vue' @@ -128,7 +129,9 @@ const emit = defineEmits(['close', 'success']) const { t } = useI18n() const appStore = useAppStore() -const PLATFORMS: PlatformQuotaPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok'] +// 配额平台镜像,单一来源 settings.ts 的 QUOTA_PLATFORMS(对齐后端 AllowedQuotaPlatforms)。 +// PUT /admin/users/:id/platform-quotas 是整体替换语义:列表缺平台 = 保存即静默删行。 +const PLATFORMS = QUOTA_PLATFORMS interface QuotaRow { platform: PlatformQuotaPlatform @@ -174,9 +177,9 @@ function emptyRow(p: PlatformQuotaPlatform): QuotaRow { } function normalize(items: PlatformQuotaItem[]): QuotaRow[] { - const byPlatform = new Map() + const byPlatform = new Map() for (const it of items) byPlatform.set(it.platform, it) - return PLATFORMS.map((p) => { + const rows = PLATFORMS.map((p) => { const it = byPlatform.get(p) if (!it) return emptyRow(p) return { @@ -189,6 +192,22 @@ function normalize(items: PlatformQuotaItem[]): QuotaRow[] { monthly_usage_usd: it.monthly_usage_usd ?? 0, } }) + // 稳健性护栏:保留响应中前端未收录(后端新加)的平台行。整体替换语义下丢弃 + // 这些行,管理员不做任何修改直接保存也会软删其配额(限额 fail-open)。 + // platform 在前端收录前以服务端返回值透传(服务端返回即其白名单成员)。 + for (const it of items) { + if (PLATFORMS.includes(it.platform)) continue + rows.push({ + platform: it.platform as PlatformQuotaPlatform, + daily_limit_usd: it.daily_limit_usd ?? null, + weekly_limit_usd: it.weekly_limit_usd ?? null, + monthly_limit_usd: it.monthly_limit_usd ?? null, + daily_usage_usd: it.daily_usage_usd ?? 0, + weekly_usage_usd: it.weekly_usage_usd ?? 0, + monthly_usage_usd: it.monthly_usage_usd ?? 0, + }) + } + return rows } function formatUsage(n: number): string { diff --git a/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts b/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts index d582126294..26cf0f4d51 100644 --- a/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts +++ b/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts @@ -49,6 +49,7 @@ vi.mock('@/components/common/BaseDialog.vue', () => ({ })) import UserPlatformQuotaModal from '../UserPlatformQuotaModal.vue' +import { QUOTA_PLATFORMS } from '@/api/admin/settings' import type { UserSubscription } from '@/types' function makeUser(overrides: { subscriptions?: UserSubscription[] } = {}) { @@ -79,14 +80,12 @@ describe('UserPlatformQuotaModal', () => { expect(apiMocks.getPlatformQuotas).toHaveBeenCalledWith(99) }) - it('空数据渲染 5 个 platform 行', async () => { + it('空数据渲染全平台(对齐后端 AllowedQuotaPlatforms)行', async () => { const w = await mountAndOpen() const html = w.html() - expect(html).toContain('anthropic') - expect(html).toContain('openai') - expect(html).toContain('gemini') - expect(html).toContain('antigravity') - expect(html).toContain('grok') + for (const p of QUOTA_PLATFORMS) { + expect(html).toContain(p) + } }) it('已有数据正确填充 limit input', async () => { @@ -98,13 +97,13 @@ describe('UserPlatformQuotaModal', () => { }) const w = await mountAndOpen() const inputs = w.findAll('input[type=number]') - // 5 platforms × 3 windows = 15 inputs - expect(inputs.length).toBe(15) + // 全平台 × 3 windows = QUOTA_PLATFORMS.length × 3 inputs + expect(inputs.length).toBe(QUOTA_PLATFORMS.length * 3) // 第一个 input 是 anthropic.daily = 10 expect((inputs[0].element as HTMLInputElement).value).toBe('10') }) - it('保存提交完整 5 platform payload', async () => { + it('保存提交完整全平台 payload', async () => { apiMocks.getPlatformQuotas.mockResolvedValueOnce({ platform_quotas: [ { platform: 'openai', daily_limit_usd: null, weekly_limit_usd: 20, monthly_limit_usd: null, @@ -121,11 +120,79 @@ describe('UserPlatformQuotaModal', () => { expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1) const [uid, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] expect(uid).toBe(99) - expect(payload).toHaveLength(5) // 5 platforms always submitted + expect(payload).toHaveLength(QUOTA_PLATFORMS.length) // 全平台总是提交(整体替换语义) const openai = payload.find((p: any) => p.platform === 'openai') expect(openai.weekly_limit_usd).toBe(20) }) + it('预置 ollama_cloud 配额后不做修改直接保存,payload 仍包含该配额(整体替换不丢行)', async () => { + apiMocks.getPlatformQuotas.mockResolvedValueOnce({ + platform_quotas: [ + { platform: 'ollama_cloud', daily_limit_usd: 3, weekly_limit_usd: 30, monthly_limit_usd: 300, + daily_usage_usd: 0.5, weekly_usage_usd: 2, monthly_usage_usd: 10 }, + ], + }) + const w = await mountAndOpen() + const saveBtn = w.findAll('button').find((b) => b.text() === 'admin.users.platformQuota.save') + await saveBtn!.trigger('click') + await flushPromises() + expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1) + const [, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] + const ollama = payload.find((p: any) => p.platform === 'ollama_cloud') + expect(ollama).toEqual({ + platform: 'ollama_cloud', + daily_limit_usd: 3, + weekly_limit_usd: 30, + monthly_limit_usd: 300, + }) + }) + + it('kimi/zhipu/deepseek/minimax/opencode_go 预置配额保存后不丢', async () => { + apiMocks.getPlatformQuotas.mockResolvedValueOnce({ + platform_quotas: (['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'] as const).map((platform, i) => ({ + platform, + daily_limit_usd: i + 1, + weekly_limit_usd: null, + monthly_limit_usd: null, + daily_usage_usd: 0, + weekly_usage_usd: 0, + monthly_usage_usd: 0, + })), + }) + const w = await mountAndOpen() + const saveBtn = w.findAll('button').find((b) => b.text() === 'admin.users.platformQuota.save') + await saveBtn!.trigger('click') + await flushPromises() + const [, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] + for (const platform of ['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go']) { + const row = payload.find((p: any) => p.platform === platform) + expect(row).toBeDefined() + expect(row.daily_limit_usd).not.toBeNull() + } + }) + + it('响应中的未知平台 key 被保留并随保存提交', async () => { + apiMocks.getPlatformQuotas.mockResolvedValueOnce({ + platform_quotas: [ + { platform: 'some_future_platform', daily_limit_usd: 7, weekly_limit_usd: null, monthly_limit_usd: 9, + daily_usage_usd: 0, weekly_usage_usd: 0, monthly_usage_usd: 0 }, + ], + }) + const w = await mountAndOpen() + expect(w.html()).toContain('some_future_platform') + const saveBtn = w.findAll('button').find((b) => b.text() === 'admin.users.platformQuota.save') + await saveBtn!.trigger('click') + await flushPromises() + const [, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] + const row = payload.find((p: any) => p.platform === 'some_future_platform') + expect(row).toEqual({ + platform: 'some_future_platform', + daily_limit_usd: 7, + weekly_limit_usd: null, + monthly_limit_usd: 9, + }) + }) + it('全部清空把所有 limit 置 null(确认通过)', async () => { const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true) apiMocks.getPlatformQuotas.mockResolvedValueOnce({ @@ -186,7 +253,7 @@ describe('UserPlatformQuotaModal', () => { it('未配置限额的平台重置按钮禁用并提示不可用', async () => { const w = await mountAndOpen() const resetBtns = w.findAll('button').filter((b) => b.text() === '↻') - expect(resetBtns.length).toBe(15) // 5 平台 × 3 窗口 + expect(resetBtns.length).toBe(QUOTA_PLATFORMS.length * 3) // 全平台 × 3 窗口 for (const b of resetBtns) { expect((b.element as HTMLButtonElement).disabled).toBe(true) expect(b.attributes('title')).toBe('admin.users.platformQuota.reset.unavailable') diff --git a/frontend/src/components/common/PlatformIcon.vue b/frontend/src/components/common/PlatformIcon.vue index df1ec46db3..a17c72e337 100644 --- a/frontend/src/components/common/PlatformIcon.vue +++ b/frontend/src/components/common/PlatformIcon.vue @@ -48,6 +48,12 @@ + + + + import { computed } from 'vue' import { useI18n } from 'vue-i18n' -import type { PlatformQuotaItem, PlatformQuotaPlatform } from '@/api/admin/users' +import type { PlatformQuotaItem } from '@/api/admin/users' +import { QUOTA_PLATFORMS } from '@/api/admin/settings' const props = defineProps<{ quotas?: PlatformQuotaItem[] }>() const { t } = useI18n() -const PLATFORM_ORDER: PlatformQuotaPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok'] +// 展示顺序镜像 quota 平台列表(单一来源 settings.ts 的 QUOTA_PLATFORMS) +const PLATFORM_ORDER = QUOTA_PLATFORMS // 仅展示「至少一档限额非空」的平台(配额列,非用量列) const configured = computed(() => { diff --git a/frontend/src/components/user/monitor/MonitorCard.vue b/frontend/src/components/user/monitor/MonitorCard.vue index 268790794c..424b6b9adb 100644 --- a/frontend/src/components/user/monitor/MonitorCard.vue +++ b/frontend/src/components/user/monitor/MonitorCard.vue @@ -91,7 +91,7 @@ import MonitorAvailabilityRow from './MonitorAvailabilityRow.vue' import MonitorTimeline from './MonitorTimeline.vue' import MonitorQuotaView from '@/components/common/MonitorQuotaView.vue' -// 图标配色与 utils/platformColors.ts 的平台色对齐(新 4 家)。 +// 图标配色与 utils/platformColors.ts 的平台色对齐(新 4 家 + ollama_cloud)。 const PROVIDER_TINT: Record = { openai: 'text-emerald-600 dark:text-emerald-300', anthropic: 'text-orange-600 dark:text-orange-300', @@ -102,6 +102,7 @@ const PROVIDER_TINT: Record = { zhipu: 'text-indigo-600 dark:text-indigo-300', deepseek: 'text-teal-600 dark:text-teal-300', opencode_go: 'text-amber-700 dark:text-amber-300', + ollama_cloud: 'text-stone-600 dark:text-stone-300', } const props = defineProps<{ diff --git a/frontend/src/components/user/monitor/ProviderIcon.vue b/frontend/src/components/user/monitor/ProviderIcon.vue index b6f4c4f7c4..4e6e566ee9 100644 --- a/frontend/src/components/user/monitor/ProviderIcon.vue +++ b/frontend/src/components/user/monitor/ProviderIcon.vue @@ -88,6 +88,12 @@ const PROVIDER_ICONS: Record = { 'M16 6H8v12h8V6zm4 16H4V2h16v20z', ], }, + // ollama_cloud 官方 logo mark(llama)搬自 PlatformIcon.vue / ModelIcon.vue,保持同步。 + ollama_cloud: { + paths: [ + 'M7.905 1.09c.216.085.411.225.588.41.295.306.544.744.734 1.263.191.522.315 1.1.362 1.68a5.054 5.054 0 012.049-.636l.051-.004c.87-.07 1.73.087 2.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67 1.67 0 01.589-.41c.257-.1.53-.118.796-.042.401.114.745.368 1.016.737.248.337.434.769.561 1.287.23.934.27 2.163.115 3.645l.053.04.026.019c.757.576 1.284 1.397 1.563 2.35.435 1.487.216 3.155-.534 4.088l-.018.021.002.003c.417.762.67 1.567.724 2.4l.002.03c.064 1.065-.2 2.137-.814 3.19l-.007.01.01.024c.472 1.157.62 2.322.438 3.486l-.006.039a.651.651 0 01-.747.536.648.648 0 01-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643 0 01.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644 0 01.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229 4.229 0 00-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653 0 01-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288 3.288 0 00-1.772-.332c-1.245.099-2.343.801-2.67 1.686a.652.652 0 01-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066 1.588a4.07 4.07 0 00-.068 1.886c.112.558.331 1.02.582 1.269l.008.007c.212.207.257.53.109.785-.36.622-.629 1.549-.673 2.44-.05 1.018.186 1.902.719 2.536l.016.019a.643.643 0 01.095.69c-.576 1.236-.753 2.252-.562 3.052a.652.652 0 01-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339 4.339 0 01-.598-1.309l-.005-.019a5.764 5.764 0 01-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352 5.352 0 01.093-2.49c.262-.915.777-1.701 1.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622 1.015-.737.266-.076.54-.059.797.042zm4.116 9.09c.936 0 1.8.313 2.446.855.63.527 1.005 1.235 1.005 1.94 0 .888-.406 1.58-1.133 2.022-.62.375-1.451.557-2.403.557-1.009 0-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845 0-.707.398-1.417 1.056-1.946.668-.537 1.55-.849 2.485-.849zm0 .896a3.07 3.07 0 00-1.916.65c-.461.37-.722.835-.722 1.25 0 .428.21.829.61 1.134.455.347 1.124.548 1.943.548.799 0 1.473-.147 1.932-.426.463-.28.7-.686.7-1.257 0-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662 1.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375 0 01-.376.373.375.375 0 01-.376-.373v-.46l-.271-.218a.347.347 0 01-.052-.49.353.353 0 01.494-.051l.215.172.22-.174a.353.353 0 01.49.051zm-5.04-1.919c.478 0 .867.39.867.871a.87.87 0 01-.868.871.87.87 0 01-.867-.87.87.87 0 01.867-.872zm8.706 0c.48 0 .868.39.868.871a.87.87 0 01-.868.871.87.87 0 01-.867-.87.87.87 0 01.867-.872zM7.44 2.3l-.003.002a.659.659 0 00-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216 1.631-.124 2.782.43-.128.899-.208 1.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628 0 00-.107-.09L7.44 2.3zm9.174.04l-.002.001a.628.628 0 00-.107.09c-.156.163-.32.45-.453.814-.29.794-.387 1.776-.23 2.572l.058.097.008.014h.03a5.184 5.184 0 011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659 0 00-.285-.239h-.004z', + ], + }, } const props = withDefaults(defineProps<{ diff --git a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts index df9f347d5a..d36239b003 100644 --- a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts +++ b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts @@ -4,9 +4,51 @@ vi.mock('@/api/admin/accounts', () => ({ getAntigravityDefaultModelMapping: vi.fn() })) -import { buildModelMappingObject, getModelsByPlatform, getPresetMappingsByPlatform, splitModelMappingObject } from '../useModelWhitelist' +import { buildModelMappingObject, claudeModels, getModelsByPlatform, getPresetMappingsByPlatform, splitModelMappingObject } from '../useModelWhitelist' describe('useModelWhitelist', () => { + // ollama_cloud 与后端同源静态表(backend/internal/service/ollama_cloud_models.go + // DefaultOllamaCloudModelIDs(),/v1/models 实测目录)——集合必须与后端一致, + // 两侧各有测试钉住(对侧:ollama_cloud_models_test.go),改任一侧须同步另一侧。 + const ollamaCloudBackendCatalog = [ + 'nemotron-3-super', + 'glm-5.3', + 'gpt-oss:120b', + 'glm-5.3-flash', + 'kimi-k2.6', + 'kimi-k3', + 'deepseek-v4.1-flash', + 'minimax-m2.7', + 'mistral-large-3:675b', + 'glm-5.1', + 'glm-5.2', + 'gpt-oss:20b', + 'qwen3.5:397b', + 'kimi-k2.7-code', + 'nemotron-3-nano:30b', + 'minimax-m3', + 'gemma4:31b', + 'nemotron-3-ultra', + 'deepseek-v4-flash:0731', + 'deepseek-v4-pro:0813' + ] + + it('ollama_cloud 模型列表与后端 DefaultOllamaCloudModelIDs 同一集合', () => { + const models = getModelsByPlatform('ollama_cloud') + + expect(models).toEqual(ollamaCloudBackendCatalog) + }) + + it('ollama_cloud 模型列表不是 Claude 列表且不含 claude 模型', () => { + const models = getModelsByPlatform('ollama_cloud') + + expect(models).not.toBe(claudeModels) + expect(models).not.toEqual(claudeModels) + for (const model of models) { + expect(model).not.toContain('claude') + } + }) + it('openai 模型列表包含 GPT-5.4 官方快照', () => { const models = getModelsByPlatform('openai') diff --git a/frontend/src/composables/useChannelMonitorFormat.ts b/frontend/src/composables/useChannelMonitorFormat.ts index 2fb5d324df..b3afaa5de6 100644 --- a/frontend/src/composables/useChannelMonitorFormat.ts +++ b/frontend/src/composables/useChannelMonitorFormat.ts @@ -23,6 +23,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, PROVIDERS, STATUS_OPERATIONAL, STATUS_DEGRADED, @@ -107,7 +108,7 @@ export function useChannelMonitorFormat() { case PROVIDER_GROK: return 'bg-zinc-100 text-zinc-700 dark:bg-zinc-500/15 dark:text-zinc-300' // 配色与 utils/platformColors.ts 的平台色对齐:antigravity=purple / - // kimi=pink / zhipu=indigo / deepseek=teal。 + // kimi=pink / zhipu=indigo / deepseek=teal / ollama_cloud=stone。 case PROVIDER_ANTIGRAVITY: return 'bg-purple-100 text-purple-700 dark:bg-purple-500/15 dark:text-purple-300' case PROVIDER_KIMI: @@ -120,6 +121,8 @@ export function useChannelMonitorFormat() { return 'bg-rose-100 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300' case PROVIDER_OPENCODE_GO: return 'bg-amber-100 text-amber-800 dark:bg-amber-500/15 dark:text-amber-300' + case PROVIDER_OLLAMA_CLOUD: + return 'bg-stone-100 text-stone-700 dark:bg-stone-500/15 dark:text-stone-300' default: return NEUTRAL_BADGE } @@ -188,6 +191,10 @@ export function useChannelMonitorFormat() { return active ? 'border-amber-500 bg-amber-50 text-amber-800 dark:bg-amber-500/15 dark:text-amber-300 dark:border-amber-400' : 'border-gray-200 bg-white text-gray-600 hover:border-amber-300 hover:text-amber-700 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-400 dark:hover:border-amber-500/50' + case PROVIDER_OLLAMA_CLOUD: + return active + ? 'border-stone-500 bg-stone-50 text-stone-700 dark:bg-stone-500/15 dark:text-stone-300 dark:border-stone-400' + : 'border-gray-200 bg-white text-gray-600 hover:border-stone-300 hover:text-stone-700 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-400 dark:hover:border-stone-500/50' default: return active ? 'border-gray-400 bg-gray-50 text-gray-700 dark:border-dark-500 dark:bg-dark-700 dark:text-gray-200' @@ -276,6 +283,8 @@ export function providerGradient(provider: string): string { return 'bg-gradient-to-br from-rose-50 to-rose-100 dark:from-rose-500/10 dark:to-rose-500/20' case PROVIDER_OPENCODE_GO: return 'bg-gradient-to-br from-amber-50 to-amber-100 dark:from-amber-500/10 dark:to-amber-500/20' + case PROVIDER_OLLAMA_CLOUD: + return 'bg-gradient-to-br from-stone-50 to-stone-200 dark:from-stone-500/10 dark:to-stone-500/20' default: return 'bg-gradient-to-br from-gray-100 to-gray-200 dark:from-dark-700 dark:to-dark-600' } diff --git a/frontend/src/composables/useModelWhitelist.ts b/frontend/src/composables/useModelWhitelist.ts index 91a847bf19..8071ec37ec 100644 --- a/frontend/src/composables/useModelWhitelist.ts +++ b/frontend/src/composables/useModelWhitelist.ts @@ -465,6 +465,31 @@ export function getModelsByPlatform(platform: string): string[] { 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.7-max', 'qwen3.7-plus', 'qwen3.6-plus', 'hy4-preview', 'hy3', 'omen-alpha' ] + // 与后端同源静态表:backend/internal/service/ollama_cloud_models.go 的 + // DefaultOllamaCloudModelIDs()(/v1/models 实测目录)——两侧集合必须一致, + // 各有测试钉住(对侧:ollama_cloud_models_test.go),改任一侧须同步另一侧。 + case 'ollama_cloud': return [ + 'nemotron-3-super', + 'glm-5.3', + 'gpt-oss:120b', + 'glm-5.3-flash', + 'kimi-k2.6', + 'kimi-k3', + 'deepseek-v4.1-flash', + 'minimax-m2.7', + 'mistral-large-3:675b', + 'glm-5.1', + 'glm-5.2', + 'gpt-oss:20b', + 'qwen3.5:397b', + 'kimi-k2.7-code', + 'nemotron-3-nano:30b', + 'minimax-m3', + 'gemma4:31b', + 'nemotron-3-ultra', + 'deepseek-v4-flash:0731', + 'deepseek-v4-pro:0813' + ] case 'doubao': return doubaoModels case 'minimax': return minimaxModels case 'baidu': return baiduModels diff --git a/frontend/src/constants/__tests__/platforms.spec.ts b/frontend/src/constants/__tests__/platforms.spec.ts index af4fc9ab49..e0266f381f 100644 --- a/frontend/src/constants/__tests__/platforms.spec.ts +++ b/frontend/src/constants/__tests__/platforms.spec.ts @@ -11,7 +11,8 @@ const concretePlatforms = [ 'zhipu', 'deepseek', 'minimax', - 'opencode_go' + 'opencode_go', + 'ollama_cloud' ] describe('platform option catalogs', () => { diff --git a/frontend/src/constants/channelMonitor.ts b/frontend/src/constants/channelMonitor.ts index 1f05acb0e3..5b33910e85 100644 --- a/frontend/src/constants/channelMonitor.ts +++ b/frontend/src/constants/channelMonitor.ts @@ -19,6 +19,7 @@ export const PROVIDER_ZHIPU: Provider = 'zhipu' export const PROVIDER_DEEPSEEK: Provider = 'deepseek' export const PROVIDER_MINIMAX: Provider = 'minimax' export const PROVIDER_OPENCODE_GO: Provider = 'opencode_go' +export const PROVIDER_OLLAMA_CLOUD: Provider = 'ollama_cloud' export const DEFAULT_GROK_ENDPOINT = 'https://api.x.ai' export const DEFAULT_GROK_MODEL = 'grok-4.5' @@ -29,6 +30,9 @@ export const DEFAULT_ZHIPU_ENDPOINT = 'https://open.bigmodel.cn' export const DEFAULT_DEEPSEEK_ENDPOINT = 'https://api.deepseek.com' export const DEFAULT_MINIMAX_ENDPOINT = 'https://api.minimaxi.com' export const DEFAULT_OPENCODE_GO_ENDPOINT = 'https://opencode.ai/zen/go/v1' +// ollama_cloud 官方 OpenAI 兼容端点:探活 adapter 追加 /v1/chat/completions, +// 与后端 DefaultOllamaCloudBaseURL (https://ollama.com/v1) 同源。 +export const DEFAULT_OLLAMA_CLOUD_ENDPOINT = 'https://ollama.com' export const CHECK_MODE_PROBE: CheckMode = 'probe' export const CHECK_MODE_QUOTA: CheckMode = 'quota' @@ -48,6 +52,7 @@ export const PROVIDERS: readonly Provider[] = [ PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, ] /** 仅支持配额模式(无探活 adapter)的 provider。 */ diff --git a/frontend/src/constants/platforms.ts b/frontend/src/constants/platforms.ts index 1b46eb1c63..fac1f52ec2 100644 --- a/frontend/src/constants/platforms.ts +++ b/frontend/src/constants/platforms.ts @@ -20,7 +20,8 @@ export const CONCRETE_PLATFORM_OPTIONS = [ { value: 'zhipu', label: 'Zhipu GLM' }, { value: 'deepseek', label: 'DeepSeek' }, { value: 'minimax', label: 'MiniMax' }, - { value: 'opencode_go', label: 'OpenCode' } + { value: 'opencode_go', label: 'OpenCode' }, + { value: 'ollama_cloud', label: 'Ollama Cloud' } ] as const satisfies readonly PlatformOption[] /** Platforms that can own a group. */ diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 8c675a1c31..eb3bff3cb4 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -109,6 +109,7 @@ export default { deepseek: 'DeepSeek', minimax: 'MiniMax', opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud', }, cnProviders: { accountMode: { @@ -252,6 +253,15 @@ export default { usageWindowsHint: '"5h / 7d" are the upstream account\'s official rolling usage windows (e.g. OpenAI ChatGPT, Claude). They are imposed by the upstream provider on the account itself — not configured by sub2api, and unrelated to the models you map. Usage resets automatically once each window rolls over, and the limit cannot be lifted from within sub2api.', ollamaCloud: { title: 'Ollama Cloud usage', + accountMode: { + title: 'Account mode', + legacy: 'Legacy (rolling window)', + legacyDesc: 'Metered and monitored via the official 5h / 7d rolling windows', + credits: 'Credits (monthly pool)', + creditsDesc: 'Metered and monitored via a monthly USD credit pool', + monthlyCreditUsd: 'Monthly credit (USD)', + monthlyCreditUsdPlaceholder: 'e.g. 60' + }, sessionSecurityHint: 'The browser session is encrypted at rest and sent only to the fixed official settings URL.', configured: 'Configured', notConfigured: 'Not configured', @@ -271,6 +281,7 @@ export default { sevenDay: '7 day', sevenDayShort: '7d', balance: 'Balance', + monthlyPoolShort: 'Pool', models: 'Models', status: 'Status', updatedAt: 'Updated', @@ -278,6 +289,11 @@ export default { unauthorized: 'Session expired', failed: 'Refresh failed', windowWithReset: '{percent} used, resets {reset}', + eligibleReason: { + platform_not_eligible: 'Platform is not in the Ollama Cloud usage allowlist', + wrong_account_type: 'Only API key accounts support usage queries', + unsupported_base_url: 'base_url is not the official ollama.com host; usage is unavailable' + }, loadFailed: 'Failed to load Ollama Cloud usage settings', sessionSaved: 'Ollama browser session saved', sessionSaveFailed: 'Failed to save Ollama browser session', diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts index 725cdada28..5ecb0f6cdd 100644 --- a/frontend/src/i18n/locales/en/admin/overview.ts +++ b/frontend/src/i18n/locales/en/admin/overview.ts @@ -984,6 +984,7 @@ export default { deepseek: 'DeepSeek', minimax: 'MiniMax', opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud', composite: 'Composite', }, deleteConfirm: diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 4a9b8842ff..85f97cf056 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -474,7 +474,8 @@ export default { zhipu: 'Zhipu GLM', deepseek: 'DeepSeek', minimax: 'MiniMax', - opencode_go: 'OpenCode' + opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud' }, // Check modes (how a monitor performs its checks) checkMode: { diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index a93e548421..940234b761 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -128,6 +128,15 @@ export default { usageWindowsHint: '“5h / 7d”是上游账号(如 OpenAI ChatGPT、Claude)官方的滚动用量窗口限制,由上游对账号设定,并非 sub2api 配置,也与你映射的模型无关。窗口滚动到期后用量会自动重置,无法在 sub2api 端解除该限制。', ollamaCloud: { title: 'Ollama Cloud 用量', + accountMode: { + title: '账号模式', + legacy: 'Legacy(滚动窗口)', + legacyDesc: '按官方 5h / 7d 滚动窗口配额计费与监控', + credits: 'Credits(月度信用池)', + creditsDesc: '按月度美元信用额度计费与监控', + monthlyCreditUsd: '月度信用额度(USD)', + monthlyCreditUsdPlaceholder: '例如 60' + }, sessionSecurityHint: '浏览器会话会加密落库,且只发送到固定的 Ollama 官方设置页。', configured: '已配置', notConfigured: '未配置', @@ -147,6 +156,7 @@ export default { sevenDay: '7 天', sevenDayShort: '7d', balance: '余额', + monthlyPoolShort: '月池', models: '模型', status: '状态', updatedAt: '更新时间', @@ -154,6 +164,11 @@ export default { unauthorized: '会话已过期', failed: '刷新失败', windowWithReset: '已用 {percent},{reset} 重置', + eligibleReason: { + platform_not_eligible: '平台不在 Ollama Cloud 用量白名单内', + wrong_account_type: '仅 API Key 账号支持用量查询', + unsupported_base_url: 'base_url 非官方 ollama.com,无法查询用量' + }, loadFailed: '加载 Ollama Cloud 用量设置失败', sessionSaved: 'Ollama 浏览器会话已保存', sessionSaveFailed: '保存 Ollama 浏览器会话失败', @@ -312,6 +327,7 @@ export default { deepseek: 'DeepSeek', minimax: 'MiniMax', opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud', }, cnProviders: { accountMode: { diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts index b3b3e706d2..751eb3d84e 100644 --- a/frontend/src/i18n/locales/zh/admin/overview.ts +++ b/frontend/src/i18n/locales/zh/admin/overview.ts @@ -917,6 +917,7 @@ export default { deepseek: 'DeepSeek', minimax: 'MiniMax', opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud', composite: 'Composite', }, saving: '保存中...', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index d0bdc9d6f4..551ce20ac0 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -479,7 +479,8 @@ export default { zhipu: '智谱 GLM', deepseek: 'DeepSeek', minimax: 'MiniMax', - opencode_go: 'OpenCode' + opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud' }, // 检查模式(监控条目的工作方式) checkMode: { diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 60eb7e5802..83a44add42 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -538,7 +538,7 @@ export interface PaginationConfig { // ==================== API Key & Group Types ==================== -export type GroupPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'composite' +export type GroupPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'ollama_cloud' | 'composite' export type VideoModelPrices = Record> @@ -918,7 +918,7 @@ export interface UpdateGroupRequest { // ==================== Account & Proxy Types ==================== -export type AccountPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' +export type AccountPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'ollama_cloud' export type AccountType = 'oauth' | 'setup-token' | 'apikey' | 'upstream' | 'bedrock' | 'service_account' export type OAuthAddMethod = 'oauth' | 'setup-token' export type ProxyProtocol = 'http' | 'https' | 'socks5' | 'socks5h' @@ -1141,6 +1141,12 @@ export interface OllamaCloudUsageSnapshot { export interface OllamaCloudUsageState { account_id: number eligible: boolean + /** eligible=false 的原因码(后端 EligibleReason,"" 缺省表示合格)。 */ + eligible_reason?: 'platform_not_eligible' | 'wrong_account_type' | 'unsupported_base_url' + /** 双额度模式:legacy=5h/7d 滚动窗口,credits=月度美元信用池;非 ollama_cloud 平台缺省。 */ + mode?: 'ollama_legacy' | 'ollama_credits' + /** credits 模式的月度信用池(USD,credentials.monthly_credit_usd);未录入时缺省。 */ + monthly_credit_usd?: number configured: boolean auto_refresh_enabled: boolean encryption_key_configured: boolean diff --git a/frontend/src/utils/platformColors.ts b/frontend/src/utils/platformColors.ts index ceb8f3a2e2..e9c3200e8f 100644 --- a/frontend/src/utils/platformColors.ts +++ b/frontend/src/utils/platformColors.ts @@ -16,6 +16,7 @@ export type Platform = | 'deepseek' | 'minimax' | 'opencode_go' + | 'ollama_cloud' | 'composite' // ── Badge (bg + text + border, for inline badges with border) ─────── @@ -30,6 +31,7 @@ const BADGE: Record = { deepseek: 'bg-teal-500/10 text-teal-600 border-teal-500/30 dark:text-teal-400', minimax: 'bg-rose-500/10 text-rose-600 border-rose-500/30 dark:text-rose-400', opencode_go: 'bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-300', + ollama_cloud: 'bg-stone-500/10 text-stone-600 border-stone-500/30 dark:text-stone-300', composite: 'bg-cyan-500/10 text-cyan-700 border-cyan-500/30 dark:text-cyan-300', } const BADGE_DEFAULT = 'bg-slate-500/10 text-slate-600 border-slate-500/30 dark:text-slate-400' @@ -46,6 +48,7 @@ const BADGE_LIGHT: Record = { deepseek: 'bg-teal-500/10 text-teal-600 dark:bg-teal-500/10 dark:text-teal-300', minimax: 'bg-rose-500/10 text-rose-600 dark:bg-rose-500/10 dark:text-rose-300', opencode_go: 'bg-amber-500/10 text-amber-700 dark:bg-amber-500/10 dark:text-amber-300', + ollama_cloud: 'bg-stone-500/10 text-stone-600 dark:bg-stone-500/10 dark:text-stone-300', composite: 'bg-cyan-500/10 text-cyan-700 dark:bg-cyan-500/10 dark:text-cyan-300', } @@ -61,6 +64,7 @@ const BORDER: Record = { deepseek: 'border-teal-500/20 dark:border-teal-500/20', minimax: 'border-rose-500/20 dark:border-rose-500/20', opencode_go: 'border-amber-500/20 dark:border-amber-500/20', + ollama_cloud: 'border-stone-500/20 dark:border-stone-500/20', composite: 'border-cyan-500/20 dark:border-cyan-500/20', } const BORDER_DEFAULT = 'border-gray-200 dark:border-dark-700' @@ -77,6 +81,7 @@ const BORDER_STRONG: Record = { deepseek: 'border-teal-500/35 dark:border-teal-500/30', minimax: 'border-rose-500/35 dark:border-rose-500/30', opencode_go: 'border-amber-500/35 dark:border-amber-500/30', + ollama_cloud: 'border-stone-500/35 dark:border-stone-500/30', composite: 'border-cyan-500/35 dark:border-cyan-500/30', } const BORDER_STRONG_DEFAULT = 'border-gray-300 dark:border-dark-600' @@ -94,6 +99,7 @@ const ACCENT: Record = { deepseek: '#14b8a6', // teal-500 minimax: '#f43f5e', // rose-500 opencode_go: '#f59e0b', // amber-500 + ollama_cloud: '#78716c', // stone-500 composite: '#06b6d4', // cyan-500 } const ACCENT_DEFAULT = '#14b8a6' // primary-500 (teal) @@ -110,6 +116,7 @@ const ACCENT_BAR: Record = { deepseek: 'bg-gradient-to-r from-teal-400 to-teal-500', minimax: 'bg-gradient-to-r from-rose-400 to-rose-500', opencode_go: 'bg-gradient-to-r from-amber-400 to-amber-500', + ollama_cloud: 'bg-gradient-to-r from-stone-400 to-stone-500', composite: 'bg-gradient-to-r from-slate-500 to-cyan-500', } const ACCENT_BAR_DEFAULT = 'bg-gradient-to-r from-primary-400 to-primary-500' @@ -126,6 +133,7 @@ const TEXT: Record = { deepseek: 'text-teal-600 dark:text-teal-400', minimax: 'text-rose-600 dark:text-rose-400', opencode_go: 'text-amber-700 dark:text-amber-300', + ollama_cloud: 'text-stone-600 dark:text-stone-300', composite: 'text-cyan-700 dark:text-cyan-300', } const TEXT_DEFAULT = 'text-primary-600 dark:text-primary-400' @@ -142,6 +150,7 @@ const ICON: Record = { deepseek: 'text-teal-500 dark:text-teal-400', minimax: 'text-rose-500 dark:text-rose-400', opencode_go: 'text-amber-500 dark:text-amber-300', + ollama_cloud: 'text-stone-500 dark:text-stone-300', composite: 'text-cyan-600 dark:text-cyan-300', } const ICON_DEFAULT = 'text-primary-500 dark:text-primary-400' @@ -158,6 +167,7 @@ const BUTTON: Record = { deepseek: 'bg-teal-500 text-white hover:bg-teal-600 active:bg-teal-700 dark:bg-teal-500/80 dark:hover:bg-teal-500', minimax: 'bg-rose-500 text-white hover:bg-rose-600 active:bg-rose-700 dark:bg-rose-500/80 dark:hover:bg-rose-500', opencode_go: 'bg-amber-500 text-white hover:bg-amber-600 active:bg-amber-700 dark:bg-amber-500/80 dark:hover:bg-amber-500', + ollama_cloud: 'bg-stone-600 text-white hover:bg-stone-700 active:bg-stone-800 dark:bg-stone-600/80 dark:hover:bg-stone-600', composite: 'bg-cyan-700 text-white hover:bg-cyan-800 active:bg-cyan-900 dark:bg-cyan-600 dark:hover:bg-cyan-500', } const BUTTON_DEFAULT = 'bg-primary-500 text-white hover:bg-primary-600 dark:bg-primary-600 dark:hover:bg-primary-500' @@ -174,6 +184,7 @@ const DISCOUNT: Record = { deepseek: 'bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300', minimax: 'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300', opencode_go: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300', + ollama_cloud: 'bg-stone-100 text-stone-800 dark:bg-stone-900/40 dark:text-stone-300', composite: 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900/40 dark:text-cyan-300', } const DISCOUNT_DEFAULT = 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' @@ -190,6 +201,7 @@ const GRADIENT: Record = { deepseek: 'from-teal-500 to-teal-600', minimax: 'from-rose-500 to-rose-600', opencode_go: 'from-amber-500 to-amber-600', + ollama_cloud: 'from-stone-600 to-stone-800', composite: 'from-slate-600 to-cyan-600', } const GRADIENT_DEFAULT = 'from-primary-500 to-primary-600' @@ -206,6 +218,7 @@ const GRADIENT_TEXT: Record = { deepseek: 'text-teal-100', minimax: 'text-rose-100', opencode_go: 'text-amber-100', + ollama_cloud: 'text-stone-100', composite: 'text-cyan-100', } const GRADIENT_TEXT_DEFAULT = 'text-primary-100' @@ -221,6 +234,7 @@ const GRADIENT_SUBTEXT: Record = { deepseek: 'text-teal-200', minimax: 'text-rose-200', opencode_go: 'text-amber-200', + ollama_cloud: 'text-stone-200', composite: 'text-cyan-200', } const GRADIENT_SUBTEXT_DEFAULT = 'text-primary-200' @@ -239,6 +253,7 @@ function isPlatform(p: string): p is Platform { p === 'deepseek' || p === 'minimax' || p === 'opencode_go' || + p === 'ollama_cloud' || p === 'composite' ) } @@ -307,6 +322,7 @@ export function platformLabel(p: string): string { case 'deepseek': return 'DeepSeek' case 'minimax': return 'MiniMax' case 'opencode_go': return 'OpenCode' + case 'ollama_cloud': return 'Ollama Cloud' case 'composite': return 'Composite' default: return p || 'API' } diff --git a/frontend/src/views/admin/ChannelsView.vue b/frontend/src/views/admin/ChannelsView.vue index ace4b14519..b13819afa5 100644 --- a/frontend/src/views/admin/ChannelsView.vue +++ b/frontend/src/views/admin/ChannelsView.vue @@ -763,9 +763,10 @@ const form = reactive({ let abortController: AbortController | null = null // ── Platform config ── -const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'] +const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'] // Composite pricing/mapping may target every concrete schedulable provider. -const compositePlatforms: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'] +// (Backend isConcreteRequestPlatform includes ollama_cloud.) +const compositePlatforms: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'] // ── Helpers ── function formatDate(value: string): string { diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue index 85da60ed41..17e1e371c0 100644 --- a/frontend/src/views/admin/GroupsView.vue +++ b/frontend/src/views/admin/GroupsView.vue @@ -158,6 +158,8 @@ ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400' : value === 'opencode_go' ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300' + : value === 'ollama_cloud' + ? 'bg-stone-100 text-stone-800 dark:bg-stone-900/30 dark:text-stone-300' : 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400', ]" > @@ -3835,6 +3837,8 @@ ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400' : group.platform === 'opencode_go' ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300' + : group.platform === 'ollama_cloud' + ? 'bg-stone-100 text-stone-800 dark:bg-stone-900/30 dark:text-stone-300' : 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400', ]" > diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue index c25b06eb3b..c436944820 100644 --- a/frontend/src/views/admin/SettingsView.vue +++ b/frontend/src/views/admin/SettingsView.vue @@ -4055,7 +4055,7 @@ -
+
{{ p }} @@ -4390,7 +4390,7 @@ - + {{ p }} @@ -8828,6 +8828,7 @@ import { normalizePlatformQuotasMap, sanitizeAccountSchedulingThresholdsMap, sanitizePlatformQuotasMap, + QUOTA_PLATFORMS, SCHEDULING_THRESHOLD_PLATFORMS, defaultWeChatConnectScopesForMode, deriveWeChatConnectStoredMode, diff --git a/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts b/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts index 007876a72f..3ffdc00a6a 100644 --- a/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts +++ b/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts @@ -100,8 +100,11 @@ describe('channel monitor Grok provider', () => { await flushPromises() expect(PROVIDERS).toContain(PROVIDER_GROK) + // Provider grid mirrors the full backend oneof list (migration 239 CHECK): + // openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ + // opencode_go/ollama_cloud. const providerButtons = wrapper.findAll('[data-testid^="monitor-provider-"]') - expect(providerButtons).toHaveLength(8) + expect(providerButtons).toHaveLength(11) expect(providerButtons[0].element.parentElement?.className).toContain('grid-cols-2') expect(providerButtons[0].element.parentElement?.className).toContain('sm:grid-cols-4') diff --git a/frontend/src/views/admin/__tests__/SettingsView.spec.ts b/frontend/src/views/admin/__tests__/SettingsView.spec.ts index 8491ff9e30..0464b5eb04 100644 --- a/frontend/src/views/admin/__tests__/SettingsView.spec.ts +++ b/frontend/src/views/admin/__tests__/SettingsView.spec.ts @@ -1885,7 +1885,7 @@ describe("admin SettingsView platform quota matrix", () => { expect(html).toContain("antigravity"); }); - it("保存时 updateSettings payload 应包含嵌套 default_platform_quotas 对象(含全 5 平台)", async () => { + it("保存时 updateSettings payload 应包含嵌套 default_platform_quotas 对象(含全平台)", async () => { const wrapper = mountView(); await flushPromises(); await openUsersTab(wrapper); @@ -1915,6 +1915,41 @@ describe("admin SettingsView platform quota matrix", () => { expect(payload).not.toHaveProperty("default_platform_quota_openai_weekly"); }); + it("预置 ollama_cloud/kimi 等新平台默认配额后不做修改直接保存,payload 仍包含(整体替换不丢行)", async () => { + getSettings.mockResolvedValueOnce({ + ...baseSettingsResponse, + default_platform_quotas: { + anthropic: { daily: 5, weekly: null, monthly: null }, + ollama_cloud: { daily: 3, weekly: 30, monthly: 300 }, + kimi: { daily: 1, weekly: null, monthly: null }, + zhipu: { daily: null, weekly: 2, monthly: null }, + deepseek: { daily: null, weekly: null, monthly: 4 }, + minimax: { daily: 0.5, weekly: null, monthly: null }, + opencode_go: { daily: 0.6, weekly: 6, monthly: 60 }, + }, + }); + + const wrapper = mountView(); + await flushPromises(); + await openUsersTab(wrapper); + + await wrapper.find("form").trigger("submit.prevent"); + await flushPromises(); + + const payload = updateSettings.mock.calls.at(-1)![0] as Record; + const quotas = payload["default_platform_quotas"] as Record>; + + // 整体替换语义下,这些平台配额行必须原样出现在提交 payload 中 + expect(quotas["ollama_cloud"]).toEqual({ daily: 3, weekly: 30, monthly: 300 }); + expect(quotas["kimi"]).toEqual({ daily: 1, weekly: null, monthly: null }); + expect(quotas["zhipu"]).toEqual({ daily: null, weekly: 2, monthly: null }); + expect(quotas["deepseek"]).toEqual({ daily: null, weekly: null, monthly: 4 }); + expect(quotas["minimax"]).toEqual({ daily: 0.5, weekly: null, monthly: null }); + expect(quotas["opencode_go"]).toEqual({ daily: 0.6, weekly: 6, monthly: 60 }); + // 已知平台不受影响 + expect(quotas["anthropic"]).toEqual({ daily: 5, weekly: null, monthly: null }); + }); + it("加载后 form.default_platform_quotas 含全 5 平台,从嵌套 JSON 正确读取数值", async () => { getSettings.mockResolvedValueOnce({ ...baseSettingsResponse, diff --git a/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts b/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts index a259234874..dc1641eda2 100644 --- a/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts +++ b/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts @@ -12,5 +12,6 @@ describe('Composite channel platform options', () => { expect(declaration).toContain("'deepseek'") expect(declaration).toContain("'minimax'") expect(declaration).toContain("'opencode_go'") + expect(declaration).toContain("'ollama_cloud'") }) })