From 883eeb87d864a0d657b39ff3703e057ebfaa523b Mon Sep 17 00:00:00 2001 From: CaIon Date: Fri, 30 Oct 2026 14:27:43 +0800 Subject: [PATCH] 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. --- common/log_text.zh-CN.json | 1 + controller/model_pricing_config.go | 9 ++ controller/task_plugin.go | 40 ++++- controller/task_plugin_test.go | 143 ++++++++++++++++++ middleware/access_token_routes.go | 1 + model/model_pricing_config.go | 112 ++++++++++++++ model/pricing_usage_schema_test.go | 71 +++++++++ router/api-router.go | 1 + .../layout/config/system-settings.config.ts | 12 +- web/src/components/layout/types.ts | 16 +- .../model-ratio-table-selection.test.tsx | 127 +++++++++++++++- .../models/model-ratio-table-columns.tsx | 106 ++++++++----- .../models/model-ratio-visual-editor.tsx | 43 +++++- .../system-settings/models/pricing-issues.ts | 84 ++++++++++ .../system-settings/utils/section-registry.ts | 8 +- .../marketplace-install-dialog.test.tsx | 34 +++++ .../__tests__/plugin-detail-sheet.test.tsx | 57 +++++++ .../__tests__/plugins-table.test.tsx | 101 +++++++++++++ .../__tests__/upload-dialog.test.tsx | 60 ++++++++ web/src/features/task-plugins/api.ts | 13 +- .../components/marketplace-install-dialog.tsx | 17 ++- .../components/plugin-detail-sheet.tsx | 10 +- .../task-plugins/components/plugins-table.tsx | 18 ++- .../components/pricing-issue-list.tsx | 53 +++++++ .../task-plugins/components/upload-dialog.tsx | 16 ++ .../task-plugins/lib/plugin-change-toast.tsx | 38 +++++ web/src/features/task-plugins/types.ts | 11 ++ .../hooks/__tests__/sidebar-config.test.tsx | 142 ++++++++++++++++- web/src/hooks/use-sidebar-data.ts | 6 +- web/src/hooks/use-sidebar-view.ts | 13 +- web/src/i18n/locales/en.json | 10 +- web/src/i18n/locales/fr.json | 10 +- web/src/i18n/locales/ja.json | 10 +- web/src/i18n/locales/ru.json | 10 +- web/src/i18n/locales/vi.json | 10 +- web/src/i18n/locales/zh-TW.json | 10 +- web/src/i18n/locales/zh.json | 10 +- 37 files changed, 1343 insertions(+), 90 deletions(-) create mode 100644 web/src/features/system-settings/models/pricing-issues.ts create mode 100644 web/src/features/task-plugins/components/pricing-issue-list.tsx create mode 100644 web/src/features/task-plugins/lib/plugin-change-toast.tsx diff --git a/common/log_text.zh-CN.json b/common/log_text.zh-CN.json index b30adf150e..f93759909f 100644 --- a/common/log_text.zh-CN.json +++ b/common/log_text.zh-CN.json @@ -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", diff --git a/controller/model_pricing_config.go b/controller/model_pricing_config.go index a9511604bc..ab702612ad 100644 --- a/controller/model_pricing_config.go +++ b/controller/model_pricing_config.go @@ -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"` diff --git a/controller/task_plugin.go b/controller/task_plugin.go index fdb9908ae4..478892926e 100644 --- a/controller/task_plugin.go +++ b/controller/task_plugin.go @@ -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()) } diff --git a/controller/task_plugin_test.go b/controller/task_plugin_test.go index 556bfb2de8..8cc0f1079b 100644 --- a/controller/task_plugin_test.go +++ b/controller/task_plugin_test.go @@ -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" diff --git a/middleware/access_token_routes.go b/middleware/access_token_routes.go index c23a2bf3db..25b96767d3 100644 --- a/middleware/access_token_routes.go +++ b/middleware/access_token_routes.go @@ -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"), diff --git a/model/model_pricing_config.go b/model/model_pricing_config.go index d501598716..4ba26a5bf6 100644 --- a/model/model_pricing_config.go +++ b/model/model_pricing_config.go @@ -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() { diff --git a/model/pricing_usage_schema_test.go b/model/pricing_usage_schema_test.go index 4f28c664b9..1909852ac7 100644 --- a/model/pricing_usage_schema_test.go +++ b/model/pricing_usage_schema_test.go @@ -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) +} diff --git a/router/api-router.go b/router/api-router.go index 1009affbf1..9049811455 100644 --- a/router/api-router.go +++ b/router/api-router.go @@ -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) diff --git a/web/src/components/layout/config/system-settings.config.ts b/web/src/components/layout/config/system-settings.config.ts index 06a6f045ad..27216d0127 100644 --- a/web/src/components/layout/config/system-settings.config.ts +++ b/web/src/components/layout/config/system-settings.config.ts @@ -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'), diff --git a/web/src/components/layout/types.ts b/web/src/components/layout/types.ts index 6a2830edc9..488f2f1cb9 100644 --- a/web/src/components/layout/types.ts +++ b/web/src/components/layout/types.ts @@ -16,8 +16,8 @@ along with this program. If not, see . 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[] } /** diff --git a/web/src/features/system-settings/models/__tests__/model-ratio-table-selection.test.tsx b/web/src/features/system-settings/models/__tests__/model-ratio-table-selection.test.tsx index c1b74e081f..7fa8e0ba64 100644 --- a/web/src/features/system-settings/models/__tests__/model-ratio-table-selection.test.tsx +++ b/web/src/features/system-settings/models/__tests__/model-ratio-table-selection.test.tsx @@ -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() +}) diff --git a/web/src/features/system-settings/models/model-ratio-table-columns.tsx b/web/src/features/system-settings/models/model-ratio-table-columns.tsx index da200d9bcb..22f948e55e 100644 --- a/web/src/features/system-settings/models/model-ratio-table-columns.tsx +++ b/web/src/features/system-settings/models/model-ratio-table-columns.tsx @@ -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 - t: (key: string) => string + /** Task model prices the gateway reports a plugin cannot charge, by model. */ + pricingIssues?: Map + t: (key: string, options?: Record) => string } export function buildModelRatioColumns({ @@ -54,6 +58,7 @@ export function buildModelRatioColumns({ onEdit, deleteDisabled, taskModelNames, + pricingIssues, t, }: BuildModelRatioColumnsOptions): ColumnDef[] { return [ @@ -86,53 +91,75 @@ export function buildModelRatioColumns({ ), 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 ( -
- {row.getValue('name')} - {showTieredBadge ? ( - - ) : null} - {showTaskPricingBadge ? ( - - ) : null} - {row.original.hasConflict && ( - - )} - {showUnconfiguredTaskBadge ? ( - +
+
+ {row.getValue('name')} + {showTieredBadge ? ( + + ) : null} + {showTaskPricingBadge ? ( + + ) : null} + {row.original.hasConflict && ( + + )} + {issues ? ( + + ) : null} +
+ {issueText ? ( + + {issueText} + ) : null}
) }, + // 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 ( diff --git a/web/src/features/system-settings/models/model-ratio-visual-editor.tsx b/web/src/features/system-settings/models/model-ratio-visual-editor.tsx index 03a24fe205..8d4e25c5fb 100644 --- a/web/src/features/system-settings/models/model-ratio-visual-editor.tsx +++ b/web/src/features/system-settings/models/model-ratio-visual-editor.tsx @@ -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([]) const [columnFilters, setColumnFilters] = useState([]) const [globalFilter, setGlobalFilter] = useState('') @@ -227,6 +230,17 @@ const ModelRatioVisualEditorComponent = forwardRef< [pricingModels] ) + const pricingIssues = useMemo(() => { + const byModel = new Map() + 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 : ( diff --git a/web/src/features/system-settings/models/pricing-issues.ts b/web/src/features/system-settings/models/pricing-issues.ts new file mode 100644 index 0000000000..676e1647d8 --- /dev/null +++ b/web/src/features/system-settings/models/pricing-issues.ts @@ -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 . + +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 { + 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) + ) +} diff --git a/web/src/features/system-settings/utils/section-registry.ts b/web/src/features/system-settings/utils/section-registry.ts index 20ba800b6f..327ecf32fd 100644 --- a/web/src/features/system-settings/utils/section-registry.ts +++ b/web/src/features/system-settings/utils/section-registry.ts @@ -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> + ) { return sections.map((section) => ({ title: t(section.titleKey), url: urlStyle === 'path' ? `${basePath}/${section.id}` : `${basePath}?section=${section.id}`, + badge: badges?.[section.id as SectionId], })) } diff --git a/web/src/features/task-plugins/__tests__/marketplace-install-dialog.test.tsx b/web/src/features/task-plugins/__tests__/marketplace-install-dialog.test.tsx index 84b1f611f4..6f8cfd3305 100644 --- a/web/src/features/task-plugins/__tests__/marketplace-install-dialog.test.tsx +++ b/web/src/features/task-plugins/__tests__/marketplace-install-dialog.test.tsx @@ -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() + 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', diff --git a/web/src/features/task-plugins/__tests__/plugin-detail-sheet.test.tsx b/web/src/features/task-plugins/__tests__/plugin-detail-sheet.test.tsx index 1012789943..9279a52303 100644 --- a/web/src/features/task-plugins/__tests__/plugin-detail-sheet.test.tsx +++ b/web/src/features/task-plugins/__tests__/plugin-detail-sheet.test.tsx @@ -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() + + 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({}) diff --git a/web/src/features/task-plugins/__tests__/plugins-table.test.tsx b/web/src/features/task-plugins/__tests__/plugins-table.test.tsx index 1d02ecddf8..8c07937412 100644 --- a/web/src/features/task-plugins/__tests__/plugins-table.test.tsx +++ b/web/src/features/task-plugins/__tests__/plugins-table.test.tsx @@ -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() + 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() + + 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() + + 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() +}) diff --git a/web/src/features/task-plugins/__tests__/upload-dialog.test.tsx b/web/src/features/task-plugins/__tests__/upload-dialog.test.tsx index 3d51ba919a..261473bc6c 100644 --- a/web/src/features/task-plugins/__tests__/upload-dialog.test.tsx +++ b/web/src/features/task-plugins/__tests__/upload-dialog.test.tsx @@ -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 diff --git a/web/src/features/task-plugins/api.ts b/web/src/features/task-plugins/api.ts index a9dac1a65f..dac3e2cdb6 100644 --- a/web/src/features/task-plugins/api.ts +++ b/web/src/features/task-plugins/api.ts @@ -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>( + const response = await api.post>( `/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>( + const response = await api.post>( `/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>( + const response = await api.delete>( `/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() { diff --git a/web/src/features/task-plugins/components/marketplace-install-dialog.tsx b/web/src/features/task-plugins/components/marketplace-install-dialog.tsx index 63bc2203fe..eee1308788 100644 --- a/web/src/features/task-plugins/components/marketplace-install-dialog.tsx +++ b/web/src/features/task-plugins/components/marketplace-install-dialog.tsx @@ -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) }, diff --git a/web/src/features/task-plugins/components/plugin-detail-sheet.tsx b/web/src/features/task-plugins/components/plugin-detail-sheet.tsx index b4a81977a1..c9decb6d10 100644 --- a/web/src/features/task-plugins/components/plugin-detail-sheet.tsx +++ b/web/src/features/task-plugins/components/plugin-detail-sheet.tsx @@ -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 . 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), }) diff --git a/web/src/features/task-plugins/components/plugins-table.tsx b/web/src/features/task-plugins/components/plugins-table.tsx index 6e550d2e98..4c2bbdd2bd 100644 --- a/web/src/features/task-plugins/components/plugins-table.tsx +++ b/web/src/features/task-plugins/components/plugins-table.tsx @@ -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) { diff --git a/web/src/features/task-plugins/components/pricing-issue-list.tsx b/web/src/features/task-plugins/components/pricing-issue-list.tsx new file mode 100644 index 0000000000..f3bc2fb8b2 --- /dev/null +++ b/web/src/features/task-plugins/components/pricing-issue-list.tsx @@ -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 . + +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 ( +
+

{t('Prices of these models need attention:')}

+
    + {props.issues.slice(0, VISIBLE_ISSUES).map((issue) => ( +
  • + {t('{{name}}: {{reason}}', { + name: issue.model_name, + reason: t(PRICING_ISSUE_REASONS[issue.reason]), + })} +
  • + ))} +
+ {hidden > 0 &&

{t('And {{count}} more models', { count: hidden })}

} +
+ ) +} diff --git a/web/src/features/task-plugins/components/upload-dialog.tsx b/web/src/features/task-plugins/components/upload-dialog.tsx index 7266c78f83..08ede403ca 100644 --- a/web/src/features/task-plugins/components/upload-dialog.tsx +++ b/web/src/features/task-plugins/components/upload-dialog.tsx @@ -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 ( )} + {pricingIssues?.length ? ( +
+ +
+ ) : null} {activateMutation.error && (