merge: official v1.5.4 release

This commit is contained in:
Codex committed 2026-09-19 15:36:02 +08:00
commit 7f389875cb
189 files changed
+13222 -8821

No files matched your search

+4 -16
View File
@@ -88,7 +88,6 @@ type AdminReferenceData struct {
type ChannelRequest struct {
Name string `json:"name"`
PublicAlias *string `json:"publicAlias"`
SortOrder *int `json:"sortOrder"`
BaseURL string `json:"baseUrl"`
APIKey string `json:"apiKey"`
@@ -106,7 +105,6 @@ type PublicModelChannel struct {
Scope model.ChannelScope `json:"scope"`
Enabled bool `json:"enabled"`
Name string `json:"name"`
PublicAlias string `json:"publicAlias,omitempty"`
SortOrder int `json:"sortOrder"`
BaseURL string `json:"baseUrl"`
APIKey string `json:"apiKey"`
@@ -124,6 +122,8 @@ type PublicModelChannel struct {
type PublicChannelModelPrice struct {
Model string `json:"model"`
DisplayName string `json:"displayName"`
ChannelLabel string `json:"channelLabel"`
Description string `json:"description"`
Icon string `json:"icon"`
Capability string `json:"capability"`
Protocol model.ChannelInterfaceType `json:"protocol"`
@@ -878,13 +878,6 @@ func (s *Service) channelFromRequest(req ChannelRequest, channel model.ModelChan
return channel, err
}
channel.Name = name
if req.PublicAlias != nil {
alias := strings.TrimSpace(*req.PublicAlias)
if len([]rune(alias)) > 80 {
return channel, BadAuthRequest("前台显示别名不能超过 80 个字符")
}
channel.PublicAlias = alias
}
if req.SortOrder != nil {
if err := validateChannelSortOrder(*req.SortOrder); err != nil {
return channel, err
@@ -949,7 +942,7 @@ func publicChannel(channel model.ModelChannel, admin bool, channelModels []model
capabilityConfig = normalized
}
}
modelCosts = append(modelCosts, PublicChannelModelPrice{Model: item.ModelKey, DisplayName: item.DisplayName, Icon: item.Icon, Capability: item.Capability, Protocol: item.Protocol, BillingMode: item.BillingMode, UnitPriceMicrocredits: item.UnitPriceMicrocredits, InputTokenPriceMicrocredits: item.InputTokenPriceMicrocredits, OutputTokenPriceMicrocredits: item.OutputTokenPriceMicrocredits, CachedTokenPriceMicrocredits: item.CachedTokenPriceMicrocredits, CapabilityConfig: capabilityConfig})
modelCosts = append(modelCosts, PublicChannelModelPrice{Model: item.ModelKey, DisplayName: item.DisplayName, ChannelLabel: item.ChannelLabel, Description: item.Description, Icon: item.Icon, Capability: item.Capability, Protocol: item.Protocol, BillingMode: item.BillingMode, UnitPriceMicrocredits: item.UnitPriceMicrocredits, InputTokenPriceMicrocredits: item.InputTokenPriceMicrocredits, OutputTokenPriceMicrocredits: item.OutputTokenPriceMicrocredits, CachedTokenPriceMicrocredits: item.CachedTokenPriceMicrocredits, CapabilityConfig: capabilityConfig})
}
}
if len(models) == 0 {
@@ -969,17 +962,12 @@ func publicChannel(channel model.ModelChannel, admin bool, channelModels []model
} else if admin {
apiKey = channel.APIKey
}
name, alias := channel.PublicName(), ""
if admin {
name, alias = channel.Name, channel.PublicAlias
}
return PublicModelChannel{
ID: channel.ID,
UserID: channel.UserID,
Scope: channel.Scope,
Enabled: channel.Enabled,
Name: name,
PublicAlias: alias,
Name: channel.Name,
SortOrder: channel.SortOrder,
BaseURL: baseURL,
APIKey: apiKey,
+1 -1
View File
@@ -141,7 +141,7 @@ func TestDuplicateSystemChannelCopiesSecretsModelsAndPriceTiers(t *testing.T) {
if err != nil {
t.Fatalf("DuplicateSystemChannel() error = %v", err)
}
if copied.Name != "方舟视频 - 副本" || copied.PublicAlias != source.PublicAlias || copied.Enabled != source.Enabled {
if copied.Name != "方舟视频 - 副本" || copied.Enabled != source.Enabled {
t.Fatalf("copied channel summary = %#v", copied)
}
var stored model.ModelChannel
@@ -0,0 +1,86 @@
package app
import (
"testing"
"infinite-canvas/backend/internal/model"
)
func TestAllVideoProtocolsQuoteReserveAndSettleWithoutProviderUsage(t *testing.T) {
for _, protocol := range []model.ChannelInterfaceType{"newapi-channel-2", "newapi-video", "custom-video"} {
t.Run(string(protocol), func(t *testing.T) {
svc, db, channel, channelModel, _ := newVideoTokenQuoteFixture(t)
if err := db.AutoMigrate(&model.ApiCallLog{}); err != nil {
t.Fatal(err)
}
if err := db.Model(&model.ChannelModel{}).Where("id = ?", channelModel.ID).Update("protocol", protocol).Error; err != nil {
t.Fatal(err)
}
intent := ModelRequestIntent{Capability: "video", Options: map[string]any{"vquality": "720p", "size": "16:9", "videoSeconds": 5}}
quote, err := svc.QuoteChannelModel(ChannelModelQuoteRequest{ChannelID: channel.ID, ModelKey: channelModel.ModelKey, Intent: intent})
if err != nil {
t.Fatal(err)
}
assertVideoTokenQuote(t, quote, 1_900_800)
input := quoteInput(intent, channelModel.ModelKey)
input["config"].(map[string]any)["channelId"] = channel.ID
input, err = svc.resolveSystemChannelModelSelection(input, "canvas_video", "")
if err != nil {
t.Fatal(err)
}
order, err := svc.taskBillingOrder("quote-user", &model.Task{ID: "generic-video", Type: "canvas_video"}, input)
if err != nil {
t.Fatal(err)
}
if order.VideoFormulaTokens != 108_000 || order.AmountMicrocredits != quote.AmountMicrocredits {
t.Fatalf("quote/order disagree: %#v / %#v", quote, order)
}
if err := svc.repo.ReserveBillingOrder(order); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
if err := svc.SettleBilling(order.ID, "completed-video"); err != nil {
t.Fatal(err)
}
}
settled, err := svc.repo.BillingOrder(order.ID)
if err != nil {
t.Fatal(err)
}
if settled.Status != model.BillingStatusSettled || settled.UsageSource != "video_formula" || settled.UsageAvailable || settled.OutputTokens != 108_000 || settled.ActualAmountMicrocredits != 1_728_000 || settled.RefundedAmountMicrocredits != 172_800 {
t.Fatalf("wrong formula settlement: %#v", settled)
}
var account model.CreditAccount
if err := db.First(&account, "user_id = ?", "quote-user").Error; err != nil {
t.Fatal(err)
}
if account.AvailableMicrocredits != 10_000_000-1_728_000 || account.ReservedMicrocredits != 250_000 {
t.Fatalf("incorrect balance after idempotent settlement: %#v", account)
}
})
}
}
func TestGenericVideoTokenDimensions(t *testing.T) {
for _, test := range []struct {
resolution, size string
width, height int64
}{
{"1440p", "16:9", 2560, 1440},
{"2K", "9:16", 1440, 2560},
{"960p", "4:3", 1280, 960},
{"768p竖", "9:16", 768, 1366},
{"720p", "2:1", 1440, 720},
{"", "1280x720", 1280, 720},
{"", "", 1280, 720},
} {
t.Run(test.resolution+"/"+test.size, func(t *testing.T) {
got := estimateArkVideoTokens(map[string]any{"config": map[string]any{
"model": "generic-video", "vquality": test.resolution, "size": test.size, "videoSeconds": 5,
}})
if got.Err != nil || got.Video.OutputWidth != test.width || got.Video.OutputHeight != test.height {
t.Fatalf("dimensions=%#v error=%v", got.Video, got.Err)
}
})
}
}
+62 -16
View File
@@ -285,6 +285,14 @@ func (s *Service) decorateAPICallLogs(logs []model.ApiCallLog) error {
if order, exists := billingOrderByID[logs[index].BillingOrderID]; exists && order.UserID == logs[index].UserID {
logs[index].BillingAvailable = true
logs[index].BillingStatus = order.Status
if order.ChannelID == logs[index].ChannelID {
logs[index].CreditCostConfigured = order.CostPricing.Configured
cost, costErr := billingCreditCost(order)
if costErr != nil {
return costErr
}
logs[index].CreditCostMicrocredits = cost
}
if order.Status == model.BillingStatusSettled {
logs[index].BillingAmount = order.ActualAmountMicrocredits
} else if order.Status != model.BillingStatusRefunded {
@@ -403,7 +411,7 @@ func (s *Service) AdminAPICallLogsCSV(actor *model.User, query APICallLogQuery)
var buffer bytes.Buffer
buffer.WriteString("\xEF\xBB\xBF")
writer := csv.NewWriter(&buffer)
_ = writer.Write([]string{"时间", "用户", "用户账号", "渠道", "模型", "能力", "状态", "轮询次数", "耗时毫秒", "输入Token", "输出Token", "缓存Token", "积分计费(微积分)", "积分计费状态", "上游估算费用(微单位)", "币种", "错误码", "错误"})
_ = writer.Write([]string{"时间", "用户", "用户账号", "渠道", "模型", "能力", "状态", "轮询次数", "耗时毫秒", "输入Token", "输出Token", "缓存Token", "销售价格(微积分)", "积分计费状态", "成本价格(微积分)", "上游估算费用(微单位)", "币种", "错误码", "错误"})
for _, log := range logs {
startedAt := log.StartedAt
if startedAt.IsZero() {
@@ -415,10 +423,14 @@ func (s *Service) AdminAPICallLogsCSV(actor *model.User, query APICallLogQuery)
billingStatus = string(log.BillingStatus)
}
upstreamCost := ""
creditCost := ""
if log.CreditCostMicrocredits != nil {
creditCost = strconv.FormatInt(*log.CreditCostMicrocredits, 10)
}
if log.CostAvailable {
upstreamCost = strconv.FormatInt(log.EstimatedCostMicros, 10)
}
_ = writer.Write([]string{startedAt.UTC().Format(time.RFC3339), log.UserDisplayName, log.UserAccount, log.ChannelName, log.Model, log.Capability, string(log.Status), strconv.Itoa(log.PollCount), strconv.FormatInt(log.DurationMs, 10), strconv.FormatInt(log.InputTokens, 10), strconv.FormatInt(log.OutputTokens, 10), strconv.FormatInt(log.CachedTokens, 10), billingAmount, billingStatus, upstreamCost, log.Currency, log.ErrorCode, log.Error})
_ = writer.Write([]string{startedAt.UTC().Format(time.RFC3339), log.UserDisplayName, log.UserAccount, log.ChannelName, log.Model, log.Capability, string(log.Status), strconv.Itoa(log.PollCount), strconv.FormatInt(log.DurationMs, 10), strconv.FormatInt(log.InputTokens, 10), strconv.FormatInt(log.OutputTokens, 10), strconv.FormatInt(log.CachedTokens, 10), billingAmount, billingStatus, creditCost, upstreamCost, log.Currency, log.ErrorCode, log.Error})
}
writer.Flush()
if err := writer.Error(); err != nil {
@@ -1035,8 +1047,12 @@ func (s *Service) enrichAPICallLogPayload(log *model.ApiCallLog, payload map[str
log.Error = errorMessage
}
}
arkVideo := log.Capability == "video" && strings.Contains(log.Path, "/contents/generations/tasks")
usage, _ := payload["usage"].(map[string]any)
if usage != nil {
if log.Capability == "video" {
log.InputTokens, log.CachedTokens = 0, 0
log.OutputTokens, log.UsageAvailable = videoCompletionTokens(payload, arkVideo)
} else if usage != nil {
inputTokens, inputAvailable := firstInt64Value(usage, "input_tokens", "prompt_tokens")
outputTokens, outputAvailable := firstInt64Value(usage, "output_tokens", "completion_tokens")
if inputAvailable {
@@ -1048,14 +1064,6 @@ func (s *Service) enrichAPICallLogPayload(log *model.ApiCallLog, payload map[str
if inputAvailable || outputAvailable {
log.UsageAvailable = true
}
// 火山方舟视频的输入 Token 恒为 0;查询任务以 completion_tokens 为实际用量,
// 兼容只返回 total_tokens 的同协议中转实现。
if log.Capability == "video" && strings.Contains(log.Path, "/contents/generations/tasks") {
if log.OutputTokens == 0 {
log.OutputTokens = firstInt64(usage, "total_tokens")
}
log.UsageAvailable = log.OutputTokens > 0
}
if details, ok := usage["input_tokens_details"].(map[string]any); ok {
log.CachedTokens = firstInt64(details, "cached_tokens", "cache_read_input_tokens")
}
@@ -1066,7 +1074,7 @@ func (s *Service) enrichAPICallLogPayload(log *model.ApiCallLog, payload map[str
log.CachedTokens = firstInt64(usage, "cached_tokens", "cache_read_input_tokens", "prompt_cache_hit_tokens")
}
}
if usageMetadata, ok := payload["usageMetadata"].(map[string]any); ok {
if usageMetadata, ok := payload["usageMetadata"].(map[string]any); ok && log.Capability != "video" {
inputTokens, inputAvailable := firstInt64Value(usageMetadata, "promptTokenCount")
outputTokens, outputAvailable := firstInt64Value(usageMetadata, "candidatesTokenCount")
if inputAvailable {
@@ -1101,12 +1109,40 @@ func (s *Service) enrichAPICallLogPayload(log *model.ApiCallLog, payload map[str
}
}
func videoCompletionTokens(payload map[string]any, arkProtocol bool) (int64, bool) {
if status, exists := payload["status"]; exists {
text, ok := status.(string)
status := strings.ToLower(strings.TrimSpace(text))
if !ok || (status != "succeeded" && (arkProtocol || (status != "completed" && status != "success"))) {
return 0, false
}
}
usage, _ := payload["usage"].(map[string]any)
value, exists := usage["completion_tokens"]
if !exists && !arkProtocol {
value, exists = usage["output_tokens"]
}
if !exists {
value = usage["total_tokens"]
}
// completion_tokens 一旦返回就是唯一结算依据,非法值不能用 total_tokens 掩盖。
// JSON Number 保留整数精度,避免浮点取整把小数或超出 int64 的值变成可计费用量。
number, ok := value.(json.Number)
if !ok {
return 0, false
}
tokens, err := number.Int64()
if err != nil || tokens <= 0 {
return 0, false
}
return tokens, true
}
func providerResponsePayloads(responseBody []byte) []map[string]any {
if len(responseBody) == 0 {
return nil
}
var payload map[string]any
if json.Unmarshal(responseBody, &payload) == nil {
if payload, ok := decodeProviderResponsePayload(responseBody); ok {
return []map[string]any{payload}
}
@@ -1121,8 +1157,7 @@ func providerResponsePayloads(responseBody []byte) []map[string]any {
if raw == "" || raw == "[DONE]" {
return
}
var event map[string]any
if json.Unmarshal([]byte(raw), &event) == nil {
if event, ok := decodeProviderResponsePayload([]byte(raw)); ok {
result = append(result, event)
}
}
@@ -1140,6 +1175,17 @@ func providerResponsePayloads(responseBody []byte) []map[string]any {
return result
}
func decodeProviderResponsePayload(data []byte) (map[string]any, bool) {
if !json.Valid(data) {
return nil, false
}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var payload map[string]any
err := decoder.Decode(&payload)
return payload, err == nil && payload != nil
}
func providerRequestIDFromPath(path string) string {
parts := strings.Split(strings.Trim(strings.TrimSpace(path), "/"), "/")
for index := len(parts) - 1; index >= 0; index-- {
+9 -1
View File
@@ -26,7 +26,7 @@ func TestDecorateAPICallLogsUsesBillingOrderSnapshot(t *testing.T) {
}
orders := []model.BillingOrder{
{ID: "settled", UserID: "user-1", IdempotencyKey: "settled", Status: model.BillingStatusSettled, ReservedAmountMicrocredits: 1_000_000, ActualAmountMicrocredits: 780_000},
{ID: "settled", UserID: "user-1", IdempotencyKey: "settled", Status: model.BillingStatusSettled, ReservedAmountMicrocredits: 1_000_000, ActualAmountMicrocredits: 780_000, BillingCostSnapshot: model.BillingCostSnapshot{CostBillingMode: "fixed_request", CostQuantity: 1, CostPricing: model.CreditCostPricing{Configured: true, UnitPriceMicrocredits: 456_789}}},
{ID: "reserved", UserID: "user-1", IdempotencyKey: "reserved", Status: model.BillingStatusReserved, ReservedAmountMicrocredits: 900_000},
{ID: "uncertain", UserID: "user-1", IdempotencyKey: "uncertain", Status: model.BillingStatusUncertain, ReservedAmountMicrocredits: 1_200_000},
{ID: "refunded", UserID: "user-1", IdempotencyKey: "refunded", Status: model.BillingStatusRefunded, ReservedAmountMicrocredits: 650_000, RefundedAmountMicrocredits: 650_000},
@@ -58,6 +58,14 @@ func TestDecorateAPICallLogsUsesBillingOrderSnapshot(t *testing.T) {
assertBillingSnapshot(t, logs[4], false, "", 0)
assertBillingSnapshot(t, logs[5], false, "", 0)
assertBillingSnapshot(t, logs[6], false, "", 0)
if !logs[0].CreditCostConfigured || logs[0].CreditCostMicrocredits == nil || *logs[0].CreditCostMicrocredits != 456_789 {
t.Fatalf("request cost missing: %#v", logs[0])
}
for _, log := range logs[1:] {
if log.CreditCostConfigured || log.CreditCostMicrocredits != nil {
t.Fatalf("fabricated cost for %s", log.ID)
}
}
}
func assertBillingSnapshot(t *testing.T, log model.ApiCallLog, available bool, status model.BillingStatus, amount int64) {
+4 -1
View File
@@ -31,7 +31,7 @@ const (
)
const (
appearanceSchemaVersion = 7
appearanceSchemaVersion = 8
appearanceLogoMaxBytes int64 = 5 << 20
appearancePosterMaxBytes int64 = 10 << 20
appearanceVideoMaxBytes int64 = 256 << 20
@@ -346,6 +346,9 @@ func (s *Service) readAppearance() (*model.SystemSetting, AppearanceSetting, err
return nil, AppearanceSetting{}, err
}
value := defaultAppearanceSetting()
// Decode stored themes without reusing built-in slice entries: omitted
// fields must be migrated according to each stored theme's identity.
value.SkinThemes = nil
if strings.TrimSpace(setting.ValueJSON) == "" || json.Unmarshal([]byte(setting.ValueJSON), &value) != nil {
return nil, AppearanceSetting{}, errors.New("外观配置格式无效")
}
@@ -0,0 +1,111 @@
package app
import (
"encoding/json"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestAppearanceButtonFillRoundTripAndValidation(t *testing.T) {
svc, _, _, admin := newAppearanceTestService(t)
themes := defaultAppearanceSkinThemes()
custom := cloneAppearanceSkin(themes[0], "custom-gradient", "渐变主题", "主按钮渐变")
custom.Tokens.Buttons.Light.Angle = 45
custom.Tokens.Buttons.Light.Start = "#123456"
custom.Tokens.Buttons.Dark.Mode = "solid"
themes = append(themes, custom)
input := AppearanceSetting{BrandName: "测试站点", BrandSlug: "test", AuthHeroTitle: defaultAppearanceHeroTitle, SkinID: custom.ID, SkinThemes: themes}
saved, err := svc.UpdateAppearance(admin, input)
if err != nil {
t.Fatal(err)
}
if saved.Public.ActiveSkin.Tokens.Buttons != custom.Tokens.Buttons {
t.Fatal("public projection lost button parameters")
}
loaded, err := svc.AdminAppearance(admin)
if err != nil {
t.Fatal(err)
}
if loaded.Public.ActiveSkin.Tokens.Buttons != custom.Tokens.Buttons {
t.Fatal("stored button parameters changed")
}
for name, mutate := range map[string]func(*AppearanceSkinButtonFill){
"mode": func(fill *AppearanceSkinButtonFill) { fill.Mode = "image" },
"negative angle": func(fill *AppearanceSkinButtonFill) { fill.Angle = -1 },
"large angle": func(fill *AppearanceSkinButtonFill) { fill.Angle = 361 },
"css injection": func(fill *AppearanceSkinButtonFill) { fill.End = "red; background:url(x)" },
"missing color": func(fill *AppearanceSkinButtonFill) { fill.Foreground = "" },
} {
t.Run(name, func(t *testing.T) {
bad := input
bad.SkinThemes = append([]AppearanceSkinTheme(nil), themes...)
mutate(&bad.SkinThemes[len(themes)-1].Tokens.Buttons.Light)
if _, err := svc.UpdateAppearance(admin, bad); err == nil {
t.Fatal("invalid fill accepted")
}
})
}
input.SkinThemes[0].Tokens.Buttons.Light.Start = "#000000"
if _, err := svc.UpdateAppearance(admin, input); err == nil {
t.Fatal("classic fill mutation accepted")
}
}
func TestAppearanceLegacyButtonFills(t *testing.T) {
themes := defaultAppearanceSkinThemes()
for index := range themes {
themes[index].Tokens.Buttons = AppearanceSkinButtons{}
}
migrated := normalizeAppearanceSkinThemes(themes)
if err := validateAppearanceSkinThemes(migrated, "classic"); err != nil {
t.Fatal(err)
}
for _, skin := range migrated {
expected := "solid"
if skin.ID == "classic" {
expected = "gradient"
}
if skin.Tokens.Buttons.Light.Mode != expected || skin.Tokens.Buttons.Dark.Mode != expected {
t.Fatalf("wrong fill for %s", skin.ID)
}
}
var fill AppearanceSkinButtonFill
if err := json.Unmarshal([]byte(`{"angle":1.5}`), &fill); err == nil {
t.Fatal("fractional angle accepted")
}
}
func TestAppearanceReadsLegacyButtonFillsByStoredIdentity(t *testing.T) {
svc, db, _, admin := newAppearanceTestService(t)
classic := defaultClassicAppearanceSkin()
custom := cloneAppearanceSkin(classic, "custom-legacy", "旧主题", "保持纯色")
encoded, err := json.Marshal([]AppearanceSkinTheme{custom, classic})
if err != nil {
t.Fatal(err)
}
var themes []map[string]any
if err := json.Unmarshal(encoded, &themes); err != nil {
t.Fatal(err)
}
for _, skin := range themes {
delete(skin["tokens"].(map[string]any), "buttons")
}
encoded, err = json.Marshal(map[string]any{"schemaVersion": 7, "skinId": custom.ID, "skinThemes": themes})
if err != nil {
t.Fatal(err)
}
if err := db.Create(&model.SystemSetting{Key: appearanceSettingKey, ValueJSON: string(encoded)}).Error; err != nil {
t.Fatal(err)
}
loaded, err := svc.AdminAppearance(admin)
if err != nil {
t.Fatal(err)
}
if loaded.Public.ActiveSkin.Tokens.Buttons.Light.Mode != "solid" || loaded.SkinThemes[1].Tokens.Buttons.Light.Mode != "gradient" {
t.Fatal("legacy fields inherited another theme's fill")
}
if err := validateAppearanceSkinThemes(loaded.SkinThemes, custom.ID); err != nil {
t.Fatal(err)
}
}
+58
View File
@@ -96,6 +96,35 @@ type AppearanceSkinTokens struct {
Light AppearanceSkinModeTokens `json:"light"`
Dark AppearanceSkinModeTokens `json:"dark"`
Components AppearanceSkinComponentTokens `json:"components"`
Buttons AppearanceSkinButtons `json:"buttons"`
}
type AppearanceSkinButtons struct {
Light AppearanceSkinButtonFill `json:"light"`
Dark AppearanceSkinButtonFill `json:"dark"`
}
type AppearanceSkinButtonFill struct {
Mode string `json:"mode"`
Angle int `json:"angle"`
Start string `json:"start"`
End string `json:"end"`
HoverStart string `json:"hoverStart"`
HoverEnd string `json:"hoverEnd"`
ActiveStart string `json:"activeStart"`
ActiveEnd string `json:"activeEnd"`
Foreground string `json:"foreground"`
}
func defaultAppearanceSkinButtons(gradient bool) AppearanceSkinButtons {
fill := AppearanceSkinButtonFill{
Mode: "solid", Angle: 115, Start: "#6554df", End: "#386fbc",
HoverStart: "#5744cf", HoverEnd: "#356bbb", ActiveStart: "#4938b8", ActiveEnd: "#2c5da5", Foreground: "#ffffff",
}
if gradient {
fill.Mode = "gradient"
}
return AppearanceSkinButtons{Light: fill, Dark: fill}
}
type AppearanceSkinTheme struct {
@@ -159,6 +188,9 @@ func defaultAppearanceSkinThemes() []AppearanceSkinTheme {
})
violet.Tokens.Components = appearanceSkinComponentPreset(7, 7, 12, 14, 9, 4)
studio.Tokens.Buttons = defaultAppearanceSkinButtons(false)
warm.Tokens.Buttons = defaultAppearanceSkinButtons(false)
violet.Tokens.Buttons = defaultAppearanceSkinButtons(false)
return []AppearanceSkinTheme{classic, studio, warm, violet}
}
@@ -181,6 +213,7 @@ func defaultClassicAppearanceSkin() AppearanceSkinTheme {
AdminBackground: "#101010", AdminSurface: "#181818", AdminSubtle: "#202020", AdminStrong: "#2a2a2a", AuthBackground: "#08090c", AuthPanel: "#0b0c10", AuthCard: "#121318", AuthAccent: "#93c5fd", AuthMuted: "#8a8b91",
},
Components: appearanceSkinComponentPreset(6, 6, 12, 12, 8, 4),
Buttons: defaultAppearanceSkinButtons(true),
},
}
}
@@ -234,6 +267,11 @@ func normalizeAppearanceSkinThemes(themes []AppearanceSkinTheme) []AppearanceSki
result[index].Name = strings.TrimSpace(result[index].Name)
result[index].Description = strings.TrimSpace(result[index].Description)
result[index].Locked = result[index].ID == defaultAppearanceSkinID
// Only a wholly absent legacy button block is upgraded. Partial or
// malformed submitted parameters remain invalid on the write path.
if result[index].Tokens.Buttons == (AppearanceSkinButtons{}) {
result[index].Tokens.Buttons = defaultAppearanceSkinButtons(result[index].Locked)
}
var fallback AppearanceSkinTokens
for _, builtin := range builtins {
if builtin.ID == result[index].ID {
@@ -325,6 +363,11 @@ func validateAppearanceSkinThemes(themes []AppearanceSkinTheme, selectedID strin
if err := validateAppearanceSkinComponents(skin.Tokens.Components); err != nil {
return err
}
for _, fill := range []AppearanceSkinButtonFill{skin.Tokens.Buttons.Light, skin.Tokens.Buttons.Dark} {
if err := validateAppearanceSkinButtonFill(fill); err != nil {
return err
}
}
}
if !foundClassic {
return BadAuthRequest("经典黑白为系统默认主题,不能修改或删除")
@@ -345,6 +388,21 @@ func validateAppearanceSkinMode(mode AppearanceSkinModeTokens) error {
return nil
}
func validateAppearanceSkinButtonFill(fill AppearanceSkinButtonFill) error {
if fill.Mode != "solid" && fill.Mode != "gradient" {
return BadAuthRequest("主按钮填充模式无效")
}
if fill.Angle < 0 || fill.Angle > 360 {
return BadAuthRequest("主按钮渐变角度必须在 0 到 360 之间")
}
for _, color := range []string{fill.Start, fill.End, fill.HoverStart, fill.HoverEnd, fill.ActiveStart, fill.ActiveEnd, fill.Foreground} {
if !appearanceColorPattern.MatchString(color) {
return BadAuthRequest("主按钮颜色必须使用 6 或 8 位十六进制颜色")
}
}
return nil
}
func validateAppearanceSkinComponents(value AppearanceSkinComponentTokens) error {
for _, candidate := range []struct {
value, min, max int
@@ -0,0 +1,86 @@
package app
import (
"strings"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestChannelModelLabelSaveAndCatalogPreserveChannelIdentity(t *testing.T) {
svc, db := newChannelModelTestService(t)
if err := db.AutoMigrate(&model.SystemSetting{}); err != nil {
t.Fatal(err)
}
admin := &model.User{ID: "admin", Role: model.UserRoleAdmin}
enabled := true
request := ChannelModelRequest{
ModelKey: "gpt-test", ProviderModelKey: "upstream-text", DisplayName: "GPT Test", Icon: "OpenAI",
ChannelLabel: " 优惠渠道-993 ", Capability: "text", Protocol: string(model.ChannelInterfaceChatCompletion),
Description: " 适合分镜脚本,请先确认输入要求。 ",
CapabilityConfig: DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceChatCompletion), "gpt-test"),
PriceTiers: []ChannelModelPriceTierRequest{{BillingMode: "fixed_request", UnitPriceMicrocredits: 300000, PriceConfigured: true, Enabled: &enabled}},
Enabled: &enabled,
}
var firstID string
for _, id := range []string{"channel-a", "channel-b"} {
channel := model.ModelChannel{ID: id, Scope: model.ChannelScopeSystem, Enabled: true, Name: "Test", BaseURL: "https://example.invalid/v1", APIKey: "synthetic", ModelsJSON: `[]`}
if err := db.Create(&channel).Error; err != nil {
t.Fatal(err)
}
saved, err := svc.SaveAdminChannelModel(admin, id, "", request)
if err != nil {
t.Fatal(err)
}
var stored model.ChannelModel
if err := db.First(&stored, "id = ?", saved.ID).Error; err != nil {
t.Fatal(err)
}
if stored.ChannelLabel != "优惠渠道-993" || stored.ModelKey != "gpt-test" || stored.ProviderModelKey != "upstream-text" || stored.ChannelID != id {
t.Fatalf("stored channel model: %#v", stored)
}
legacy := publicChannel(channel, false, []model.ChannelModel{*saved})
if stored.Description != "适合分镜脚本,请先确认输入要求。" || legacy.ModelCosts[0].Description != stored.Description {
t.Fatal("model description was not persisted or projected")
}
if legacy.ModelCosts[0].ChannelLabel != "优惠渠道-993" {
t.Fatal("session projection lost channel label")
}
if id == "channel-a" {
firstID = saved.ID
}
}
catalog, err := svc.ModelCatalog(nil)
if err != nil || len(catalog.Channels) != 2 {
t.Fatalf("catalog: %#v, %v", catalog, err)
}
for _, channel := range catalog.Channels {
if len(channel.Models) == 1 && channel.Models[0].Description != "适合分镜脚本,请先确认输入要求。" {
t.Fatal("catalog lost model description")
}
if len(channel.Models) != 1 || channel.Models[0].ChannelLabel != "优惠渠道-993" || !channel.Models[0].Available || channel.Models[0].PriceTiers[0].UnitPriceMicrocredits != 300000 {
t.Fatalf("catalog lost label or pricing: %#v", channel)
}
}
request.ChannelLabel = strings.Repeat("字", 81)
if _, err := svc.SaveAdminChannelModel(admin, "channel-a", firstID, request); err == nil {
t.Fatal("accepted oversized channel label")
}
request.ChannelLabel = " "
request.Description = strings.Repeat("字", 501)
if _, err := svc.SaveAdminChannelModel(admin, "channel-a", firstID, request); err == nil {
t.Fatal("accepted oversized description")
}
request.Description = strings.Repeat("字", 500)
if _, err := svc.SaveAdminChannelModel(admin, "channel-a", firstID, request); err != nil {
t.Fatalf("rejected valid 500-character description: %v", err)
}
request.Description = " "
updated, err := svc.SaveAdminChannelModel(admin, "channel-a", firstID, request)
if err != nil || updated.ChannelLabel != "" || updated.Description != "" || updated.ID != firstID {
t.Fatalf("label clearing changed identity: %#v, %v", updated, err)
}
if _, err := svc.SaveAdminChannelModel(&model.User{ID: "user", Role: model.UserRoleUser}, "channel-a", firstID, request); err == nil {
t.Fatal("non-admin changed channel label")
}
}
+35 -13
View File
@@ -21,8 +21,9 @@ type ChannelModelRequest struct {
ModelKey string `json:"modelKey"`
ProviderModelKey string `json:"providerModelKey"`
DisplayName string `json:"displayName"`
Icon string `json:"icon"`
ChannelLabel string `json:"channelLabel"`
Description string `json:"description"`
Icon string `json:"icon"`
Capability string `json:"capability"`
Protocol string `json:"protocol"`
BillingMode string `json:"billingMode"`
@@ -41,7 +42,8 @@ const maxAdminChannelModelBatchDeleteCount = 100
// ChannelModelPriceTierRequest 是系统渠道内某个规格的上游 SKU 与结算价格。
// Resolution="*"、VideoSeconds=0 分别表示任意分辨率和任意时长。
type ChannelModelPriceTierRequest struct {
// Selector 是 SKU 的规范匹配条件。支持 operation、quality、size、vquality、videoSeconds、imageCount;
CostPricing model.CreditCostPricing `json:"costPricing"`
// Selector 是 SKU 的规范匹配条件。支持 operation、quality、size、vquality、videoSeconds、imageCount、videoGenerateAudio;
// operation 可区分文生/图生/视频生,避免同一分辨率下错误复用价格。
Selector map[string]string `json:"selector"`
Resolution string `json:"resolution"`
@@ -297,6 +299,14 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
if err := s.RequireAdmin(actor); err != nil {
return nil, err
}
channelLabel := strings.TrimSpace(req.ChannelLabel)
description := strings.TrimSpace(req.Description)
if len([]rune(description)) > 500 {
return nil, BadAuthRequest("模型描述不能超过 500 字")
}
if len([]rune(channelLabel)) > 80 {
return nil, BadAuthRequest("渠道展示名不能超过 80 字")
}
channel, err := s.repo.AdminSystemChannel(channelID)
if err != nil {
return nil, err
@@ -348,11 +358,12 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
item.ModelKey = modelKey
item.ProviderModelKey = providerModelKey
item.DisplayName = strings.TrimSpace(req.DisplayName)
item.ChannelLabel = channelLabel
item.Description = description
if item.DisplayName == "" {
item.DisplayName = modelKey
}
item.Icon = strings.TrimSpace(req.Icon)
item.Description = truncateRunes(strings.TrimSpace(req.Description), 600)
item.Capability = capability
item.Protocol = protocol
s.applyChannelModelPriceTierSummary(item, tiers)
@@ -439,8 +450,8 @@ func (s *Service) syncLogicalModelsFromChannelModel(actor *model.User, channelMo
return nil
}
func supportsTokenBilling(capability string, protocol model.ChannelInterfaceType) bool {
return capability == "text" || (capability == "video" && model.IsVolcengineArkVideoProtocol(protocol))
func supportsTokenBilling(capability string, _ model.ChannelInterfaceType) bool {
return capability == "text" || capability == "video"
}
func (s *Service) normalizeChannelModelPriceTiers(req ChannelModelRequest, capability string, protocol model.ChannelInterfaceType, fallbackProviderModelKey string) ([]model.ChannelModelPriceTier, error) {
@@ -483,6 +494,7 @@ func (s *Service) normalizeChannelModelPriceTiers(req ChannelModelRequest, capab
}
enabled := input.Enabled == nil || *input.Enabled
result = append(result, model.ChannelModelPriceTier{
CostPricing: input.CostPricing,
ID: id,
SelectorKey: key,
SelectorJSON: key,
@@ -539,6 +551,17 @@ func normalizeChannelModelTierSelector(capability string, input ChannelModelPric
continue
}
value = strconv.Itoa(count)
case "videoGenerateAudio":
if capability != "video" {
return nil, "", 0, BadAuthRequest("只有视频模型可以按是否生成音频配置价格档")
}
value = strings.ToLower(value)
if value == "*" {
continue
}
if value != "true" && value != "false" {
return nil, "", 0, BadAuthRequest("视频价格档音频条件必须为 true、false 或 *")
}
default:
return nil, "", 0, BadAuthRequest("价格档不支持规格字段:" + key)
}
@@ -584,6 +607,9 @@ func normalizeChannelModelTierSelector(capability string, input ChannelModelPric
}
func validateChannelModelTierPricing(capability string, protocol model.ChannelInterfaceType, billingMode string, input ChannelModelPriceTierRequest) error {
if err := validateCreditCostPricing(capability, billingMode, input.CostPricing); err != nil {
return err
}
if billingMode != "fixed_request" && billingMode != "per_second" && billingMode != "token" {
return BadAuthRequest("模型计费方式仅支持按次、按秒或 Token")
}
@@ -591,19 +617,15 @@ func validateChannelModelTierPricing(capability string, protocol model.ChannelIn
return BadAuthRequest("只有视频模型可以按秒计费")
}
if billingMode == "token" && !supportsTokenBilling(capability, protocol) {
return BadAuthRequest("Token 计费仅支持文本模型和火山方舟视频协议")
return BadAuthRequest("Token 计费仅支持文本和视频模型")
}
if input.UnitPriceMicrocredits < 0 || input.InputTokenPriceMicrocredits < 0 || input.OutputTokenPriceMicrocredits < 0 || input.CachedTokenPriceMicrocredits < 0 {
return BadAuthRequest("模型积分价格不能小于 0")
}
if !input.PriceConfigured {
return nil
if billingMode == "token" {
return validateTokenPrices(capability, input.InputTokenPriceMicrocredits, input.OutputTokenPriceMicrocredits, input.CachedTokenPriceMicrocredits)
}
const maxTokenPriceMicrocredits = int64(1_000_000) * CreditScale
if input.InputTokenPriceMicrocredits > maxTokenPriceMicrocredits || input.OutputTokenPriceMicrocredits > maxTokenPriceMicrocredits || input.CachedTokenPriceMicrocredits > maxTokenPriceMicrocredits {
return BadAuthRequest("Token 每百万用量价格不能超过 1,000,000 积分")
}
return nil
return validateTokenPrices("", input.InputTokenPriceMicrocredits, input.OutputTokenPriceMicrocredits, input.CachedTokenPriceMicrocredits)
}
func normalizeChannelModelTierResolution(raw string) string {
+2 -10
View File
@@ -1,14 +1,13 @@
package app
import (
"strings"
"time"
"infinite-canvas/backend/internal/model"
)
func (req ChannelRequest) presentationOnly() bool {
return (req.PublicAlias != nil || req.SortOrder != nil) && req.Name == "" && req.BaseURL == "" && req.APIKey == "" && req.SecretKey == "" && req.ConcurrencyLimit == nil && req.UseGlobalConcurrency == nil && req.Models == nil && req.Headers == nil && req.Enabled == nil
return req.SortOrder != nil && req.Name == "" && req.BaseURL == "" && req.APIKey == "" && req.SecretKey == "" && req.ConcurrencyLimit == nil && req.UseGlobalConcurrency == nil && req.Models == nil && req.Headers == nil && req.Enabled == nil
}
func (s *Service) updateChannelPresentation(id string, req ChannelRequest) (*PublicModelChannel, error) {
@@ -17,14 +16,7 @@ func (s *Service) updateChannelPresentation(id string, req ChannelRequest) (*Pub
return nil, err
}
}
if req.PublicAlias != nil {
alias := strings.TrimSpace(*req.PublicAlias)
if len([]rune(alias)) > 80 {
return nil, BadAuthRequest("前台别名不能超过 80 字")
}
req.PublicAlias = &alias
}
if err := s.repo.UpdateSystemChannelPresentation(id, req.PublicAlias, req.SortOrder, time.Now()); err != nil {
if err := s.repo.UpdateSystemChannelPresentation(id, req.SortOrder, time.Now()); err != nil {
return nil, err
}
s.invalidateRouteCatalog()
@@ -10,12 +10,12 @@ import (
"infinite-canvas/backend/internal/model"
)
func TestChannelPresentationAliasAndPublicOrder(t *testing.T) {
func TestChannelPresentationUsesModelLabelsAndPublicOrder(t *testing.T) {
svc, db := newChannelModelTestService(t)
svc.dataDir = t.TempDir()
admin := &model.User{ID: "admin", Role: model.UserRoleAdmin}
for i, id := range []string{"first", "second"} {
channel := model.ModelChannel{ID: id, Name: "内部" + id, Scope: model.ChannelScopeSystem, Enabled: true, BaseURL: "https://dead.invalid/v1", ModelsJSON: `[]`, CreatedAt: time.Unix(int64(i+1), 0)}
channel := model.ModelChannel{ID: id, Name: "渠道" + id, PublicAlias: "已废弃前台名称", Scope: model.ChannelScopeSystem, Enabled: true, BaseURL: "https://dead.invalid/v1", ModelsJSON: `[]`, CreatedAt: time.Unix(int64(i+1), 0)}
if err := db.Create(&channel).Error; err != nil {
t.Fatal(err)
}
@@ -27,13 +27,12 @@ func TestChannelPresentationAliasAndPublicOrder(t *testing.T) {
t.Fatal(err)
}
}
alias := " 创作精选 "
updated, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{PublicAlias: &alias})
updated, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{SortOrder: intPtr(0)})
if err != nil {
t.Fatal(err)
}
if updated.Name != "内部second" || updated.PublicAlias != "创作精选" {
t.Fatalf("admin alias: %#v", updated)
if updated.Name != "渠道second" {
t.Fatalf("admin name: %#v", updated)
}
if _, err := svc.UpdateSystemChannel(admin, "first", ChannelRequest{SortOrder: intPtr(20)}); err != nil {
t.Fatal(err)
@@ -42,52 +41,47 @@ func TestChannelPresentationAliasAndPublicOrder(t *testing.T) {
if err != nil || total != 2 || len(adminRows) != 1 || adminRows[0].ID != "second" {
t.Fatalf("pagination before sort: %v %v %v", adminRows, total, err)
}
search, _, err := svc.repo.AdminSystemChannels("精选", "all", 10, 0)
search, _, err := svc.repo.AdminSystemChannels("second", "all", 10, 0)
if err != nil || len(search) != 1 {
t.Fatalf("alias search: %v %v", search, err)
t.Fatalf("name search: %v %v", search, err)
}
catalog, err := svc.publicSystemChannelCatalog(nil)
if err != nil {
t.Fatal(err)
}
if len(catalog) != 2 || catalog[0].ID != "second" || catalog[0].Name != "创作精选" || catalog[0].DisplayName != "创作精选" {
if len(catalog) != 2 || catalog[0].ID != "second" || catalog[0].Name != "渠道second" || catalog[0].DisplayName != "渠道second" {
t.Fatalf("public catalog: %#v", catalog)
}
legacy, err := svc.PublicSystemChannels()
if err != nil {
t.Fatal(err)
}
if legacy[0].Name != "创作精选" {
if legacy[0].Name != "渠道second" {
t.Fatalf("public session: %#v", legacy)
}
encoded, _ := json.Marshal([]any{catalog[0], legacy[0]})
if strings.Contains(string(encoded), "内部second") {
t.Fatal("internal channel name leaked into public payload")
if strings.Contains(string(encoded), "已废弃前台名称") || strings.Contains(string(encoded), "publicAlias") {
t.Fatal("retired alias leaked into public payload")
}
if _, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{SortOrder: intPtr(5)}); err != nil {
t.Fatal(err)
}
stored, _ := svc.repo.AdminSystemChannel("second")
if stored.PublicAlias != "创作精选" {
t.Fatal("partial sort patch cleared alias")
if stored.Name != "渠道second" {
t.Fatal("partial sort patch changed channel name")
}
alias = " "
if _, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{PublicAlias: &alias, SortOrder: intPtr(0)}); err != nil {
if _, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{SortOrder: intPtr(0)}); err != nil {
t.Fatal(err)
}
catalog, err = svc.publicSystemChannelCatalog(nil)
if err != nil || catalog[0].Name != "内部second" {
t.Fatalf("empty alias fallback: %v %v", catalog, err)
if err != nil || catalog[0].Name != "渠道second" {
t.Fatalf("channel name: %v %v", catalog, err)
}
for _, invalid := range []int{-1, 1000000} {
if _, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{SortOrder: &invalid}); err == nil {
t.Fatal("invalid sort accepted")
}
}
alias = strings.Repeat("字", 81)
if _, err := svc.UpdateSystemChannel(admin, "second", ChannelRequest{PublicAlias: &alias}); err == nil {
t.Fatal("long alias accepted")
}
}
func TestChannelModelSortPreservesConfigurationAndOwnership(t *testing.T) {
+70
View File
@@ -0,0 +1,70 @@
package app
import (
"infinite-canvas/backend/internal/kernel"
"infinite-canvas/backend/internal/model"
)
func validateCreditCostPricing(capability, billingMode string, cost model.CreditCostPricing) error {
for _, price := range []int64{cost.UnitPriceMicrocredits, cost.InputTokenPriceMicrocredits, cost.OutputTokenPriceMicrocredits, cost.CachedTokenPriceMicrocredits} {
if price < 0 || price > 1_000_000_000_000 {
return BadAuthRequest("积分成本价必须在 0 到 1000000 积分之间")
}
}
if !cost.Configured {
return nil
}
if billingMode != "token" {
capability = ""
}
return validateTokenPrices(capability, cost.InputTokenPriceMicrocredits, cost.OutputTokenPriceMicrocredits, cost.CachedTokenPriceMicrocredits)
}
func snapshotCreditCost(order *model.BillingOrder, tier *model.ChannelModelPriceTier, quantity int64, estimate tokenBillingEstimate) {
if tier == nil {
return
}
order.CostPricing = tier.CostPricing
order.CostBillingMode = tier.BillingMode
order.CostQuantity = 1
if tier.BillingMode == "per_second" {
order.CostQuantity = quantity
}
if tier.BillingMode == "token" && estimate.Video != nil {
order.CostVideoFormulaTokens = estimate.Video.FormulaTokens
}
}
// 成本使用下单快照和真实用量,不套用销售倍率或用户扣费上限。
// 未结算、未配置或无法确定用量时不编造金额,历史订单也不反查当前价格。
func billingCreditCost(order model.BillingOrder) (*int64, error) {
if !order.CostPricing.Configured || order.Status != model.BillingStatusSettled {
return nil, nil
}
cost := order.CostPricing
var amount int64
var err error
switch order.CostBillingMode {
case "fixed_request", "per_second":
amount, err = creditAmount(cost.UnitPriceMicrocredits, order.CostQuantity, 10_000)
case "token":
input, output, cached := order.InputTokens, order.OutputTokens, order.CachedTokens
if !order.UsageAvailable {
if order.Capability != "video" || order.CostVideoFormulaTokens <= 0 {
return nil, nil
}
input, cached, output = 0, 0, order.CostVideoFormulaTokens
}
amount, err = kernel.TokenBillingAmount(10_000,
kernel.TokenBillingTerm{Tokens: max(0, input-cached), PriceMicrocredits: cost.InputTokenPriceMicrocredits},
kernel.TokenBillingTerm{Tokens: output, PriceMicrocredits: cost.OutputTokenPriceMicrocredits},
kernel.TokenBillingTerm{Tokens: cached, PriceMicrocredits: cost.CachedTokenPriceMicrocredits},
)
default:
return nil, nil
}
if err != nil {
return nil, err
}
return &amount, nil
}
+142
View File
@@ -0,0 +1,142 @@
package app
import (
"encoding/json"
"strings"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestCreditCostSnapshotPersistsWithoutChangingSalesOrPublicResponses(t *testing.T) {
svc, db := newChannelModelTestService(t)
if err := db.AutoMigrate(&model.SystemSetting{}, &model.BillingOrder{}); err != nil {
t.Fatal(err)
}
admin := &model.User{ID: "admin", Role: model.UserRoleAdmin}
channel := model.ModelChannel{ID: "channel", Scope: model.ChannelScopeSystem, Name: "供应渠道", Enabled: true, ModelsJSON: `[]`}
if err := db.Create(&channel).Error; err != nil {
t.Fatal(err)
}
req := ChannelModelRequest{
ModelKey: "model-a", DisplayName: "产品模型", ChannelLabel: "优惠渠道", Capability: "text", Protocol: string(model.ChannelInterfaceChatCompletion),
CapabilityConfig: DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceChatCompletion), "model-a"),
PriceTiers: []ChannelModelPriceTierRequest{{BillingMode: "fixed_request", UnitPriceMicrocredits: 900_000, PriceConfigured: true, CostPricing: model.CreditCostPricing{Configured: true, UnitPriceMicrocredits: 123_456}}},
}
for _, actor := range []*model.User{nil, {ID: "user", Role: model.UserRoleUser}} {
if _, err := svc.SaveAdminChannelModel(actor, channel.ID, "", req); err == nil {
t.Fatal("non-admin wrote cost")
}
if _, err := svc.AdminChannelModels(actor, channel.ID); err == nil {
t.Fatal("non-admin read cost")
}
if _, err := svc.AdminAPICallLogs(actor, APICallLogQuery{}); err == nil {
t.Fatal("non-admin read request cost")
}
}
saved, err := svc.SaveAdminChannelModel(admin, channel.ID, "", req)
if err != nil {
t.Fatal(err)
}
rows, err := svc.AdminChannelModels(admin, channel.ID)
if err != nil || len(rows) != 1 || rows[0].PriceTiers[0].CostPricing.UnitPriceMicrocredits != 123_456 {
t.Fatalf("persisted cost: %#v %v", rows, err)
}
order, err := svc.newBillingOrder("user", "task", "request", channel.ID, saved.ModelKey, "text", "test", 1, tokenBillingEstimate{})
if err != nil {
t.Fatal(err)
}
if order.AmountMicrocredits != 900_000 || order.CostPricing.UnitPriceMicrocredits != 123_456 {
t.Fatalf("sales/cost snapshot: %#v", order)
}
if err := db.Create(order).Error; err != nil {
t.Fatal(err)
}
req.PriceTiers[0].CostPricing.UnitPriceMicrocredits = 654_321
if _, err := svc.SaveAdminChannelModel(admin, channel.ID, saved.ID, req); err != nil {
t.Fatal(err)
}
var historical model.BillingOrder
if err := db.First(&historical, "id = ?", order.ID).Error; err != nil {
t.Fatal(err)
}
historical.Status = model.BillingStatusSettled
cost, err := billingCreditCost(historical)
if err != nil || cost == nil || *cost != 123_456 {
t.Fatalf("historical cost changed: %v %v", cost, err)
}
catalog, err := svc.ModelCatalog(nil)
if err != nil {
t.Fatal(err)
}
public := publicChannel(channel, false, []model.ChannelModel{*saved})
for _, value := range []any{saved, saved.PriceTiers, order, catalog, public, quoteFromOrder("", order, tokenBillingEstimate{})} {
encoded, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
for _, forbidden := range []string{"costPricing", "costConfigured", "CostPricing", "123456", "654321"} {
if strings.Contains(string(encoded), forbidden) {
t.Fatalf("cost leaked into %T: %s", value, encoded)
}
}
}
// The catalog must not query logical models, even if their old feature flag is enabled.
if err := db.Create(&model.SystemSetting{Key: featureAvailabilitySettingKey, ValueJSON: `{"frontendModelsEnabled":true}`}).Error; err != nil {
t.Fatal(err)
}
if err := db.Migrator().DropTable(&model.LogicalModel{}); err != nil {
t.Fatal(err)
}
catalog, err = svc.ModelCatalog(nil)
if err != nil || catalog.Source != ModelCatalogSourceSystem || len(catalog.Channels) != 1 {
t.Fatalf("catalog depends on logical models: %#v %v", catalog, err)
}
}
func TestBillingCreditCostUsesExactUsageAndIgnoresSalesMultiplier(t *testing.T) {
for _, tc := range []struct {
name, mode, capability string
quantity, input, output, cached, formula, want int64
usage bool
}{
{name: "request", mode: "fixed_request", quantity: 1, want: 90_000},
{name: "seconds", mode: "per_second", quantity: 15, want: 1_350_000},
{name: "text cached tokens", mode: "token", capability: "text", input: 1_000_000, output: 500_000, cached: 200_000, usage: true, want: 1_820_000},
{name: "video formula", mode: "token", capability: "video", formula: 250_000, want: 500_000},
{name: "video provider", mode: "token", capability: "video", output: 100_000, formula: 250_000, usage: true, want: 200_000},
} {
t.Run(tc.name, func(t *testing.T) {
order := model.BillingOrder{Status: model.BillingStatusSettled, Capability: tc.capability, InputTokens: tc.input, OutputTokens: tc.output, CachedTokens: tc.cached, UsageAvailable: tc.usage, MultiplierBasisPoints: 30_000, ChargeLimitMicrocredits: 1,
BillingCostSnapshot: model.BillingCostSnapshot{CostBillingMode: tc.mode, CostQuantity: tc.quantity, CostVideoFormulaTokens: tc.formula,
CostPricing: model.CreditCostPricing{Configured: true, UnitPriceMicrocredits: 90_000, InputTokenPriceMicrocredits: 1_000_000, OutputTokenPriceMicrocredits: 2_000_000, CachedTokenPriceMicrocredits: 100_000}}}
got, err := billingCreditCost(order)
if err != nil || got == nil || *got != tc.want {
t.Fatalf("cost=%v want=%d err=%v", got, tc.want, err)
}
order.CostPricing = model.CreditCostPricing{Configured: true}
got, err = billingCreditCost(order)
if err != nil || got == nil || *got != 0 {
t.Fatal("explicit zero cost must remain available")
}
for _, status := range []model.BillingStatus{model.BillingStatusReserved, model.BillingStatusRunning, model.BillingStatusRefunded, model.BillingStatusUncertain} {
order.Status = status
got, err = billingCreditCost(order)
if err != nil || got != nil {
t.Fatalf("unsettled cost fabricated for %s", status)
}
}
})
}
}
func TestCreditCostRejectsInvalidPrices(t *testing.T) {
for _, price := range []int64{-1, 1_000_000_000_001} {
if err := validateCreditCostPricing("text", "fixed_request", model.CreditCostPricing{Configured: true, UnitPriceMicrocredits: price}); err == nil {
t.Fatalf("accepted cost %d", price)
}
}
if err := validateCreditCostPricing("video", "token", model.CreditCostPricing{Configured: true, InputTokenPriceMicrocredits: 1}); err == nil {
t.Fatal("accepted video input cost")
}
}
+47 -117
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"infinite-canvas/backend/internal/kernel"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/repository"
@@ -106,6 +107,8 @@ type ResolveBillingBatchResult struct {
type tokenBillingEstimate struct {
InputTokens int64
OutputTokens int64
Video *VideoTokenEstimate
Err error
}
func (s *Service) Wallet(user *model.User, entryType string, page int, limit int) (*WalletSummary, error) {
@@ -505,6 +508,9 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
if channelModel.Capability != capability || !supportsTokenBilling(capability, channelModel.Protocol) {
return nil, BadAuthRequest("当前供应线路不支持前台模型的 Token 计费方式")
}
if capability == "video" && (logicalModel.InputPriceMicrocredits != 0 || logicalModel.CachedPriceMicrocredits != 0) {
return nil, BadAuthRequest("视频 Token 仅按视频用量定价,请将输入与缓存价格设为 0")
}
pricing := &model.ChannelModel{InputTokenPriceMicrocredits: logicalModel.InputPriceMicrocredits, OutputTokenPriceMicrocredits: logicalModel.OutputPriceMicrocredits, CachedTokenPriceMicrocredits: logicalModel.CachedPriceMicrocredits}
amount, err = tokenEstimateAmount(pricing, tokenEstimate, 10_000)
quantity = tokenEstimate.InputTokens + tokenEstimate.OutputTokens
@@ -514,22 +520,31 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
if err != nil {
return nil, err
}
if amount <= 0 {
if amount < 0 {
return nil, BadAuthRequest("当前模型尚未配置有效的用户价格")
}
revision, err := s.repo.LogicalModelRevision(task.LogicalModelRevisionID)
if err != nil {
return nil, err
}
return &model.BillingOrder{
var videoFormulaTokens int64
if logicalModel.BillingMode == "token" && tokenEstimate.Video != nil {
videoFormulaTokens = tokenEstimate.Video.FormulaTokens
}
order := &model.BillingOrder{
ID: newID(), UserID: userID, IdempotencyKey: "task:" + task.ID + ":" + newID(), TaskID: task.ID,
ChannelID: channelModel.ChannelID, ChannelModelID: channelModel.ID, Model: logicalModel.Code, Capability: capability,
Scene: truncateRunes(firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), 80), BillingMode: logicalModel.BillingMode, PriceVersion: int64(revision.Version),
UnitPriceMicrocredits: logicalModel.UnitPriceMicrocredits, MultiplierBasisPoints: 10_000, Quantity: quantity, AmountMicrocredits: amount,
ReservedAmountMicrocredits: amount, InputTokenPriceMicrocredits: logicalModel.InputPriceMicrocredits,
OutputTokenPriceMicrocredits: logicalModel.OutputPriceMicrocredits, CachedTokenPriceMicrocredits: logicalModel.CachedPriceMicrocredits,
Status: model.BillingStatusReserved,
}, nil
VideoFormulaTokens: videoFormulaTokens,
Status: model.BillingStatusReserved,
}
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
priceTierID, _ := config["priceTierId"].(string)
snapshotCreditCost(order, channelModelPriceTierForBilling(*channelModel, priceTierID, capability, intent), billingQuantity(capability, config["videoSeconds"]), tokenEstimate)
return order, nil
}
func (s *Service) ReserveProxyBilling(userID string, channelID string, modelKey string, capability string, scene string, idempotencyKey string, quantity int64) (*model.BillingOrder, error) {
@@ -589,14 +604,20 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
}
quantity = requestedQuantity
case "token":
if tokenEstimate.Err != nil {
return nil, tokenEstimate.Err
}
if !supportsTokenBilling(item.Capability, item.Protocol) || item.Capability != capability {
return nil, BadAuthRequest("Token 计费仅支持文本生成和火山方舟视频生成")
return nil, BadAuthRequest("Token 计费仅支持文本和视频生成")
}
if capability == "text" && (tokenEstimate.InputTokens <= 0 || tokenEstimate.OutputTokens <= 0) {
return nil, BadAuthRequest("无法估算文本 Token 用量")
}
if capability == "video" && tokenEstimate.OutputTokens <= 0 {
return nil, BadAuthRequest("无法估算火山方舟视频 Token 用量")
return nil, BadAuthRequest("无法计算视频 Token 用量,请检查时长与尺寸")
}
if capability == "video" && (tier.InputTokenPriceMicrocredits != 0 || tier.CachedTokenPriceMicrocredits != 0) {
return nil, BadAuthRequest("视频 Token 仅按视频用量定价,请将输入与缓存价格设为 0")
}
quantity = tokenEstimate.InputTokens + tokenEstimate.OutputTokens
default:
@@ -618,15 +639,22 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
if err != nil {
return nil, err
}
return &model.BillingOrder{
var videoFormulaTokens int64
if tier.BillingMode == "token" && tokenEstimate.Video != nil {
videoFormulaTokens = tokenEstimate.Video.FormulaTokens
}
order := &model.BillingOrder{
ID: newID(), UserID: userID, IdempotencyKey: idempotencyKey, TaskID: taskID,
ChannelID: channelID, ChannelModelID: item.ID, PriceTierID: tier.ID, PriceTierVersion: tier.PriceVersion, PriceSelectorJSON: tier.SelectorJSON, Model: modelKey, Capability: capability,
Scene: truncateRunes(scene, 80), BillingMode: tier.BillingMode, PriceVersion: item.PriceVersion,
UnitPriceMicrocredits: tier.UnitPriceMicrocredits, MultiplierBasisPoints: multiplierBPS, Quantity: quantity, AmountMicrocredits: amount,
ReservedAmountMicrocredits: amount, InputTokenPriceMicrocredits: tier.InputTokenPriceMicrocredits,
OutputTokenPriceMicrocredits: tier.OutputTokenPriceMicrocredits, CachedTokenPriceMicrocredits: tier.CachedTokenPriceMicrocredits,
Status: model.BillingStatusReserved,
}, nil
VideoFormulaTokens: videoFormulaTokens,
Status: model.BillingStatusReserved,
}
snapshotCreditCost(order, tier, requestedQuantity, tokenEstimate)
return order, nil
}
func channelModelPriceTierForBilling(channelModel model.ChannelModel, priceTierID string, capability string, intents ...ModelRequestIntent) *model.ChannelModelPriceTier {
@@ -661,94 +689,6 @@ func estimateTaskBillingTokens(input map[string]any, capability string) tokenBil
return estimateTaskTokens(input)
}
// 方舟视频成功后才返回真实 completion_tokens;创建任务前按官方像素帧公式预授权,
// 并保留少量帧率/取整余量,实际结算时会按 usage 自动退回差额。
func estimateArkVideoTokens(input map[string]any) tokenBillingEstimate {
config, _ := input["config"].(map[string]any)
if config == nil {
return tokenBillingEstimate{}
}
durationSeconds, err := strconv.ParseInt(strings.TrimSpace(fmt.Sprint(config["videoSeconds"])), 10, 64)
if err != nil || durationSeconds <= 0 {
return tokenBillingEstimate{}
}
pixels := arkVideoOutputPixels(fmt.Sprint(config["vquality"]), fmt.Sprint(config["size"]), fmt.Sprint(config["model"]))
if pixels <= 0 {
return tokenBillingEstimate{}
}
if durationSeconds > (1<<63-1)/1000 {
return tokenBillingEstimate{}
}
totalDurationMillis := durationSeconds * 1000
referenceCount := int64(0)
if references, ok := input["referenceVideos"].([]any); ok && len(references) > 0 {
referenceCount = int64(len(references))
knownDurationMillis := int64(0)
unknownDuration := false
for _, raw := range references {
media, _ := raw.(map[string]any)
durationMillis := firstInt64(media, "durationMs")
if durationMillis <= 0 {
unknownDuration = true
continue
}
knownDurationMillis = min(15_000, knownDurationMillis+min(durationMillis, int64(15_000)))
}
// 方舟参考视频总时长上限为 15 秒;缺少媒体元数据时按上限预留。
if unknownDuration {
knownDurationMillis = 15_000
}
totalDurationMillis += knownDurationMillis
}
frames := (totalDurationMillis*24+999)/1000 + 1 + referenceCount
if pixels > (1<<63-1-1023)/frames {
return tokenBillingEstimate{}
}
tokens := (pixels*frames + 1023) / 1024
if tokens > (1<<63-1-99)/110 {
return tokenBillingEstimate{}
}
return tokenBillingEstimate{OutputTokens: (tokens*110 + 99) / 100}
}
func arkVideoOutputPixels(resolution string, ratio string, modelName string) int64 {
resolution = normalizeSeedanceResolution(resolution, modelName)
ratio = normalizeSeedanceRatio(ratio)
pixelsByRatio := map[string]map[string]int64{
"480p": {
"16:9": 864 * 496, "4:3": 752 * 560, "1:1": 640 * 640,
"3:4": 560 * 752, "9:16": 496 * 864, "21:9": 992 * 432,
},
"720p": {
"16:9": 1280 * 720, "4:3": 1112 * 834, "1:1": 960 * 960,
"3:4": 834 * 1112, "9:16": 720 * 1280, "21:9": 1470 * 630,
},
"1080p": {
"16:9": 1920 * 1080, "4:3": 1664 * 1248, "1:1": 1440 * 1440,
"3:4": 1248 * 1664, "9:16": 1080 * 1920, "21:9": 2206 * 946,
},
}
values := pixelsByRatio[resolution]
if resolution == "2160p" {
values = make(map[string]int64, len(pixelsByRatio["1080p"]))
for key, value := range pixelsByRatio["1080p"] {
values[key] = value * 4
}
}
if len(values) == 0 {
return 0
}
if ratio != "adaptive" {
return values[ratio]
}
var largest int64
for _, value := range values {
largest = max(largest, value)
}
return largest
}
func estimateProxyTokens(body []byte) tokenBillingEstimate {
var payload map[string]any
_ = json.Unmarshal(body, &payload)
@@ -781,35 +721,25 @@ func maxOutputTokens(payload map[string]any) int64 {
// Token 单价按每百万 Token 配置;预授权使用输入价估算缓存 Token,真实结算再按 usage 拆分。
func tokenEstimateAmount(item *model.ChannelModel, estimate tokenBillingEstimate, multiplierBPS int64) (int64, error) {
if estimate.Err != nil {
return 0, estimate.Err
}
if item == nil || estimate.InputTokens < 0 || estimate.OutputTokens <= 0 || multiplierBPS <= 0 {
return 0, errors.New("Token 计费参数无效")
}
inputAmount, ok := safeTokenProduct(estimate.InputTokens, item.InputTokenPriceMicrocredits)
if !ok {
amount, err := kernel.TokenBillingAmount(multiplierBPS,
kernel.TokenBillingTerm{Tokens: estimate.InputTokens, PriceMicrocredits: item.InputTokenPriceMicrocredits},
kernel.TokenBillingTerm{Tokens: estimate.OutputTokens, PriceMicrocredits: item.OutputTokenPriceMicrocredits},
)
if errors.Is(err, kernel.ErrTokenBillingOverflow) {
return 0, errors.New("Token 计费金额溢出")
}
outputAmount, ok := safeTokenProduct(estimate.OutputTokens, item.OutputTokenPriceMicrocredits)
if !ok || inputAmount > 1<<63-1-outputAmount {
return 0, errors.New("Token 计费金额溢出")
}
base := inputAmount + outputAmount
if base > (1<<63-1-9_999_999_999)/multiplierBPS {
return 0, errors.New("Token 计费金额溢出")
}
amount := (base*multiplierBPS + 9_999_999_999) / 10_000_000_000
if amount <= 0 {
return 0, errors.New("Token 计费金额必须大于 0")
if err != nil {
return 0, errors.New("Token 计费参数无效")
}
return amount, nil
}
func safeTokenProduct(tokens int64, price int64) (int64, bool) {
if tokens < 0 || price < 0 || (tokens > 0 && price > (1<<63-1)/tokens) {
return 0, false
}
return tokens * price, true
}
func billingQuantity(capability string, value any) int64 {
if capability != "video" {
return 1
@@ -0,0 +1,73 @@
package app
import (
"math"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestTokenEstimateAmountUsesExactArithmetic(t *testing.T) {
for _, test := range []struct {
name string
prices model.ChannelModel
estimate tokenBillingEstimate
multiplier int64
want int64
}{
{
name: "video maximum price with multiplier",
prices: model.ChannelModel{
InputTokenPriceMicrocredits: 1_000_000_000_000, OutputTokenPriceMicrocredits: 1_000_000_000_000,
},
estimate: tokenBillingEstimate{OutputTokens: 10_000_000}, multiplier: 12_500, want: 12_500_000_000_000,
},
{
name: "text estimates input at full input price",
prices: model.ChannelModel{
InputTokenPriceMicrocredits: 2_000_000, OutputTokenPriceMicrocredits: 5_000_000, CachedTokenPriceMicrocredits: 1_000_000,
},
estimate: tokenBillingEstimate{InputTokens: 100, OutputTokens: 20}, multiplier: 10_000, want: 300,
},
{
name: "round after combining input and output",
prices: model.ChannelModel{
InputTokenPriceMicrocredits: 400_000, OutputTokenPriceMicrocredits: 400_000,
},
estimate: tokenBillingEstimate{InputTokens: 1, OutputTokens: 1}, multiplier: 12_500, want: 1,
},
{
name: "maximum final amount",
prices: model.ChannelModel{OutputTokenPriceMicrocredits: 1_000_000},
estimate: tokenBillingEstimate{OutputTokens: math.MaxInt64}, multiplier: 10_000, want: math.MaxInt64,
},
} {
t.Run(test.name, func(t *testing.T) {
amount, err := tokenEstimateAmount(&test.prices, test.estimate, test.multiplier)
if err != nil || amount != test.want {
t.Fatalf("tokenEstimateAmount() = %d, %v; want %d", amount, err, test.want)
}
})
}
}
func TestTokenEstimateAmountRejectsInvalidArithmetic(t *testing.T) {
for _, test := range []struct {
name string
prices model.ChannelModel
estimate tokenBillingEstimate
multiplier int64
}{
{name: "negative input", estimate: tokenBillingEstimate{InputTokens: -1, OutputTokens: 1}, multiplier: 10_000},
{name: "negative output", estimate: tokenBillingEstimate{OutputTokens: -1}, multiplier: 10_000},
{name: "negative price", prices: model.ChannelModel{OutputTokenPriceMicrocredits: -1}, estimate: tokenBillingEstimate{OutputTokens: 1}, multiplier: 10_000},
{name: "zero multiplier", estimate: tokenBillingEstimate{OutputTokens: 1}},
{name: "final overflow", prices: model.ChannelModel{OutputTokenPriceMicrocredits: 1_000_000}, estimate: tokenBillingEstimate{OutputTokens: math.MaxInt64}, multiplier: 10_001},
} {
t.Run(test.name, func(t *testing.T) {
if amount, err := tokenEstimateAmount(&test.prices, test.estimate, test.multiplier); amount != 0 || err == nil {
t.Fatalf("invalid estimate billed %d, %v", amount, err)
}
})
}
}
+8 -8
View File
@@ -15,8 +15,8 @@ func TestSupportsTokenBillingForVolcengineArkVideo(t *testing.T) {
if !supportsTokenBilling("video", model.ChannelInterfaceVolcengineArkVideo) {
t.Fatal("Volcengine Ark video should support Token billing")
}
if supportsTokenBilling("video", model.ChannelInterfaceNewAPIVideo) {
t.Fatal("video protocols without a final usage contract must not support Token billing")
if !supportsTokenBilling("video", model.ChannelInterfaceNewAPIVideo) {
t.Fatal("all video protocols must support formula-based Token billing")
}
}
@@ -26,8 +26,8 @@ func TestEstimateArkVideoTokensUsesPixelFrameEstimate(t *testing.T) {
"model": "doubao-seedance-1-5-pro", "videoSeconds": "5", "vquality": "720", "size": "16:9",
},
})
// 1280*720*(5*24+1)/1024 = 108900,预授权再保留 10% 余量。
if estimate.InputTokens != 0 || estimate.OutputTokens != 119790 {
// 官方公式 1280*720*5*24/1024 = 108000;平台另预留 10%。
if estimate.Err != nil || estimate.InputTokens != 0 || estimate.OutputTokens != 118800 {
t.Fatalf("estimateArkVideoTokens() = %#v", estimate)
}
}
@@ -39,20 +39,20 @@ func TestEstimateArkVideoTokensIncludesUnknownReferenceVideo(t *testing.T) {
},
"referenceVideos": []any{map[string]any{"id": "video-1"}},
})
if estimate.OutputTokens != 477180 {
if estimate.Err != nil || estimate.OutputTokens != 475200 || !estimate.Video.ReferenceDurationEstimated {
t.Fatalf("estimateArkVideoTokens() = %#v", estimate)
}
}
func TestEstimateArkVideoTokensCapsReferenceDuration(t *testing.T) {
func TestEstimateVideoTokensIncludesLongReferenceDuration(t *testing.T) {
estimate := estimateArkVideoTokens(map[string]any{
"config": map[string]any{
"model": "doubao-seedance-2-0", "videoSeconds": "5", "vquality": "720p", "size": "16:9",
},
"referenceVideos": []any{map[string]any{"id": "video-1", "durationMs": int64(60_000)}},
})
if estimate.OutputTokens != 477180 {
t.Fatalf("estimateArkVideoTokens() = %#v", estimate)
if estimate.Err != nil || estimate.Video.ReferenceSeconds != 60 || estimate.Video.FormulaTokens != 1_404_000 {
t.Fatalf("reference duration must be counted without silent capping: %#v", estimate)
}
}
+86 -19
View File
@@ -1,18 +1,78 @@
package app
import "infinite-canvas/backend/internal/model"
import (
"strings"
"infinite-canvas/backend/internal/model"
)
// LogicalModelQuote 是创作端当前参数命中的实际供应线路报价。
// Token 视频在上游返回真实 usage 前只能预估,创建任务仍以账务预留逻辑为准。
type LogicalModelQuote struct {
LogicalModelID string `json:"logicalModelId"`
BillingMode string `json:"billingMode"`
Quantity int64 `json:"quantity"`
AmountMicrocredits int64 `json:"amountMicrocredits"`
Estimated bool `json:"estimated"`
LogicalModelID string `json:"logicalModelId"`
BillingMode string `json:"billingMode"`
Quantity int64 `json:"quantity"`
AmountMicrocredits int64 `json:"amountMicrocredits"`
Estimated bool `json:"estimated"`
VideoTokenEstimate *VideoTokenEstimate `json:"videoTokenEstimate,omitempty"`
}
type ChannelModelQuoteRequest struct {
ChannelID string `json:"channelId"`
ModelKey string `json:"modelKey"`
Intent ModelRequestIntent `json:"intent"`
}
// QuoteChannelModel uses the same admission/defaults/SKU selection as task
// creation, without reserving credits or submitting a provider request.
func (s *Service) QuoteChannelModel(req ChannelModelQuoteRequest) (*LogicalModelQuote, error) {
if strings.TrimSpace(req.ChannelID) == "" || strings.TrimSpace(req.ModelKey) == "" {
return nil, InvalidModelSelection("报价必须指定系统渠道和模型")
}
if err := validateQuoteIntent(req.Intent); err != nil {
return nil, err
}
input := quoteInput(req.Intent, req.ModelKey)
config := input["config"].(map[string]any)
config["channelId"] = req.ChannelID
input, err := s.resolveSystemChannelModelSelection(input, "canvas_"+req.Intent.Capability, req.Intent.Operation)
if err != nil {
return nil, err
}
config = input["config"].(map[string]any)
estimate := estimateTaskBillingTokens(input, req.Intent.Capability)
intent := ModelRequestIntentFromTaskInput(input, "canvas_"+req.Intent.Capability, req.Intent.Operation)
order, err := s.newBillingOrderWithPriceTier("", "", "quote", req.ChannelID, req.ModelKey, req.Intent.Capability, "model_quote", billingQuantity(req.Intent.Capability, config["videoSeconds"]), estimate, stringValue(config["priceTierId"]), intent)
if err != nil {
return nil, err
}
return quoteFromOrder("", order, estimate), nil
}
func validateQuoteIntent(intent ModelRequestIntent) error {
if intent.Capability != "text" && intent.Capability != "image" && intent.Capability != "video" && intent.Capability != "audio" {
return BadAuthRequest("报价请求缺少有效的模型能力类型")
}
for _, count := range intent.Inputs {
if count < 0 || count > 128 {
return BadAuthRequest("报价参考素材数量必须为 0 到 128 的整数")
}
}
return nil
}
func quoteFromOrder(logicalModelID string, order *model.BillingOrder, estimate tokenBillingEstimate) *LogicalModelQuote {
quote := &LogicalModelQuote{LogicalModelID: logicalModelID, BillingMode: order.BillingMode, Quantity: order.Quantity, AmountMicrocredits: order.AmountMicrocredits, Estimated: order.BillingMode == "token"}
if order.BillingMode == "token" && order.Capability == "video" {
quote.VideoTokenEstimate = estimate.Video
}
return quote
}
func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIntent) (*LogicalModelQuote, error) {
if err := validateQuoteIntent(intent); err != nil {
return nil, err
}
routed, err := s.ResolveLogicalModel(logicalModelID, intent)
if err != nil {
return nil, err
@@ -24,6 +84,11 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
resolvedIntent := intent
resolvedIntent.Options = mergeIntentDefaults(intent.Options, routed.Defaults)
input := quoteInput(resolvedIntent, routed.ChannelModel.ModelKey)
providerModelKey := routed.ChannelModel.ProviderModelKey
if routed.PriceTier != nil {
providerModelKey = firstNonEmpty(routed.PriceTier.ProviderModelKey, providerModelKey)
}
input["config"].(map[string]any)["providerModelKey"] = providerModelKey
quantity := billingQuantity(capability, inputConfigValue(input, "videoSeconds"))
if capability != "video" {
quantity = 1
@@ -39,13 +104,7 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
if billingErr != nil {
return nil, billingErr
}
return &LogicalModelQuote{
LogicalModelID: routed.LogicalModel.ID,
BillingMode: order.BillingMode,
Quantity: order.Quantity,
AmountMicrocredits: order.AmountMicrocredits,
Estimated: order.BillingMode == "token",
}, nil
return quoteFromOrder(routed.LogicalModel.ID, order, tokenEstimate), nil
}
if routed.LogicalModel.PricePolicy != "unified" {
@@ -65,6 +124,9 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
if routed.ChannelModel.Capability != capability || !supportsTokenBilling(capability, routed.ChannelModel.Protocol) {
return nil, BadAuthRequest("当前供应线路不支持前台模型的 Token 计费方式")
}
if capability == "video" && (routed.LogicalModel.InputPriceMicrocredits != 0 || routed.LogicalModel.CachedPriceMicrocredits != 0) {
return nil, BadAuthRequest("视频 Token 仅按视频用量定价,请将输入与缓存价格设为 0")
}
pricing := &model.ChannelModel{
InputTokenPriceMicrocredits: routed.LogicalModel.InputPriceMicrocredits,
OutputTokenPriceMicrocredits: routed.LogicalModel.OutputPriceMicrocredits,
@@ -78,16 +140,20 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
if err != nil {
return nil, err
}
if amount <= 0 {
if amount < 0 {
return nil, BadAuthRequest("当前模型尚未配置有效的用户价格")
}
return &LogicalModelQuote{
quote := &LogicalModelQuote{
LogicalModelID: routed.LogicalModel.ID,
BillingMode: routed.LogicalModel.BillingMode,
Quantity: quantity,
AmountMicrocredits: amount,
Estimated: routed.LogicalModel.BillingMode == "token",
}, nil
}
if quote.Estimated && capability == "video" {
quote.VideoTokenEstimate = tokenEstimate.Video
}
return quote, nil
}
func quoteInput(intent ModelRequestIntent, modelKey string) map[string]any {
@@ -97,9 +163,10 @@ func quoteInput(intent ModelRequestIntent, modelKey string) map[string]any {
}
config["model"] = modelKey
input := map[string]any{"mode": intent.Capability, "config": config}
if count := intent.Inputs["video"]; count > 0 {
references := make([]any, count)
input["referenceVideos"] = references
for kind, key := range map[string]string{"image": "referenceImages", "video": "referenceVideos", "audio": "referenceAudios"} {
if count := intent.Inputs[kind]; count > 0 {
input[key] = make([]any, count)
}
}
return input
}
+6 -1
View File
@@ -664,6 +664,11 @@ func (s *Service) logicalModelBundle(actor *model.User, id string, req LogicalMo
if pricePolicy == "unified" && billingMode == "per_second" && capability != "video" {
return nil, nil, nil, false, BadAuthRequest("只有视频前台模型可以按秒计费")
}
if pricePolicy == "unified" && billingMode == "token" {
if err := validateTokenPrices(capability, req.InputPriceMicrocredits, req.OutputPriceMicrocredits, req.CachedPriceMicrocredits); err != nil {
return nil, nil, nil, false, err
}
}
creating := strings.TrimSpace(id) == ""
var item *model.LogicalModel
if creating {
@@ -756,7 +761,7 @@ func (s *Service) logicalModelBundle(actor *model.User, id string, req LogicalMo
}
if pricePolicy == "unified" && billingMode == "token" {
if !supportsLogicalModelTokenBilling(capability, enabledRouteProtocols) {
return nil, nil, nil, false, BadAuthRequest("Token 计费仅支持文本前台模型,或全部启用供应线路均为火山方舟视频协议的视频前台模型")
return nil, nil, nil, false, BadAuthRequest("Token 计费仅支持文本和视频前台模型")
}
}
// 停用必须始终可执行,便于管理员立即阻止失效线路继续对外服务;重新启用时再强校验结构能力和计费可用性。
+2 -2
View File
@@ -279,8 +279,8 @@ func TestSupportsLogicalModelTokenBillingForArkVideoRoutes(t *testing.T) {
if supportsLogicalModelTokenBilling("video", nil) {
t.Fatal("video logical models without an enabled route must not support Token billing")
}
if supportsLogicalModelTokenBilling("video", []model.ChannelInterfaceType{model.ChannelInterfaceVolcengineArkVideo, model.ChannelInterfaceNewAPIVideo}) {
t.Fatal("mixed video protocols must not support Token billing")
if !supportsLogicalModelTokenBilling("video", []model.ChannelInterfaceType{model.ChannelInterfaceVolcengineArkVideo, model.ChannelInterfaceNewAPIVideo}) {
t.Fatal("all video protocols must support Token billing")
}
}
+9 -26
View File
@@ -8,20 +8,16 @@ import (
"infinite-canvas/backend/internal/model"
)
// ModelCatalogSource 决定 ModelCatalogResponse 中哪一个集合具有语义。
// frontend 与 system 的数据形状互斥,调用方不能把缺失集合解释成空目录。
// ModelCatalogSource 标识创作目录来自系统渠道模型。
type ModelCatalogSource string
const (
// ModelCatalogSourceFrontend 表示目录由前台逻辑模型组成。
ModelCatalogSourceFrontend ModelCatalogSource = "frontend"
// ModelCatalogSourceSystem 表示目录由脱敏后的系统渠道与渠道模型组成。
ModelCatalogSourceSystem ModelCatalogSource = "system"
)
// ModelCatalogResponse 是创作端模型选择的统一读模型。
// Source=frontend 时读取 Models;Source=system 时读取 Channels。
// 两个集合都始终序列化为数组:空目录必须发 [],缺字段会被前端判成畸形响应。
// Channels 为唯一数据源;Models 固定为空,两个集合始终序列化为数组。
type ModelCatalogResponse struct {
Source ModelCatalogSource `json:"source"`
Models []PublicLogicalModel `json:"models"`
@@ -41,10 +37,11 @@ type PublicChannelCatalog struct {
type PublicChannelModel struct {
ID string `json:"id"`
ModelKey string `json:"modelKey"`
ChannelLabel string `json:"channelLabel"`
Description string `json:"description"`
DisplayName string `json:"displayName"`
SortOrder int `json:"sortOrder"`
Icon string `json:"icon"`
Description string `json:"description,omitempty"`
Capability string `json:"capability"`
Protocol model.ChannelInterfaceType `json:"protocol"`
CapabilityConfig map[string]any `json:"capabilityConfig,omitempty"`
@@ -68,26 +65,11 @@ type PublicChannelModelPriceTier struct {
CachedTokenPriceMicrocredits int64 `json:"cachedTokenPriceMicrocredits"`
}
// ModelCatalog 按功能开关返回互斥的数据形状:frontend 使用 Models,system 使用 Channels。
// ModelCatalog 的创作端目录始终来自系统渠道模型,不反查逻辑模型或路由。
// 系统渠道目录只负责安全发布可解释的读模型;任务创建仍会用持久化能力与价格档再次强校验。
func (s *Service) ModelCatalog(intent *ModelRequestIntent) (*ModelCatalogResponse, error) {
frontendEnabled, err := s.FeatureEnabled(FeatureFrontendModels)
if err != nil {
return nil, err
}
// 两个集合都初始化成非 nil 空切片:空目录要发 [],不能因为“没有模型”而丢掉字段。
response := &ModelCatalogResponse{Models: []PublicLogicalModel{}, Channels: []PublicChannelCatalog{}}
if frontendEnabled {
models, err := s.PublicLogicalModels(intent)
if err != nil {
return nil, err
}
response.Source = ModelCatalogSourceFrontend
response.Models = append(response.Models, models...)
return response, nil
}
channels, err := s.publicSystemChannelCatalog(intent)
if err != nil {
return nil, err
@@ -146,8 +128,8 @@ func (s *Service) publicSystemChannelCatalog(intent *ModelRequestIntent) ([]Publ
if len(publicModels) > 0 {
result = append(result, PublicChannelCatalog{
ID: channel.ID,
Name: channel.PublicName(),
DisplayName: channel.PublicName(),
Name: channel.Name,
DisplayName: channel.Name,
SortOrder: channel.SortOrder,
Models: publicModels,
})
@@ -202,10 +184,11 @@ func (s *Service) sanitizeChannelModel(cm *model.ChannelModel) (PublicChannelMod
return PublicChannelModel{
ID: cm.ID,
ModelKey: cm.ModelKey,
ChannelLabel: cm.ChannelLabel,
Description: cm.Description,
DisplayName: cm.DisplayName,
SortOrder: cm.SortOrder,
Icon: cm.Icon,
Description: cm.Description,
Capability: cm.Capability,
Protocol: cm.Protocol,
CapabilityConfig: capabilityConfig,
+2 -4
View File
@@ -11,16 +11,14 @@ import (
"gorm.io/gorm"
)
// 前台模型目录为空时也必须发 models: [],不能因为 omitempty 丢掉字段:
// 前端在 source=frontend 时强制校验 models 是数组,缺字段会被判成畸形响应;
// 而 auth-session-hydrator 会把该异常当成未登录并清掉会话,表现为刷新后跳回登录页。
// 目录始终来自系统渠道;空目录也要显式返回数组,不能被会话初始化判成畸形响应。
func TestModelCatalogAlwaysSerializesCollectionsAsArrays(t *testing.T) {
for _, test := range []struct {
name string
frontendEnabled bool
wantSource string
}{
{name: "空的前台模型目录", frontendEnabled: true, wantSource: "frontend"},
{name: "逻辑模型开关不改变目录来源", frontendEnabled: true, wantSource: "system"},
{name: "空的系统渠道目录", frontendEnabled: false, wantSource: "system"},
} {
t.Run(test.name, func(t *testing.T) {
File diff suppressed because it is too large. Load diff
+4
View File
@@ -7,8 +7,12 @@ import (
const (
PaymentPluginWeChatNative = "official-payment-wechat-native"
PaymentPluginAlipayPage = "official-payment-alipay-page"
PaymentPluginXunHuPay = "official-payment-xunhupay"
PaymentPluginZhiFuFM = "official-payment-zhifufm"
PaymentProviderWeChat = "wechat-native"
PaymentProviderAlipay = "alipay-page-pay"
PaymentProviderXunHuPay = "xunhupay-aggregate"
PaymentProviderZhiFuFM = "zhifufm-pay"
)
func bundledPaymentPluginManifests() []protocol.Manifest {
@@ -151,3 +151,38 @@ func TestXunHuPayOfficialPackageIsPaymentPlugin(t *testing.T) {
t.Fatalf("xunhupay provider type = %T", provider)
}
}
func TestZhiFuFMOfficialPackageIsPaymentPlugin(t *testing.T) {
center, err := newPluginRuntime(t.TempDir())
if err != nil {
t.Fatal(err)
}
var plugin PluginView
for _, item := range center.list() {
if item.Manifest.ID == "official-payment-zhifufm" {
plugin = item
plugin.Management = pluginManagementFromView(item)
break
}
}
if plugin.Manifest.ID == "" {
t.Fatal("official-payment-zhifufm is missing")
}
if plugin.Management.Kind != PluginKindPayment || plugin.Source != PluginOriginOfficial {
t.Fatalf("zhifufm plugin = %#v", plugin)
}
if len(plugin.Manifest.Contributes.PaymentProviders) != 1 || plugin.Manifest.Contributes.PaymentProviders[0].ID != "zhifufm-pay" {
t.Fatalf("zhifufm contributions = %#v", plugin.Manifest.Contributes.PaymentProviders)
}
registry := center.paymentRegistrySnapshot()
if registry == nil {
t.Fatal("payment registry is nil")
}
provider, ok := registry.Get("zhifufm-pay")
if !ok {
t.Fatal("zhifufm-pay provider is missing")
}
if _, ok := provider.(*payment.RPCProvider); !ok {
t.Fatalf("zhifufm provider type = %T", provider)
}
}
+20 -2
View File
@@ -2,6 +2,21 @@ package app
import "infinite-canvas/backend/internal/model"
const maxChannelModelTokenPriceMicrocredits = int64(1_000_000) * CreditScale
func validateTokenPrices(capability string, inputPrice, outputPrice, cachedPrice int64) error {
if inputPrice < 0 || outputPrice < 0 || cachedPrice < 0 {
return BadAuthRequest("模型积分价格不能小于 0")
}
if capability == "video" && (inputPrice != 0 || cachedPrice != 0) {
return BadAuthRequest("视频 Token 仅按视频用量计费,输入和缓存 Token 价格必须为 0")
}
if inputPrice > maxChannelModelTokenPriceMicrocredits || outputPrice > maxChannelModelTokenPriceMicrocredits || cachedPrice > maxChannelModelTokenPriceMicrocredits {
return BadAuthRequest("Token 每百万用量价格不能超过 1,000,000 积分")
}
return nil
}
// ValidateChannelModelPrice 校验渠道模型价格配置的有效性
// 根据 billingMode 检查必要的价格字段是否已配置
func ValidateChannelModelPrice(billingMode string, capability string, protocol model.ChannelInterfaceType, unitPrice, inputPrice, outputPrice, cachedPrice int64) bool {
@@ -13,14 +28,17 @@ func ValidateChannelModelPrice(billingMode string, capability string, protocol m
// 按秒计费:0 表示免费,负数无效。
return unitPrice >= 0
case "token":
if validateTokenPrices(capability, inputPrice, outputPrice, cachedPrice) != nil {
return false
}
if capability == "video" {
return model.IsVolcengineArkVideoProtocol(protocol) && inputPrice >= 0 && outputPrice >= 0 && cachedPrice >= 0
return true
}
if capability != "" && capability != "text" {
return false
}
// 文本模型:所有 Token 价格为 0 时表示免费。
return inputPrice >= 0 && outputPrice >= 0 && cachedPrice >= 0
return true
default:
return false
}
@@ -6,14 +6,14 @@ import (
"infinite-canvas/backend/internal/model"
)
func TestValidateChannelModelPriceSupportsArkVideoTokensOnly(t *testing.T) {
func TestValidateChannelModelPriceSupportsAllVideoTokens(t *testing.T) {
const outputPrice = int64(16_000_000)
if !ValidateChannelModelPrice("token", "video", model.ChannelInterfaceVolcengineArkVideo, 0, 0, outputPrice, 0) {
t.Fatal("Volcengine Ark video Token price should be valid")
}
for _, protocol := range []model.ChannelInterfaceType{model.ChannelInterfaceVolcengineJiMengVideo, model.ChannelInterfaceNewAPIVideo} {
if ValidateChannelModelPrice("token", "video", protocol, 0, 0, outputPrice, 0) {
t.Fatalf("video protocol %q should not support Token pricing", protocol)
if !ValidateChannelModelPrice("token", "video", protocol, 0, 0, outputPrice, 0) {
t.Fatalf("video protocol %q should support Token pricing", protocol)
}
}
}
@@ -26,7 +26,7 @@ func TestHasValidPriceUsesChannelProtocolForTokenTiers(t *testing.T) {
}
jimeng := &model.ChannelModel{Capability: "video", Protocol: model.ChannelInterfaceVolcengineJiMengVideo, PriceTiers: []model.ChannelModelPriceTier{tier}}
if HasValidPrice(jimeng) {
t.Fatal("JiMeng video Token tier should be invalid")
if !HasValidPrice(jimeng) {
t.Fatal("JiMeng video Token tier should be valid")
}
}
+3 -1
View File
@@ -230,10 +230,12 @@ func applyRoutedProviderSelection(input map[string]any, routed *RoutedModel) map
nextConfig["channelId"] = routed.ChannelModel.ChannelID
nextConfig["model"] = routed.ChannelModel.ModelKey
nextConfig["channelModelKey"] = routed.ChannelModel.ModelKey
providerModelKey := routed.ChannelModel.ProviderModelKey
if routed.PriceTier != nil {
nextConfig["priceTierId"] = routed.PriceTier.ID
nextConfig["providerModelKey"] = routed.PriceTier.ProviderModelKey
providerModelKey = firstNonEmpty(routed.PriceTier.ProviderModelKey, providerModelKey)
}
nextConfig["providerModelKey"] = firstNonEmpty(providerModelKey, routed.ChannelModel.ModelKey)
input["config"] = nextConfig
return input
}
@@ -0,0 +1,129 @@
package app
import (
"encoding/json"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestUnifiedVideoQuoteAndTaskUseResolvedProviderGeneration(t *testing.T) {
svc, db, _, channelModel, profile := newVideoTokenQuoteFixture(t)
const upstream = "doubao-seedance-2-5"
channelModel.ProviderModelKey = upstream
if err := db.Model(&model.ChannelModel{}).Where("id = ?", channelModel.ID).Update("provider_model_key", upstream).Error; err != nil {
t.Fatal(err)
}
spec, err := CapabilitySpecFromModelCapabilityConfig(profile, "video")
if err != nil {
t.Fatal(err)
}
specJSON, err := json.Marshal(spec)
if err != nil {
t.Fatal(err)
}
logical := model.LogicalModel{
ID: "logical-aliased-video", Code: "video-alias", Capability: "video", Enabled: true,
ActiveRevisionID: "aliased-video-revision", PricePolicy: "unified", BillingMode: "token", OutputPriceMicrocredits: 16_000_000,
}
revision := model.LogicalModelRevision{
ID: logical.ActiveRevisionID, LogicalModelID: logical.ID, Version: 1, CapabilitySpecJSON: string(specJSON),
DefaultOptionsJSON: `{"vquality":"480p","size":"16:9","videoSeconds":5,"videoGenerateAudio":true}`,
}
route := model.LogicalModelRoute{ID: "aliased-video-route", LogicalModelRevisionID: revision.ID, ChannelModelID: channelModel.ID, Enabled: true, Weight: 1}
for _, row := range []any{&logical, &revision, &route} {
if err := db.Create(row).Error; err != nil {
t.Fatal(err)
}
}
quote, err := svc.QuoteLogicalModel(logical.ID, ModelRequestIntent{Capability: "video"})
if err != nil {
t.Fatal(err)
}
routed, input, err := svc.resolveTaskModelSelection(map[string]any{"mode": "video", "config": map[string]any{}}, logical.ID, "canvas_video", "", true)
if err != nil {
t.Fatal(err)
}
if routed.PriceTier != nil || input["config"].(map[string]any)["providerModelKey"] != upstream {
t.Fatalf("unified route did not preserve its provider model: %#v", input)
}
order, err := svc.taskBillingOrder("quote-user", &model.Task{
ID: "aliased-video-task", Type: "canvas_video", LogicalModelID: logical.ID,
LogicalModelRevisionID: revision.ID, RouteID: route.ID, ChannelModelID: channelModel.ID,
}, input)
if err != nil {
t.Fatal(err)
}
if quote.VideoTokenEstimate == nil || quote.VideoTokenEstimate.OutputWidth != 854 || quote.VideoTokenEstimate.OutputHeight != 480 || quote.VideoTokenEstimate.DimensionsEstimated {
t.Fatalf("wrong generation-specific quote: %#v", quote.VideoTokenEstimate)
}
if order == nil || order.VideoFormulaTokens != 48038 || order.Quantity != 52842 || order.AmountMicrocredits != 845472 || quote.Quantity != order.Quantity || quote.AmountMicrocredits != order.AmountMicrocredits {
t.Fatalf("quote/task mismatch: quote=%#v order=%#v", quote, order)
}
assertVideoQuoteHasNoFinancialWrites(t, db)
}
func TestRoutedProviderSelectionFallsBackWithoutTierOverride(t *testing.T) {
for _, test := range []struct {
name string
provider string
tier *model.ChannelModelPriceTier
want string
}{
{name: "unified without tier", provider: "provider-default", want: "provider-default"},
{name: "empty tier override", provider: "provider-default", tier: &model.ChannelModelPriceTier{ID: "tier"}, want: "provider-default"},
{name: "tier override", provider: "provider-default", tier: &model.ChannelModelPriceTier{ID: "tier", ProviderModelKey: "provider-tier"}, want: "provider-tier"},
{name: "model key fallback", tier: &model.ChannelModelPriceTier{ID: "tier"}, want: "model-alias"},
} {
t.Run(test.name, func(t *testing.T) {
input := applyRoutedProviderSelection(map[string]any{"config": map[string]any{"providerModelKey": "untrusted-client-model"}}, &RoutedModel{
ChannelModel: model.ChannelModel{ChannelID: "channel", ModelKey: "model-alias", ProviderModelKey: test.provider}, PriceTier: test.tier,
})
if got := input["config"].(map[string]any)["providerModelKey"]; got != test.want {
t.Fatalf("providerModelKey = %v, want %s", got, test.want)
}
})
}
}
func TestUnifiedVideoModelSaveRejectsInvalidTokenPricesBeforePersistence(t *testing.T) {
for _, test := range []struct {
name string
input, output int64
cached int64
}{
{name: "hidden input", input: 1, output: 16_000_000},
{name: "hidden cache", output: 16_000_000, cached: 1},
{name: "too expensive", output: maxChannelModelTokenPriceMicrocredits + 1},
} {
t.Run(test.name, func(t *testing.T) {
// A nil repository proves invalid price fields fail before IDs or revisions are written.
_, _, _, _, err := (&Service{}).logicalModelBundle(&model.User{ID: "admin"}, "", LogicalModelRequest{
Code: "video-test", Name: "Video", Capability: "video", PricePolicy: "unified", BillingMode: "token",
CapabilitySpec: CapabilitySpec{Version: 1, Capability: "video"},
InputPriceMicrocredits: test.input, OutputPriceMicrocredits: test.output, CachedPriceMicrocredits: test.cached,
})
if err == nil {
t.Fatal("invalid unified video pricing accepted")
}
})
}
}
func TestUnifiedVideoModelSaveAllowsFreeAndMaximumTokenPrices(t *testing.T) {
for _, outputPrice := range []int64{0, 16_000_000, maxChannelModelTokenPriceMicrocredits} {
svc, _, _, channelModel, profile := newVideoTokenQuoteFixture(t)
spec, err := CapabilitySpecFromModelCapabilityConfig(profile, "video")
if err != nil {
t.Fatal(err)
}
item, _, _, _, err := svc.logicalModelBundle(&model.User{ID: "admin"}, "", LogicalModelRequest{
Code: "video-test", Name: "Video", Capability: "video", PricePolicy: "unified", BillingMode: "token", Enabled: true,
CapabilitySpec: spec, OutputPriceMicrocredits: outputPrice,
Routes: []LogicalRouteRequest{{ChannelModelID: channelModel.ID, Enabled: true, Weight: 1}},
})
if err != nil || item == nil || item.OutputPriceMicrocredits != outputPrice {
t.Fatalf("output price %d: model=%#v error=%v", outputPrice, item, err)
}
}
}
+241
View File
@@ -0,0 +1,241 @@
package app
import (
"fmt"
"math"
"strconv"
"strings"
)
// VideoTokenEstimate separates the provider's pixel-frame estimate from our
// reservation margin. The formula snapshot can settle videos without provider usage.
type VideoTokenEstimate struct {
FormulaTokens int64 `json:"formulaTokens"`
ReservedTokens int64 `json:"reservedTokens"`
OutputWidth int64 `json:"outputWidth"`
OutputHeight int64 `json:"outputHeight"`
FramesPerSecond int64 `json:"framesPerSecond"`
OutputSeconds int64 `json:"outputSeconds"`
ReferenceSeconds float64 `json:"referenceSeconds"`
ReferenceDurationEstimated bool `json:"referenceDurationEstimated"`
DimensionsEstimated bool `json:"dimensionsEstimated"`
ReservationMarginPercent int64 `json:"reservationMarginPercent"`
}
type videoDimensions struct{ width, height int64 }
// Official Seedance dimensions, not resolution-label multiplication. 4K's
// 4:3 and 21:9 dimensions in particular differ from twice the 1080p dimensions.
var arkVideoDimensions = map[string][]videoDimensions{
"480p": {{864, 496}, {752, 560}, {640, 640}, {560, 752}, {496, 864}, {992, 432}},
"720p": {{1280, 720}, {1112, 834}, {960, 960}, {834, 1112}, {720, 1280}, {1470, 630}},
"1080p": {{1920, 1080}, {1664, 1248}, {1440, 1440}, {1248, 1664}, {1080, 1920}, {2206, 946}},
"2160p": {{3840, 2160}, {3326, 2494}, {2880, 2880}, {2494, 3326}, {2160, 3840}, {4398, 1886}},
}
var arkVideo10Dimensions = map[string][]videoDimensions{
"480p": {{864, 480}, {736, 544}, {640, 640}, {544, 736}, {480, 864}, {960, 416}},
"720p": {{1248, 704}, {1120, 832}, {960, 960}, {832, 1120}, {704, 1248}, {1504, 640}},
"1080p": {{1920, 1088}, {1664, 1248}, {1440, 1440}, {1248, 1664}, {1088, 1920}, {2176, 928}},
}
func estimateArkVideoTokens(input map[string]any) tokenBillingEstimate {
detail, err := estimateArkVideoTokenUsage(input)
if err != nil {
return tokenBillingEstimate{Err: err}
}
return tokenBillingEstimate{OutputTokens: detail.ReservedTokens, Video: detail}
}
func estimateArkVideoTokenUsage(input map[string]any) (*VideoTokenEstimate, error) {
config, _ := input["config"].(map[string]any)
seconds, err := strconv.ParseInt(strings.TrimSpace(fmt.Sprint(config["videoSeconds"])), 10, 64)
if err != nil || seconds <= 0 || seconds > (math.MaxInt64-15_000)/1000 {
return nil, BadAuthRequest("视频 Token 预估需要有效的正整数生成时长")
}
modelName := firstNonEmpty(stringValue(config["providerModelKey"]), stringValue(config["model"]))
dimensions, dimensionsEstimated, err := arkVideoBillingDimensions(stringValue(config["vquality"]), stringValue(config["size"]), modelName)
if err != nil {
return nil, err
}
referenceMillis, durationEstimated, err := videoReferenceMillis(input["referenceVideos"])
if err != nil {
return nil, err
}
const fps, margin = int64(24), int64(10)
if dimensions.width > math.MaxInt64/dimensions.height/fps {
return nil, BadAuthRequest("视频尺寸超出 Token 计算范围")
}
pixels := dimensions.width * dimensions.height
if seconds > (math.MaxInt64-referenceMillis)/1000 {
return nil, BadAuthRequest("视频时长超出 Token 计算范围")
}
millis := seconds*1000 + referenceMillis
if millis > (math.MaxInt64-1_023_999)/(pixels*fps) {
return nil, BadAuthRequest("视频 Token 预估用量超出支持范围")
}
// Official formula: (input seconds + output seconds) * W * H * FPS / 1024.
// Provider usage takes precedence; otherwise the formula snapshot is billable.
formulaTokens := (millis*pixels*fps + 1_023_999) / 1_024_000
if formulaTokens > (math.MaxInt64-99)/(100+margin) {
return nil, BadAuthRequest("视频 Token 预授权用量超出支持范围")
}
return &VideoTokenEstimate{
FormulaTokens: formulaTokens, ReservedTokens: (formulaTokens*(100+margin) + 99) / 100,
OutputWidth: dimensions.width, OutputHeight: dimensions.height, FramesPerSecond: fps,
OutputSeconds: seconds, ReferenceSeconds: float64(referenceMillis) / 1000,
ReferenceDurationEstimated: durationEstimated, DimensionsEstimated: dimensionsEstimated,
ReservationMarginPercent: margin,
}, nil
}
func videoReferenceMillis(raw any) (int64, bool, error) {
if raw == nil {
return 0, false, nil
}
references, ok := raw.([]any)
if !ok || len(references) > 128 {
return 0, false, BadAuthRequest("视频 Token 预估的参考视频参数无效")
}
var total int64
unknown := false
for _, rawReference := range references {
media, ok := rawReference.(map[string]any)
if rawReference != nil && !ok {
return 0, false, BadAuthRequest("视频 Token 预估的参考视频参数无效")
}
value := media["durationMs"]
if value == nil {
unknown = true
continue
}
duration, err := strconv.ParseInt(fmt.Sprint(value), 10, 64)
if err != nil || duration < 0 || duration > math.MaxInt64-total {
return 0, false, BadAuthRequest("参考视频时长参数无效,durationMs 必须为非负整数且不能溢出")
}
if duration == 0 {
unknown = true
}
total += duration
}
if unknown {
// The catalog quote has only reference counts; reserve the documented
// maximum and disclose it instead of pretending the references cost zero.
return max(total, 15_000), true, nil
}
return total, false, nil
}
func arkVideoBillingDimensions(resolution, ratio, modelName string) (videoDimensions, bool, error) {
resolution = strings.ToLower(strings.TrimSpace(resolution))
ratio = strings.ToLower(strings.TrimSpace(ratio))
// Some video protocols expose exact pixels in size instead of a resolution tier.
if dimensions, ok := videoPixelDimensions(ratio); ok {
return dimensions, false, nil
}
defaulted := resolution == "" || resolution == "auto" || resolution == "high" || resolution == "medium"
if defaulted {
resolution = "720p"
}
if resolution == "low" {
resolution = "480p"
}
if ratio == "" {
ratio = "16:9"
defaulted = true
}
switch resolution {
case "480", "720", "1080", "2160":
resolution += "p"
case "4k":
resolution = "2160p"
case "2k":
resolution = "1440p"
}
base, exists := arkVideoDimensions[resolution]
if !exists {
return videoScaledDimensions(resolution, ratio)
}
ratios := []string{"16:9", "4:3", "1:1", "3:4", "9:16", "21:9"}
ratio = strings.ToLower(strings.TrimSpace(ratio))
adaptive := ratio == "adaptive" || ratio == "auto"
ratioIndex := -1
for index, value := range ratios {
if value == ratio {
ratioIndex = index
}
}
if ratioIndex < 0 && !adaptive {
return videoScaledDimensions(resolution, ratio)
}
name := strings.ReplaceAll(strings.ToLower(modelName), ".", "-")
is10 := strings.Contains(name, "seedance-1-0")
is25 := strings.Contains(name, "seedance-2-5")
known := is10 || is25 || strings.Contains(name, "seedance-1-5") || strings.Contains(name, "seedance-2-0")
values := append([]videoDimensions(nil), base...)
if is10 {
if resolution == "2160p" {
defaulted = true
} else {
values = arkVideo10Dimensions[resolution]
}
} else if is25 && resolution == "480p" {
values[0], values[4] = videoDimensions{854, 480}, videoDimensions{480, 854}
} else if !known {
// Endpoint IDs don't identify a model generation. Use the largest
// documented dimensions per ratio, with an explicit estimate flag.
for index, value := range arkVideo10Dimensions[resolution] {
if value.width*value.height > values[index].width*values[index].height {
values[index] = value
}
}
}
if !adaptive {
return values[ratioIndex], !known || defaulted, nil
}
largest := values[0]
for _, value := range values[1:] {
if value.width*value.height > largest.width*largest.height {
largest = value
}
}
return largest, true, nil
}
func videoPixelDimensions(size string) (videoDimensions, bool) {
parts := strings.Split(strings.ReplaceAll(size, "×", "x"), "x")
if len(parts) != 2 {
return videoDimensions{}, false
}
w, ew := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
h, eh := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
return videoDimensions{w, h}, ew == nil && eh == nil && w > 0 && h > 0
}
// Generic video tiers use the short edge and requested aspect ratio. This is a
// platform pricing convention for non-Seedance sizes, not a provider pixel claim.
func videoScaledDimensions(resolution, ratio string) (videoDimensions, bool, error) {
raw := strings.TrimSuffix(strings.TrimSuffix(resolution, "横"), "竖")
edge, err := strconv.ParseInt(strings.TrimSuffix(raw, "p"), 10, 64)
if err != nil || edge <= 0 {
return videoDimensions{}, false, BadAuthRequest("视频 Token 计费需要有效分辨率或明确的宽×高尺寸")
}
if ratio == "auto" || ratio == "adaptive" {
ratio = "16:9"
}
parts := strings.Split(ratio, ":")
if len(parts) != 2 {
return videoDimensions{}, false, BadAuthRequest("视频 Token 计费需要有效画幅比例")
}
w, ew := strconv.ParseInt(parts[0], 10, 64)
h, eh := strconv.ParseInt(parts[1], 10, 64)
if ew != nil || eh != nil || w <= 0 || h <= 0 || edge > (math.MaxInt64-min(w, h))/max(w, h) {
return videoDimensions{}, false, BadAuthRequest("视频画幅超出 Token 计算范围")
}
longEdge := (edge*max(w, h) + min(w, h) - 1) / min(w, h)
longEdge = (longEdge + 1) / 2 * 2
if w >= h {
return videoDimensions{longEdge, edge}, true, nil
}
return videoDimensions{edge, longEdge}, true, nil
}
@@ -0,0 +1,67 @@
package app
import (
"math"
"testing"
)
func TestArkVideoEstimateUsesOfficialDimensionsAndNoExtraFrames(t *testing.T) {
for _, tt := range []struct {
name, model, resolution, ratio string
width, height int64
estimated bool
}{
{"1.0 fast retains 1080", "doubao-seedance-1-0-pro-fast", "1080P", "16:9", 1920, 1088, false},
{"1.5", "doubao-seedance-1-5-pro", "720", "16:9", 1280, 720, false},
{"2.5", "doubao-seedance-2-5", "480p", "9:16", 480, 854, false},
{"4K widescreen", "doubao-seedance-2-0", "4K", "21:9", 4398, 1886, false},
{"4K classic", "doubao-seedance-2-0", "2160p", "4:3", 3326, 2494, false},
{"endpoint conservative size", "ep-custom", "720p", "21:9", 1504, 640, true},
{"adaptive", "doubao-seedance-2-0", "720p", "adaptive", 1112, 834, true},
} {
t.Run(tt.name, func(t *testing.T) {
estimate := estimateArkVideoTokens(map[string]any{"config": map[string]any{
"model": "display-name-fast", "providerModelKey": tt.model, "vquality": tt.resolution, "size": tt.ratio, "videoSeconds": "5",
}})
if estimate.Err != nil {
t.Fatal(estimate.Err)
}
got := estimate.Video
want := (tt.width*tt.height*24*5 + 1023) / 1024
if got.OutputWidth != tt.width || got.OutputHeight != tt.height || got.FormulaTokens != want || got.DimensionsEstimated != tt.estimated || got.ReservedTokens != (want*110+99)/100 {
t.Fatalf("estimate=%#v, want %dx%d, tokens=%d", got, tt.width, tt.height, want)
}
})
}
}
func TestArkVideoEstimateRejectsInvalidParameters(t *testing.T) {
for _, patch := range []map[string]any{
{"vquality": "garbage"}, {"size": "invalid"}, {"size": "0:7"},
{"videoSeconds": "-1"}, {"videoSeconds": "1.5"}, {"videoSeconds": math.MaxInt64},
} {
config := map[string]any{"model": "doubao-seedance-2-0", "vquality": "720p", "size": "16:9", "videoSeconds": "5"}
for k, v := range patch {
config[k] = v
}
if got := estimateArkVideoTokens(map[string]any{"config": config}); got.Err == nil || got.OutputTokens != 0 {
t.Fatalf("invalid config %#v yielded %#v", patch, got)
}
}
}
func TestArkVideoReferenceUsesOutputPixelsAndFractionalSeconds(t *testing.T) {
input := map[string]any{"config": map[string]any{"model": "doubao-seedance-2-0", "videoSeconds": "5", "vquality": "720p", "size": "16:9"},
"referenceVideos": []any{map[string]any{"durationMs": 1250, "width": 3840, "height": 2160}, map[string]any{"durationMs": 250}},
}
got := estimateArkVideoTokens(input)
if got.Err != nil || got.Video.FormulaTokens != 140400 || got.Video.ReferenceSeconds != 1.5 || got.Video.ReferenceDurationEstimated {
t.Fatalf("estimate=%#v error=%v", got.Video, got.Err)
}
for _, references := range []any{[]any{map[string]any{"durationMs": -1}}, []any{map[string]any{"durationMs": 1.5}}, []any{map[string]any{"durationMs": int64(math.MaxInt64)}, map[string]any{"durationMs": 6000}}, "invalid", make([]any, 129)} {
input["referenceVideos"] = references
if got := estimateArkVideoTokens(input); got.Err == nil {
t.Fatalf("accepted invalid references: %#v", references)
}
}
}
@@ -0,0 +1,221 @@
package app
import (
"encoding/json"
"fmt"
"reflect"
"testing"
"infinite-canvas/backend/internal/model"
"gorm.io/gorm"
)
func TestVideoTokenChannelQuoteAgreesWithTaskBilling(t *testing.T) {
for _, test := range []struct {
name string
audio any
free bool
wantTier string
wantPrice int64
wantCost int64
}{
{name: "audio default", wantTier: "video-audio", wantPrice: 16_000_000, wantCost: 1_900_800},
{name: "explicit audio", audio: true, wantTier: "video-audio", wantPrice: 16_000_000, wantCost: 1_900_800},
{name: "silent", audio: false, wantTier: "video-silent", wantPrice: 8_000_000, wantCost: 950_400},
{name: "configured free", audio: true, free: true, wantTier: "video-audio"},
} {
t.Run(test.name, func(t *testing.T) {
svc, db, channel, channelModel, _ := newVideoTokenQuoteFixture(t)
if test.free {
if err := db.Model(&model.ChannelModelPriceTier{}).Where("id = ?", test.wantTier).Update("output_token_price_microcredits", 0).Error; err != nil {
t.Fatal(err)
}
}
intent := ModelRequestIntent{Capability: "video", Options: map[string]any{
"vquality": "720p", "size": "16:9", "videoSeconds": 5,
}}
if test.audio != nil {
intent.Options["videoGenerateAudio"] = test.audio
}
quote, err := svc.QuoteChannelModel(ChannelModelQuoteRequest{ChannelID: channel.ID, ModelKey: channelModel.ModelKey, Intent: intent})
if err != nil {
t.Fatalf("QuoteChannelModel() error = %v", err)
}
assertVideoTokenQuote(t, quote, test.wantCost)
assertVideoQuoteHasNoFinancialWrites(t, db)
input := quoteInput(intent, channelModel.ModelKey)
input["config"].(map[string]any)["channelId"] = channel.ID
resolved, err := svc.resolveSystemChannelModelSelection(input, "canvas_video", "")
if err != nil {
t.Fatalf("resolveSystemChannelModelSelection() error = %v", err)
}
order, err := svc.taskBillingOrder("quote-user", &model.Task{ID: "video-task", Type: "canvas_video"}, resolved)
if err != nil {
t.Fatalf("taskBillingOrder() error = %v", err)
}
if order == nil || order.PriceTierID != test.wantTier || order.OutputTokenPriceMicrocredits != test.wantPrice || order.InputTokenPriceMicrocredits != 0 || order.CachedTokenPriceMicrocredits != 0 {
t.Fatalf("wrong video price tier: %#v", order)
}
if order.AmountMicrocredits != quote.AmountMicrocredits || order.ReservedAmountMicrocredits != quote.AmountMicrocredits || order.Quantity != quote.Quantity {
t.Fatalf("quote and task reservation disagree: quote=%#v order=%#v", quote, order)
}
assertVideoQuoteHasNoFinancialWrites(t, db)
})
}
}
func TestVideoTokenLogicalQuoteAgreesWithSystemChannel(t *testing.T) {
for _, policy := range []string{"channel", "unified"} {
t.Run(policy, func(t *testing.T) {
svc, db, channel, channelModel, profile := newVideoTokenQuoteFixture(t)
spec, err := CapabilitySpecFromModelCapabilityConfig(profile, "video")
if err != nil {
t.Fatal(err)
}
specJSON, err := json.Marshal(spec)
if err != nil {
t.Fatal(err)
}
logical := model.LogicalModel{
ID: "logical-video", Code: "seedance-video", Capability: "video", Enabled: true,
ActiveRevisionID: "video-revision", PricePolicy: policy, BillingMode: "token", OutputPriceMicrocredits: 16_000_000,
}
revision := model.LogicalModelRevision{
ID: logical.ActiveRevisionID, LogicalModelID: logical.ID, Version: 1,
CapabilitySpecJSON: string(specJSON),
DefaultOptionsJSON: `{"vquality":"720p","size":"16:9","videoSeconds":5,"videoGenerateAudio":true}`,
}
route := model.LogicalModelRoute{
ID: "video-route", LogicalModelRevisionID: revision.ID, ChannelModelID: channelModel.ID, Enabled: true, Weight: 1,
}
for _, row := range []any{&logical, &revision, &route} {
if err := db.Create(row).Error; err != nil {
t.Fatal(err)
}
}
intent := ModelRequestIntent{Capability: "video"}
logicalQuote, err := svc.QuoteLogicalModel(logical.ID, intent)
if err != nil {
t.Fatalf("QuoteLogicalModel() error = %v", err)
}
assertVideoTokenQuote(t, logicalQuote, 1_900_800)
if logicalQuote.LogicalModelID != logical.ID {
t.Fatalf("logicalModelId = %q, want %q", logicalQuote.LogicalModelID, logical.ID)
}
channelQuote, err := svc.QuoteChannelModel(ChannelModelQuoteRequest{ChannelID: channel.ID, ModelKey: channelModel.ModelKey, Intent: intent})
if err != nil {
t.Fatal(err)
}
if logicalQuote.AmountMicrocredits != channelQuote.AmountMicrocredits || logicalQuote.Quantity != channelQuote.Quantity || !reflect.DeepEqual(logicalQuote.VideoTokenEstimate, channelQuote.VideoTokenEstimate) {
t.Fatalf("logical and channel quote disagree: logical=%#v channel=%#v", logicalQuote, channelQuote)
}
assertVideoQuoteHasNoFinancialWrites(t, db)
})
}
}
func TestVideoTokenChannelQuoteRejectsUnavailableChannel(t *testing.T) {
for _, test := range []struct {
name string
field string
value any
}{
{name: "disabled channel", field: "enabled", value: false},
{name: "private channel", field: "scope", value: model.ChannelScopeUser},
{name: "disabled model", field: "enabled", value: false},
} {
t.Run(test.name, func(t *testing.T) {
svc, db, channel, channelModel, _ := newVideoTokenQuoteFixture(t)
row, id := any(&model.ModelChannel{}), channel.ID
if test.name == "disabled model" {
row, id = &model.ChannelModel{}, channelModel.ID
}
if err := db.Model(row).Where("id = ?", id).Update(test.field, test.value).Error; err != nil {
t.Fatal(err)
}
quote, err := svc.QuoteChannelModel(ChannelModelQuoteRequest{ChannelID: channel.ID, ModelKey: channelModel.ModelKey, Intent: ModelRequestIntent{Capability: "video"}})
if err == nil || quote != nil {
t.Fatalf("unavailable channel/model must be rejected: quote=%#v error=%v", quote, err)
}
assertVideoQuoteHasNoFinancialWrites(t, db)
})
}
}
func TestVideoTokenQuoteRejectsInvalidReferenceCounts(t *testing.T) {
for _, count := range []int{-1, 129, int(^uint(0) >> 1)} {
for _, kind := range []string{"image", "video", "audio"} {
t.Run(fmt.Sprintf("%s/%d", kind, count), func(t *testing.T) {
intent := ModelRequestIntent{Capability: "video", Inputs: map[string]int{kind: count}}
// A nil repository verifies counts fail before allocation, lookup, or routing.
svc := &Service{}
if quote, err := svc.QuoteChannelModel(ChannelModelQuoteRequest{ChannelID: "system-video", ModelKey: "video", Intent: intent}); err == nil || quote != nil {
t.Fatalf("channel quote must reject invalid count: quote=%#v error=%v", quote, err)
}
if quote, err := svc.QuoteLogicalModel("logical-video", intent); err == nil || quote != nil {
t.Fatalf("logical quote must reject invalid count: quote=%#v error=%v", quote, err)
}
})
}
}
}
func newVideoTokenQuoteFixture(t *testing.T) (*Service, *gorm.DB, model.ModelChannel, model.ChannelModel, *ModelCapabilityConfig) {
t.Helper()
const providerModel = "doubao-seedance-1-5-pro-251215"
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceVolcengineArkVideo), providerModel)
profile.Video.Duration.Default = 5
tiers := []model.ChannelModelPriceTier{
{ID: "video-audio", SelectorKey: `{"videoGenerateAudio":"true"}`, SelectorJSON: `{"videoGenerateAudio":"true"}`, ProviderModelKey: providerModel, BillingMode: "token", OutputTokenPriceMicrocredits: 16_000_000, PriceConfigured: true, Enabled: true},
{ID: "video-silent", SelectorKey: `{"videoGenerateAudio":"false"}`, SelectorJSON: `{"videoGenerateAudio":"false"}`, ProviderModelKey: providerModel, BillingMode: "token", OutputTokenPriceMicrocredits: 8_000_000, PriceConfigured: true, Enabled: true},
}
svc, db, channel, channelModel := createSystemChannelSelectionFixture(t, "video", model.ChannelInterfaceVolcengineArkVideo, profile, tiers)
channelModel.ProviderModelKey = providerModel
if err := db.Model(&model.ChannelModel{}).Where("id = ?", channelModel.ID).Update("provider_model_key", providerModel).Error; err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.SystemSetting{}, &model.CreditAccount{}, &model.CreditLedgerEntry{}, &model.BillingOrder{}); err != nil {
t.Fatal(err)
}
account := model.CreditAccount{UserID: "quote-user", AvailableMicrocredits: 10_000_000, ReservedMicrocredits: 250_000, Version: 7}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
return svc, db, channel, channelModel, profile
}
func assertVideoTokenQuote(t *testing.T, quote *LogicalModelQuote, amount int64) {
t.Helper()
if quote == nil || quote.BillingMode != "token" || !quote.Estimated || quote.Quantity != 118_800 || quote.AmountMicrocredits != amount {
t.Fatalf("unexpected video quote: %#v, want 118800 tokens and %d microcredits", quote, amount)
}
want := VideoTokenEstimate{
FormulaTokens: 108_000, ReservedTokens: 118_800, OutputWidth: 1280, OutputHeight: 720,
FramesPerSecond: 24, OutputSeconds: 5, ReservationMarginPercent: 10,
}
if quote.VideoTokenEstimate == nil || *quote.VideoTokenEstimate != want {
t.Fatalf("video estimate = %#v, want %#v", quote.VideoTokenEstimate, want)
}
}
func assertVideoQuoteHasNoFinancialWrites(t *testing.T, db *gorm.DB) {
t.Helper()
var account model.CreditAccount
if err := db.First(&account, "user_id = ?", "quote-user").Error; err != nil {
t.Fatal(err)
}
if account.AvailableMicrocredits != 10_000_000 || account.ReservedMicrocredits != 250_000 || account.Version != 7 {
t.Fatalf("read-only quote changed the credit account: %#v", account)
}
for _, row := range []any{&model.BillingOrder{}, &model.CreditLedgerEntry{}, &model.Task{}} {
var count int64
if err := db.Model(row).Count(&count).Error; err != nil {
t.Fatal(err)
}
if count != 0 {
t.Fatalf("read-only quote created %d records of %T", count, row)
}
}
}
@@ -0,0 +1,123 @@
package app
import (
"testing"
"infinite-canvas/backend/internal/model"
)
func TestNormalizeVideoAudioPriceSelector(t *testing.T) {
for _, test := range []struct {
value string
want string
}{
{value: "true", want: "true"},
{value: "false", want: "false"},
{value: " FALSE ", want: "false"},
{value: "*", want: ""},
} {
t.Run(test.value, func(t *testing.T) {
selector, _, _, err := normalizeChannelModelTierSelector("video", ChannelModelPriceTierRequest{
Selector: map[string]string{"videoGenerateAudio": test.value},
})
if err != nil || selector["videoGenerateAudio"] != test.want {
t.Fatalf("selector = %#v, error = %v, want audio %q", selector, err, test.want)
}
if test.want == "" && len(selector) != 0 {
t.Fatalf("wildcard must share the default selector, got %#v", selector)
}
})
}
for _, value := range []string{"yes", "1", "0", "auto"} {
if _, _, _, err := normalizeChannelModelTierSelector("video", ChannelModelPriceTierRequest{
Selector: map[string]string{"videoGenerateAudio": value},
}); err == nil {
t.Fatalf("invalid audio selector %q accepted", value)
}
}
for _, capability := range []string{"text", "image", "audio"} {
for _, value := range []string{"true", "false", "*"} {
if _, _, _, err := normalizeChannelModelTierSelector(capability, ChannelModelPriceTierRequest{
Selector: map[string]string{"videoGenerateAudio": value},
}); err == nil {
t.Fatalf("%s model accepted video audio selector %q", capability, value)
}
}
}
}
func TestVideoPriceTierMatchesAudioAndActualReferences(t *testing.T) {
channelModel := model.ChannelModel{PriceTiers: []model.ChannelModelPriceTier{
{ID: "default", SelectorJSON: `{}`, Enabled: true, PriceConfigured: true},
{ID: "reference", SelectorJSON: `{"operation":"video_to_video"}`, Enabled: true, PriceConfigured: true},
{ID: "reference-audio", SelectorJSON: `{"operation":"video_to_video","videoGenerateAudio":"true"}`, Enabled: true, PriceConfigured: true},
{ID: "reference-silent", SelectorJSON: `{"operation":"video_to_video","videoGenerateAudio":"false"}`, Enabled: true, PriceConfigured: true},
}}
for _, test := range []struct {
name string
value any
want string
}{
{name: "audio boolean", value: true, want: "reference-audio"},
{name: "silent boolean", value: false, want: "reference-silent"},
{name: "audio string", value: "true", want: "reference-audio"},
{name: "silent string", value: "false", want: "reference-silent"},
{name: "unspecified", want: "reference"},
{name: "invalid is not silent", value: "invalid", want: "reference"},
} {
t.Run(test.name, func(t *testing.T) {
options := map[string]any{}
if test.value != nil {
options["videoGenerateAudio"] = test.value
}
for _, source := range []string{"config", "capabilityOptions"} {
intent := ModelRequestIntentFromTaskInput(map[string]any{
"mode": "video", "referenceVideos": []any{map[string]any{"id": "video-reference"}}, source: options,
}, "canvas_video", "reference_to_video")
tier := channelModelPriceTierForIntent(channelModel, intent)
if tier == nil || tier.ID != test.want {
t.Fatalf("%s matched %#v, want %s", source, tier, test.want)
}
}
})
}
intent := ModelRequestIntent{Capability: "video", Inputs: map[string]int{"video": 1}}
intent.Options = mergeIntentDefaults(map[string]any{"videoGenerateAudio": false}, map[string]any{"videoGenerateAudio": true})
if tier := channelModelPriceTierForIntent(channelModel, intent); tier == nil || tier.ID != "reference-silent" {
t.Fatalf("explicit false must override audio default: %#v", tier)
}
}
func TestVideoTokenPricesUseOutputOnlyAndSharedBounds(t *testing.T) {
for _, protocol := range []model.ChannelInterfaceType{model.ChannelInterfaceVolcengineArkVideo, model.ChannelInterfaceVolcengineArkAgentPlanVideo, model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceType("newapi-channel-2"), model.ChannelInterfaceType("custom-video")} {
for _, test := range []struct {
name string
input, output int64
cached int64
valid bool
}{
{name: "free", valid: true},
{name: "paid", output: 16_000_000, valid: true},
{name: "maximum", output: maxChannelModelTokenPriceMicrocredits, valid: true},
{name: "over maximum", output: maxChannelModelTokenPriceMicrocredits + 1},
{name: "negative", output: -1},
{name: "hidden input price", input: 1, output: 16_000_000},
{name: "hidden cached price", output: 16_000_000, cached: 1},
} {
t.Run(string(protocol)+"/"+test.name, func(t *testing.T) {
if got := ValidateChannelModelPrice("token", "video", protocol, 0, test.input, test.output, test.cached); got != test.valid {
t.Fatalf("price validity = %v, want %v", got, test.valid)
}
for _, configured := range []bool{true, false} {
err := validateChannelModelTierPricing("video", protocol, "token", ChannelModelPriceTierRequest{
PriceConfigured: configured, InputTokenPriceMicrocredits: test.input,
OutputTokenPriceMicrocredits: test.output, CachedTokenPriceMicrocredits: test.cached,
})
if (err == nil) != test.valid {
t.Fatalf("configured=%v error=%v, want validity %v", configured, err, test.valid)
}
}
})
}
}
}
+90
View File
@@ -0,0 +1,90 @@
package app
import (
"fmt"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestArkVideoUsageRequiresValidFinalCompletionTokens(t *testing.T) {
for _, path := range []string{"/api/v3/contents/generations/tasks/video-1", "/api/plan/v3/contents/generations/tasks/video-1"} {
for _, test := range []struct {
name string
payload string
want int64
}{
{name: "completion", payload: `{"status":"succeeded","usage":{"completion_tokens":108900}}`, want: 108900},
{name: "completion precedes output and total", payload: `{"usage":{"completion_tokens":108900,"output_tokens":900000,"total_tokens":200000}}`, want: 108900},
{name: "total when completion missing", payload: `{"usage":{"total_tokens":35800}}`, want: 35800},
{name: "total precedes output alias", payload: `{"usage":{"output_tokens":900000,"total_tokens":35800}}`, want: 35800},
{name: "nested response", payload: `{"data":{"status":"succeeded","usage":{"completion_tokens":35800}}}`, want: 35800},
{name: "integer beyond float precision", payload: `{"usage":{"completion_tokens":9007199254740993}}`, want: 9007199254740993},
{name: "largest int64", payload: `{"usage":{"completion_tokens":9223372036854775807}}`, want: 9223372036854775807},
{name: "processing", payload: `{"status":"running","usage":{"completion_tokens":108900}}`},
{name: "queued", payload: `{"status":"queued","usage":{"completion_tokens":108900}}`},
{name: "failed", payload: `{"status":"failed","usage":{"completion_tokens":108900}}`},
{name: "invalid status", payload: `{"status":true,"usage":{"completion_tokens":108900}}`},
{name: "missing usage", payload: `{"status":"succeeded"}`},
{name: "empty usage", payload: `{"status":"succeeded","usage":{}}`},
{name: "output alias only", payload: `{"usage":{"output_tokens":108900}}`},
{name: "unrelated usage metadata", payload: `{"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":108900,"cachedContentTokenCount":1}}`},
} {
t.Run(path+"/"+test.name, func(t *testing.T) {
log := &model.ApiCallLog{Capability: "video", Path: path, InputTokens: 1, CachedTokens: 1, OutputTokens: 1, UsageAvailable: true}
(&Service{}).EnrichAPICallLog(log, []byte(test.payload))
if log.InputTokens != 0 || log.CachedTokens != 0 || log.OutputTokens != test.want || log.UsageAvailable != (test.want > 0) {
t.Fatalf("usage = input:%d cached:%d output:%d available:%v, want output:%d", log.InputTokens, log.CachedTokens, log.OutputTokens, log.UsageAvailable, test.want)
}
})
}
}
}
func TestArkVideoUsageDoesNotMaskMalformedCompletionWithTotal(t *testing.T) {
for _, invalid := range []string{"0", "-1", "1.5", "1.0", `"108900"`, "9223372036854775808", "1e100", "null", "true", "{}"} {
for _, field := range []string{"completion_tokens", "total_tokens"} {
t.Run(field+"/"+invalid, func(t *testing.T) {
usage := fmt.Sprintf(`{"%s":%s}`, field, invalid)
if field == "completion_tokens" {
usage = fmt.Sprintf(`{"completion_tokens":%s,"total_tokens":108900}`, invalid)
}
log := &model.ApiCallLog{Capability: "video", Path: "/api/v3/contents/generations/tasks/video-1"}
(&Service{}).EnrichAPICallLog(log, []byte(`{"status":"succeeded","usage":`+usage+`}`))
if log.UsageAvailable || log.OutputTokens != 0 {
t.Fatalf("accepted invalid usage %s: output:%d available:%v", usage, log.OutputTokens, log.UsageAvailable)
}
})
}
}
}
func TestArkVideoUsageNeverAddsInputOrCachedTokens(t *testing.T) {
log := &model.ApiCallLog{Capability: "video", Path: "/api/v3/contents/generations/tasks/video-1"}
(&Service{}).EnrichAPICallLog(log, []byte(`{"status":"succeeded","usage":{"completion_tokens":108900,"input_tokens":999,"cached_tokens":50,"prompt_tokens_details":{"cached_tokens":100}},"usageMetadata":{"promptTokenCount":888,"candidatesTokenCount":777,"cachedContentTokenCount":200}}`))
if !log.UsageAvailable || log.InputTokens != 0 || log.CachedTokens != 0 || log.OutputTokens != 108900 {
t.Fatalf("video usage was contaminated by text usage: %#v", log)
}
}
func TestGenericVideoUsageRequiresPositiveFinalIntegerTokens(t *testing.T) {
for _, test := range []struct {
payload string
want int64
}{
{`{"data":{"status":"completed","usage":{"completion_tokens":108000}}}`, 108000},
{`{"status":"SUCCESS","usage":{"output_tokens":100000,"input_tokens":20}}`, 100000},
{`{"status":"succeeded","usage":{"total_tokens":90000}}`, 90000},
{`{"status":"running","usage":{"completion_tokens":108000}}`, 0},
{`{"status":"failed","usage":{"output_tokens":108000}}`, 0},
{`{"usage":{"completion_tokens":1.5,"total_tokens":108000}}`, 0},
{`{"usage":{"output_tokens":-1,"total_tokens":108000}}`, 0},
{`{"usage":{"input_tokens":108000}}`, 0},
} {
log := &model.ApiCallLog{Capability: "video", Path: "/v1/video/generations/task-1"}
(&Service{}).EnrichAPICallLog(log, []byte(test.payload))
if log.OutputTokens != test.want || log.UsageAvailable != (test.want > 0) || log.InputTokens != 0 || log.CachedTokens != 0 {
t.Fatalf("payload=%s log=%#v", test.payload, log)
}
}
}