feat(plugins): warn about task models a plugin cannot charge

A plugin change can leave a task model without a usable price: no price
is set, the price uses usage the plugin no longer provides, or the
plugin no longer offers the model. The gateway now lists these models.
The list follows the plugins currently serving, so a gateway update
that changes a built-in plugin shows up too.

- Uploading, installing from the marketplace, activating or enabling a
  plugin, or deleting its active version, lists the models it cannot
  charge in the upload dialog or in the notice after the action.
- Model pricing marks each of them "Price needs attention" with the
  reason, and a "Price status" filter lists them. A plugin model that
  was never priced now appears in the table too. The badge replaces
  "Task pricing not configured".
- The sidebar shows how many models need attention on System Settings,
  Billing & Payment and Model Pricing, for super administrators.
- GET /api/option/model_pricing/issues returns the list. It is root
  only; access tokens need the option:read scope.
- Prices kept for a switched-off plugin are not reported. They apply
  again when the plugin is switched back on.
This commit is contained in:
CaIon committed 2026-10-30 17:34:37 +08:00
1 parent 1e8c707aca
commit 883eeb87d8
37 files changed
+1343 -90

No files matched your search

+1
View File
@@ -682,6 +682,7 @@
"quota saturation on consume log: op=%s kind=%s original=%g clamped=%d user=%d model=%s": "消费日志: 额度超出上限,已按上限记录: op=%s kind=%s original=%g clamped=%d user=%d model=%s",
"rate limit check failed (key=%s): %v": "限流检查失败 (key=%s): %v",
"rate limit check failed (mark=%s): %v": "限流检查失败 (mark=%s): %v",
"read pricing issues of task plugin %s: %v": "读取任务插件 %s 待处理的价格失败: %v",
"read response failed from %s: %s": "读取 %s 的响应失败: %s",
"ready in %d ms": "启动完成,耗时 %d ms",
"realtime error: %s": "Realtime 出错: %s",
+9
View File
@@ -18,6 +18,15 @@ func GetModelPricingConfig(c *gin.Context) {
common.ApiSuccess(c, snapshot)
}
func GetModelPricingIssues(c *gin.Context) {
issues, err := model.GetModelPricingIssues("")
if err != nil {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, issues)
}
func PreviewModelPricingConversion(c *gin.Context) {
var request struct {
ModelName string `json:"model_name"`
+35 -5
View File
@@ -104,7 +104,11 @@ func UploadTaskPlugin(c *gin.Context) {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, taskPluginDetail{Plugin: &plugin, Meta: loaded.Meta, Source: string(plugin.Source), Layer: "override", HasIcon: plugin.HasIcon()})
detail := taskPluginDetail{Plugin: &plugin, Meta: loaded.Meta, Source: string(plugin.Source), Layer: "override", HasIcon: plugin.HasIcon()}
if plugin.Active && plugin.Enabled {
detail.PricingIssues = taskPluginPricingIssues(plugin.Key)
}
common.ApiSuccess(c, detail)
}
func GetTaskPluginVersions(c *gin.Context) {
@@ -304,6 +308,8 @@ type taskPluginDetail struct {
Source string `json:"source"`
Layer string `json:"layer"`
HasIcon bool `json:"has_icon"`
// PricingIssues is set by an upload that puts the version into service.
PricingIssues []model.ModelPricingIssue `json:"pricing_issues,omitempty"`
}
// GetTaskPluginIcon serves a plugin logo as an image. The active override wins
@@ -453,7 +459,12 @@ func DeleteTaskPluginVersion(c *gin.Context) {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, nil)
var data any
if plugin.Active {
// Deleting the active version changes which plugin, if any, serves key.
data = gin.H{"pricing_issues": taskPluginPricingIssues(key)}
}
common.ApiSuccess(c, data)
}
type taskPluginActivateRequest struct {
@@ -494,7 +505,7 @@ func ActivateTaskPlugin(c *gin.Context) {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, nil)
common.ApiSuccess(c, gin.H{"pricing_issues": taskPluginPricingIssues(target.Key)})
}
type taskPluginStatusRequest struct {
@@ -552,6 +563,7 @@ func SetTaskPluginStatus(c *gin.Context) {
common.ApiError(c, lookupErr)
return
}
response := gin.H{"plugin_enabled": *request.Enabled, "disabled_channels": disabledChannels, "unbound_channels": unboundChannels}
// Switching a key off must silence every layer that can serve it. The
// factory built-in goes into the disabled set even when an override row
// exists; otherwise the built-in would keep routing the same models (and
@@ -584,7 +596,10 @@ func SetTaskPluginStatus(c *gin.Context) {
return
}
if !hasActiveOverride {
common.ApiSuccess(c, gin.H{"plugin_enabled": *request.Enabled, "disabled_channels": disabledChannels, "unbound_channels": unboundChannels})
if *request.Enabled {
response["pricing_issues"] = taskPluginPricingIssues(key)
}
common.ApiSuccess(c, response)
return
}
}
@@ -596,7 +611,10 @@ func SetTaskPluginStatus(c *gin.Context) {
common.ApiError(c, err)
return
}
common.ApiSuccess(c, gin.H{"plugin_enabled": *request.Enabled, "disabled_channels": disabledChannels, "unbound_channels": unboundChannels})
if *request.Enabled {
response["pricing_issues"] = taskPluginPricingIssues(key)
}
common.ApiSuccess(c, response)
}
func taskPluginHasFactory(key string) bool {
@@ -608,6 +626,18 @@ func taskPluginHasFactory(key string) bool {
return false
}
// taskPluginPricingIssues lists, after the registry sync, the task model prices
// the plugin serving key cannot charge. The plugin change is already saved, so
// a failed read only drops the notice; the model pricing page still shows them.
func taskPluginPricingIssues(key string) []model.ModelPricingIssue {
issues, err := model.GetModelPricingIssues(key)
if err != nil {
common.SysError(common.LogText("read pricing issues of task plugin %s: %v", key, err))
return nil
}
return issues
}
func GetTaskPluginMarketplaceSources(c *gin.Context) {
common.ApiSuccess(c, setting.GetTaskPluginMarketplaceSources())
}
+143
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"regexp"
"slices"
"strings"
"testing"
@@ -17,6 +18,8 @@ import (
"github.com/QuantumNous/new-api/pkg/jsplugin"
"github.com/QuantumNous/new-api/plugins"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/billing_setting"
"github.com/QuantumNous/new-api/setting/config"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
@@ -639,6 +642,146 @@ func TestActivateTaskPluginRefreshesRuntimeSyncState(t *testing.T) {
assert.False(t, hasSyncError)
}
// Every change that puts a version into service answers with the prices the
// serving plugin cannot charge, read after the registry sync.
func TestTaskPluginChangesReportPricingIssuesOfServingPlugin(t *testing.T) {
setupTaskPluginControllerTest(t)
// Pricing reads need the production key-column quoting.
previousLogDB := model.LOG_DB
t.Cleanup(func() { model.LOG_DB = previousLogDB })
t.Setenv("LOG_SQL_DSN", "")
require.NoError(t, model.InitLogDB())
key := "pricing-notice-probe"
cleanupTaskPluginControllerRuntime(t, key)
upload := func(version string) string {
body, err := common.Marshal(map[string]any{"source": taskPluginControllerTestSource(key, version)})
require.NoError(t, err)
return string(body)
}
unpriced := []model.ModelPricingIssue{{ModelName: "doc-1", PluginKey: key, PluginName: "Test", Reason: model.ModelPricingIssueUnconfigured}}
statusPath := "/api/plugin/task/" + key + "/status"
for _, step := range []struct {
name, method, path, body string
params gin.Params
handler gin.HandlerFunc
want []model.ModelPricingIssue
}{
{"first upload serves", http.MethodPost, "/api/plugin/task", upload("1.0.0"), nil, UploadTaskPlugin, unpriced},
{"later upload waits for activation", http.MethodPost, "/api/plugin/task", upload("2.0.0"), nil, UploadTaskPlugin, nil},
{"activation", http.MethodPost, "/api/plugin/task/" + key + "/activate", `{"version":"2.0.0"}`, gin.Params{{Key: "key", Value: key}}, ActivateTaskPlugin, unpriced},
{"switching off", http.MethodPost, statusPath, `{"enabled":false}`, gin.Params{{Key: "key", Value: key}}, SetTaskPluginStatus, nil},
{"switching on", http.MethodPost, statusPath, `{"enabled":true}`, gin.Params{{Key: "key", Value: key}}, SetTaskPluginStatus, unpriced},
{"deleting the active version promotes another", http.MethodDelete, "/api/plugin/task/" + key + "/versions/2.0.0", "", gin.Params{{Key: "key", Value: key}, {Key: "version", Value: "2.0.0"}}, DeleteTaskPluginVersion, unpriced},
} {
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
context.Params = step.params
context.Request = httptest.NewRequest(step.method, step.path, strings.NewReader(step.body))
context.Request.Header.Set("Content-Type", "application/json")
step.handler(context)
var response struct {
Success bool `json:"success"`
Message string `json:"message"`
Data struct {
PricingIssues []model.ModelPricingIssue `json:"pricing_issues"`
} `json:"data"`
}
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response), step.name)
require.True(t, response.Success, "%s: %s", step.name, response.Message)
assert.Equal(t, step.want, response.Data.PricingIssues, step.name)
}
active, err := model.GetTaskPluginVersion(key, "")
require.NoError(t, err)
assert.Equal(t, "1.0.0", active.Version)
}
// A plugin switched off keeps its saved prices for when it is switched back
// on, whether its override row is stored disabled or its built-in sits in the
// disabled set: prices for models its installed version declares are not
// issues, and none of its models counts as unpriced. Prices turn stale once the
// installed version stops declaring the model or the plugin is gone.
func TestSwitchedOffPluginPricesAreNotPricingIssues(t *testing.T) {
setupTaskPluginFactoryDisableTest(t)
// Pricing reads need the production key-column quoting.
previousLogDB := model.LOG_DB
t.Cleanup(func() { model.LOG_DB = previousLogDB })
t.Setenv("LOG_SQL_DSN", "")
require.NoError(t, model.InitLogDB())
savedConfig := config.GlobalConfig.ExportAllConfigs()
t.Cleanup(func() { require.NoError(t, config.GlobalConfig.LoadFromDB(savedConfig)) })
key := "pricing-off-probe"
cleanupTaskPluginControllerRuntime(t, key)
body, err := common.Marshal(map[string]any{"source": taskPluginControllerTestSource(key, "1.0.0")})
require.NoError(t, err)
upload := httptest.NewRecorder()
context, _ := gin.CreateTestContext(upload)
context.Request = httptest.NewRequest(http.MethodPost, "/api/plugin/task", strings.NewReader(string(body)))
context.Request.Header.Set("Content-Type", "application/json")
UploadTaskPlugin(context)
require.Contains(t, upload.Body.String(), `"success":true`)
var kling jsplugin.Meta
for _, meta := range jsplugin.DefaultRegistry.Snapshot().Factory {
if meta.Key == "kling" {
kling = meta
}
}
require.NotEmpty(t, kling.Models)
prices, err := common.Marshal(map[string]string{
key + "::doc-1": `tier("base", u("units") * 0.1)`,
key + "::retired-model": `tier("base", u("units") * 0.1)`,
"kling::" + kling.Models[0]: `tier("base", u("units") * 0.1)`,
"kling::kling-retired-model": `tier("base", u("units") * 0.1)`,
})
require.NoError(t, err)
require.NoError(t, model.DB.Save(&model.Option{Key: billing_setting.PluginBillingExprOption, Value: string(prices)}).Error)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{billing_setting.PluginBillingExprOption: string(prices)}))
readIssues := func() []model.ModelPricingIssue {
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
context.Request = httptest.NewRequest(http.MethodGet, "/api/option/model_pricing/issues", nil)
GetModelPricingIssues(context)
var response struct {
Success bool `json:"success"`
Data []model.ModelPricingIssue `json:"data"`
}
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
require.True(t, response.Success)
return slices.DeleteFunc(response.Data, func(issue model.ModelPricingIssue) bool {
return issue.PluginKey != key && issue.PluginKey != "kling"
})
}
unpricedKling := func(issue model.ModelPricingIssue) bool {
return issue.PluginKey == "kling" && issue.Reason == model.ModelPricingIssueUnconfigured
}
if len(kling.Models) > 1 {
require.True(t, slices.ContainsFunc(readIssues(), unpricedKling), "a serving built-in reports its unpriced models")
}
for _, plugin := range []string{key, "kling"} {
require.Contains(t, postTaskPluginStatus(t, plugin, "", `{"enabled":false}`).Body.String(), `"success":true`)
}
row, err := model.GetTaskPluginVersion(key, "")
require.NoError(t, err)
require.False(t, row.Enabled)
require.Equal(t, []string{"kling"}, setting.GetTaskPluginDisabledFactoryKeys())
_, serving := jsplugin.DefaultRegistry.Get("kling")
require.False(t, serving)
// A plugin missing from the live generation is named by its key.
stale := func(name, plugin string) model.ModelPricingIssue {
return model.ModelPricingIssue{ModelName: name, PluginKey: plugin, PluginName: plugin, Reason: model.ModelPricingIssueStale}
}
assert.Equal(t, []model.ModelPricingIssue{stale("kling-retired-model", "kling"), stale("retired-model", key)}, readIssues())
remove := httptest.NewRecorder()
context, _ = gin.CreateTestContext(remove)
context.Params = gin.Params{{Key: "key", Value: key}, {Key: "version", Value: "1.0.0"}}
context.Request = httptest.NewRequest(http.MethodDelete, "/api/plugin/task/"+key+"/versions/1.0.0", nil)
DeleteTaskPluginVersion(context)
require.Contains(t, remove.Body.String(), `"success":true`)
assert.Equal(t, []model.ModelPricingIssue{stale("doc-1", key), stale("kling-retired-model", "kling"), stale("retired-model", key)}, readIssues())
}
func TestSyncTaskPluginsPublishesOneGenerationForWholeBatch(t *testing.T) {
setupTaskPluginControllerTest(t)
firstKey := "batch-sync-first"
+1
View File
@@ -150,6 +150,7 @@ var accessTokenRouteRules = map[string]accessTokenRouteRule{
"PUT /api/option/": accessTokenScopeRule("option:write"),
"PUT /api/option/passkey/domains": accessTokenScopeRule("option:write"),
"GET /api/option/model_pricing": accessTokenScopeRule("option:read"),
"GET /api/option/model_pricing/issues": accessTokenScopeRule("option:read"),
"PATCH /api/option/model_pricing": accessTokenScopeRule("option:write"),
"POST /api/option/model_pricing/convert": accessTokenScopeRule("option:read"),
"POST /api/option/model_pricing/preview": accessTokenScopeRule("option:read"),
+112
View File
@@ -344,6 +344,118 @@ func GetModelPricingSnapshot(names []string) (*ModelPricingSnapshot, error) {
return result, nil
}
// Reasons a plugin provider cannot charge a task model with the saved prices.
const (
ModelPricingIssueUnconfigured = "unconfigured"
ModelPricingIssueIncompatible = "incompatible"
ModelPricingIssueStale = "stale"
)
type ModelPricingIssue struct {
ModelName string `json:"model_name"`
PluginKey string `json:"plugin_key"`
PluginName string `json:"plugin_name"`
Reason string `json:"reason"`
}
// GetModelPricingIssues reads the provider variants of the pricing snapshot for
// every model a live plugin declares or a saved provider price names. A
// provider with neither an expression nor a per-call price is unconfigured, one
// whose expression reads usage its schema lacks is incompatible, and a saved
// provider price whose plugin is not installed or whose installed version no
// longer declares the model is stale. A plugin switched off keeps its prices
// for when it is switched back on. An empty pluginKey covers every plugin.
func GetModelPricingIssues(pluginKey string) ([]ModelPricingIssue, error) {
generation := jsplugin.DefaultRegistry.Generation()
names := make(map[string]bool)
for _, plugin := range generation.Plugins() {
if pluginKey == "" || plugin.Meta.Key == pluginKey {
for _, name := range plugin.Meta.Models {
names[name] = true
}
}
}
// Models of the installed versions of plugins with saved prices that are
// missing from the live generation, such as plugins switched off.
stopped := make(map[string][]string)
for key := range billing_setting.GetPluginBillingExprCopy() {
plugin, name, ok := billing_setting.SplitPluginBillingExprKey(key)
if !ok || (pluginKey != "" && plugin != pluginKey) {
continue
}
names[name] = true
if _, live := generation.Get(plugin); live {
continue
}
if _, read := stopped[plugin]; read {
continue
}
models, err := installedTaskPluginModels(plugin)
if err != nil {
return nil, err
}
stopped[plugin] = models
}
issues := make([]ModelPricingIssue, 0)
if len(names) == 0 {
return issues, nil
}
snapshot, err := GetModelPricingSnapshot(slices.Collect(maps.Keys(names)))
if err != nil {
return nil, err
}
for _, entry := range snapshot.Entries {
// A model in expression mode never falls back to its per-call price.
_, perCall := entry.Effective["ModelPrice"]
perCall = perCall && entry.Effective["billing_setting.billing_mode"] != billing_setting.BillingModeTieredExpr
for _, variant := range entry.PluginVariants {
if pluginKey != "" && variant.PluginKey != pluginKey {
continue
}
reason := ModelPricingIssueUnconfigured
switch {
case variant.Stale && slices.Contains(stopped[variant.PluginKey], entry.ModelName):
continue
case variant.Stale:
reason = ModelPricingIssueStale
case variant.Compatible:
continue
// fixed() marks ordinary channel pricing: the provider has no task price.
case variant.Effective != "" && !billingexpr.UsesFixedPricing(variant.Effective):
reason = ModelPricingIssueIncompatible
case perCall:
continue
}
issues = append(issues, ModelPricingIssue{ModelName: entry.ModelName, PluginKey: variant.PluginKey, PluginName: variant.PluginName, Reason: reason})
}
}
return issues, nil
}
// installedTaskPluginModels returns the models declared by the installed version
// of a plugin: its active override row, or else its built-in. A plugin that is
// not installed declares none, and neither does a stored source that no longer
// compiles.
func installedTaskPluginModels(key string) ([]string, error) {
row, err := GetTaskPluginVersion(key, "")
if err == nil {
loaded, compileErr := jsplugin.CompilePlugin(string(row.Source), jsplugin.Options{Key: row.Key, Version: row.Version})
if compileErr != nil {
return nil, nil
}
return loaded.Meta.Models, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
for _, meta := range jsplugin.DefaultRegistry.Snapshot().Factory {
if meta.Key == key {
return meta.Models, nil
}
}
return nil, nil
}
func ValidateModelPricing(name string, values PricingValues) error {
variants := make(map[string]any)
for key, expression := range billing_setting.GetPluginBillingExprCopy() {
+71
View File
@@ -2,6 +2,7 @@ package model
import (
"fmt"
"slices"
"strings"
"testing"
"time"
@@ -310,3 +311,73 @@ func TestPricingSharedPluginVariantsUseEachSchemaAndExpression(t *testing.T) {
require.NoError(t, err)
assert.Contains(t, string(encoded), "billing_plugin_variants")
}
// Prices saved while a plugin fit stop fitting when it changes: a dropped model
// leaves its provider price stale, and a new provider without the usage the
// model expression reads cannot charge it. Unpriced models are listed too,
// including those whose only expression prices ordinary channels.
func TestModelPricingIssuesFollowPluginChanges(t *testing.T) {
require.NoError(t, DB.AutoMigrate(&Option{}))
saved := config.GlobalConfig.ExportAllConfigs()
t.Cleanup(func() {
require.NoError(t, DB.Where(commonKeyCol+" IN ?", modelPricingOptionKeys).Delete(&Option{}).Error)
require.NoError(t, config.GlobalConfig.LoadFromDB(saved))
})
pluginSource := func(key, name, version, models, usageSchema string) string {
source := strings.ReplaceAll(pricingUsagePluginSource(version, usageSchema), "pricing-usage-probe", key)
source = strings.Replace(source, "Pricing Usage Probe", name, 1)
return strings.Replace(source, `["pricing-usage-model"]`, models, 1)
}
savePricing := func(options map[string]string) {
for key, value := range options {
require.NoError(t, DB.Save(&Option{Key: key, Value: value}).Error)
}
require.NoError(t, config.GlobalConfig.LoadFromDB(options))
}
const seconds = `{seconds:{type:"number",unit:"second"}}`
_, err := jsplugin.DefaultRegistry.Register(pluginSource("issue-alpha", "Alpha", "1.0.0", `["issue-priced","issue-per-call","issue-unpriced","issue-ordinary","issue-shared","issue-dropped"]`, seconds), jsplugin.Options{})
require.NoError(t, err)
t.Cleanup(func() { jsplugin.DefaultRegistry.Unregister("issue-alpha") })
savePricing(map[string]string{
"ModelPrice": `{"issue-per-call":0.3}`,
"billing_setting.billing_mode": `{"issue-priced":"tiered_expr","issue-ordinary":"tiered_expr","issue-shared":"tiered_expr"}`,
"billing_setting.billing_expr": `{"issue-priced":"u(\"seconds\") * 0.1","issue-ordinary":"tier(\"image\", fixed(0.02)) * image_count","issue-shared":"u(\"seconds\") * 0.2"}`,
billing_setting.PluginBillingExprOption: `{"issue-alpha::issue-dropped":"u(\"seconds\") * 0.5"}`,
})
unpriced := ModelPricingIssue{ModelName: "issue-unpriced", PluginKey: "issue-alpha", PluginName: "Alpha", Reason: ModelPricingIssueUnconfigured}
ordinary := ModelPricingIssue{ModelName: "issue-ordinary", PluginKey: "issue-alpha", PluginName: "Alpha", Reason: ModelPricingIssueUnconfigured}
// Other tests leave their plugins in the shared registry.
ownIssues := func() []ModelPricingIssue {
issues, err := GetModelPricingIssues("")
require.NoError(t, err)
return slices.DeleteFunc(issues, func(issue ModelPricingIssue) bool { return !strings.HasPrefix(issue.PluginKey, "issue-") })
}
assert.Equal(t, []ModelPricingIssue{ordinary, unpriced}, ownIssues())
_, err = jsplugin.DefaultRegistry.Register(pluginSource("issue-alpha", "Alpha", "1.1.0", `["issue-priced","issue-per-call","issue-unpriced","issue-ordinary","issue-shared"]`, seconds), jsplugin.Options{})
require.NoError(t, err)
_, err = jsplugin.DefaultRegistry.Register(pluginSource("issue-beta", "Beta", "1.0.0", `["issue-shared"]`, `{credits:{type:"number",unit:"credit"}}`), jsplugin.Options{})
require.NoError(t, err)
t.Cleanup(func() { jsplugin.DefaultRegistry.Unregister("issue-beta") })
incompatible := ModelPricingIssue{ModelName: "issue-shared", PluginKey: "issue-beta", PluginName: "Beta", Reason: ModelPricingIssueIncompatible}
assert.Equal(t, []ModelPricingIssue{
{ModelName: "issue-dropped", PluginKey: "issue-alpha", PluginName: "Alpha", Reason: ModelPricingIssueStale},
ordinary,
incompatible,
unpriced,
}, ownIssues())
issues, err := GetModelPricingIssues("issue-beta")
require.NoError(t, err)
assert.Equal(t, []ModelPricingIssue{incompatible}, issues)
// A provider price that reads the provider's own usage replaces the model
// expression for that provider only.
savePricing(map[string]string{
billing_setting.PluginBillingExprOption: `{"issue-alpha::issue-dropped":"u(\"seconds\") * 0.5","issue-beta::issue-shared":"u(\"credits\") * 2"}`,
})
issues, err = GetModelPricingIssues("issue-beta")
require.NoError(t, err)
assert.Empty(t, issues)
}
+1
View File
@@ -218,6 +218,7 @@ func SetApiRouter(router *gin.Engine) {
optionRoute.PUT("/", controller.UpdateOption)
optionRoute.PUT("/passkey/domains", controller.UpdatePasskeyDomains)
optionRoute.GET("/model_pricing", controller.GetModelPricingConfig)
optionRoute.GET("/model_pricing/issues", controller.GetModelPricingIssues)
optionRoute.PATCH("/model_pricing", controller.UpdateModelPricingConfig)
optionRoute.POST("/model_pricing/convert", controller.PreviewModelPricingConversion)
optionRoute.POST("/model_pricing/preview", controller.PreviewModelPricing)
@@ -37,7 +37,7 @@ import { getPolicySectionNavItems } from '@/features/system-settings/request-pol
import { getSecuritySectionNavItems } from '@/features/system-settings/security/section-registry.tsx'
import { getSiteSectionNavItems } from '@/features/system-settings/site/section-registry.tsx'
import type { NavGroup, SidebarView } from '../types'
import type { NavGroup, SidebarBadges, SidebarView } from '../types'
/**
* Sidebar nav groups for the System Settings nested view.
@@ -46,7 +46,10 @@ import type { NavGroup, SidebarView } from '../types'
* header already provides top-level context — the inner group label
* scopes the items as "administration" actions.
*/
function getSystemSettingsNavGroups(t: TFunction): NavGroup[] {
function getSystemSettingsNavGroups(
t: TFunction,
badges: SidebarBadges
): NavGroup[] {
return [
{
id: 'system-administration',
@@ -65,7 +68,10 @@ function getSystemSettingsNavGroups(t: TFunction): NavGroup[] {
{
title: t('Billing & Payment'),
icon: CreditCard,
items: getBillingSectionNavItems(t),
badge: badges.modelPricing,
items: getBillingSectionNavItems(t, {
'model-pricing': badges.modelPricing,
}),
},
{
title: t('Models'),
+12 -4
View File
@@ -16,8 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type LinkProps } from '@tanstack/react-router'
import { type TFunction } from 'i18next'
import type { LinkProps } from '@tanstack/react-router'
import type { TFunction } from 'i18next'
/**
* Base navigation item type
@@ -109,6 +109,14 @@ export type SidebarViewParent = {
label: string
}
/**
* Counts shown next to sidebar entries, already formatted for display
*/
export type SidebarBadges = {
/** Task models whose price needs attention, on the entries leading to model pricing */
modelPricing?: string
}
/**
* Nested sidebar view configuration
*
@@ -124,8 +132,8 @@ export type SidebarView = {
pathPattern: RegExp
/** Back-navigation descriptor; required for nested views */
parent: SidebarViewParent
/** Nav group builder, called per render with the active translator */
getNavGroups: (t: TFunction) => NavGroup[]
/** Nav group builder, called per render with the active translator and badges */
getNavGroups: (t: TFunction, badges: SidebarBadges) => NavGroup[]
}
/**
@@ -24,11 +24,15 @@ import {
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, expect, it, vi } from 'vitest'
import { api } from '@/lib/api'
import { ROLE } from '@/lib/roles'
import { useAuthStore } from '@/stores/auth-store'
import { ModelRatioVisualEditor } from '../model-ratio-visual-editor'
import type { ModelPricingIssue } from '../pricing-issues'
let client: QueryClient | undefined
@@ -37,19 +41,43 @@ afterEach(() => {
localStorage.clear()
window.getSelection()?.removeAllRanges()
vi.restoreAllMocks()
useAuthStore.getState().auth.reset()
})
async function renderEditor() {
type EditorFixture = {
issues?: ModelPricingIssue[]
taskModels?: string[]
billingMode?: string
billingExpr?: string
pluginBillingExpr?: string
}
async function renderEditor(fixture: EditorFixture = {}) {
vi.spyOn(api, 'get').mockImplementation(async (url) => {
if (url === '/api/pricing') {
return { data: { success: true, data: [], vendors: [] } }
const data = (fixture.taskModels ?? []).map((name) => ({
model_name: name,
billing_usage_schema: { seconds: { type: 'number', unit: 'second' } },
}))
return { data: { success: true, data, vendors: [] } }
}
if (url === '/api/option/model_pricing/issues') {
return { data: { success: true, data: fixture.issues ?? [] } }
}
return { data: { success: true, data: {} } }
})
if (fixture.issues) {
useAuthStore
.getState()
.auth.setUser({ id: 1, username: 'root', role: ROLE.SUPER_ADMIN })
}
const modelRatio = JSON.stringify({
'gpt-4.1-mini': 0.2,
'claude-sonnet': 1.5,
})
const billingMode = fixture.billingMode ?? '{}'
const billingExpr = fixture.billingExpr ?? '{}'
const pluginBillingExpr = fixture.pluginBillingExpr ?? '{}'
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
@@ -65,8 +93,9 @@ async function renderEditor() {
savedImageRatio='{}'
savedAudioRatio='{}'
savedAudioCompletionRatio='{}'
savedBillingMode='{}'
savedBillingExpr='{}'
savedBillingMode={billingMode}
savedBillingExpr={billingExpr}
savedPluginBillingExpr={pluginBillingExpr}
modelPrice='{}'
modelRatio={modelRatio}
cacheRatio='{}'
@@ -75,8 +104,9 @@ async function renderEditor() {
imageRatio='{}'
audioRatio='{}'
audioCompletionRatio='{}'
billingMode='{}'
billingExpr='{}'
billingMode={billingMode}
billingExpr={billingExpr}
pluginBillingExpr={pluginBillingExpr}
onChange={vi.fn()}
onSave={vi.fn()}
isSaving={false}
@@ -123,3 +153,88 @@ it('keeps other rows mounted when a different model is opened for editing', asyn
).toBeInTheDocument()
expect(otherName).toBeInTheDocument()
})
// kling-v3 was never priced, issue-shared's model expression reads usage its
// new provider lacks, and vidu1.5 keeps a provider price its plugin dropped.
const pricingIssueFixture: EditorFixture = {
taskModels: ['issue-shared'],
billingMode: JSON.stringify({ 'issue-shared': 'tiered_expr' }),
billingExpr: JSON.stringify({ 'issue-shared': 'u("seconds") * 0.2' }),
pluginBillingExpr: JSON.stringify({ 'vidu::vidu1.5': 'u("seconds") * 0.1' }),
issues: [
{
model_name: 'issue-shared',
plugin_key: 'beta',
plugin_name: 'Beta',
reason: 'incompatible',
},
{
model_name: 'kling-v3',
plugin_key: 'kling',
plugin_name: 'Kling',
reason: 'unconfigured',
},
{
model_name: 'vidu1.5',
plugin_key: 'vidu',
plugin_name: 'Vidu',
reason: 'stale',
},
],
}
it.each([
['issue-shared', 'Beta: The price uses usage the plugin no longer provides'],
['kling-v3', 'Kling: No price set'],
['vidu1.5', 'Vidu: The plugin no longer offers this model'],
])(
'marks %s as needing price attention with the reason instead of a configured price',
async (name, reason) => {
await renderEditor(pricingIssueFixture)
const row = await screen.findByRole('row', {
name: new RegExp(name.replace('.', '\\.')),
})
expect(within(row).getByText('Price needs attention')).toBeVisible()
expect(within(row).getByText(reason)).toBeVisible()
expect(within(row).queryByText('Task pricing')).not.toBeInTheDocument()
}
)
it('keeps the configured badges on models without pricing issues', async () => {
await renderEditor({ ...pricingIssueFixture, issues: [] })
const row = await screen.findByRole('row', { name: /issue-shared/ })
expect(within(row).getByText('Task pricing')).toBeVisible()
expect(
within(row).queryByText('Price needs attention')
).not.toBeInTheDocument()
expect(
screen.queryByRole('row', { name: /kling-v3/ })
).not.toBeInTheDocument()
})
it('filters the table down to the models whose price needs attention', async () => {
const user = userEvent.setup()
await renderEditor(pricingIssueFixture)
await screen.findByRole('row', { name: /kling-v3/ })
const filter = screen.getByRole('button', { name: /Price status/ })
await user.click(filter)
await user.click(
await screen.findByRole('option', { name: /Price needs attention/ })
)
await waitFor(() =>
expect(
screen.queryByRole('row', { name: /gpt-4\.1-mini/ })
).not.toBeInTheDocument()
)
for (const name of [/issue-shared/, /kling-v3/, /vidu1\.5/]) {
expect(screen.getByRole('row', { name })).toBeInTheDocument()
}
expect(
screen.queryByRole('row', { name: /claude-sonnet/ })
).not.toBeInTheDocument()
expect(within(filter).getByText('Price needs attention')).toBeInTheDocument()
})
@@ -30,8 +30,10 @@ import {
getPriceSummary,
type ModelRow,
} from './model-pricing-snapshots'
import { PRICING_ISSUE_REASONS, type ModelPricingIssue } from './pricing-issues'
export const TASK_PRICING_MODE_FILTER = 'tiered_expr_task'
export const PRICE_ATTENTION_FILTER = 'needs-attention'
const filterBySelectedValues = (
rowValue: unknown,
@@ -46,7 +48,9 @@ type BuildModelRatioColumnsOptions = {
onEdit: (model: ModelRow) => void
deleteDisabled?: boolean
taskModelNames?: Set<string>
t: (key: string) => string
/** Task model prices the gateway reports a plugin cannot charge, by model. */
pricingIssues?: Map<string, ModelPricingIssue[]>
t: (key: string, options?: Record<string, unknown>) => string
}
export function buildModelRatioColumns({
@@ -54,6 +58,7 @@ export function buildModelRatioColumns({
onEdit,
deleteDisabled,
taskModelNames,
pricingIssues,
t,
}: BuildModelRatioColumnsOptions): ColumnDef<ModelRow>[] {
return [
@@ -86,53 +91,75 @@ export function buildModelRatioColumns({
<DataTableColumnHeader column={column} title={t('Model name')} />
),
cell: ({ row }) => {
const issues = pricingIssues?.get(row.original.name)
const isTaskModel = Boolean(taskModelNames?.has(row.original.name))
const hasConfiguredTaskPricing =
row.original.billingMode === 'tiered_expr' &&
Boolean(row.original.billingExpr)
const showTaskPricingBadge = isTaskModel && hasConfiguredTaskPricing
// A price that needs attention must not look configured.
const showTaskPricingBadge =
!issues && isTaskModel && hasConfiguredTaskPricing
const showTieredBadge =
row.original.billingMode === 'tiered_expr' && !isTaskModel
const showUnconfiguredTaskBadge = isTaskModel && !hasConfiguredTaskPricing
!issues && row.original.billingMode === 'tiered_expr' && !isTaskModel
const issueText = issues
?.map((issue) =>
t('{{name}}: {{reason}}', {
name: issue.plugin_name,
reason: t(PRICING_ISSUE_REASONS[issue.reason]),
})
)
.join(' · ')
return (
<div className='flex min-w-0 items-center gap-2 font-medium'>
<span className='min-w-0 truncate'>{row.getValue('name')}</span>
{showTieredBadge ? (
<StatusBadge
label={t('Tiered')}
variant='info'
copyable={false}
className='shrink-0'
/>
) : null}
{showTaskPricingBadge ? (
<StatusBadge
label={t('Task pricing')}
variant='info'
copyable={false}
className='shrink-0'
/>
) : null}
{row.original.hasConflict && (
<StatusBadge
label={t('Conflict')}
variant='danger'
copyable={false}
className='shrink-0'
/>
)}
{showUnconfiguredTaskBadge ? (
<StatusBadge
label={t('Task pricing not configured')}
variant='warning'
copyable={false}
className='shrink-0'
/>
<div className='flex min-w-0 flex-col gap-0.5'>
<div className='flex min-w-0 items-center gap-2 font-medium'>
<span className='min-w-0 truncate'>{row.getValue('name')}</span>
{showTieredBadge ? (
<StatusBadge
label={t('Tiered')}
variant='info'
copyable={false}
className='shrink-0'
/>
) : null}
{showTaskPricingBadge ? (
<StatusBadge
label={t('Task pricing')}
variant='info'
copyable={false}
className='shrink-0'
/>
) : null}
{row.original.hasConflict && (
<StatusBadge
label={t('Conflict')}
variant='danger'
copyable={false}
className='shrink-0'
/>
)}
{issues ? (
<StatusBadge
label={t('Price needs attention')}
variant='warning'
copyable={false}
className='shrink-0'
/>
) : null}
</div>
{issueText ? (
<span
className='text-muted-foreground truncate text-xs'
title={issueText}
>
{issueText}
</span>
) : null}
</div>
)
},
// The only option is PRICE_ATTENTION_FILTER.
filterFn: (row) => Boolean(pricingIssues?.has(row.original.name)),
enableHiding: false,
},
{
@@ -151,7 +178,10 @@ export function buildModelRatioColumns({
),
filterFn: (row, id, value) => {
if (filterBySelectedValues(row.getValue(id), value)) return true
if (!Array.isArray(value) || !value.includes(TASK_PRICING_MODE_FILTER)) {
if (
!Array.isArray(value) ||
!value.includes(TASK_PRICING_MODE_FILTER)
) {
return false
}
return (
@@ -72,8 +72,10 @@ import {
} from './model-pricing-snapshots'
import {
buildModelRatioColumns,
PRICE_ATTENTION_FILTER,
TASK_PRICING_MODE_FILTER,
} from './model-ratio-table-columns'
import { type ModelPricingIssue, useModelPricingIssues } from './pricing-issues'
type ModelRatioVisualEditorProps = {
savedModelPrice: string
@@ -158,6 +160,7 @@ const ModelRatioVisualEditorComponent = forwardRef<
editData?.name ? [editData.name] : [],
Boolean(editData?.name)
)
const pricingIssuesQuery = useModelPricingIssues()
const [sorting, setSorting] = useState<SortingState>([])
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])
const [globalFilter, setGlobalFilter] = useState('')
@@ -227,6 +230,17 @@ const ModelRatioVisualEditorComponent = forwardRef<
[pricingModels]
)
const pricingIssues = useMemo(() => {
const byModel = new Map<string, ModelPricingIssue[]>()
for (const issue of pricingIssuesQuery.data ?? []) {
byModel.set(issue.model_name, [
...(byModel.get(issue.model_name) ?? []),
issue,
])
}
return byModel
}, [pricingIssuesQuery.data])
const models = useMemo(() => {
const savedRows = buildModelSnapshots({
modelPrice: savedModelPrice,
@@ -257,10 +271,16 @@ const ModelRatioVisualEditorComponent = forwardRef<
const savedByName = new Map(savedRows.map((row) => [row.name, row]))
const draftByName = new Map(draftRows.map((row) => [row.name, row]))
// A plugin model that was never priced has no saved row; list it so its
// pricing issue can be seen and fixed here.
const modelNames =
filterMode === 'unset'
? new Set(candidateModelNames ?? [])
: new Set([...savedByName.keys(), ...draftByName.keys()])
: new Set([
...savedByName.keys(),
...draftByName.keys(),
...pricingIssues.keys(),
])
return [...modelNames]
.map((name) => {
@@ -286,6 +306,7 @@ const ModelRatioVisualEditorComponent = forwardRef<
}, [
candidateModelNames,
filterMode,
pricingIssues,
savedModelPrice,
savedModelRatio,
savedCacheRatio,
@@ -334,6 +355,10 @@ const ModelRatioVisualEditorComponent = forwardRef<
}
return counts
}, [models, taskModelNames])
const attentionCount = useMemo(
() => models.filter((model) => pricingIssues.has(model.name)).length,
[models, pricingIssues]
)
const handleEdit = useCallback(
(model: ModelRow) => {
@@ -502,9 +527,10 @@ const ModelRatioVisualEditorComponent = forwardRef<
onEdit: handleEdit,
deleteDisabled: filterMode === 'unset',
taskModelNames,
pricingIssues,
t,
}),
[handleEdit, handleDelete, filterMode, t, taskModelNames]
[handleEdit, handleDelete, filterMode, t, taskModelNames, pricingIssues]
)
const ensurePageInRange = useCallback((pageCount: number) => {
@@ -631,6 +657,8 @@ const ModelRatioVisualEditorComponent = forwardRef<
let emptyStateText = t('No models configured. Use Add model to get started.')
if (table.getState().globalFilter) {
emptyStateText = t('No models match your search')
} else if (table.getState().columnFilters.length > 0) {
emptyStateText = t('No models match the selected filters')
} else if (filterMode === 'unset') {
emptyStateText = candidateModelsLoading
? t('Loading...')
@@ -676,6 +704,17 @@ const ModelRatioVisualEditorComponent = forwardRef<
},
],
},
{
columnId: 'name',
title: t('Price status'),
options: [
{
label: 'Price needs attention',
value: PRICE_ATTENTION_FILTER,
count: attentionCount,
},
],
},
]}
preActions={
filterMode === 'unset' ? undefined : (
@@ -0,0 +1,84 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useQuery } from '@tanstack/react-query'
import { t } from 'i18next'
import { useTranslation } from 'react-i18next'
import { useCanEditModelPricing } from '@/features/model-pricing/api'
import { toIntlLocale } from '@/i18n/languages'
import { api } from '@/lib/api'
import { formatNumber } from '@/lib/format'
import { createServerError } from '@/lib/server-error-message'
/** A task model price one plugin provider cannot charge, as the gateway reports it. */
export type ModelPricingIssue = {
model_name: string
plugin_key: string
plugin_name: string
reason: 'unconfigured' | 'incompatible' | 'stale'
}
/** Plain-language reason labels; the values are i18n keys. */
export const PRICING_ISSUE_REASONS: Record<
ModelPricingIssue['reason'],
string
> = {
unconfigured: 'No price set',
incompatible: 'The price uses usage the plugin no longer provides',
stale: 'The plugin no longer offers this model',
}
/**
* Kept under the model pricing config key, so every pricing save that
* invalidates that key also refreshes the issues.
*/
export const MODEL_PRICING_ISSUES_QUERY_KEY = [
'model-pricing-config',
{ issues: true },
] as const
export async function getModelPricingIssues(): Promise<ModelPricingIssue[]> {
const res = await api.get('/api/option/model_pricing/issues')
if (!res.data.success) {
throw createServerError(res.data, t('Failed to load model pricing'))
}
return res.data.data ?? []
}
export function useModelPricingIssues() {
const canEdit = useCanEditModelPricing()
return useQuery({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
queryFn: getModelPricingIssues,
enabled: canEdit,
meta: { errorToast: false },
})
}
/** The number of task models whose price needs attention, for nav badges. */
export function useModelPricingIssueBadge(): string | undefined {
const { i18n } = useTranslation()
const issues = useModelPricingIssues().data ?? []
const count = new Set(issues.map((issue) => issue.model_name)).size
if (count === 0) return undefined
return formatNumber(
count,
toIntlLocale(i18n.resolvedLanguage || i18n.language)
)
}
@@ -61,15 +61,19 @@ export function createSectionRegistry<
]
/**
* Get navigation items for sidebar
* Get navigation items for sidebar, with an optional badge per section
*/
function getSectionNavItems(t: TFunction) {
function getSectionNavItems(
t: TFunction,
badges?: Partial<Record<SectionId, string>>
) {
return sections.map((section) => ({
title: t(section.titleKey),
url:
urlStyle === 'path'
? `${basePath}/${section.id}`
: `${basePath}?section=${section.id}`,
badge: badges?.[section.id as SectionId],
}))
}
@@ -25,6 +25,7 @@ import {
} from '@tanstack/react-query'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Toaster } from 'sonner'
import { afterEach, expect, test, vi } from 'vitest'
import {
@@ -437,6 +438,39 @@ test('selecting a historical version installs its source and hash', async () =>
})
})
test('an install that needs activation reports what the activated version cannot charge', async () => {
const user = userEvent.setup()
vi.stubGlobal('crypto', webcrypto)
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response(source))
)
api.installMarketplacePlugin.mockResolvedValue({
meta: { key: 'demo', name: 'Demo', version: '1.1' },
plugin: { active: false },
})
api.activateTaskPlugin.mockResolvedValue({
pricing_issues: [
{
model_name: 'demo-video',
plugin_key: 'demo',
plugin_name: 'Demo',
reason: 'unconfigured',
},
],
})
renderDialog()
render(<Toaster />)
const install = screen.getByRole('button', { name: 'Install and enable' })
await waitFor(() => expect(install).toBeEnabled())
await user.click(install)
expect(api.activateTaskPlugin).toHaveBeenCalledWith('demo', '1.1')
expect(await screen.findByText('Installed Demo v1.1')).toBeVisible()
expect(screen.getByText('demo-video: No price set')).toBeVisible()
})
test('a single published version remains visible and cannot be changed', () => {
vi.stubGlobal(
'fetch',
@@ -20,6 +20,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { Toaster } from 'sonner'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { api } from '@/lib/api'
@@ -29,6 +30,7 @@ import type {
TaskPluginDetail,
TaskPluginListItem,
TaskPluginMeta,
TaskPluginRecord,
} from '../types'
const queryClients: QueryClient[] = []
@@ -446,6 +448,61 @@ test('keeps header and navigation outside the scrolling content with long metada
)
})
test('activating a version lists the models it cannot charge', async () => {
const user = userEvent.setup()
const fixture = renderSheet({})
const version = (number: string, active: boolean): TaskPluginRecord => ({
id: active ? 2 : 1,
key: 'kling',
api_version: 1,
version: number,
source: '',
source_hash: number,
enabled: true,
active,
created_at: active ? 2 : 1,
remark: '',
})
const versions = [version('1.2.3', true), version('1.0.0', false)]
fixture.queryClient.setQueryData(['task-plugin-versions', 'kling'], versions)
vi.spyOn(api, 'get').mockImplementation(async (url) => ({
data: {
success: true,
data: url.endsWith('/versions') ? versions : fixture.detail,
},
}))
const post = vi.spyOn(api, 'post').mockResolvedValue({
data: {
success: true,
data: {
pricing_issues: [
{
model_name: 'kling-v1',
plugin_key: 'kling',
plugin_name: 'Kling',
reason: 'unconfigured',
},
],
},
},
})
render(<Toaster />)
await user.click(screen.getByRole('tab', { name: 'Version history' }))
const row = screen.getByRole('row', { name: /1\.0\.0/ })
await user.click(
within(row).getByRole('button', { name: 'Activate / Roll back' })
)
expect(post).toHaveBeenCalledWith(
'/api/plugin/task/kling/activate',
{ version: '1.0.0' },
expect.any(Object)
)
expect(await screen.findByText('Plugin version activated')).toBeVisible()
expect(screen.getByText('kling-v1: No price set')).toBeVisible()
})
test('version loading and failure allow retry without hiding the overview', async () => {
const user = userEvent.setup()
const fixture = renderSheet({})
@@ -19,8 +19,13 @@ For commercial licensing, please contact support@quantumnous.com
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Toaster } from 'sonner'
import { afterEach, expect, test, vi } from 'vitest'
import {
MODEL_PRICING_ISSUES_QUERY_KEY,
type ModelPricingIssue,
} from '@/features/system-settings/models/pricing-issues'
import { api } from '@/lib/api'
import { PluginsTable } from '../components/plugins-table'
@@ -283,3 +288,99 @@ test.each(['factory', 'override_over_factory'] as const)(
}
}
)
function pricingIssue(
modelName: string,
reason: ModelPricingIssue['reason'] = 'unconfigured'
): ModelPricingIssue {
return {
model_name: modelName,
plugin_key: 'example',
plugin_name: 'Example',
reason,
}
}
test('switching a plugin on lists the models it cannot charge and refreshes the pricing count', async () => {
const user = userEvent.setup()
vi.spyOn(api, 'post').mockResolvedValue({
data: {
success: true,
data: {
plugin_enabled: true,
pricing_issues: [pricingIssue('example-v3')],
},
},
})
const toggle = renderPlugins(false, 'table')
render(<Toaster />)
const [client] = clients
client.setQueryData(MODEL_PRICING_ISSUES_QUERY_KEY, [])
await user.click(toggle)
await user.click(
within(
await screen.findByRole('alertdialog', { name: 'Enable plugin?' })
).getByRole('button', { name: 'Enable' })
)
expect(await screen.findByText('Plugin enabled')).toBeVisible()
expect(screen.getByText('example-v3: No price set')).toBeVisible()
expect(
client.getQueryState(MODEL_PRICING_ISSUES_QUERY_KEY)?.isInvalidated
).toBe(true)
})
test('deleting the active custom version lists what the version taking over cannot charge', async () => {
const user = userEvent.setup()
const remove = vi.spyOn(api, 'delete').mockResolvedValue({
data: {
success: true,
data: { pricing_issues: [pricingIssue('example-old', 'stale')] },
},
})
renderPlugins(true, 'table', 'override_over_factory')
render(<Toaster />)
await user.click(screen.getAllByRole('button', { name: 'Open menu' })[0])
await user.click(
screen.getByRole('menuitem', { name: 'Delete active custom version' })
)
await user.click(
within(
await screen.findByRole('alertdialog', { name: 'Delete plugin version?' })
).getByRole('button', { name: 'Delete' })
)
expect(remove).toHaveBeenCalledWith(
'/api/plugin/task/example/versions/1.0.0',
expect.any(Object)
)
expect(await screen.findByText('Plugin version deleted')).toBeVisible()
expect(
screen.getByText('example-old: The plugin no longer offers this model')
).toBeVisible()
})
test('a long pricing notice names five models and counts the rest', async () => {
const user = userEvent.setup()
const issues = Array.from({ length: 7 }, (_, index) =>
pricingIssue(`example-m${index + 1}`)
)
vi.spyOn(api, 'post').mockResolvedValue({
data: { success: true, data: { pricing_issues: issues } },
})
const toggle = renderPlugins(false, 'table')
render(<Toaster />)
await user.click(toggle)
await user.click(
within(
await screen.findByRole('alertdialog', { name: 'Enable plugin?' })
).getByRole('button', { name: 'Enable' })
)
expect(await screen.findByText('And 2 more models')).toBeVisible()
expect(screen.getByText('example-m5: No price set')).toBeVisible()
expect(screen.queryByText('example-m6: No price set')).not.toBeInTheDocument()
})
@@ -21,6 +21,11 @@ import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, test, vi } from 'vitest'
import {
MODEL_PRICING_ISSUES_QUERY_KEY,
type ModelPricingIssue,
} from '@/features/system-settings/models/pricing-issues'
import { UploadDialog } from '../components/upload-dialog'
import { MAX_PLUGIN_SOURCE_BYTES } from '../lib/plugin-url'
import type { TaskPluginDetail } from '../types'
@@ -381,6 +386,61 @@ describe('UploadDialog upload lifecycle', () => {
expect(activateTaskPlugin).not.toHaveBeenCalled()
})
test('lists the models it cannot charge once the uploaded version serves', async () => {
const user = userEvent.setup()
const issue: ModelPricingIssue = {
model_name: 'demo-video',
plugin_key: 'demo',
plugin_name: 'Demo',
reason: 'unconfigured',
}
uploadTaskPlugin.mockResolvedValue({
...savedPlugin(true),
pricing_issues: [issue],
})
const { queryClient } = renderDialog()
queryClient.setQueryData(MODEL_PRICING_ISSUES_QUERY_KEY, [])
await uploadSource(user)
expect(
await screen.findByText('Prices of these models need attention:')
).toBeVisible()
expect(screen.getByText('demo-video: No price set')).toBeVisible()
expect(
queryClient.getQueryState(MODEL_PRICING_ISSUES_QUERY_KEY)?.isInvalidated
).toBe(true)
})
test('lists what the activation reports after saving an inactive version', async () => {
const user = userEvent.setup()
uploadTaskPlugin.mockResolvedValue(savedPlugin(false))
activateTaskPlugin.mockResolvedValue({
pricing_issues: [
{
model_name: 'demo-old',
plugin_key: 'demo',
plugin_name: 'Demo',
reason: 'stale',
},
],
})
renderDialog()
await uploadSource(user)
await screen.findByText('Plugin saved, activation required')
expect(
screen.queryByText('Prices of these models need attention:')
).not.toBeInTheDocument()
await user.click(footerButton('Activate now'))
expect(
await screen.findByText(
'demo-old: The plugin no longer offers this model'
)
).toBeVisible()
})
test('disables Upload while the source is empty and shows a pending label', async () => {
const user = userEvent.setup()
let resolveUpload: (value: unknown) => void = () => undefined
+7 -6
View File
@@ -24,6 +24,7 @@ import type {
MarketplaceSource,
TaskPluginDetail,
TaskPluginListItem,
TaskPluginPricingNotice,
TaskPluginRecord,
TaskPluginUsage,
TaskPluginDryRunRequest,
@@ -147,12 +148,12 @@ export async function updateMarketplaceSources(sources: MarketplaceSource[]) {
}
export async function activateTaskPlugin(key: string, version: string) {
const response = await api.post<ApiResponse<null>>(
const response = await api.post<ApiResponse<TaskPluginPricingNotice>>(
`/api/plugin/task/${encodeURIComponent(key)}/activate`,
{ version },
mutationConfig
)
requireSuccess(response.data)
return requireSuccess(response.data)
}
export async function setTaskPluginStatus(
@@ -160,12 +161,12 @@ export async function setTaskPluginStatus(
enabled: boolean,
options?: { cascade?: boolean; force?: boolean }
) {
const response = await api.post<ApiResponse<null>>(
const response = await api.post<ApiResponse<TaskPluginPricingNotice>>(
`/api/plugin/task/${encodeURIComponent(key)}/status`,
{ enabled },
{ ...mutationConfig, params: options }
)
requireSuccess(response.data)
return requireSuccess(response.data)
}
export async function deleteTaskPluginVersion(
@@ -173,11 +174,11 @@ export async function deleteTaskPluginVersion(
version: string,
force = false
) {
const response = await api.delete<ApiResponse<null>>(
const response = await api.delete<ApiResponse<TaskPluginPricingNotice>>(
`/api/plugin/task/${encodeURIComponent(key)}/versions/${encodeURIComponent(version)}`,
{ ...mutationConfig, params: force ? { force: true } : undefined }
)
requireSuccess(response.data)
return requireSuccess(response.data)
}
export async function getTaskPluginEnabledOption() {
@@ -20,7 +20,6 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { AlertTriangle, Download } from 'lucide-react'
import { lazy, Suspense, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Dialog } from '@/components/dialog'
import { LoadingState } from '@/components/loading-state'
@@ -29,6 +28,7 @@ import { Button } from '@/components/ui/button'
import { Combobox } from '@/components/ui/combobox'
import { Spinner } from '@/components/ui/spinner'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { MODEL_PRICING_ISSUES_QUERY_KEY } from '@/features/system-settings/models/pricing-issues'
import {
activateTaskPlugin,
@@ -40,6 +40,7 @@ import {
resolvePluginSourceUrl,
type InstallState,
} from '../lib/marketplace'
import { toastPluginChange } from '../lib/plugin-change-toast'
import { fetchPluginIconDataUri } from '../lib/plugin-icon-file'
import {
computeSourceSha256,
@@ -161,7 +162,11 @@ function MarketplaceInstallContent(
icon: sourceQuery.data.icon ?? undefined,
})
if (detail.plugin && !detail.plugin.active) {
await activateTaskPlugin(detail.meta.key, detail.meta.version)
const notice = await activateTaskPlugin(
detail.meta.key,
detail.meta.version
)
return { ...detail, pricing_issues: notice?.pricing_issues ?? [] }
}
return detail
},
@@ -171,13 +176,17 @@ function MarketplaceInstallContent(
queryClient.invalidateQueries({
queryKey: ['task-plugin-versions', pluginKey],
})
queryClient.invalidateQueries({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
})
},
onSuccess: (detail) => {
toast.success(
toastPluginChange(
t('Installed {{name}} v{{version}}', {
name: detail.meta.name,
version: detail.meta.version,
})
}),
detail.pricing_issues
)
props.onOpenChange(false)
},
@@ -2,7 +2,6 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { RotateCcw, X } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { CopyButton } from '@/components/copy-button'
import { EmptyState } from '@/components/empty-state'
@@ -46,6 +45,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MODEL_PRICING_ISSUES_QUERY_KEY } from '@/features/system-settings/models/pricing-issues'
import { handleServerError } from '@/lib/handle-server-error'
import { resolveLocalizedText } from '@/lib/localized-text'
@@ -54,6 +54,7 @@ import {
getTaskPlugin,
getTaskPluginVersions,
} from '../api'
import { toastPluginChange } from '../lib/plugin-change-toast'
import type { TaskPluginListItem } from '../types'
import { JavaScriptViewer } from './javascript-viewer'
import { PluginIcon } from './plugin-icon'
@@ -105,12 +106,15 @@ function PluginDetailContent(props: { plugin: TaskPluginListItem }) {
})
const activateMutation = useMutation({
mutationFn: (version: string) => activateTaskPlugin(key, version),
onSuccess: () => {
onSuccess: (notice) => {
setCompareVersion('')
toast.success(t('Plugin version activated'))
toastPluginChange(t('Plugin version activated'), notice?.pricing_issues)
queryClient.invalidateQueries({ queryKey: ['task-plugins'] })
queryClient.invalidateQueries({ queryKey: ['task-plugin', key] })
queryClient.invalidateQueries({ queryKey: ['task-plugin-versions', key] })
queryClient.invalidateQueries({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
})
},
onError: (error) => handleServerError(error),
})
@@ -21,7 +21,6 @@ import type { ColumnDef, ColumnFiltersState } from '@tanstack/react-table'
import { Eye, MoreHorizontal, Trash2, Upload } from 'lucide-react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { DataTablePage, useDataTable } from '@/components/data-table'
@@ -35,6 +34,7 @@ import {
} from '@/components/ui/dropdown-menu'
import { Switch } from '@/components/ui/switch'
import { getChannelTypeLabel } from '@/features/channels/lib'
import { MODEL_PRICING_ISSUES_QUERY_KEY } from '@/features/system-settings/models/pricing-issues'
import { handleServerError } from '@/lib/handle-server-error'
import { resolveLocalizedText } from '@/lib/localized-text'
@@ -45,6 +45,7 @@ import {
TaskPluginUsageError,
} from '../api'
import { isStaleFactoryOverride } from '../lib/marketplace'
import { toastPluginChange } from '../lib/plugin-change-toast'
import type { TaskPluginListItem, TaskPluginUsage } from '../types'
import { PluginCard } from './plugin-card'
import { PluginIcon } from './plugin-icon'
@@ -88,8 +89,14 @@ export function PluginsTable(props: PluginsTableProps) {
enabled: boolean
options?: { cascade?: boolean; force?: boolean }
}) => setTaskPluginStatus(key, enabled, options),
onSuccess: () => {
onSuccess: (notice, variables) => {
queryClient.invalidateQueries({ queryKey: ['task-plugins'] })
queryClient.invalidateQueries({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
})
if (variables.enabled && notice?.pricing_issues?.length) {
toastPluginChange(t('Plugin enabled'), notice.pricing_issues)
}
setStatusConfirmation(null)
setStatusTarget(null)
setBlockedAction(null)
@@ -113,12 +120,15 @@ export function PluginsTable(props: PluginsTableProps) {
plugin: TaskPluginListItem
force?: boolean
}) => deleteTaskPluginVersion(plugin.meta.key, plugin.meta.version, force),
onSuccess: () => {
onSuccess: (notice) => {
setDeleteTarget(null)
setBlockedAction(null)
setBlockedUsage(null)
toast.success(t('Plugin version deleted'))
toastPluginChange(t('Plugin version deleted'), notice?.pricing_issues)
queryClient.invalidateQueries({ queryKey: ['task-plugins'] })
queryClient.invalidateQueries({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
})
},
onError: (error) => {
if (error instanceof TaskPluginUsageError) {
@@ -0,0 +1,53 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useTranslation } from 'react-i18next'
import {
PRICING_ISSUE_REASONS,
type ModelPricingIssue,
} from '@/features/system-settings/models/pricing-issues'
/** A plugin reports one issue per model; a long catalog stays readable. */
const VISIBLE_ISSUES = 5
type PricingIssueListProps = {
issues: ModelPricingIssue[]
}
/** The models whose price a plugin change left without a usable price. */
export function PricingIssueList(props: PricingIssueListProps) {
const { t } = useTranslation()
const hidden = props.issues.length - VISIBLE_ISSUES
return (
<div className='flex flex-col gap-0.5'>
<p>{t('Prices of these models need attention:')}</p>
<ul>
{props.issues.slice(0, VISIBLE_ISSUES).map((issue) => (
<li key={`${issue.model_name}:${issue.plugin_key}`}>
{t('{{name}}: {{reason}}', {
name: issue.model_name,
reason: t(PRICING_ISSUE_REASONS[issue.reason]),
})}
</li>
))}
</ul>
{hidden > 0 && <p>{t('And {{count}} more models', { count: hidden })}</p>}
</div>
)
}
@@ -35,6 +35,7 @@ import {
} from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Spinner } from '@/components/ui/spinner'
import { MODEL_PRICING_ISSUES_QUERY_KEY } from '@/features/system-settings/models/pricing-issues'
import { activateTaskPlugin, uploadTaskPlugin } from '../api'
import {
@@ -50,6 +51,7 @@ import { MarketplaceCapabilities } from './marketplace-capabilities'
import { PluginIcon } from './plugin-icon'
import { PluginSourcePicker } from './plugin-source-picker'
import { PluginUrlImportField } from './plugin-url-import-field'
import { PricingIssueList } from './pricing-issue-list'
type UploadDialogProps = {
open: boolean
@@ -83,6 +85,9 @@ export function UploadDialog(props: UploadDialogProps) {
queryClient.invalidateQueries({
queryKey: ['task-plugin-versions', data.meta.key],
})
queryClient.invalidateQueries({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
})
toast.success(
data.plugin?.active === false
? t('Plugin saved, activation required')
@@ -101,6 +106,9 @@ export function UploadDialog(props: UploadDialogProps) {
queryClient.invalidateQueries({
queryKey: ['task-plugin-versions', detail.meta.key],
})
queryClient.invalidateQueries({
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
})
toast.success(t('Plugin version activated'))
},
})
@@ -162,6 +170,9 @@ export function UploadDialog(props: UploadDialogProps) {
if (result) {
const needsActivation =
result.plugin?.active === false && !activateMutation.isSuccess
const pricingIssues = activateMutation.isSuccess
? activateMutation.data?.pricing_issues
: result.pricing_issues
return (
<Dialog
@@ -220,6 +231,11 @@ export function UploadDialog(props: UploadDialogProps) {
</AlertDescription>
)}
</Alert>
{pricingIssues?.length ? (
<div className='text-muted-foreground text-sm'>
<PricingIssueList issues={pricingIssues} />
</div>
) : null}
{activateMutation.error && (
<Alert variant='destructive'>
<AlertTriangle aria-hidden='true' />
@@ -0,0 +1,38 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { toast } from 'sonner'
import type { ModelPricingIssue } from '@/features/system-settings/models/pricing-issues'
import { PricingIssueList } from '../components/pricing-issue-list'
/**
* Confirms a plugin change. When the serving plugin cannot charge some of its
* models, the toast lists them instead of reporting plain success.
*/
export function toastPluginChange(
title: string,
issues: ModelPricingIssue[] | null | undefined
) {
if (!issues?.length) {
toast.success(title)
return
}
toast.warning(title, { description: <PricingIssueList issues={issues} /> })
}
+11
View File
@@ -20,6 +20,7 @@ import type {
BillingUsageSchema,
BillingUsageExample,
} from '@/features/pricing/types'
import type { ModelPricingIssue } from '@/features/system-settings/models/pricing-issues'
export type TaskPluginProtocolClaim =
| string
@@ -112,8 +113,18 @@ export type TaskPluginDetail = {
source: string
layer: 'factory' | 'override'
has_icon?: boolean
/** Set when the upload put this version into service. */
pricing_issues?: ModelPricingIssue[]
}
/**
* Answer of an activation, a switch-on or the deletion of the active version:
* the prices the plugin now serving the key cannot charge.
*/
export type TaskPluginPricingNotice = {
pricing_issues?: ModelPricingIssue[] | null
} | null
export type ApiResponse<T> = {
success: boolean
message: string
+141 -1
View File
@@ -17,19 +17,40 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, renderHook } from '@testing-library/react'
import {
createMemoryHistory,
createRootRoute,
createRouter,
RouterProvider,
} from '@tanstack/react-router'
import {
act,
cleanup,
render,
renderHook,
screen,
waitFor,
} from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { checkIsActive } from '@/components/layout/lib/url-utils'
import { invalidateModelPricing } from '@/features/model-pricing/api'
import {
parseSidebarModulesAdmin,
serializeSidebarModulesAdmin,
} from '@/features/system-settings/maintenance/config'
import {
MODEL_PRICING_ISSUES_QUERY_KEY,
type ModelPricingIssue,
} from '@/features/system-settings/models/pricing-issues'
import { api } from '@/lib/api'
import { ROLE } from '@/lib/roles'
import { useAuthStore } from '@/stores/auth-store'
import { useSidebarConfig } from '../use-sidebar-config'
import { useSidebarData } from '../use-sidebar-data'
import { useSidebarView } from '../use-sidebar-view'
beforeEach(() => {
vi.stubGlobal('localStorage', {
@@ -180,3 +201,122 @@ describe('audit log sidebar entry', () => {
expect(titles).toContain('Audit Logs')
})
})
describe('model pricing badge', () => {
function issue(modelName: string, pluginKey: string): ModelPricingIssue {
return {
model_name: modelName,
plugin_key: pluginKey,
plugin_name: pluginKey,
reason: 'unconfigured',
}
}
/** Lists the sidebar entries of the current view that carry a badge. */
function BadgedEntries() {
const { navGroups } = useSidebarView()
const entries = navGroups
.flatMap((group) => group.items)
.flatMap((item) => [item, ...(item.items ?? [])])
.filter((item) => item.badge)
return (
<ul aria-label='Badged entries'>
{entries.map((item) => (
<li key={item.title}>{`${item.title}: ${item.badge}`}</li>
))}
</ul>
)
}
async function renderSidebar(
path: string,
role: number,
issues: () => ModelPricingIssue[]
) {
const get = vi.spyOn(api, 'get').mockImplementation(async (url) => ({
data: {
success: true,
data: url === '/api/option/model_pricing/issues' ? issues() : {},
},
}))
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
client.setQueryData(['status'], { SidebarModulesAdmin: '' })
useAuthStore.getState().auth.setUser({ id: 1, username: 'root', role })
const router = createRouter({
routeTree: createRootRoute({ component: BadgedEntries }),
history: createMemoryHistory({ initialEntries: [path] }),
})
await router.load()
render(
<QueryClientProvider client={client}>
<RouterProvider router={router} />
</QueryClientProvider>
)
return { client, get }
}
function badgedEntries() {
return screen
.getByRole('list', { name: 'Badged entries' })
.querySelectorAll('li')
}
it('counts each task model once on the System Settings entry of the main sidebar', async () => {
await renderSidebar('/dashboard/overview', ROLE.SUPER_ADMIN, () => [
issue('kling-v3', 'kling'),
issue('shared-video', 'alpha'),
issue('shared-video', 'beta'),
])
expect(await screen.findByText('System Settings: 2')).toBeInTheDocument()
expect(badgedEntries()).toHaveLength(1)
})
it('inside System Settings shows the count on Billing & Payment and Model Pricing', async () => {
await renderSidebar('/system-settings/site', ROLE.SUPER_ADMIN, () => [
issue('kling-v3', 'kling'),
])
expect(await screen.findByText('Model Pricing: 1')).toBeInTheDocument()
expect(screen.getByText('Billing & Payment: 1')).toBeInTheDocument()
expect(badgedEntries()).toHaveLength(2)
})
it('follows plugin changes and saved prices without a page reload', async () => {
let issues = [issue('kling-v3', 'kling')]
const { client } = await renderSidebar(
'/dashboard/overview',
ROLE.SUPER_ADMIN,
() => issues
)
await screen.findByText('System Settings: 1')
// A plugin action refreshes the count it may have changed.
issues = [issue('kling-v3', 'kling'), issue('vidu-q3', 'vidu')]
await act(() =>
client.invalidateQueries({ queryKey: MODEL_PRICING_ISSUES_QUERY_KEY })
)
expect(await screen.findByText('System Settings: 2')).toBeInTheDocument()
// Every pricing save runs this invalidation.
issues = []
await act(() => invalidateModelPricing(client))
await waitFor(() => expect(badgedEntries()).toHaveLength(0))
})
it('never asks for the count below the super administrator role', async () => {
const { get } = await renderSidebar(
'/dashboard/overview',
ROLE.ADMIN,
() => [issue('kling-v3', 'kling')]
)
expect(
await screen.findByRole('list', { name: 'Badged entries' })
).toBeInTheDocument()
expect(get).not.toHaveBeenCalledWith('/api/option/model_pricing/issues')
expect(badgedEntries()).toHaveLength(0)
})
})
+4 -2
View File
@@ -39,7 +39,7 @@ import {
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import type { SidebarData } from '@/components/layout/types'
import type { SidebarBadges, SidebarData } from '@/components/layout/types'
import { ROLE } from '@/lib/roles'
/**
@@ -48,7 +48,7 @@ import { ROLE } from '@/lib/roles'
* These are shown when the URL does not match any nested sidebar view
* registered in `layout/lib/sidebar-view-registry.ts`.
*/
export function useSidebarData(): SidebarData {
export function useSidebarData(badges: SidebarBadges = {}): SidebarData {
const { t } = useTranslation()
return {
@@ -175,6 +175,8 @@ export function useSidebarData(): SidebarData {
activeUrls: ['/system-settings'],
icon: Settings,
requiredRole: ROLE.SUPER_ADMIN,
// Model pricing lives in System Settings.
badge: badges.modelPricing,
},
],
},
+10 -3
View File
@@ -21,7 +21,12 @@ import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { resolveSidebarView } from '@/components/layout/lib/sidebar-view-registry'
import type { NavGroup, ResolvedSidebarView } from '@/components/layout/types'
import type {
NavGroup,
ResolvedSidebarView,
SidebarBadges,
} from '@/components/layout/types'
import { useModelPricingIssueBadge } from '@/features/system-settings/models/pricing-issues'
import { ROLE } from '@/lib/roles'
import { useAuthStore } from '@/stores/auth-store'
@@ -48,7 +53,9 @@ export function useSidebarView(): ResolvedSidebarView {
const { t } = useTranslation()
const pathname = useLocation({ select: (l) => l.pathname })
const userRole = useAuthStore((s) => s.auth.user?.role)
const rootSidebarData = useSidebarData()
const modelPricingBadge = useModelPricingIssueBadge()
const badges: SidebarBadges = { modelPricing: modelPricingBadge }
const rootSidebarData = useSidebarData(badges)
const configFilteredRoot = useSidebarConfig(rootSidebarData.navGroups)
const rootNavGroups = useMemo<NavGroup[]>(() => {
@@ -70,7 +77,7 @@ export function useSidebarView(): ResolvedSidebarView {
return {
key: view.id,
view,
navGroups: view.getNavGroups(t),
navGroups: view.getNavGroups(t, badges),
}
}
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "All files exceed the maximum size.",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.",
"All Groups": "All Groups",
"And {{count}} more models": "And {{count}} more models",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.",
"All models": "All models",
"All Models": "All Models",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "No endpoints inferred from channels",
"No extra domains declared": "No extra domains declared",
"No FAQ entries available": "No FAQ entries available",
"No price set": "No price set",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "No FAQ entries yet. Click \"Add FAQ\" to create one.",
"No files match the accepted types.": "No files match the accepted types.",
"No flow data available": "No flow data available",
@@ -4642,6 +4644,7 @@
"Personal area": "Personal area",
"Personal Center Area": "Personal Center Area",
"Personal info settings": "Personal info settings",
"Plugin enabled": "Plugin enabled",
"Personal Settings": "Personal Settings",
"Personal settings and profile management.": "Personal settings and profile management.",
"Personal use": "Personal use",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "Plugins can access channel credentials. Review the source and differences before installing.",
"Policy JSON": "Policy JSON",
"Polling": "Polling",
"Price needs attention": "Price needs attention",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded",
"Poor": "Poor",
"Port": "Port",
"Price status": "Price status",
"Port must be a positive integer": "Port must be a positive integer",
"Position {{position}}": "Position {{position}}",
"Possibly an upstream timeout": "Possibly an upstream timeout",
"Post Delta": "Post Delta",
"PostgreSQL detected": "PostgreSQL detected",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL offers advanced reliability and data integrity for production workloads.",
"Prices of these models need attention:": "Prices of these models need attention:",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.",
"Power AI applications, manage digital assets, connect the Future": "Power AI applications, manage digital assets, connect the Future",
"Powerful API Management Platform": "Powerful API Management Platform",
@@ -6167,7 +6173,6 @@
"Task Plugins": "Task Plugins",
"Task pricing": "Task pricing",
"Task pricing must be converted manually using the task usage schema.": "Task pricing must be converted manually using the task usage schema.",
"Task pricing not configured": "Task pricing not configured",
"Task timed out": "Task timed out",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "Task timed out (a task left by the old system is not refunded; contact the administrator)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "Task usage data is required to estimate this expression. Check the model's task plugin configuration.",
@@ -6179,6 +6184,8 @@
"Technical Support": "Technical Support",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "Telegram authorization failed. Please try again.",
"The plugin no longer offers this model": "The plugin no longer offers this model",
"The price uses usage the plugin no longer provides": "The price uses usage the plugin no longer provides",
"Telegram binding failed. Please try again.": "Telegram binding failed. Please try again.",
"Telegram binding is disabled.": "Telegram binding is disabled.",
"Telegram ID is empty!": "Telegram ID is empty!",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.",
"You will be redirected to Telegram to complete the binding process.": "You will be redirected to Telegram to complete the binding process.",
"{{name}}: {{reason}}": "{{name}}: {{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.",
"Your account can edit sensitive channel settings.": "Your account can edit sensitive channel settings.",
"Your account cannot edit sensitive channel settings.": "Your account cannot edit sensitive channel settings.",
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "Tous les fichiers dépassent la taille maximale.",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "Tous les noms de groupes sont gérés ici. Le taux s’applique lorsque les appels sont facturés sous ce groupe ; le taux de recharge s’applique aux utilisateurs appartenant à ce groupe.",
"All Groups": "Tous les groupes",
"And {{count}} more models": "Et {{count}} autres modèles",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "Tous les groupes partagent un même ensemble de noms géré dans le tableau des groupes tarifaires, mais un nom joue deux rôles distincts : en tant que groupe d’utilisateurs il décrit l’utilisateur, en tant que groupe de jetons il détermine le routage et la facturation.",
"All models": "Tous les modèles",
"All Models": "Tous les modèles",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "Aucun point de terminaison déduit des canaux",
"No extra domains declared": "Aucun domaine supplémentaire déclaré",
"No FAQ entries available": "Aucune entrée FAQ disponible",
"No price set": "Aucun prix défini",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "Aucune entrée FAQ pour l'instant. Cliquez sur \"Ajouter une FAQ\" pour en créer une.",
"No files match the accepted types.": "Aucun fichier ne correspond aux types acceptés.",
"No flow data available": "Aucune donnée de flux disponible",
@@ -4642,6 +4644,7 @@
"Personal area": "Espace personnel",
"Personal Center Area": "Espace personnel",
"Personal info settings": "Paramètres d'informations personnelles",
"Plugin enabled": "Plugin activé",
"Personal Settings": "Paramètres personnels",
"Personal settings and profile management.": "Paramètres personnels et gestion du profil.",
"Personal use": "Usage personnel",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "Les plugins peuvent accéder aux identifiants des canaux. Examinez le code et les différences avant l’installation.",
"Policy JSON": "JSON de stratégie",
"Polling": "Sondage",
"Price needs attention": "Prix à vérifier",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "Le mode d'interrogation nécessite Redis et un cache mémoire, sinon les performances seront considérablement dégradées",
"Poor": "Mauvais",
"Port": "Port",
"Price status": "État du prix",
"Port must be a positive integer": "Le port doit être un entier positif",
"Position {{position}}": "Position {{position}}",
"Possibly an upstream timeout": "Probablement un délai d'attente en amont",
"Post Delta": "Delta post-calcul",
"PostgreSQL detected": "PostgreSQL détecté",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL offre une fiabilité avancée et une intégrité des données pour les charges de travail en production.",
"Prices of these models need attention:": "Les prix de ces modèles sont à vérifier :",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQL offre de solides garanties de fiabilité. Vérifiez votre fenêtre de maintenance et vos politiques de rétention avant la mise en production.",
"Power AI applications, manage digital assets, connect the Future": "Propulser les applications IA, gérer les actifs numériques, connecter l'Avenir",
"Powerful API Management Platform": "Plateforme puissante de gestion d'API",
@@ -6167,7 +6173,6 @@
"Task Plugins": "Plugins de tâches",
"Task pricing": "Tarification des tâches",
"Task pricing must be converted manually using the task usage schema.": "La tarification des tâches doit être convertie manuellement selon leur schéma d’utilisation.",
"Task pricing not configured": "Tarification des tâches non configurée",
"Task timed out": "La tâche a expiré",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "La tâche a expiré (une tâche laissée par l'ancien système n'est pas remboursée ; contactez l'administrateur)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "Les données d’utilisation des tâches sont nécessaires pour estimer le coût de cette expression. Vérifiez la configuration du plugin de tâches du modèle.",
@@ -6179,6 +6184,8 @@
"Technical Support": "Support technique",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "L’autorisation Telegram a échoué. Réessayez.",
"The plugin no longer offers this model": "Le plugin ne propose plus ce modèle",
"The price uses usage the plugin no longer provides": "Le prix utilise un usage que le plugin ne fournit plus",
"Telegram binding failed. Please try again.": "Échec de la liaison Telegram. Veuillez réessayer.",
"Telegram binding is disabled.": "La liaison Telegram est désactivée.",
"Telegram ID is empty!": "L’ID Telegram est vide !",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "Vous comprenez et assumez indépendamment la responsabilité juridique découlant du déploiement, de l’exploitation et de la facturation.",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "Vous comprenez que ce rappel de conformité est uniquement un avis de risque et ne constitue ni un conseil juridique, ni une conclusion d’examen de conformité, ni une garantie de la légalité de votre utilisation de ce système ; vous devez consulter des conseillers juridiques ou conformité professionnels selon votre situation réelle.",
"You will be redirected to Telegram to complete the binding process.": "Vous serez redirigé vers Telegram pour terminer le processus de liaison.",
"{{name}}: {{reason}}": "{{name}} : {{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "Vous serez redirigé automatiquement. Vous pouvez revenir à la page précédente si rien ne se passe après quelques secondes.",
"Your account can edit sensitive channel settings.": "Votre compte peut modifier les paramètres sensibles des canaux.",
"Your account cannot edit sensitive channel settings.": "Votre compte ne peut pas modifier les paramètres sensibles des canaux.",
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "すべてのファイルが最大サイズを超えています。",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "すべてのグループ名はここで管理します。倍率はこのグループとして課金される呼び出しに適用され、チャージ倍率はこのグループに所属するユーザーに適用されます。",
"All Groups": "すべてのグループ",
"And {{count}} more models": "ほか {{count}} 個のモデル",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "すべてのグループは料金グループ表で管理される同じ名前プールを共有しますが、1つの名前には2つの役割があります。ユーザーグループとしてはユーザーの属性を表し、トークングループとしてはルーティングと課金を決定します。",
"All models": "すべてのモデル",
"All Models": "すべてのモデル",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "チャネルから取得したエンドポイントなし",
"No extra domains declared": "追加ドメインの宣言なし",
"No FAQ entries available": "FAQエントリがありません",
"No price set": "価格が未設定です",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "FAQエントリはまだありません。「FAQを追加」をクリックして作成してください。",
"No files match the accepted types.": "許可された種類に一致するファイルがありません。",
"No flow data available": "フローデータがありません",
@@ -4642,6 +4644,7 @@
"Personal area": "個人エリア",
"Personal Center Area": "パーソナルセンターエリア",
"Personal info settings": "個人情報設定",
"Plugin enabled": "プラグインを有効にしました",
"Personal Settings": "個人設定",
"Personal settings and profile management.": "個人設定とプロフィール管理。",
"Personal use": "個人利用",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "プラグインはチャネルの認証情報にアクセスできます。インストール前にソースコードと差分を確認してください。",
"Policy JSON": "ポリシーJSON",
"Polling": "ポーリング",
"Price needs attention": "価格の対応が必要",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "ポーリングモードにはRedisとメモリキャッシュが必要です。そうでない場合、パフォーマンスが大幅に低下します",
"Poor": "悪い",
"Port": "ポート",
"Price status": "価格の状態",
"Port must be a positive integer": "ポートは正の整数でなければなりません",
"Position {{position}}": "{{position}} 番目",
"Possibly an upstream timeout": "上流のタイムアウトの可能性があります",
"Post Delta": "事後差額",
"PostgreSQL detected": "PostgreSQLが検出されました",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL は本番ワークロード向けの高度な信頼性とデータ整合性を提供します。",
"Prices of these models need attention:": "次のモデルの価格を確認してください:",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQLは強力な信頼性保証を提供します。本番稼働する前に、メンテナンスウィンドウと保持ポリシーを再確認してください。",
"Power AI applications, manage digital assets, connect the Future": "AIアプリケーションを支え、デジタル資産を管理し、未来をつなぐ",
"Powerful API Management Platform": "強力なAPI管理プラットフォーム",
@@ -6167,7 +6173,6 @@
"Task Plugins": "タスクプラグイン",
"Task pricing": "タスク料金",
"Task pricing must be converted manually using the task usage schema.": "タスク料金はタスクの使用量スキーマに基づいて手動で変換してください。",
"Task pricing not configured": "タスク料金が未設定",
"Task timed out": "タスクがタイムアウトしました",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "タスクがタイムアウトしました(旧システムのタスクは返金されません。管理者に連絡してください)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "この式の料金を見積もるにはタスク使用量データが必要です。モデルのタスクプラグイン設定をご確認ください。",
@@ -6179,6 +6184,8 @@
"Technical Support": "テクニカルサポート",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "Telegram の認証に失敗しました。もう一度お試しください。",
"The plugin no longer offers this model": "プラグインはこのモデルを提供しなくなりました",
"The price uses usage the plugin no longer provides": "価格が、プラグインで提供されなくなった使用量を使っています",
"Telegram binding failed. Please try again.": "Telegram の連携に失敗しました。もう一度お試しください。",
"Telegram binding is disabled.": "Telegram 連携は無効です。",
"Telegram ID is empty!": "Telegram ID が空です!",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "デプロイ、運用、課金行為に起因する法的責任を理解し、独立して負います。",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "このコンプライアンス注意事項はリスク通知にすぎず、法的助言、コンプライアンス審査の結論、または本システム利用の合法性の保証ではないことを理解しています。実際の事業状況に応じて、専門の法律またはコンプライアンス担当者に相談してください。",
"You will be redirected to Telegram to complete the binding process.": "バインドプロセスを完了するためにTelegramにリダイレクトされます。",
"{{name}}: {{reason}}": "{{name}}:{{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "自動的にリダイレクトされます。数秒経っても何も起こらない場合は、前のページに戻ることができます。",
"Your account can edit sensitive channel settings.": "あなたのアカウントは機密チャネル設定を編集できます。",
"Your account cannot edit sensitive channel settings.": "あなたのアカウントは機密チャネル設定を編集できません。",
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "Все файлы превышают максимальный размер.",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "Все названия групп управляются здесь. Коэффициент применяется, когда вызовы тарифицируются по этой группе; коэффициент пополнения применяется к пользователям, состоящим в этой группе.",
"All Groups": "Все группы",
"And {{count}} more models": "И ещё моделей: {{count}}",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "Все группы используют общий набор имён из таблицы тарифных групп, но одно имя играет две разные роли: как группа пользователя оно описывает пользователя, как группа токена — определяет маршрутизацию и тарификацию.",
"All models": "Все модели",
"All Models": "Все модели",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "Конечные точки не определены по каналам",
"No extra domains declared": "Дополнительные домены не объявлены",
"No FAQ entries available": "Нет доступных записей FAQ",
"No price set": "Цена не задана",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "Пока нет записей FAQ. Нажмите \"Добавить FAQ\", чтобы создать одну.",
"No files match the accepted types.": "Нет файлов, соответствующих допустимым типам.",
"No flow data available": "Нет данных потока",
@@ -4642,6 +4644,7 @@
"Personal area": "Личный кабинет",
"Personal Center Area": "Область личного кабинета",
"Personal info settings": "Настройки личной информации",
"Plugin enabled": "Плагин включён",
"Personal Settings": "Личные настройки",
"Personal settings and profile management.": "Персональные настройки и управление профилем.",
"Personal use": "Личное использование",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "Плагины могут получать доступ к учётным данным каналов. Перед установкой проверьте исходный код и различия.",
"Policy JSON": "JSON политики",
"Polling": "Опрос",
"Price needs attention": "Цена требует внимания",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "Режим опроса требует Redis и кэш памяти, в противном случае производительность будет значительно снижена",
"Poor": "Плохо",
"Port": "Порт",
"Price status": "Статус цены",
"Port must be a positive integer": "Порт должен быть положительным целым числом",
"Position {{position}}": "Позиция {{position}}",
"Possibly an upstream timeout": "Возможно, истекло время ожидания upstream",
"Post Delta": "Дельта после расчёта",
"PostgreSQL detected": "PostgreSQL обнаружен",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL обеспечивает высокую надёжность и целостность данных для продакшен-нагрузок.",
"Prices of these models need attention:": "Цены этих моделей требуют внимания:",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQL предлагает надежные гарантии. Дважды проверьте окно обслуживания и политики хранения данных перед запуском.",
"Power AI applications, manage digital assets, connect the Future": "Обеспечивайте AI-приложения, управляйте цифровыми активами, соединяйте Будущее",
"Powerful API Management Platform": "Мощная платформа управления API",
@@ -6167,7 +6173,6 @@
"Task Plugins": "Плагины задач",
"Task pricing": "Тарификация задач",
"Task pricing must be converted manually using the task usage schema.": "Тарифы задач необходимо преобразовать вручную по схеме использования задачи.",
"Task pricing not configured": "Тарификация задач не настроена",
"Task timed out": "Истекло время выполнения задачи",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "Истекло время выполнения задачи (задачи старой системы не возмещаются; обратитесь к администратору)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "Для оценки стоимости по этому выражению нужны данные использования задач. Проверьте настройки плагина задач модели.",
@@ -6179,6 +6184,8 @@
"Technical Support": "Техническая поддержка",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "Не удалось выполнить авторизацию Telegram. Повторите попытку.",
"The plugin no longer offers this model": "Плагин больше не предоставляет эту модель",
"The price uses usage the plugin no longer provides": "Цена использует данные об использовании, которые плагин больше не передаёт",
"Telegram binding failed. Please try again.": "Не удалось привязать Telegram. Повторите попытку.",
"Telegram binding is disabled.": "Привязка Telegram отключена.",
"Telegram ID is empty!": "Telegram ID не указан!",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "Вы понимаете и самостоятельно несете юридическую ответственность, возникающую из развертывания, эксплуатации и взимания платы.",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "Вы понимаете, что это напоминание о соответствии является только уведомлением о рисках и не является юридической консультацией, заключением проверки соответствия или гарантией законности использования этой системы; вам следует обратиться к профессиональным юридическим или комплаенс-консультантам с учетом вашей реальной бизнес-ситуации.",
"You will be redirected to Telegram to complete the binding process.": "Вы будете перенаправлены в Telegram для завершения процесса привязки.",
"{{name}}: {{reason}}": "{{name}}: {{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "Вы будете автоматически перенаправлены. Если через несколько секунд ничего не происходит, вы можете вернуться на предыдущую страницу.",
"Your account can edit sensitive channel settings.": "Ваша учетная запись может изменять чувствительные настройки каналов.",
"Your account cannot edit sensitive channel settings.": "Ваша учетная запись не может изменять чувствительные настройки каналов.",
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "Tất cả các tệp vượt quá kích thước tối đa.",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "Tất cả tên nhóm được quản lý tại đây. Hệ số áp dụng khi cuộc gọi được tính phí theo nhóm này; hệ số nạp tiền áp dụng cho người dùng thuộc nhóm này.",
"All Groups": "Tất cả các nhóm",
"And {{count}} more models": "Và {{count}} mô hình khác",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "Tất cả các nhóm dùng chung một bộ tên được quản lý trong bảng nhóm định giá, nhưng một tên có hai vai trò khác nhau: là nhóm người dùng thì mô tả người dùng, là nhóm token thì quyết định định tuyến và tính phí.",
"All models": "Tất cả mô hình",
"All Models": "Tất cả các mẫu",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "Không xác định được điểm cuối từ kênh",
"No extra domains declared": "Không khai báo miền bổ sung",
"No FAQ entries available": "Không có mục FAQ nào.",
"No price set": "Chưa đặt giá",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "Chưa có mục FAQ nào. Nhấp vào \"Thêm FAQ\" để tạo một mục.",
"No files match the accepted types.": "Không có tệp nào khớp với các loại được chấp nhận.",
"No flow data available": "Không có dữ liệu luồng",
@@ -4642,6 +4644,7 @@
"Personal area": "Khu vực cá nhân",
"Personal Center Area": "Khu vực cá nhân",
"Personal info settings": "Cài đặt thông tin cá nhân",
"Plugin enabled": "Đã bật plugin",
"Personal Settings": "Cài đặt cá nhân",
"Personal settings and profile management.": "Cài đặt cá nhân và quản lý hồ sơ.",
"Personal use": "Sử dụng cá nhân",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "Plugin có thể truy cập thông tin xác thực kênh. Hãy kiểm tra mã nguồn và các khác biệt trước khi cài đặt.",
"Policy JSON": "JSON chính sách",
"Polling": "Thăm dò",
"Price needs attention": "Giá cần xử lý",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "Chế độ thăm dò yêu cầu Redis và bộ nhớ đệm, nếu không hiệu suất sẽ bị suy giảm đáng kể.",
"Poor": "Nghèo",
"Port": "Cảng",
"Price status": "Trạng thái giá",
"Port must be a positive integer": "Cổng phải là số nguyên dương",
"Position {{position}}": "Vị trí {{position}}",
"Possibly an upstream timeout": "Có thể do thượng nguồn hết thời gian chờ",
"Post Delta": "Chênh lệch sau",
"PostgreSQL detected": "Phát hiện PostgreSQL",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL cung cấp độ tin cậy cao và tính toàn vẹn dữ liệu cho khối lượng công việc production.",
"Prices of these models need attention:": "Giá của các mô hình sau cần xử lý:",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQL cung cấp các đảm bảo độ tin cậy cao. Hãy kiểm tra kỹ lưỡng cửa sổ bảo trì và các chính sách lưu giữ của bạn trước khi vận hành chính thức.",
"Power AI applications, manage digital assets, connect the Future": "Vận hành ứng dụng AI, quản lý tài sản số, kết nối Tương lai",
"Powerful API Management Platform": "Nền tảng Quản lý API mạnh mẽ",
@@ -6167,7 +6173,6 @@
"Task Plugins": "Plugin tác vụ",
"Task pricing": "Giá tác vụ",
"Task pricing must be converted manually using the task usage schema.": "Cần chuyển đổi giá tác vụ thủ công theo lược đồ mức sử dụng tác vụ.",
"Task pricing not configured": "Chưa cấu hình giá tác vụ",
"Task timed out": "Tác vụ hết thời gian",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "Tác vụ hết thời gian (tác vụ còn sót từ hệ thống cũ không được hoàn tiền; hãy liên hệ quản trị viên)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "Cần dữ liệu sử dụng tác vụ để ước tính chi phí theo biểu thức này. Hãy kiểm tra cấu hình plugin tác vụ của mô hình.",
@@ -6179,6 +6184,8 @@
"Technical Support": "Hỗ trợ kỹ thuật",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "Ủy quyền Telegram thất bại. Vui lòng thử lại.",
"The plugin no longer offers this model": "Plugin không còn cung cấp mô hình này",
"The price uses usage the plugin no longer provides": "Giá dùng mức sử dụng mà plugin không còn cung cấp",
"Telegram binding failed. Please try again.": "Liên kết Telegram không thành công. Vui lòng thử lại.",
"Telegram binding is disabled.": "Tính năng liên kết Telegram đã bị tắt.",
"Telegram ID is empty!": "ID Telegram trống!",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "Bạn hiểu và tự chịu trách nhiệm pháp lý phát sinh từ việc triển khai, vận hành và thu phí.",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "Bạn hiểu rằng nhắc nhở tuân thủ này chỉ là thông báo rủi ro, không cấu thành tư vấn pháp lý, kết luận rà soát tuân thủ hoặc bảo đảm tính hợp pháp của việc sử dụng hệ thống; bạn nên tham khảo cố vấn pháp lý hoặc tuân thủ chuyên nghiệp dựa trên tình huống kinh doanh thực tế.",
"You will be redirected to Telegram to complete the binding process.": "Bạn sẽ được chuyển hướng đến Telegram để hoàn tất quá trình liên kết.",
"{{name}}: {{reason}}": "{{name}}: {{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "Bạn sẽ được chuyển hướng tự động. Bạn có thể quay lại trang trước nếu không có gì xảy ra sau vài giây.",
"Your account can edit sensitive channel settings.": "Tài khoản của bạn có thể chỉnh sửa cài đặt kênh nhạy cảm.",
"Your account cannot edit sensitive channel settings.": "Tài khoản của bạn không thể chỉnh sửa cài đặt kênh nhạy cảm.",
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "所有檔案都超過最大尺寸。",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "所有分組名稱都在這裡管理。倍率在呼叫按該分組收費時生效;儲值倍率對所屬該分組的用戶生效。",
"All Groups": "所有分組",
"And {{count}} more models": "另外還有 {{count}} 個模型",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "所有分組共用定價分組表中的同一批名稱,但同一個名稱有兩種角色:作為用戶分組表示用戶身份,作為令牌分組決定路由和收費。",
"All models": "所有模型",
"All Models": "所有模型",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "未從渠道推導出端點",
"No extra domains declared": "未宣告額外網域",
"No FAQ entries available": "暫無 FAQ 條目",
"No price set": "還沒設定價格",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "暫無常見問題條目。點擊「新增常見問題」來建立一個。",
"No files match the accepted types.": "沒有檔案匹配接受的類型。",
"No flow data available": "暫無分流數據",
@@ -4642,6 +4644,7 @@
"Personal area": "個人中心",
"Personal Center Area": "個人中心區域",
"Personal info settings": "個人資訊設定",
"Plugin enabled": "外掛已啟用",
"Personal Settings": "個人設定",
"Personal settings and profile management.": "個人設定和個人資料管理。",
"Personal use": "個人使用",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "外掛可存取渠道憑證。安裝前請檢查原始碼與差異。",
"Policy JSON": "政策 JSON",
"Polling": "輪詢",
"Price needs attention": "價格待處理",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "輪詢模式需要 Redis 和記憶體緩存,否則效能將顯著下降",
"Poor": "差",
"Port": "端口",
"Price status": "價格狀態",
"Port must be a positive integer": "端口必須為正整數",
"Position {{position}}": "第 {{position}} 位",
"Possibly an upstream timeout": "可能是上游逾時",
"Post Delta": "結算差額",
"PostgreSQL detected": "偵測到 PostgreSQL",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL 為生產工作負載提供進階可靠性和數據完整性。",
"Prices of these models need attention:": "以下模型的價格需要處理:",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQL 提供強大的可靠性保證。在上線之前,請仔細檢查您的維護窗口和保留策略。",
"Power AI applications, manage digital assets, connect the Future": "承載 AI 套用,管理數位資產,連接未來",
"Powerful API Management Platform": "強大的 API 管理平台",
@@ -6167,7 +6173,6 @@
"Task Plugins": "任务外掛",
"Task pricing": "任務定價",
"Task pricing must be converted manually using the task usage schema.": "任務定價需根據任務用量定義手動轉換。",
"Task pricing not configured": "尚未設定任務定價",
"Task timed out": "任務逾時",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "任務逾時(舊系統遺留任務,不進行退款,請聯絡管理員)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "此運算式需要任務用量資料才能估算費用,請檢查模型的任務外掛設定。",
@@ -6179,6 +6184,8 @@
"Technical Support": "技術支援",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "Telegram 授權失敗,請重試。",
"The plugin no longer offers this model": "外掛已不再提供這個模型",
"The price uses usage the plugin no longer provides": "價格用到了外掛不再提供的用量",
"Telegram binding failed. Please try again.": "Telegram 綁定失敗,請再試一次。",
"Telegram binding is disabled.": "Telegram 綁定已停用。",
"Telegram ID is empty!": "Telegram ID 為空!",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "你理解並獨立承擔因部署、運營和收費行為產生的法律責任。",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "你理解此合規提醒僅用於風險提示,不構成法律意見、合規審查結論或對你使用本系統合法性的保證;你應結合實際業務場景諮詢專業法律或合規顧問。",
"You will be redirected to Telegram to complete the binding process.": "您將被重新導向到 Telegram 以完成連結過程。",
"{{name}}: {{reason}}": "{{name}}:{{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "您將被自動重新導向。如果幾秒鐘後無反應,您可以返回上一頁。",
"Your account can edit sensitive channel settings.": "你的賬號可以編輯敏感渠道設定。",
"Your account cannot edit sensitive channel settings.": "你的賬號不能編輯敏感渠道設定。",
+9 -1
View File
@@ -437,6 +437,7 @@
"All files exceed the maximum size.": "所有文件都超过最大尺寸。",
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "所有分组名称都在这里管理。倍率在调用按该分组计费时生效;充值倍率对所属该分组的用户生效。",
"All Groups": "所有分组",
"And {{count}} more models": "另外还有 {{count}} 个模型",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "所有分组共用定价分组表中的同一批名称,但同一个名称有两种角色:作为用户分组表示用户身份,作为令牌分组决定路由和计费。",
"All models": "所有模型",
"All Models": "所有模型",
@@ -4037,6 +4038,7 @@
"No endpoints inferred from channels": "未从渠道推导出端点",
"No extra domains declared": "未声明额外域名",
"No FAQ entries available": "暂无 FAQ 条目",
"No price set": "还没设置价格",
"No FAQ entries yet. Click \"Add FAQ\" to create one.": "暂无常见问题条目。点击“添加常见问题”来创建一个。",
"No files match the accepted types.": "没有文件匹配接受的类型。",
"No flow data available": "暂无分流数据",
@@ -4642,6 +4644,7 @@
"Personal area": "个人中心",
"Personal Center Area": "个人中心区域",
"Personal info settings": "个人信息设置",
"Plugin enabled": "插件已启用",
"Personal Settings": "个人设置",
"Personal settings and profile management.": "个人设置和个人资料管理。",
"Personal use": "个人使用",
@@ -4756,15 +4759,18 @@
"Plugins can access channel credentials. Review the source and differences before installing.": "插件可访问渠道凭据。安装前请审查源码与差异。",
"Policy JSON": "策略 JSON",
"Polling": "轮询",
"Price needs attention": "价格待处理",
"Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded": "轮询模式需要 Redis 和内存缓存,否则性能将显著下降",
"Poor": "差",
"Port": "端口",
"Price status": "价格状态",
"Port must be a positive integer": "端口必须为正整数",
"Position {{position}}": "第 {{position}} 位",
"Possibly an upstream timeout": "可能是上游超时",
"Post Delta": "结算差额",
"PostgreSQL detected": "检测到 PostgreSQL",
"PostgreSQL offers advanced reliability and data integrity for production workloads.": "PostgreSQL 为生产工作负载提供高级可靠性和数据完整性。",
"Prices of these models need attention:": "以下模型的价格需要处理:",
"PostgreSQL offers strong reliability guarantees. Double check your maintenance window and retention policies before going live.": "PostgreSQL 提供强大的可靠性保证。在上线之前,请仔细检查您的维护窗口和保留策略。",
"Power AI applications, manage digital assets, connect the Future": "承载 AI 应用,管理数字资产,连接未来",
"Powerful API Management Platform": "强大的 API 管理平台",
@@ -6167,7 +6173,6 @@
"Task Plugins": "任务插件",
"Task pricing": "任务定价",
"Task pricing must be converted manually using the task usage schema.": "任务定价需根据任务用量定义手动转换。",
"Task pricing not configured": "尚未配置任务定价",
"Task timed out": "任务超时",
"Task timed out (a task left by the old system is not refunded; contact the administrator)": "任务超时(旧系统遗留任务,不进行退款,请联系管理员)",
"Task usage data is required to estimate this expression. Check the model's task plugin configuration.": "此表达式需要任务用量数据才能估算费用,请检查模型的任务插件配置。",
@@ -6179,6 +6184,8 @@
"Technical Support": "技术支持",
"Telegram": "Telegram",
"Telegram authorization failed. Please try again.": "Telegram 授权失败,请重试。",
"The plugin no longer offers this model": "插件已不再提供这个模型",
"The price uses usage the plugin no longer provides": "价格用到了插件不再提供的用量",
"Telegram binding failed. Please try again.": "Telegram 绑定失败,请重试。",
"Telegram binding is disabled.": "Telegram 绑定已禁用。",
"Telegram ID is empty!": "Telegram ID 为空!",
@@ -7334,6 +7341,7 @@
"You understand and independently bear legal responsibility arising from deployment, operation, and charging behavior.": "你理解并独立承担因部署、运营和收费行为产生的法律责任。",
"You understand this compliance reminder is only for risk notice and does not constitute legal advice, a compliance review conclusion, or a guarantee of the legality of your use of this system; you should consult professional legal or compliance advisors based on your actual business scenario.": "你理解此合规提醒仅用于风险提示,不构成法律意见、合规审查结论或对你使用本系统合法性的保证;你应结合实际业务场景咨询专业法律或合规顾问。",
"You will be redirected to Telegram to complete the binding process.": "您将被重定向到 Telegram 以完成绑定过程。",
"{{name}}: {{reason}}": "{{name}}:{{reason}}",
"You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds.": "您将被自动重定向。如果几秒钟后无反应,您可以返回上一页。",
"Your account can edit sensitive channel settings.": "你的账号可以编辑敏感渠道设置。",
"Your account cannot edit sensitive channel settings.": "你的账号不能编辑敏感渠道设置。",