mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
Merge pull request #9099 from PMExtra/feat/channel-expose-response-model
feat(channel): 渠道支持向用户显示实际响应模型
This commit is contained in:
20 files changed
+441
-10
No files matched your search
@@ -175,7 +175,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
authCacheInvalidationOutboxRepository := repository.NewAuthCacheInvalidationOutboxRepository(db)
|
||||
authCacheInvalidationWorker := service.ProvideAuthCacheInvalidationWorker(authCacheInvalidationOutboxRepository, apiKeyCache, apiKeyService)
|
||||
opsService := service.ProvideOpsService(opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink, settingService, authCacheInvalidationWorker, apiKeyService)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService, channelService)
|
||||
redeemHandler := handler.NewRedeemHandler(redeemService)
|
||||
subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService)
|
||||
announcementRepository := repository.NewAnnouncementRepository(client)
|
||||
|
||||
@@ -763,6 +763,28 @@ func UsageLogFromService(l *service.UsageLog) *UsageLog {
|
||||
return &u
|
||||
}
|
||||
|
||||
// ApplyResponseModel fills ResponseModel with the final response model of l
|
||||
// (upstream_response_model → upstream_model → model). It is left empty when the
|
||||
// final model equals the client-facing requested model, so users only ever see
|
||||
// "requested model" and "final response model", never the mapping chain.
|
||||
func (u *UsageLog) ApplyResponseModel(l *service.UsageLog) {
|
||||
if u == nil || l == nil {
|
||||
return
|
||||
}
|
||||
final := strings.TrimSpace(derefString(l.UpstreamResponseModel))
|
||||
if final == "" {
|
||||
final = strings.TrimSpace(derefString(l.UpstreamModel))
|
||||
}
|
||||
if final == "" {
|
||||
final = strings.TrimSpace(l.Model)
|
||||
}
|
||||
if final == "" || final == u.Model {
|
||||
u.ResponseModel = nil
|
||||
return
|
||||
}
|
||||
u.ResponseModel = &final
|
||||
}
|
||||
|
||||
// UsageLogFromServiceAdmin converts a service UsageLog to DTO for admin users.
|
||||
// It includes minimal Account info (ID, Name only) and IP address.
|
||||
func UsageLogFromServiceAdmin(l *service.UsageLog) *AdminUsageLog {
|
||||
|
||||
@@ -332,3 +332,69 @@ func TestUsageLogFromService_PreservesHistoricalMissingImageSize(t *testing.T) {
|
||||
func f64Ptr(value float64) *float64 {
|
||||
return &value
|
||||
}
|
||||
|
||||
func TestUsageLogApplyResponseModel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
strPtr := func(s string) *string { return &s }
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
log service.UsageLog
|
||||
want *string
|
||||
}{
|
||||
{
|
||||
name: "prefers upstream response model and hides mapping chain",
|
||||
log: service.UsageLog{
|
||||
Model: "claude-sonnet-4-5",
|
||||
RequestedModel: "claude-sonnet-4-5",
|
||||
UpstreamModel: strPtr("mid-model"),
|
||||
UpstreamResponseModel: strPtr("final-model-20260101"),
|
||||
ModelMappingChain: strPtr("claude-sonnet-4-5→mid-model→final-model"),
|
||||
},
|
||||
want: strPtr("final-model-20260101"),
|
||||
},
|
||||
{
|
||||
name: "falls back to upstream model",
|
||||
log: service.UsageLog{
|
||||
Model: "gpt-5",
|
||||
RequestedModel: "gpt-5",
|
||||
UpstreamModel: strPtr("gpt-5-mini"),
|
||||
},
|
||||
want: strPtr("gpt-5-mini"),
|
||||
},
|
||||
{
|
||||
name: "falls back to billing model when requested differs",
|
||||
log: service.UsageLog{
|
||||
Model: "gpt-5-mini",
|
||||
RequestedModel: "gpt-5",
|
||||
},
|
||||
want: strPtr("gpt-5-mini"),
|
||||
},
|
||||
{
|
||||
name: "omitted when final equals requested",
|
||||
log: service.UsageLog{
|
||||
Model: "gpt-5",
|
||||
RequestedModel: "gpt-5",
|
||||
UpstreamResponseModel: strPtr(" gpt-5 "),
|
||||
},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
out := UsageLogFromService(&tc.log)
|
||||
require.Nil(t, out.ResponseModel, "response_model must be opt-in")
|
||||
|
||||
out.ApplyResponseModel(&tc.log)
|
||||
require.Equal(t, tc.want, out.ResponseModel)
|
||||
|
||||
raw, err := json.Marshal(out)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "model_mapping_chain")
|
||||
require.NotContains(t, string(raw), "upstream_model")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -604,6 +604,11 @@ type UsageLog struct {
|
||||
AccountID int64 `json:"account_id"`
|
||||
RequestID string `json:"request_id"`
|
||||
Model string `json:"model"`
|
||||
// ResponseModel is the final model that actually answered the request. It is
|
||||
// only populated for regular users when the record's channel enables
|
||||
// features_config.expose_response_model and it differs from Model. The
|
||||
// intermediate mapping chain is never exposed.
|
||||
ResponseModel *string `json:"response_model,omitempty"`
|
||||
// ServiceTier records the OpenAI service tier used for billing, e.g. "priority" / "flex".
|
||||
ServiceTier *string `json:"service_tier,omitempty"`
|
||||
// ReasoningEffort is the client-requested effort (mapping-hidden, like Model).
|
||||
|
||||
@@ -50,6 +50,7 @@ type UsageHandler struct {
|
||||
apiKeyService *service.APIKeyService
|
||||
opsService *service.OpsService
|
||||
settingService *service.SettingService
|
||||
channelService *service.ChannelService
|
||||
}
|
||||
|
||||
// NewUsageHandler creates a new UsageHandler
|
||||
@@ -58,15 +59,51 @@ func NewUsageHandler(
|
||||
apiKeyService *service.APIKeyService,
|
||||
opsService *service.OpsService,
|
||||
settingService *service.SettingService,
|
||||
channelService *service.ChannelService,
|
||||
) *UsageHandler {
|
||||
return &UsageHandler{
|
||||
usageService: usageService,
|
||||
apiKeyService: apiKeyService,
|
||||
opsService: opsService,
|
||||
settingService: settingService,
|
||||
channelService: channelService,
|
||||
}
|
||||
}
|
||||
|
||||
// userUsageLogs 将使用记录转换为普通用户 DTO。对于所属渠道开启了
|
||||
// "向用户显示实际响应模型"的记录,额外填充 response_model。
|
||||
// 渠道开关一次性从渠道内存缓存中批量读取,不产生额外数据库查询。
|
||||
func (h *UsageHandler) userUsageLogs(c *gin.Context, records []service.UsageLog) []dto.UsageLog {
|
||||
var exposed map[int64]bool
|
||||
if h.channelService != nil && len(records) > 0 {
|
||||
seen := make(map[int64]struct{}, 2)
|
||||
ids := make([]int64, 0, 2)
|
||||
for i := range records {
|
||||
if records[i].ChannelID == nil {
|
||||
continue
|
||||
}
|
||||
id := *records[i].ChannelID
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
exposed = h.channelService.ResponseModelExposedChannels(c.Request.Context(), ids)
|
||||
}
|
||||
|
||||
acceptLanguage := c.GetHeader("Accept-Language")
|
||||
out := make([]dto.UsageLog, 0, len(records))
|
||||
for i := range records {
|
||||
item := dto.UsageLogFromService(&records[i]).Localized(acceptLanguage)
|
||||
if records[i].ChannelID != nil && exposed[*records[i].ChannelID] {
|
||||
item.ApplyResponseModel(&records[i])
|
||||
}
|
||||
out = append(out, *item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *UsageHandler) parseUserUsageFilters(c *gin.Context, requireRange bool) (*userUsageFilters, bool) {
|
||||
subject, ok := middleware2.GetAuthSubjectFromContext(c)
|
||||
if !ok {
|
||||
@@ -252,11 +289,7 @@ func (h *UsageHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]dto.UsageLog, 0, len(records))
|
||||
for i := range records {
|
||||
out = append(out, *dto.UsageLogFromService(&records[i]).Localized(c.GetHeader("Accept-Language")))
|
||||
}
|
||||
response.Paginated(c, out, result.Total, page, pageSize)
|
||||
response.Paginated(c, h.userUsageLogs(c, records), result.Total, page, pageSize)
|
||||
}
|
||||
|
||||
// ListErrors handles listing the current user's failed requests (redacted).
|
||||
@@ -400,7 +433,7 @@ func (h *UsageHandler) GetByID(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, dto.UsageLogFromService(record).Localized(c.GetHeader("Accept-Language")))
|
||||
response.Success(c, &h.userUsageLogs(c, []service.UsageLog{*record})[0])
|
||||
}
|
||||
|
||||
// Stats handles getting usage statistics
|
||||
|
||||
@@ -64,7 +64,7 @@ func newDailyUsageTestRouter(usageRepo *dailyUsageRepoStub, apiKeyRepo *dailyUsa
|
||||
gin.SetMode(gin.TestMode)
|
||||
usageSvc := service.NewUsageService(usageRepo, nil, nil, nil)
|
||||
apiKeySvc := service.NewAPIKeyService(apiKeyRepo, nil, nil, nil, nil, nil, nil)
|
||||
handler := NewUsageHandler(usageSvc, apiKeySvc, nil, nil)
|
||||
handler := NewUsageHandler(usageSvc, apiKeySvc, nil, nil, nil)
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: userID})
|
||||
|
||||
@@ -81,7 +81,7 @@ func (s *userUsageRepoCapture) GetGroupStatsWithFilters(ctx context.Context, sta
|
||||
func newUserUsageRequestTypeTestRouter(repo *userUsageRepoCapture) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
usageSvc := service.NewUsageService(repo, nil, nil, nil)
|
||||
handler := NewUsageHandler(usageSvc, nil, nil, nil)
|
||||
handler := NewUsageHandler(usageSvc, nil, nil, nil, nil)
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 42})
|
||||
|
||||
@@ -1500,7 +1500,7 @@ func newContractDeps(t *testing.T) *contractDeps {
|
||||
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)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil, nil)
|
||||
adminSettingHandler := adminhandler.NewSettingHandler(settingService, nil, nil, nil, nil, nil, nil)
|
||||
adminAccountHandler := adminhandler.NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
|
||||
|
||||
@@ -312,6 +312,20 @@ func (c *Channel) IsBedrockCCCompatEnabled(platform string) bool {
|
||||
return ok && enabled
|
||||
}
|
||||
|
||||
// featureKeyExposeResponseModel is the Channel.FeaturesConfig key that lets
|
||||
// regular users see the final upstream response model in their usage records.
|
||||
const featureKeyExposeResponseModel = "expose_response_model"
|
||||
|
||||
// IsResponseModelExposed 返回该渠道是否允许普通用户在使用记录中看到实际响应模型。
|
||||
// 默认关闭;仅暴露请求模型与最终响应模型,不暴露中间映射链。
|
||||
func (c *Channel) IsResponseModelExposed() bool {
|
||||
if c == nil || c.FeaturesConfig == nil {
|
||||
return false
|
||||
}
|
||||
enabled, ok := c.FeaturesConfig[featureKeyExposeResponseModel].(bool)
|
||||
return ok && enabled
|
||||
}
|
||||
|
||||
// deepCopyFeaturesConfig creates a deep copy of FeaturesConfig to prevent cache pollution.
|
||||
func deepCopyFeaturesConfig(src map[string]any) map[string]any {
|
||||
dst := make(map[string]any, len(src))
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestChannelIsResponseModelExposed(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.False(t, (*Channel)(nil).IsResponseModelExposed())
|
||||
require.False(t, (&Channel{}).IsResponseModelExposed())
|
||||
require.False(t, (&Channel{FeaturesConfig: map[string]any{featureKeyExposeResponseModel: false}}).IsResponseModelExposed())
|
||||
require.False(t, (&Channel{FeaturesConfig: map[string]any{featureKeyExposeResponseModel: "true"}}).IsResponseModelExposed())
|
||||
require.True(t, (&Channel{FeaturesConfig: map[string]any{featureKeyExposeResponseModel: true}}).IsResponseModelExposed())
|
||||
}
|
||||
|
||||
func TestChannelService_ResponseModelExposedChannels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
channels := []Channel{
|
||||
{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{featureKeyExposeResponseModel: true}},
|
||||
{ID: 2, Status: StatusActive, FeaturesConfig: map[string]any{featureKeyExposeResponseModel: false}},
|
||||
{ID: 3, Status: StatusActive},
|
||||
}
|
||||
svc := &ChannelService{}
|
||||
svc.cache.Store(populateChannelCache(channels, map[int64]string{}))
|
||||
|
||||
got := svc.ResponseModelExposedChannels(context.Background(), []int64{1, 2, 3, 404})
|
||||
require.Equal(t, map[int64]bool{1: true}, got)
|
||||
|
||||
require.Nil(t, svc.ResponseModelExposedChannels(context.Background(), nil))
|
||||
require.Nil(t, (*ChannelService)(nil).ResponseModelExposedChannels(context.Background(), []int64{1}))
|
||||
}
|
||||
@@ -507,6 +507,28 @@ func (s *ChannelService) GetChannelForGroup(ctx context.Context, groupID int64)
|
||||
return ch.Clone(), nil
|
||||
}
|
||||
|
||||
// ResponseModelExposedChannels 返回给定渠道 ID 中开启了"向用户显示实际响应模型"的集合。
|
||||
// 只读取内存缓存(与网关热路径共用),不会产生额外的数据库查询。
|
||||
func (s *ChannelService) ResponseModelExposedChannels(ctx context.Context, ids []int64) map[int64]bool {
|
||||
if s == nil || len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
cache, err := s.loadCache(ctx)
|
||||
if err != nil || cache == nil {
|
||||
return nil
|
||||
}
|
||||
var out map[int64]bool
|
||||
for _, id := range ids {
|
||||
if ch, ok := cache.byID[id]; ok && ch.IsResponseModelExposed() {
|
||||
if out == nil {
|
||||
out = make(map[int64]bool, len(ids))
|
||||
}
|
||||
out[id] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GetGroupPlatform 获取分组的平台标识(从缓存)
|
||||
func (s *ChannelService) GetGroupPlatform(ctx context.Context, groupID int64) string {
|
||||
cache, err := s.loadCache(ctx)
|
||||
|
||||
@@ -70,6 +70,14 @@
|
||||
<span class="mr-0.5">↳</span>{{ row.upstream_model }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="row.response_model && row.response_model !== row.model" class="space-y-0.5">
|
||||
<div class="break-all font-medium text-gray-900 dark:text-white">
|
||||
{{ row.model }}
|
||||
</div>
|
||||
<div class="break-all text-gray-500 dark:text-gray-400" :title="t('usage.responseModel')">
|
||||
<span class="mr-0.5">↳</span>{{ row.response_model }}
|
||||
</div>
|
||||
</div>
|
||||
<span v-else class="font-medium text-gray-900 dark:text-white">{{ row.model }}</span>
|
||||
<div
|
||||
v-if="row.upstream_model_mismatch === true && row.upstream_response_model"
|
||||
|
||||
@@ -440,6 +440,47 @@ describe('admin UsageTable tooltip', () => {
|
||||
expect(text).toContain('claude-sonnet-4-20250514')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['shows', 'gpt-5.5-2026-01-01', true],
|
||||
['hides', null, false],
|
||||
])('%s the actual response model for user rows', (_label, responseModel, visible) => {
|
||||
const row = {
|
||||
request_id: 'req-user-model-1',
|
||||
model: 'gpt-5.5',
|
||||
response_model: responseModel,
|
||||
actual_cost: 0,
|
||||
total_cost: 0,
|
||||
rate_multiplier: 1,
|
||||
input_cost: 0,
|
||||
output_cost: 0,
|
||||
cache_creation_cost: 0,
|
||||
cache_read_cost: 0,
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
}
|
||||
|
||||
const wrapper = mount(UsageTable, {
|
||||
props: {
|
||||
data: [row],
|
||||
loading: false,
|
||||
columns: [],
|
||||
showAccountBilling: false,
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
DataTable: DataTableStub,
|
||||
EmptyState: true,
|
||||
Icon: true,
|
||||
Teleport: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('gpt-5.5')
|
||||
expect(text.includes('↳gpt-5.5-2026-01-01') || text.includes('↳ gpt-5.5-2026-01-01')).toBe(visible)
|
||||
})
|
||||
|
||||
it('shows requested and forwarded reasoning effort separately when they differ', () => {
|
||||
const wrapper = mount(UsageTable, {
|
||||
props: {
|
||||
|
||||
@@ -205,6 +205,8 @@ export default {
|
||||
noGroupsMatch: 'No groups match your search',
|
||||
restrictModels: 'Restrict Models',
|
||||
restrictModelsHint: 'When enabled, only models in the pricing list are allowed. Others will be rejected.',
|
||||
exposeResponseModel: 'Show Actual Model to Users',
|
||||
exposeResponseModelHint: 'When enabled, users can see both the requested model and the actual response model in their usage records (the intermediate mapping chain stays hidden).',
|
||||
defaultPerRequestPrice: 'Default per-request price (fallback when no tier matches)',
|
||||
defaultImagePrice: 'Default image price (fallback when no tier matches)',
|
||||
defaultVideoPrice: 'Default video price per second (fallback when no tier matches)',
|
||||
|
||||
@@ -372,6 +372,7 @@ export default {
|
||||
model: 'Model',
|
||||
requestedModel: 'Requested',
|
||||
upstreamModel: 'Upstream',
|
||||
responseModel: 'Actual response model',
|
||||
sentUpstreamModel: 'Sent upstream',
|
||||
upstreamResponseModel: 'Upstream response',
|
||||
upstreamModelMismatch: 'Response model mismatch',
|
||||
|
||||
@@ -205,6 +205,8 @@ export default {
|
||||
noGroupsMatch: '没有匹配的分组',
|
||||
restrictModels: '限制模型',
|
||||
restrictModelsHint: '开启后,仅允许模型定价列表中的模型。不在列表中的模型请求将被拒绝。',
|
||||
exposeResponseModel: '向用户显示实际模型',
|
||||
exposeResponseModelHint: '开启后,用户可在使用记录中看到请求模型与实际响应模型(不包含中间映射链)。',
|
||||
defaultPerRequestPrice: '默认单次价格(未命中层级时使用)',
|
||||
defaultImagePrice: '默认图片价格(未命中层级时使用)',
|
||||
defaultVideoPrice: '默认视频每秒价格(未命中层级时使用)',
|
||||
|
||||
@@ -377,6 +377,7 @@ export default {
|
||||
model: '模型',
|
||||
requestedModel: '请求',
|
||||
upstreamModel: '上游',
|
||||
responseModel: '实际响应模型',
|
||||
sentUpstreamModel: '发往上游',
|
||||
upstreamResponseModel: '上游响应',
|
||||
upstreamModelMismatch: '上游响应模型不一致',
|
||||
|
||||
@@ -1836,6 +1836,8 @@ export interface UsageLog {
|
||||
account_id: number | null
|
||||
request_id: string
|
||||
model: string
|
||||
/** Final response model; only present for user rows when the channel enables expose_response_model. */
|
||||
response_model?: string | null
|
||||
service_tier?: string | null
|
||||
reasoning_effort?: string | null
|
||||
inbound_endpoint?: string | null
|
||||
|
||||
@@ -219,6 +219,22 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Expose actual response model to users -->
|
||||
<div>
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="form.expose_response_model"
|
||||
data-testid="channel-expose-response-model"
|
||||
class="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
|
||||
/>
|
||||
<span class="input-label mb-0">{{ t('admin.channels.form.exposeResponseModel', 'Show Actual Model to Users') }}</span>
|
||||
</label>
|
||||
<p class="mt-1 ml-6 text-xs text-gray-400">
|
||||
{{ t('admin.channels.form.exposeResponseModelHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Billing Basis -->
|
||||
<div>
|
||||
<label class="input-label">{{ t('admin.channels.form.billingModelSource', 'Billing Basis') }}</label>
|
||||
@@ -771,6 +787,7 @@ const form = reactive({
|
||||
description: '',
|
||||
status: 'active',
|
||||
restrict_models: false,
|
||||
expose_response_model: false,
|
||||
billing_model_source: 'channel_mapped' as string,
|
||||
platforms: [] as PlatformSection[],
|
||||
apply_pricing_to_account_stats: false,
|
||||
@@ -1203,6 +1220,8 @@ function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[
|
||||
featuresConfig.bedrock_cc_compat = form.platforms.some(
|
||||
section => section.enabled && section.platform === 'anthropic' && section.bedrock_cc_compat
|
||||
)
|
||||
// Channel-level boolean: lets users see the actual response model in usage records.
|
||||
featuresConfig.expose_response_model = !!form.expose_response_model
|
||||
|
||||
return { group_ids: uniqueGroupIds, model_pricing, model_mapping, features_config: featuresConfig }
|
||||
}
|
||||
@@ -1373,6 +1392,7 @@ function resetForm() {
|
||||
form.description = ''
|
||||
form.status = 'active'
|
||||
form.restrict_models = false
|
||||
form.expose_response_model = false
|
||||
form.billing_model_source = 'channel_mapped'
|
||||
form.platforms = []
|
||||
form.apply_pricing_to_account_stats = false
|
||||
@@ -1395,6 +1415,7 @@ async function openEditDialog(channel: Channel) {
|
||||
form.description = channel.description || ''
|
||||
form.status = channel.status
|
||||
form.restrict_models = channel.restrict_models || false
|
||||
form.expose_response_model = channel.features_config?.expose_response_model === true
|
||||
form.billing_model_source = channel.billing_model_source || 'channel_mapped'
|
||||
form.apply_pricing_to_account_stats = channel.apply_pricing_to_account_stats || false
|
||||
// Must load groups first so apiToForm can map groupID → platform
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { defineComponent } from 'vue'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Channel, CreateChannelRequest, UpdateChannelRequest } from '@/api/admin/channels'
|
||||
import ChannelsView from '@/views/admin/ChannelsView.vue'
|
||||
|
||||
const { listChannels, createChannel, updateChannel, getGroups, showSuccess, showError } = vi.hoisted(() => ({
|
||||
listChannels: vi.fn(),
|
||||
createChannel: vi.fn(),
|
||||
updateChannel: vi.fn(),
|
||||
getGroups: vi.fn(),
|
||||
showSuccess: vi.fn(),
|
||||
showError: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/api/admin', () => ({
|
||||
adminAPI: {
|
||||
channels: { list: listChannels, create: createChannel, update: updateChannel },
|
||||
groups: { getAll: getGroups },
|
||||
settings: { getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false }) }
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showSuccess, showError }) }))
|
||||
|
||||
vi.mock('vue-i18n', async () => ({
|
||||
...await vi.importActual<typeof import('vue-i18n')>('vue-i18n'),
|
||||
useI18n: () => ({ t: (key: string) => key })
|
||||
}))
|
||||
|
||||
function mountView() {
|
||||
return mount(ChannelsView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AppLayout: defineComponent({ template: '<main><slot /></main>' }),
|
||||
TablePageLayout: defineComponent({
|
||||
template: '<section><slot name="filters" /><slot name="table" /><slot name="pagination" /></section>'
|
||||
}),
|
||||
BaseDialog: defineComponent({
|
||||
props: ['show'],
|
||||
template: '<section v-if="show"><slot /><slot name="footer" /></section>'
|
||||
}),
|
||||
DataTable: defineComponent({
|
||||
props: ['data'],
|
||||
template: '<div v-for="row in data" :key="row.id"><slot name="cell-actions" :row="row" /></div>'
|
||||
}),
|
||||
Pagination: true,
|
||||
ConfirmDialog: true,
|
||||
EmptyState: true,
|
||||
Select: true,
|
||||
Icon: true,
|
||||
PlatformIcon: true,
|
||||
PricingEntryCard: true
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type View = ReturnType<typeof mountView>
|
||||
|
||||
async function clickButton(wrapper: View, text: string) {
|
||||
const button = wrapper.findAll('button').find(button => button.text() === text)
|
||||
expect(button).toBeDefined()
|
||||
await button!.trigger('click')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
function platformCheckbox(wrapper: View, platform: string) {
|
||||
return wrapper.findAll('label')
|
||||
.find(label => label.text() === `admin.groups.platforms.${platform}`)!
|
||||
.get('input[type="checkbox"]')
|
||||
}
|
||||
|
||||
|
||||
function makeChannel(features: Record<string, unknown>): Channel {
|
||||
return {
|
||||
id: 1, name: 'Bedrock relay', description: '', status: 'active',
|
||||
billing_model_source: 'channel_mapped', restrict_models: false,
|
||||
features_config: features, group_ids: [11, 22], model_pricing: [], model_mapping: {},
|
||||
apply_pricing_to_account_stats: false, account_stats_pricing_rules: [],
|
||||
created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z'
|
||||
}
|
||||
}
|
||||
|
||||
function exposeCheckbox(wrapper: View) {
|
||||
return wrapper.get('[data-testid="channel-expose-response-model"]')
|
||||
}
|
||||
|
||||
describe('ChannelsView expose response model', () => {
|
||||
let stored: Channel[]
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
stored = []
|
||||
listChannels.mockImplementation(async () => ({ items: stored, total: stored.length }))
|
||||
getGroups.mockResolvedValue([
|
||||
{ id: 11, name: 'Anthropic group', platform: 'anthropic', rate_multiplier: 1 },
|
||||
{ id: 22, name: 'OpenAI group', platform: 'openai', rate_multiplier: 1 }
|
||||
])
|
||||
createChannel.mockImplementation(async (request: CreateChannelRequest) => {
|
||||
const channel = makeChannel(request.features_config || {})
|
||||
channel.group_ids = request.group_ids || []
|
||||
stored = [channel]
|
||||
return channel
|
||||
})
|
||||
updateChannel.mockImplementation(async (_id: number, request: UpdateChannelRequest) => {
|
||||
stored = [{ ...stored[0], ...request } as Channel]
|
||||
return stored[0]
|
||||
})
|
||||
})
|
||||
|
||||
it.each([true, false])('creates and reopens a channel with expose_response_model %s', async enabled => {
|
||||
const wrapper = mountView()
|
||||
await flushPromises()
|
||||
await clickButton(wrapper, 'admin.channels.createChannel')
|
||||
expect((exposeCheckbox(wrapper).element as HTMLInputElement).checked).toBe(false)
|
||||
await wrapper.get('input[required]').setValue('Relay')
|
||||
await platformCheckbox(wrapper, 'anthropic').setValue(true)
|
||||
await clickButton(wrapper, 'admin.groups.platforms.anthropic')
|
||||
await wrapper.findAll('label').find(label => label.text().includes('Anthropic group'))!
|
||||
.get('input[type="checkbox"]').setValue(true)
|
||||
if (enabled) await exposeCheckbox(wrapper).setValue(true)
|
||||
|
||||
await wrapper.get('#channel-form').trigger('submit')
|
||||
await flushPromises()
|
||||
expect(showError).not.toHaveBeenCalled()
|
||||
expect(createChannel).toHaveBeenCalledOnce()
|
||||
expect(createChannel.mock.calls[0][0].features_config.expose_response_model).toBe(enabled)
|
||||
|
||||
await clickButton(wrapper, 'common.edit')
|
||||
expect((exposeCheckbox(wrapper).element as HTMLInputElement).checked).toBe(enabled)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('turns the toggle off on update while preserving other features', async () => {
|
||||
stored = [makeChannel({ expose_response_model: true, future_feature: { enabled: true } })]
|
||||
const wrapper = mountView()
|
||||
await flushPromises()
|
||||
await clickButton(wrapper, 'common.edit')
|
||||
expect((exposeCheckbox(wrapper).element as HTMLInputElement).checked).toBe(true)
|
||||
await exposeCheckbox(wrapper).setValue(false)
|
||||
|
||||
await wrapper.get('#channel-form').trigger('submit')
|
||||
await flushPromises()
|
||||
expect(showError).not.toHaveBeenCalled()
|
||||
expect(updateChannel).toHaveBeenCalledOnce()
|
||||
const features = updateChannel.mock.calls[0][1].features_config
|
||||
expect(features.expose_response_model).toBe(false)
|
||||
expect(features.future_feature).toEqual({ enabled: true })
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user