feat(groups): 强制 Ultra Fast 按模型门控,可与强制 Fast 并存

- 强制 Ultra Fast 只对支持的模型(GPT-6 Astra、GPT-6.1 Sol)写入
  service_tier=ultrafast;其余模型在同时开启强制 Fast 时写入 priority,
  否则跟随客户端。优先级:Ultra Fast > Fast > 客户端
- 去掉 force_openai_fast 与 force_openai_ultrafast 的互斥校验
  (GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT)
- gpt-6.1-sol 的 Ultra Fast 计费由 2x 修正为 6x,与 Astra 一致;门控与
  计费共用 openAIModelSupportsUltrafast,避免两者漂移
- 管理端由下拉三选一改回两个独立开关,说明文案点名支持的模型与 6x 计费
This commit is contained in:
shaw committed 2026-11-16 21:17:31 +08:00
1 parent e257b78117
commit ad9eeedebb
18 files changed
+348 -240

No files matched your search

+1 -1
View File
@@ -128,7 +128,7 @@ type Group struct {
AllowLive bool `json:"allow_live,omitempty"`
// 是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority
ForceOpenaiFast bool `json:"force_openai_fast,omitempty"`
// 是否强制此 OpenAI/Composite 分组请求使用 service_tier=ultrafast(与 force_openai_fast 互斥)
// 是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)
ForceOpenaiUltrafast bool `json:"force_openai_ultrafast,omitempty"`
// 是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费
FreeOpenaiFast bool `json:"free_openai_fast,omitempty"`
+1 -1
View File
@@ -255,7 +255,7 @@ func (Group) Fields() []ent.Field {
Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority"),
field.Bool("force_openai_ultrafast").
Default(false).
Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=ultrafast(与 force_openai_fast 互斥)"),
Comment("是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)"),
field.Bool("free_openai_fast").
Default(false).
Comment("是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费"),
-19
View File
@@ -375,19 +375,6 @@ func sanitizeGroupOpenAIFast(group *Group) {
}
}
// validateGroupOpenAIForcedServiceTier 拒绝同时强制 Fast 与 Ultrafast:一次请求
// 只能携带一个 service_tier,两者并存没有确定语义。须在 sanitizeGroupOpenAIFast
// 之后调用,使不支持该能力的平台先被清零而不是误报。
func validateGroupOpenAIForcedServiceTier(group *Group) error {
if group != nil && group.ForceOpenAIFast && group.ForceOpenAIUltrafast {
return infraerrors.BadRequest(
"GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT",
"force_openai_fast and force_openai_ultrafast cannot both be enabled",
)
}
return nil
}
func normalizeCreateGroupInputForSimpleMode(input *CreateGroupInput) {
if input == nil {
return
@@ -657,9 +644,6 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn
}
sanitizeGroupMessagesDispatchFields(group)
sanitizeGroupOpenAIFast(group)
if err := validateGroupOpenAIForcedServiceTier(group); err != nil {
return nil, err
}
if group.Platform != PlatformOpenAI && group.Platform != PlatformComposite {
group.AllowLive = false
}
@@ -1091,9 +1075,6 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd
}
sanitizeGroupMessagesDispatchFields(group)
sanitizeGroupOpenAIFast(group)
if err := validateGroupOpenAIForcedServiceTier(group); err != nil {
return nil, err
}
if group.Platform != PlatformOpenAI && group.Platform != PlatformComposite {
group.AllowLive = false
}
@@ -2377,7 +2377,8 @@ func TestAdminService_CreateGroup_NormalizesForceOpenAIUltrafastByPlatform(t *te
}
}
func TestAdminService_CreateGroup_RejectsForcingFastAndUltrafastTogether(t *testing.T) {
// 两个开关相互独立:同时开启表示"支持的模型走 Ultra Fast,其余走 Fast"。
func TestAdminService_CreateGroup_AllowsForcingFastAndUltrafastTogether(t *testing.T) {
repo := &groupRepoStubForAdmin{}
svc := &adminServiceImpl{groupRepo: repo}
@@ -2385,12 +2386,13 @@ func TestAdminService_CreateGroup_RejectsForcingFastAndUltrafastTogether(t *test
Name: "both", Platform: PlatformOpenAI, RateMultiplier: 1, ForceOpenAIFast: true, ForceOpenAIUltrafast: true,
})
require.Nil(t, group)
require.Equal(t, "GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT", infraerrors.Reason(err))
require.Nil(t, repo.created)
require.NoError(t, err)
require.NotNil(t, group)
require.True(t, repo.created.ForceOpenAIFast)
require.True(t, repo.created.ForceOpenAIUltrafast)
}
// 不支持该能力的平台两个开关都会被清零,不应因为"同时为真"被拒绝。
// 不支持该能力的平台两个开关都会被清零。
func TestAdminService_CreateGroup_UnsupportedPlatformIgnoresBothForcedTiers(t *testing.T) {
repo := &groupRepoStubForAdmin{}
svc := &adminServiceImpl{groupRepo: repo}
@@ -2436,28 +2438,40 @@ func TestAdminService_UpdateGroup_ForceOpenAIUltrafast(t *testing.T) {
require.True(t, repo.updated.ForceOpenAIUltrafast)
})
t.Run("enabling ultrafast while fast stays on is rejected", func(t *testing.T) {
t.Run("enabling ultrafast leaves fast untouched", func(t *testing.T) {
existing := &Group{ID: 1, Name: "g", Platform: PlatformOpenAI, Status: StatusActive, ForceOpenAIFast: true}
repo := &groupRepoStubForAdmin{getByID: existing}
svc := &adminServiceImpl{groupRepo: repo}
group, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{ForceOpenAIUltrafast: &truth})
_, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{ForceOpenAIUltrafast: &truth})
require.Nil(t, group)
require.Equal(t, "GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT", infraerrors.Reason(err))
require.Nil(t, repo.updated)
require.NoError(t, err)
require.True(t, repo.updated.ForceOpenAIFast)
require.True(t, repo.updated.ForceOpenAIUltrafast)
})
t.Run("enabling fast while ultrafast stays on is rejected", func(t *testing.T) {
t.Run("enabling fast leaves ultrafast untouched", func(t *testing.T) {
existing := &Group{ID: 1, Name: "g", Platform: PlatformOpenAI, Status: StatusActive, ForceOpenAIUltrafast: true}
repo := &groupRepoStubForAdmin{getByID: existing}
svc := &adminServiceImpl{groupRepo: repo}
group, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{ForceOpenAIFast: &truth})
_, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{ForceOpenAIFast: &truth})
require.Nil(t, group)
require.Equal(t, "GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT", infraerrors.Reason(err))
require.Nil(t, repo.updated)
require.NoError(t, err)
require.True(t, repo.updated.ForceOpenAIFast)
require.True(t, repo.updated.ForceOpenAIUltrafast)
})
t.Run("platform change clears both", func(t *testing.T) {
existing := &Group{ID: 1, Name: "g", Platform: PlatformOpenAI, Status: StatusActive, ForceOpenAIFast: true, ForceOpenAIUltrafast: true}
repo := &groupRepoStubForAdmin{getByID: existing}
svc := &adminServiceImpl{groupRepo: repo}
_, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{Platform: PlatformAnthropic})
require.NoError(t, err)
require.False(t, repo.updated.ForceOpenAIFast)
require.False(t, repo.updated.ForceOpenAIUltrafast)
})
t.Run("platform change clears ultrafast", func(t *testing.T) {
+1 -1
View File
@@ -2020,7 +2020,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
return pricing
}
cloned := *pricing
if isOpenAIGPT6AstraModel(normalized) {
if openAIModelSupportsUltrafast(normalized) {
cloned.UltrafastMultiplier = 6
}
if needsOpus55FastMultiplier {
+1 -1
View File
@@ -103,7 +103,7 @@ type Group struct {
AllowMessagesDispatch bool
AllowLive bool
ForceOpenAIFast bool // 强制 OpenAI 网关请求使用 service_tier=priority
ForceOpenAIUltrafast bool // 强制 OpenAI 网关请求使用 service_tier=ultrafast(与 ForceOpenAIFast 互斥)
ForceOpenAIUltrafast bool // 对支持 Ultrafast 的模型强制 service_tier=ultrafast,优先于 ForceOpenAIFast
FreeOpenAIFast bool // OpenAI Fast 请求按 Standard 价格向用户计费
RequireOAuthOnly bool // 仅允许非 apikey 类型账号关联(OpenAI/Antigravity/Anthropic/Gemini)
RequirePrivacySet bool // 调度时仅允许 privacy 已成功设置的账号(OpenAI/Antigravity/Anthropic/Gemini)
@@ -595,15 +595,15 @@ func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastInjectsAndOverridesTier(
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
for _, body := range [][]byte{
[]byte(`{"model":"gpt-5.6-sol","input":"hi"}`),
[]byte(`{"model":"gpt-5.6-sol","service_tier":"default"}`),
[]byte(`{"model":"gpt-5.6-sol","service_tier":"fast"}`),
[]byte(`{"model":"gpt-5.6-sol","service_tier":"priority"}`),
[]byte(`{"model":"gpt-5.6-sol","service_tier":"flex"}`),
[]byte(`{"model":"gpt-5.6-sol","service_tier":"ultrafast"}`),
[]byte(`{"model":"gpt-5.6-sol","service_tier":"client-unknown"}`),
[]byte(`{"model":"gpt-6.1-sol","input":"hi"}`),
[]byte(`{"model":"gpt-6.1-sol","service_tier":"default"}`),
[]byte(`{"model":"gpt-6.1-sol","service_tier":"fast"}`),
[]byte(`{"model":"gpt-6.1-sol","service_tier":"priority"}`),
[]byte(`{"model":"gpt-6.1-sol","service_tier":"flex"}`),
[]byte(`{"model":"gpt-6.1-sol","service_tier":"ultrafast"}`),
[]byte(`{"model":"gpt-6.1-sol","service_tier":"client-unknown"}`),
} {
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", body)
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-6.1-sol", body)
require.NoError(t, err)
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(updated, "service_tier").String(), "body %s", body)
}
@@ -613,7 +613,7 @@ func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastInjectsAndOverridesTier(
// 规则必须作用在分组写入的 ultrafast 上,而只针对 priority 的规则不应误伤。
func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastStillHonorsGlobalPolicy(t *testing.T) {
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
body := []byte(`{"model":"gpt-5.6-sol"}`)
body := []byte(`{"model":"gpt-6.1-sol"}`)
rule := func(tier, action string) *OpenAIFastPolicySettings {
return &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{
ServiceTier: tier, Action: action, Scope: BetaPolicyScopeAll, ErrorMessage: "ultrafast disabled",
@@ -622,14 +622,14 @@ func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastStillHonorsGlobalPolicy(
t.Run("ultrafast filter strips the forced tier", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, rule(OpenAIFastTierUltrafast, BetaPolicyActionFilter))
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", body)
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-6.1-sol", body)
require.NoError(t, err)
require.False(t, gjson.GetBytes(updated, "service_tier").Exists())
})
t.Run("ultrafast block rejects the request", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, rule(OpenAIFastTierUltrafast, BetaPolicyActionBlock))
_, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", body)
_, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-6.1-sol", body)
var blocked *OpenAIFastBlockedError
require.ErrorAs(t, err, &blocked)
require.Equal(t, "ultrafast disabled", blocked.Message)
@@ -637,14 +637,14 @@ func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastStillHonorsGlobalPolicy(
t.Run("ultrafast force_priority downgrades to priority", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, rule(OpenAIFastTierUltrafast, OpenAIFastPolicyActionForcePriority))
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", body)
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-6.1-sol", body)
require.NoError(t, err)
require.Equal(t, OpenAIFastTierPriority, gjson.GetBytes(updated, "service_tier").String())
})
t.Run("priority-only filter leaves ultrafast alone", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, openAIFastFilterPriorityPolicy())
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", body)
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-6.1-sol", body)
require.NoError(t, err)
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(updated, "service_tier").String())
})
@@ -652,43 +652,153 @@ func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastStillHonorsGlobalPolicy(
t.Run("model whitelist fallback filters unsupported models", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{
ServiceTier: OpenAIFastTierUltrafast, Action: BetaPolicyActionPass, Scope: BetaPolicyScopeAll,
ModelWhitelist: []string{"gpt-5.6-sol"}, FallbackAction: BetaPolicyActionFilter,
ModelWhitelist: []string{"gpt-6.1-sol"}, FallbackAction: BetaPolicyActionFilter,
}}})
supported, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", body)
supported, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-6.1-sol", body)
require.NoError(t, err)
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(supported, "service_tier").String())
unsupported, err := svc.applyOpenAIFastPolicyToBody(
openAIUltrafastGroupContext(), account, "gpt-5.4-mini", []byte(`{"model":"gpt-5.4-mini"}`))
// Astra 支持 Ultrafast,分组会写入;不在白名单内,由 fallback 过滤掉。
notWhitelisted, err := svc.applyOpenAIFastPolicyToBody(
openAIUltrafastGroupContext(), account, "gpt-6-astra", []byte(`{"model":"gpt-6-astra"}`))
require.NoError(t, err)
require.False(t, gjson.GetBytes(unsupported, "service_tier").Exists())
require.False(t, gjson.GetBytes(notWhitelisted, "service_tier").Exists())
})
}
func TestOpenAIModelSupportsUltrafast(t *testing.T) {
for _, model := range []string{
"gpt-6-astra", "gpt-6", "GPT-6-Astra", "openai/gpt-6-astra",
"gpt-6.1-sol", "gpt-6.1-sol-high", "openai/gpt-6.1-sol", "gpt-6.1-sol-openai-compact",
} {
require.True(t, openAIModelSupportsUltrafast(model), model)
}
for _, model := range []string{
"", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.5", "gpt-5.4-mini",
"gpt-6.1-solar", "grok-4", "claude-opus-5-5",
} {
require.False(t, openAIModelSupportsUltrafast(model), model)
}
}
// 门控与计费共用同一判定:凡是分组会强制写入 ultrafast 的模型,都必须按 6x 计费。
func TestOpenAIUltrafastGateMatchesBilling(t *testing.T) {
svc := newTestBillingService()
for _, tt := range []struct {
model string
want float64
}{
{model: "gpt-6-astra", want: 6},
{model: "gpt-6.1-sol", want: 6},
{model: "gpt-6.1-sol-high", want: 6},
{model: "gpt-6.1-terra", want: 2},
{model: "gpt-6-sol", want: 2},
{model: "gpt-5.6-sol", want: 2},
} {
pricing, err := svc.GetModelPricing(tt.model)
require.NoError(t, err, tt.model)
require.Equal(t, tt.want, configuredServiceTierMultiplier(OpenAIFastTierUltrafast, pricing), tt.model)
require.Equal(t, tt.want == 6, openAIModelSupportsUltrafast(tt.model), tt.model)
// 渠道自定义价格与显式 Fast 倍率都不改变 Ultrafast 倍率。
custom, fast := 1e-6, 3.0
channelPricing, err := svc.GetModelPricingWithChannel(tt.model, &ChannelModelPricing{
InputPrice: &custom, OutputPrice: &custom, FastMultiplier: &fast,
})
require.NoError(t, err, tt.model)
require.Equal(t, tt.want, configuredServiceTierMultiplier(OpenAIFastTierUltrafast, channelPricing), tt.model)
}
}
func TestOpenAIGroupForcedServiceTier(t *testing.T) {
openAIAccount := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
groupCtx := func(g *Group) context.Context {
return context.WithValue(context.Background(), ctxkey.Group, g)
const sol, astra, unsupported = "gpt-6.1-sol", "gpt-6-astra", "gpt-5.6-sol"
group := func(platform string, fast, ultrafast bool) context.Context {
return context.WithValue(context.Background(), ctxkey.Group, &Group{
ID: 7, Platform: platform, Status: StatusActive, Hydrated: true,
ForceOpenAIFast: fast, ForceOpenAIUltrafast: ultrafast,
})
}
for _, tt := range []struct {
name string
ctx context.Context
account *Account
model string
want string
}{
{name: "no group", ctx: context.Background(), account: openAIAccount, want: ""},
{name: "nil account", ctx: openAIUltrafastGroupContext(), account: nil, want: ""},
{name: "follow client", ctx: groupCtx(&Group{ID: 7, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true}), account: openAIAccount, want: ""},
{name: "force fast", ctx: groupCtx(&Group{ID: 7, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true, ForceOpenAIFast: true}), account: openAIAccount, want: OpenAIFastTierPriority},
{name: "force ultrafast", ctx: openAIUltrafastGroupContext(), account: openAIAccount, want: OpenAIFastTierUltrafast},
{name: "composite group with openai account", ctx: groupCtx(&Group{ID: 7, Platform: PlatformComposite, Status: StatusActive, Hydrated: true, ForceOpenAIUltrafast: true}), account: openAIAccount, want: OpenAIFastTierUltrafast},
{name: "composite group with grok account", ctx: groupCtx(&Group{ID: 7, Platform: PlatformComposite, Status: StatusActive, Hydrated: true, ForceOpenAIUltrafast: true}), account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}, want: ""},
{name: "unsupported group platform", ctx: groupCtx(&Group{ID: 7, Platform: PlatformAnthropic, Status: StatusActive, Hydrated: true, ForceOpenAIUltrafast: true}), account: openAIAccount, want: ""},
{name: "unhydrated group", ctx: groupCtx(&Group{ID: 7, Platform: PlatformOpenAI, Status: StatusActive, ForceOpenAIUltrafast: true}), account: openAIAccount, want: ""},
{name: "both flags resolve to ultrafast", ctx: groupCtx(&Group{ID: 7, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true, ForceOpenAIFast: true, ForceOpenAIUltrafast: true}), account: openAIAccount, want: OpenAIFastTierUltrafast},
{name: "no group", ctx: context.Background(), account: openAIAccount, model: sol, want: ""},
{name: "nil account", ctx: group(PlatformOpenAI, true, true), account: nil, model: sol, want: ""},
{name: "follow client", ctx: group(PlatformOpenAI, false, false), account: openAIAccount, model: sol, want: ""},
{name: "fast only, ultrafast-capable model", ctx: group(PlatformOpenAI, true, false), account: openAIAccount, model: sol, want: OpenAIFastTierPriority},
{name: "fast only, other model", ctx: group(PlatformOpenAI, true, false), account: openAIAccount, model: unsupported, want: OpenAIFastTierPriority},
{name: "fast only, empty model", ctx: group(PlatformOpenAI, true, false), account: openAIAccount, model: "", want: OpenAIFastTierPriority},
{name: "ultrafast only, sol", ctx: group(PlatformOpenAI, false, true), account: openAIAccount, model: sol, want: OpenAIFastTierUltrafast},
{name: "ultrafast only, astra", ctx: group(PlatformOpenAI, false, true), account: openAIAccount, model: astra, want: OpenAIFastTierUltrafast},
{name: "ultrafast only, sol effort alias", ctx: group(PlatformOpenAI, false, true), account: openAIAccount, model: "gpt-6.1-sol-high", want: OpenAIFastTierUltrafast},
{name: "ultrafast only, unsupported model follows client", ctx: group(PlatformOpenAI, false, true), account: openAIAccount, model: unsupported, want: ""},
{name: "ultrafast only, empty model follows client", ctx: group(PlatformOpenAI, false, true), account: openAIAccount, model: "", want: ""},
{name: "both, supported model gets ultrafast", ctx: group(PlatformOpenAI, true, true), account: openAIAccount, model: sol, want: OpenAIFastTierUltrafast},
{name: "both, unsupported model falls back to fast", ctx: group(PlatformOpenAI, true, true), account: openAIAccount, model: unsupported, want: OpenAIFastTierPriority},
{name: "composite group with openai account", ctx: group(PlatformComposite, false, true), account: openAIAccount, model: sol, want: OpenAIFastTierUltrafast},
{name: "composite group with grok account", ctx: group(PlatformComposite, true, true), account: &Account{Platform: PlatformGrok}, model: sol, want: ""},
{name: "unsupported group platform", ctx: group(PlatformAnthropic, true, true), account: openAIAccount, model: sol, want: ""},
{name: "unhydrated group", ctx: context.WithValue(context.Background(), ctxkey.Group, &Group{ID: 7, Platform: PlatformOpenAI, Status: StatusActive, ForceOpenAIFast: true, ForceOpenAIUltrafast: true}), account: openAIAccount, model: sol, want: ""},
} {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, openAIGroupForcedServiceTier(tt.ctx, tt.account))
require.Equal(t, tt.want, openAIGroupForcedServiceTier(tt.ctx, tt.account, tt.model))
})
}
}
// 仅强制 Ultra Fast 的分组:不支持的模型保留客户端传入的档位(含省略)。
func TestApplyOpenAIFastPolicyToBody_GroupForceUltrafastSkipsUnsupportedModels(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, DefaultOpenAIFastPolicySettings())
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
for _, tt := range []struct {
body string
want string
}{
{body: `{"model":"gpt-5.6-sol","input":"hi"}`, want: ""},
{body: `{"model":"gpt-5.6-sol","service_tier":"fast"}`, want: OpenAIFastTierPriority},
{body: `{"model":"gpt-5.6-sol","service_tier":"flex"}`, want: OpenAIFastTierFlex},
{body: `{"model":"gpt-5.6-sol","service_tier":"ultrafast"}`, want: OpenAIFastTierUltrafast},
} {
updated, err := svc.applyOpenAIFastPolicyToBody(openAIUltrafastGroupContext(), account, "gpt-5.6-sol", []byte(tt.body))
require.NoError(t, err)
require.Equal(t, tt.want, gjson.GetBytes(updated, "service_tier").String(), "body %s", tt.body)
}
}
// 两个开关同时开启:支持的模型写 ultrafast,其余模型写 priority。
func TestApplyOpenAIFastPolicyToBody_GroupForceFastAndUltrafastTogether(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, DefaultOpenAIFastPolicySettings())
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
ctx := context.WithValue(context.Background(), ctxkey.Group, &Group{
ID: 7, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true, ForceOpenAIFast: true, ForceOpenAIUltrafast: true,
})
for _, tt := range []struct {
model string
want string
}{
{model: "gpt-6.1-sol", want: OpenAIFastTierUltrafast},
{model: "gpt-6-astra", want: OpenAIFastTierUltrafast},
{model: "gpt-5.6-sol", want: OpenAIFastTierPriority},
{model: "gpt-6.1-terra", want: OpenAIFastTierPriority},
} {
for _, body := range []string{
`{"model":"` + tt.model + `"}`,
`{"model":"` + tt.model + `","service_tier":"flex"}`,
`{"model":"` + tt.model + `","service_tier":"ultrafast"}`,
} {
updated, err := svc.applyOpenAIFastPolicyToBody(ctx, account, tt.model, []byte(body))
require.NoError(t, err)
require.Equal(t, tt.want, gjson.GetBytes(updated, "service_tier").String(), "body %s", body)
}
}
}
@@ -1212,21 +1212,50 @@ func TestWSResponseCreate_GroupForceUltrafast(t *testing.T) {
t.Run("injects and overrides tier on response.create", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, DefaultOpenAIFastPolicySettings())
for _, frame := range [][]byte{
[]byte(`{"type":"response.create","model":"gpt-5.6-sol","input":[]}`),
[]byte(`{"type":"response.create","model":"gpt-5.6-sol","service_tier":"priority"}`),
[]byte(`{"type":"response.create","model":"gpt-5.6-sol","service_tier":"flex"}`),
[]byte(`{"type":"response.create","model":"gpt-6.1-sol","input":[]}`),
[]byte(`{"type":"response.create","model":"gpt-6.1-sol","service_tier":"priority"}`),
[]byte(`{"type":"response.create","model":"gpt-6.1-sol","service_tier":"flex"}`),
} {
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(ctx, account, "gpt-5.6-sol", frame)
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(ctx, account, "gpt-6.1-sol", frame)
require.NoError(t, err)
require.Nil(t, blocked)
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(updated, "service_tier").String(), "frame %s", frame)
}
})
t.Run("unsupported model keeps the client tier", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, DefaultOpenAIFastPolicySettings())
missing, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(
ctx, account, "gpt-5.6-sol", []byte(`{"type":"response.create","model":"gpt-5.6-sol"}`))
require.NoError(t, err)
require.Nil(t, blocked)
require.False(t, gjson.GetBytes(missing, "service_tier").Exists())
flex, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(
ctx, account, "gpt-5.6-sol", []byte(`{"type":"response.create","model":"gpt-5.6-sol","service_tier":"flex"}`))
require.NoError(t, err)
require.Nil(t, blocked)
require.Equal(t, OpenAIFastTierFlex, gjson.GetBytes(flex, "service_tier").String())
})
t.Run("with force fast also on, unsupported model gets priority", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, DefaultOpenAIFastPolicySettings())
bothCtx := context.WithValue(context.Background(), ctxkey.Group, &Group{
ID: 7, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true, ForceOpenAIFast: true, ForceOpenAIUltrafast: true,
})
for model, want := range map[string]string{"gpt-6.1-sol": OpenAIFastTierUltrafast, "gpt-5.6-sol": OpenAIFastTierPriority} {
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(
bothCtx, account, model, []byte(`{"type":"response.create","model":"`+model+`","service_tier":"flex"}`))
require.NoError(t, err)
require.Nil(t, blocked)
require.Equal(t, want, gjson.GetBytes(updated, "service_tier").String(), model)
}
})
t.Run("does not touch other frames", func(t *testing.T) {
svc := newOpenAIGatewayServiceWithSettings(t, DefaultOpenAIFastPolicySettings())
frame := []byte(`{"type":"response.cancel","model":"gpt-5.6-sol"}`)
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(ctx, account, "gpt-5.6-sol", frame)
frame := []byte(`{"type":"response.cancel","model":"gpt-6.1-sol"}`)
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(ctx, account, "gpt-6.1-sol", frame)
require.NoError(t, err)
require.Nil(t, blocked)
require.Equal(t, string(frame), string(updated))
@@ -1237,7 +1266,7 @@ func TestWSResponseCreate_GroupForceUltrafast(t *testing.T) {
ServiceTier: OpenAIFastTierUltrafast, Action: BetaPolicyActionFilter, Scope: BetaPolicyScopeAll,
}}})
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(
ctx, account, "gpt-5.6-sol", []byte(`{"type":"response.create","model":"gpt-5.6-sol"}`))
ctx, account, "gpt-6.1-sol", []byte(`{"type":"response.create","model":"gpt-6.1-sol"}`))
require.NoError(t, err)
require.Nil(t, blocked)
require.False(t, gjson.GetBytes(updated, "service_tier").Exists())
@@ -1248,7 +1277,7 @@ func TestWSResponseCreate_GroupForceUltrafast(t *testing.T) {
ServiceTier: OpenAIFastTierUltrafast, Action: BetaPolicyActionBlock, Scope: BetaPolicyScopeAll,
}}})
_, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(
ctx, account, "gpt-5.6-sol", []byte(`{"type":"response.create","model":"gpt-5.6-sol"}`))
ctx, account, "gpt-6.1-sol", []byte(`{"type":"response.create","model":"gpt-6.1-sol"}`))
require.NoError(t, err)
require.NotNil(t, blocked)
})
@@ -678,7 +678,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
}
rawTier := requestView.ServiceTier
if forcedTier := openAIGroupForcedServiceTier(ctx, account); forcedTier != "" {
if forcedTier := openAIGroupForcedServiceTier(ctx, account, upstreamModel); forcedTier != "" {
rawTier = forcedTier
if requestView.ServiceTier != forcedTier {
markPatchSet("service_tier", forcedTier)
@@ -2188,12 +2188,27 @@ func openAIFastPolicySettingsFromContext(ctx context.Context) *OpenAIFastPolicyS
return nil
}
// openAIModelSupportsUltrafast reports whether OpenAI offers the Ultrafast
// service tier for the model: GPT-6 Astra and GPT-6.1 Sol only. It is the single
// source for both the group-forced tier gate and the 6x Ultrafast billing
// multiplier, so a model can never be forced onto Ultrafast yet billed below it.
func openAIModelSupportsUltrafast(model string) bool {
normalized := normalizeKnownOpenAICodexModel(model)
return isOpenAIGPT6AstraModel(normalized) || normalized == "gpt-6.1-sol"
}
// openAIGroupForcedServiceTier returns the service_tier that the trusted request
// Group forces onto OpenAI-account requests: "ultrafast" for ForceOpenAIUltrafast,
// "priority" for ForceOpenAIFast, "" when the group forces nothing. The admin
// service keeps the two flags mutually exclusive; Ultrafast is checked first so
// a row that somehow carries both still resolves deterministically.
func openAIGroupForcedServiceTier(ctx context.Context, account *Account) string {
// Group forces onto an OpenAI-account request for the given upstream model, or
// "" when the group forces nothing and the client's value is kept.
//
// The two group flags are independent and resolve as Ultrafast > Fast > client:
// - ForceOpenAIUltrafast applies only to models that support Ultrafast
// (openAIModelSupportsUltrafast) and yields "ultrafast".
// - Otherwise ForceOpenAIFast yields "priority", for every model.
//
// So a group with only ForceOpenAIUltrafast leaves unsupported models to the
// client, and a group with both flags falls back to Fast for them.
func openAIGroupForcedServiceTier(ctx context.Context, account *Account, model string) string {
if ctx == nil || account == nil || account.Platform != PlatformOpenAI {
return ""
}
@@ -2202,7 +2217,7 @@ func openAIGroupForcedServiceTier(ctx context.Context, account *Account) string
return ""
}
switch {
case group.ForceOpenAIUltrafast:
case group.ForceOpenAIUltrafast && openAIModelSupportsUltrafast(model):
return OpenAIFastTierUltrafast
case group.ForceOpenAIFast:
return OpenAIFastTierPriority
@@ -2218,7 +2233,8 @@ func openAIGroupForcedServiceTier(ctx context.Context, account *Account) string
// action=force_priority rewrites any matched known tier to "priority". Before
// the global policy is evaluated, a trusted request Group with
// ForceOpenAIFast enabled unconditionally sets service_tier to "priority";
// ForceOpenAIUltrafast sets it to "ultrafast" instead.
// ForceOpenAIUltrafast sets it to "ultrafast" for models that support it and
// takes precedence there (see openAIGroupForcedServiceTier).
// The global policy remains authoritative and may still pass, filter, or block
// that final value.
//
@@ -2231,7 +2247,7 @@ func (s *OpenAIGatewayService) applyOpenAIFastPolicyToBody(ctx context.Context,
if len(body) == 0 {
return body, nil
}
if forcedTier := openAIGroupForcedServiceTier(ctx, account); forcedTier != "" {
if forcedTier := openAIGroupForcedServiceTier(ctx, account, model); forcedTier != "" {
updated, err := sjson.SetBytes(body, "service_tier", forcedTier)
if err != nil {
return body, fmt.Errorf("force group service_tier %s on body: %w", forcedTier, err)
@@ -2319,7 +2335,8 @@ func writeOpenAIFastPolicyBlockedResponse(c *gin.Context, err *OpenAIFastBlocked
// - force_priority: keeps service_tier and rewrites it to "priority"
// - block: returns (frame, *OpenAIFastBlockedError)
// - Group ForceOpenAIFast / ForceOpenAIUltrafast: sets priority / ultrafast
// first, then applies the global rule
// (ultrafast only for models that support it) first, then applies the
// global rule
//
// Only frames whose "type" field strictly equals "response.create" are
// inspected/mutated. Any other frame type — including the empty string —
@@ -2358,7 +2375,7 @@ func (s *OpenAIGatewayService) applyOpenAIFastPolicyToWSResponseCreate(
if frameType != "response.create" {
return frame, nil, nil
}
if forcedTier := openAIGroupForcedServiceTier(ctx, account); forcedTier != "" {
if forcedTier := openAIGroupForcedServiceTier(ctx, account, model); forcedTier != "" {
updated, err := sjson.SetBytes(frame, "service_tier", forcedTier)
if err != nil {
return frame, nil, fmt.Errorf("force group service_tier %s in ws frame: %w", forcedTier, err)
@@ -2776,7 +2776,7 @@ func TestOpenAIGatewayService_OAuthPassthrough_GroupForceOpenAIUltrafastOverride
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.1")
body := []byte(`{"model":"gpt-5.6-sol","stream":true,"instructions":"test","input":"hi","service_tier":"priority"}`)
body := []byte(`{"model":"gpt-6.1-sol","stream":true,"instructions":"test","input":"hi","service_tier":"priority"}`)
upstream := &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
@@ -2833,7 +2833,7 @@ func TestOpenAIGatewayService_OAuthLegacy_GroupForceOpenAIUltrafast(t *testing.T
t.Run("injects missing tier", func(t *testing.T) {
result, upstream, err := forward(t, DefaultOpenAIFastPolicySettings(),
[]byte(`{"model":"gpt-5.6-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
[]byte(`{"model":"gpt-6.1-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
require.NoError(t, err)
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(upstream.lastBody, "service_tier").String())
require.NotNil(t, result.ServiceTier)
@@ -2842,7 +2842,7 @@ func TestOpenAIGatewayService_OAuthLegacy_GroupForceOpenAIUltrafast(t *testing.T
t.Run("overrides client priority", func(t *testing.T) {
result, upstream, err := forward(t, DefaultOpenAIFastPolicySettings(),
[]byte(`{"model":"gpt-5.6-sol","stream":false,"service_tier":"fast","input":[{"type":"text","text":"hi"}]}`))
[]byte(`{"model":"gpt-6.1-sol","stream":false,"service_tier":"fast","input":[{"type":"text","text":"hi"}]}`))
require.NoError(t, err)
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(upstream.lastBody, "service_tier").String())
require.NotNil(t, result.ServiceTier)
@@ -2852,7 +2852,7 @@ func TestOpenAIGatewayService_OAuthLegacy_GroupForceOpenAIUltrafast(t *testing.T
t.Run("global ultrafast filter remains authoritative", func(t *testing.T) {
result, upstream, err := forward(t, &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{
ServiceTier: OpenAIFastTierUltrafast, Action: BetaPolicyActionFilter, Scope: BetaPolicyScopeAll,
}}}, []byte(`{"model":"gpt-5.6-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
}}}, []byte(`{"model":"gpt-6.1-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
require.NoError(t, err)
require.False(t, gjson.GetBytes(upstream.lastBody, "service_tier").Exists())
require.Nil(t, result.ServiceTier)
@@ -2861,7 +2861,7 @@ func TestOpenAIGatewayService_OAuthLegacy_GroupForceOpenAIUltrafast(t *testing.T
t.Run("global force_priority downgrades the forced ultrafast", func(t *testing.T) {
result, upstream, err := forward(t, &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{
ServiceTier: OpenAIFastTierUltrafast, Action: OpenAIFastPolicyActionForcePriority, Scope: BetaPolicyScopeAll,
}}}, []byte(`{"model":"gpt-5.6-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
}}}, []byte(`{"model":"gpt-6.1-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
require.NoError(t, err)
require.Equal(t, OpenAIFastTierPriority, gjson.GetBytes(upstream.lastBody, "service_tier").String())
require.NotNil(t, result.ServiceTier)
@@ -2871,7 +2871,7 @@ func TestOpenAIGatewayService_OAuthLegacy_GroupForceOpenAIUltrafast(t *testing.T
t.Run("global ultrafast block rejects with 403", func(t *testing.T) {
_, upstream, err := forward(t, &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{
ServiceTier: OpenAIFastTierUltrafast, Action: BetaPolicyActionBlock, Scope: BetaPolicyScopeAll,
}}}, []byte(`{"model":"gpt-5.6-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
}}}, []byte(`{"model":"gpt-6.1-sol","stream":false,"input":[{"type":"text","text":"hi"}]}`))
var blocked *OpenAIFastBlockedError
require.ErrorAs(t, err, &blocked)
require.Nil(t, upstream.lastReq)
@@ -2,4 +2,4 @@ ALTER TABLE groups
ADD COLUMN IF NOT EXISTS force_openai_ultrafast BOOLEAN NOT NULL DEFAULT FALSE;
COMMENT ON COLUMN groups.force_openai_ultrafast IS
'Force OpenAI gateway requests in this group to use service_tier=ultrafast before global Fast/Flex policy evaluation; mutually exclusive with force_openai_fast';
'Force service_tier=ultrafast on OpenAI gateway requests in this group for models that support Ultrafast, before global Fast/Flex policy evaluation; takes precedence over force_openai_fast';
@@ -1271,11 +1271,10 @@ export default {
},
openaiFast: {
title: 'OpenAI Fast mode',
forcedTier: 'Forced service tier',
followClient: 'Follow client',
force: 'Force Fast (priority)',
hint: 'Forces service_tier=priority on OpenAI requests in this group. The global Fast/Flex policy can still filter or block it. New requests update immediately after saving; existing WebSocket sessions must reconnect.',
forceUltrafast: 'Force Ultra Fast (ultrafast)',
hint: 'When a tier is forced, OpenAI requests in this group are rewritten to service_tier=priority or service_tier=ultrafast, overriding the client value. The global Fast/Flex policy can still filter or block it. Ultra Fast is only supported by some models and accounts, is billed at the Ultra Fast rate, and is not covered by "Free Fast". New requests update immediately after saving; existing WebSocket sessions must reconnect.',
ultrafastHint: 'Forces service_tier=ultrafast only on models that support Ultra Fast (GPT-6 Astra, GPT-6.1 Sol), taking precedence over "Force Fast". Other models get priority when "Force Fast" is also on, otherwise they follow the client. Ultra Fast is billed at 6x the Standard price, is not covered by "Free Fast", and requires upstream accounts with Ultra Fast access.',
free: 'Free Fast',
freeHint: 'Fast requests in this group still use the priority tier, but customers are charged the equivalent Standard price.'
},
@@ -1269,11 +1269,10 @@ export default {
},
openaiFast: {
title: 'OpenAI Fast 模式',
forcedTier: '强制服务档位',
followClient: '跟随客户端',
force: '强制使用 Fast(priority)',
hint: '开启后,此分组的 OpenAI 请求会强制写入 service_tier=priority;全局 Fast/Flex 策略仍可过滤或拦截。保存后新请求立即生效,已建立的 WebSocket 会话需重连。',
forceUltrafast: '强制使用 Ultra Fast(ultrafast)',
hint: '选择强制档位后,此分组的 OpenAI 请求会强制写入 service_tier=priority 或 service_tier=ultrafast,覆盖客户端传入的值;全局 Fast/Flex 策略仍可过滤或拦截。Ultra Fast 仅部分模型与账号支持,且按 Ultra Fast 价格计费,不受"免费 Fast"影响。保存后新请求立即生效,已建立的 WebSocket 会话需重连。',
ultrafastHint: '开启后,仅对支持 Ultra Fast 的模型(GPT-6 Astra、GPT-6.1 Sol)强制写入 service_tier=ultrafast,优先于"强制使用 Fast";其他模型在同时开启"强制使用 Fast"时写入 priority,否则跟随客户端。Ultra Fast 按标准价 6 倍计费,不受"免费 Fast"影响,且需要上游账号具备 Ultra Fast 权限。',
free: '免费 Fast',
freeHint: '该分组的 Fast 请求仍使用 priority 档位,但客户实际费用按同一请求的 Standard 价格计算。'
},
+40 -24
View File
@@ -1579,20 +1579,32 @@
<h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
{{ t("admin.groups.openaiFast.title") }}
</h4>
<div>
<label class="input-label">
{{ t("admin.groups.openaiFast.forcedTier") }}
<div class="flex items-center justify-between gap-4">
<label class="text-sm text-gray-600 dark:text-gray-400">
{{ t("admin.groups.openaiFast.force") }}
</label>
<Select
data-testid="create-openai-forced-tier"
:model-value="groupOpenAIForcedTier(createForm)"
:options="openAIForcedTierOptions"
@update:model-value="setGroupOpenAIForcedTier(createForm, $event)"
<Toggle
data-testid="create-force-openai-fast"
:aria-label="t('admin.groups.openaiFast.force')"
v-model="createForm.force_openai_fast"
/>
</div>
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
{{ t("admin.groups.openaiFast.hint") }}
</p>
<div class="flex items-center justify-between gap-4 mt-4">
<label class="text-sm text-gray-600 dark:text-gray-400">
{{ t("admin.groups.openaiFast.forceUltrafast") }}
</label>
<Toggle
data-testid="create-force-openai-ultrafast"
:aria-label="t('admin.groups.openaiFast.forceUltrafast')"
v-model="createForm.force_openai_ultrafast"
/>
</div>
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
{{ t("admin.groups.openaiFast.ultrafastHint") }}
</p>
<div class="flex items-center justify-between gap-4 mt-4">
<label class="text-sm text-gray-600 dark:text-gray-400">
{{ t("admin.groups.openaiFast.free") }}
@@ -3244,20 +3256,32 @@
<h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
{{ t("admin.groups.openaiFast.title") }}
</h4>
<div>
<label class="input-label">
{{ t("admin.groups.openaiFast.forcedTier") }}
<div class="flex items-center justify-between gap-4">
<label class="text-sm text-gray-600 dark:text-gray-400">
{{ t("admin.groups.openaiFast.force") }}
</label>
<Select
data-testid="edit-openai-forced-tier"
:model-value="groupOpenAIForcedTier(editForm)"
:options="openAIForcedTierOptions"
@update:model-value="setGroupOpenAIForcedTier(editForm, $event)"
<Toggle
data-testid="edit-force-openai-fast"
:aria-label="t('admin.groups.openaiFast.force')"
v-model="editForm.force_openai_fast"
/>
</div>
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
{{ t("admin.groups.openaiFast.hint") }}
</p>
<div class="flex items-center justify-between gap-4 mt-4">
<label class="text-sm text-gray-600 dark:text-gray-400">
{{ t("admin.groups.openaiFast.forceUltrafast") }}
</label>
<Toggle
data-testid="edit-force-openai-ultrafast"
:aria-label="t('admin.groups.openaiFast.forceUltrafast')"
v-model="editForm.force_openai_ultrafast"
/>
</div>
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
{{ t("admin.groups.openaiFast.ultrafastHint") }}
</p>
<div class="flex items-center justify-between gap-4 mt-4">
<label class="text-sm text-gray-600 dark:text-gray-400">
{{ t("admin.groups.openaiFast.free") }}
@@ -4363,9 +4387,7 @@ import {
type MessagesDispatchMappingRow,
} from "./groupsMessagesDispatch";
import {
groupOpenAIForcedTier,
normalizeGroupOpenAIFast,
setGroupOpenAIForcedTier,
supportsGroupOpenAIFast,
} from "./groupsOpenAIFast";
import {
@@ -4706,12 +4728,6 @@ const subscriptionTypeOptions = computed(() => [
{ value: "subscription", label: t("admin.groups.subscription.subscription") },
]);
const openAIForcedTierOptions = computed(() => [
{ value: "client", label: t("admin.groups.openaiFast.followClient") },
{ value: "priority", label: t("admin.groups.openaiFast.force") },
{ value: "ultrafast", label: t("admin.groups.openaiFast.forceUltrafast") },
]);
// 降级分组选项(创建时)- 仅包含 anthropic 平台且未启用 claude_code_only 的分组
const fallbackGroupOptions = computed(() => {
const options: { value: number | null; label: string }[] = [
@@ -159,17 +159,6 @@ const BaseDialogStub = defineComponent({
template: '<div v-if="show"><slot /><slot name="footer" /></div>',
});
// 透传 data-testid 的 Select 桩:暴露 modelValue / options,供用例读取当前档位并切换。
const SelectStub = defineComponent({
name: "SelectStub",
props: {
modelValue: { type: [String, Number, Boolean, null], default: null },
options: { type: Array, default: () => [] },
},
emits: ["update:modelValue"],
setup: () => () => h("div"),
});
// 表单提交前会调用这些子组件的 validate(),自动桩不提供该方法。
const ValidatingFieldStub = defineComponent({
setup(_, { expose }) {
@@ -190,7 +179,7 @@ const mountView = () =>
BaseDialog: BaseDialogStub,
ConfirmDialog: true,
EmptyState: true,
Select: SelectStub,
Select: true,
PlatformIcon: true,
Icon: true,
GroupCapacityBadge: true,
@@ -223,10 +212,21 @@ const openEditDialog = async (group: AdminGroup) => {
return wrapper;
};
const forcedTierSelect = (wrapper: ReturnType<typeof mountView>) =>
wrapper.getComponent<typeof SelectStub>(
'[data-testid="edit-openai-forced-tier"]',
);
const toggle = (
wrapper: ReturnType<typeof mountView>,
name: "fast" | "ultrafast",
) => wrapper.get(`[data-testid="edit-force-openai-${name}"]`);
const isOn = (wrapper: ReturnType<typeof mountView>, name: "fast" | "ultrafast") =>
toggle(wrapper, name).attributes("aria-checked") === "true";
const submit = async (wrapper: ReturnType<typeof mountView>) => {
await wrapper.get("#edit-group-form").trigger("submit");
await flushPromises();
expect(updateGroup).toHaveBeenCalledTimes(1);
expect(updateGroup.mock.calls[0][0]).toBe(sourceGroup.id);
return updateGroup.mock.calls[0][1];
};
describe("GroupsView OpenAI forced service tier", () => {
beforeEach(() => {
@@ -246,46 +246,59 @@ describe("GroupsView OpenAI forced service tier", () => {
updateGroup.mockResolvedValue({});
});
it("offers follow-client, Fast and Ultra Fast", async () => {
it("shows both switches off for a group that follows the client", async () => {
const wrapper = await openEditDialog(sourceGroup);
expect(forcedTierSelect(wrapper).props("options")).toEqual([
{ value: "client", label: "admin.groups.openaiFast.followClient" },
{ value: "priority", label: "admin.groups.openaiFast.force" },
{ value: "ultrafast", label: "admin.groups.openaiFast.forceUltrafast" },
]);
expect(forcedTierSelect(wrapper).props("modelValue")).toBe("client");
expect(isOn(wrapper, "fast")).toBe(false);
expect(isOn(wrapper, "ultrafast")).toBe(false);
wrapper.unmount();
});
it.each([
[{ force_openai_fast: true, force_openai_ultrafast: false }, "priority"],
[{ force_openai_fast: false, force_openai_ultrafast: true }, "ultrafast"],
])("loads the saved tier %o as %s", async (flags, tier) => {
[{ force_openai_fast: true, force_openai_ultrafast: false }],
[{ force_openai_fast: false, force_openai_ultrafast: true }],
[{ force_openai_fast: true, force_openai_ultrafast: true }],
])("loads and resaves the stored flags %o unchanged", async (flags) => {
const wrapper = await openEditDialog({ ...sourceGroup, ...flags });
expect(forcedTierSelect(wrapper).props("modelValue")).toBe(tier);
expect(isOn(wrapper, "fast")).toBe(flags.force_openai_fast);
expect(isOn(wrapper, "ultrafast")).toBe(flags.force_openai_ultrafast);
expect(await submit(wrapper)).toMatchObject(flags);
wrapper.unmount();
});
it("saves Ultra Fast as the only forced tier when switching from Fast", async () => {
it("turning on Ultra Fast keeps Force Fast as the fallback for other models", async () => {
const wrapper = await openEditDialog({
...sourceGroup,
force_openai_fast: true,
});
forcedTierSelect(wrapper).vm.$emit("update:modelValue", "ultrafast");
await flushPromises();
expect(forcedTierSelect(wrapper).props("modelValue")).toBe("ultrafast");
await toggle(wrapper, "ultrafast").trigger("click");
expect(isOn(wrapper, "fast")).toBe(true);
expect(isOn(wrapper, "ultrafast")).toBe(true);
await wrapper.get("#edit-group-form").trigger("submit");
await flushPromises();
expect(await submit(wrapper)).toMatchObject({
force_openai_fast: true,
force_openai_ultrafast: true,
});
expect(updateGroup).toHaveBeenCalledTimes(1);
expect(updateGroup.mock.calls[0][0]).toBe(sourceGroup.id);
expect(updateGroup.mock.calls[0][1]).toMatchObject({
wrapper.unmount();
});
it("the two switches toggle independently", async () => {
const wrapper = await openEditDialog({
...sourceGroup,
force_openai_fast: true,
force_openai_ultrafast: true,
});
await toggle(wrapper, "fast").trigger("click");
expect(isOn(wrapper, "fast")).toBe(false);
expect(isOn(wrapper, "ultrafast")).toBe(true);
expect(await submit(wrapper)).toMatchObject({
force_openai_fast: false,
force_openai_ultrafast: true,
});
@@ -293,18 +306,17 @@ describe("GroupsView OpenAI forced service tier", () => {
wrapper.unmount();
});
it("clears both flags when switching back to follow-client", async () => {
it("clears both flags when both switches are turned off", async () => {
const wrapper = await openEditDialog({
...sourceGroup,
force_openai_fast: true,
force_openai_ultrafast: true,
});
forcedTierSelect(wrapper).vm.$emit("update:modelValue", "client");
await flushPromises();
await wrapper.get("#edit-group-form").trigger("submit");
await flushPromises();
await toggle(wrapper, "fast").trigger("click");
await toggle(wrapper, "ultrafast").trigger("click");
expect(updateGroup.mock.calls[0][1]).toMatchObject({
expect(await submit(wrapper)).toMatchObject({
force_openai_fast: false,
force_openai_ultrafast: false,
});
@@ -1,9 +1,7 @@
import { describe, expect, it } from "vitest";
import {
groupOpenAIForcedTier,
normalizeGroupOpenAIFast,
setGroupOpenAIForcedTier,
supportsGroupOpenAIFast,
} from "../groupsOpenAIFast";
import en from "@/i18n/locales/en/admin/overview";
@@ -23,57 +21,14 @@ describe("groupsOpenAIFast", () => {
expect(normalizeGroupOpenAIFast("openai", false)).toBe(false);
});
it("derives the forced tier from the two mutually exclusive flags", () => {
expect(groupOpenAIForcedTier({})).toBe("client");
expect(
groupOpenAIForcedTier({
force_openai_fast: false,
force_openai_ultrafast: false,
}),
).toBe("client");
expect(groupOpenAIForcedTier({ force_openai_fast: true })).toBe("priority");
expect(groupOpenAIForcedTier({ force_openai_ultrafast: true })).toBe(
"ultrafast",
);
});
it("never leaves both forced-tier flags enabled", () => {
const flags = { force_openai_fast: true, force_openai_ultrafast: false };
setGroupOpenAIForcedTier(flags, "ultrafast");
expect(flags).toEqual({
force_openai_fast: false,
force_openai_ultrafast: true,
});
setGroupOpenAIForcedTier(flags, "priority");
expect(flags).toEqual({
force_openai_fast: true,
force_openai_ultrafast: false,
});
setGroupOpenAIForcedTier(flags, "client");
expect(flags).toEqual({
force_openai_fast: false,
force_openai_ultrafast: false,
});
setGroupOpenAIForcedTier(flags, "ultrafast");
setGroupOpenAIForcedTier(flags, null);
expect(flags).toEqual({
force_openai_fast: false,
force_openai_ultrafast: false,
});
});
it("provides localized forced-tier labels", () => {
it("provides localized Ultra Fast switch labels naming the supported models", () => {
for (const locale of [zh, en]) {
expect(locale.groups.openaiFast).toMatchObject({
forcedTier: expect.any(String),
followClient: expect.any(String),
forceUltrafast: expect.stringContaining("ultrafast"),
hint: expect.stringContaining("service_tier=ultrafast"),
ultrafastHint: expect.stringContaining("service_tier=ultrafast"),
});
expect(locale.groups.openaiFast.ultrafastHint).toContain("GPT-6 Astra");
expect(locale.groups.openaiFast.ultrafastHint).toContain("GPT-6.1 Sol");
}
});
@@ -8,27 +8,3 @@ export function normalizeGroupOpenAIFast(
): boolean {
return supportsGroupOpenAIFast(platform) && enabled;
}
// 分组强制的 OpenAI 服务档位。后端用两个互斥的布尔列表达,表单用单选避免
// 同时勾选两者(后端会以 400 拒绝)。
export type GroupOpenAIForcedTier = "client" | "priority" | "ultrafast";
interface GroupOpenAIForcedTierFlags {
force_openai_fast?: boolean;
force_openai_ultrafast?: boolean;
}
export function groupOpenAIForcedTier(
flags: GroupOpenAIForcedTierFlags,
): GroupOpenAIForcedTier {
if (flags.force_openai_ultrafast) return "ultrafast";
return flags.force_openai_fast ? "priority" : "client";
}
export function setGroupOpenAIForcedTier(
flags: GroupOpenAIForcedTierFlags,
tier: unknown,
): void {
flags.force_openai_fast = tier === "priority";
flags.force_openai_ultrafast = tier === "ultrafast";
}