Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b4262f9e2 | ||
|
|
199cbc0e32 | ||
|
|
b71ac7aa88 | ||
|
|
9b8f0584e6 | ||
|
|
f8e485b555 | ||
|
|
d74ad18614 | ||
|
|
6627f0e3f3 | ||
|
|
c53dcf3356 | ||
|
|
cb074d31e2 | ||
|
|
ede88eb1cc | ||
|
|
51a1ceeaec | ||
|
|
1a395c76a9 | ||
|
|
185e1e51a0 | ||
|
|
8542c9d649 | ||
|
|
ac1330c5c8 | ||
|
|
a85f7e844d | ||
|
|
48f9df96ea | ||
|
|
5cc159213b | ||
|
|
4407b8470f | ||
|
|
329e899ebe | ||
|
|
b2d12187a0 |
No files matched your search
@@ -66,6 +66,8 @@
|
||||
# TASK_POLL_MAX_FAILURES=20
|
||||
# 插件每次调用的 JavaScript 最多可分配的内存,单位 MB,默认 512,0 表示不限制;调大 MAX_REQUEST_BODY_MB 时通常也要调大
|
||||
# PLUGIN_MEMORY_LIMIT_MB=512
|
||||
# 每个网关进程同时压缩的图片数,0(默认)取 Go 可用的 CPU 核数(GOMAXPROCS)
|
||||
# IMAGE_REENCODE_CONCURRENCY=0
|
||||
|
||||
# 对话超时设置
|
||||
# 所有请求超时时间,单位秒,默认为0,表示不限制
|
||||
|
||||
@@ -14,7 +14,7 @@ Transitive dependencies should be audited before a final external release.
|
||||
| backend | production | Go | `github.com/Calcium-Ion/go-epay` | `v0.0.6` | MIT |
|
||||
| backend | production | Go | `github.com/ClickHouse/clickhouse-go/v2` | `v2.46.0` | Apache-2.0 |
|
||||
| backend | production | Go | `github.com/HugoSmits86/nativewebp` | `v1.3.0` | MIT |
|
||||
| backend | production | Go | `github.com/MoeForge/moego` | `v0.1.0-alpha.3` | MIT |
|
||||
| backend | production | Go | `github.com/MoeForge/moego` | `v0.1.0-alpha.5` | MIT |
|
||||
| backend | production | Go | `github.com/MoeForge/moejs` | `v0.1.0` | Apache-2.0 |
|
||||
| backend | production | Go | `github.com/abema/go-mp4` | `v1.4.1` | MIT |
|
||||
| backend | test | Go | `github.com/alicebob/miniredis/v2` | `v2.38.0` | MIT |
|
||||
|
||||
@@ -35,6 +35,12 @@ func GetEndpointTypesByChannelType(channelType int, modelName string) []constant
|
||||
endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAI}
|
||||
case constant.ChannelTypeXai:
|
||||
endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAI, constant.EndpointTypeOpenAIResponse}
|
||||
case constant.ChannelTypeDeepSeek:
|
||||
endpointTypes = []constant.EndpointType{
|
||||
constant.EndpointTypeOpenAI,
|
||||
constant.EndpointTypeOpenAIResponse,
|
||||
constant.EndpointTypeAnthropic,
|
||||
}
|
||||
case constant.ChannelTypeVLLM, constant.ChannelTypeSGLang:
|
||||
endpointTypes = GetAdvancedCustomPreset(channelType).SupportedEndpointTypesForModel(modelName)
|
||||
case constant.ChannelTypeSora:
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
"Epay webhook failed to write response trade_no=%s client_ip=%s error=%q": "易支付 webhook 响应写入失败 trade_no=%s client_ip=%s error=%q",
|
||||
"Epay webhook ignored event trade_no=%s callback_type=%s trade_status=%s client_ip=%s verify_info=%q": "易支付 webhook 忽略事件 trade_no=%s callback_type=%s trade_status=%s client_ip=%s verify_info=%q",
|
||||
"Epay webhook params are empty path=%q client_ip=%s": "易支付 webhook 参数为空 path=%q client_ip=%s",
|
||||
"Epay webhook partner id mismatch path=%q client_ip=%s callback_pid=%q": "易支付 webhook 商户 ID 不匹配 path=%q client_ip=%s callback_pid=%q",
|
||||
"Epay webhook received request path=%q client_ip=%s method=%s params=%q": "易支付 webhook 收到请求 path=%q client_ip=%s method=%s params=%q",
|
||||
"Epay webhook rejected reason=webhook_disabled path=%q client_ip=%s": "易支付 webhook 被拒绝 reason=webhook_disabled path=%q client_ip=%s",
|
||||
"Epay webhook signature verification failed path=%q client_ip=%s verify_error=%q": "易支付 webhook 验签失败 path=%q client_ip=%s verify_error=%q",
|
||||
|
||||
@@ -28,11 +28,16 @@ func TestWanEndpointsDistinguishImagesFromVideos(t *testing.T) {
|
||||
}
|
||||
|
||||
// /v1/models reports the DeepSeek Search and Fetch routing names with their
|
||||
// own endpoint on the channels that relay them; chat models keep their list.
|
||||
// own endpoint on the channels that relay them; chat models report every
|
||||
// protocol DeepSeek serves.
|
||||
func TestDeepSeekToolRoutingNamesReportTheirEndpoint(t *testing.T) {
|
||||
for _, channelType := range []int{constant.ChannelTypeDeepSeek, constant.ChannelTypeNewAPI} {
|
||||
assert.Equal(t, []constant.EndpointType{constant.EndpointTypeDeepSeekToolsSearch}, common.GetEndpointTypesByChannelType(channelType, constant.DeepSeekSearchModel))
|
||||
assert.Equal(t, []constant.EndpointType{constant.EndpointTypeDeepSeekToolsFetch}, common.GetEndpointTypesByChannelType(channelType, constant.DeepSeekFetchModel))
|
||||
}
|
||||
assert.Equal(t, []constant.EndpointType{constant.EndpointTypeOpenAI}, common.GetEndpointTypesByChannelType(constant.ChannelTypeDeepSeek, "deepseek-flash"))
|
||||
assert.Equal(t, []constant.EndpointType{
|
||||
constant.EndpointTypeOpenAI,
|
||||
constant.EndpointTypeOpenAIResponse,
|
||||
constant.EndpointTypeAnthropic,
|
||||
}, common.GetEndpointTypesByChannelType(constant.ChannelTypeDeepSeek, "deepseek-flash"))
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -826,15 +827,25 @@ type releasedAuditLog struct {
|
||||
|
||||
func (releasedAuditLog) TableName() string { return "logs" }
|
||||
|
||||
// sqliteTestDatabaseDSN keeps file-backed persistence and production locking.
|
||||
// These fixtures do not simulate power loss, so NORMAL avoids syncing every write.
|
||||
func sqliteTestDatabaseDSN(t *testing.T, name string) string {
|
||||
t.Helper()
|
||||
return filepath.Join(t.TempDir(), name) + "?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_txlock=immediate"
|
||||
}
|
||||
|
||||
// External tests create a new database per case on a loopback-only disposable
|
||||
// instance. They never drop databases or tables supplied through an environment variable.
|
||||
func newAuditTestDatabase(t *testing.T, kind, dsn string) (*gorm.DB, string) {
|
||||
t.Helper()
|
||||
if kind == "sqlite" {
|
||||
path := t.TempDir() + "/audit.db"
|
||||
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
|
||||
dsn := sqliteTestDatabaseDSN(t, "audit.db")
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
return db, path
|
||||
connection, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { assert.NoError(t, connection.Close()) })
|
||||
return db, dsn
|
||||
}
|
||||
require.NotEmpty(t, dsn)
|
||||
name := fmt.Sprintf("newapi_audit_%d", time.Now().UnixNano())
|
||||
@@ -983,6 +994,11 @@ func verifyAuditJSONStorage(t *testing.T) {
|
||||
assert.JSONEq(t, `{}`, string(empty))
|
||||
for range 2 {
|
||||
require.NoError(t, model.InitLogDB())
|
||||
if os.Getenv("LOG_SQL_DSN") != "" {
|
||||
connection, err := model.LOG_DB.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { assert.NoError(t, connection.Close()) })
|
||||
}
|
||||
}
|
||||
entries, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
@@ -1076,6 +1092,9 @@ func TestAuditDatabaseMatrix(t *testing.T) {
|
||||
}
|
||||
for range 2 {
|
||||
require.NoError(t, model.InitDB())
|
||||
connection, err := model.DB.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { assert.NoError(t, connection.Close()) })
|
||||
require.NoError(t, model.InitLogDB())
|
||||
}
|
||||
if !upgrade {
|
||||
@@ -1188,8 +1207,12 @@ func TestIndependentAuditLogStores(t *testing.T) {
|
||||
}
|
||||
t.Setenv("LOG_SQL_DSN", isolatedDSN)
|
||||
t.Setenv("LOG_SQL_CLICKHOUSE_TTL_DAYS", "7")
|
||||
require.NoError(t, model.InitLogDB())
|
||||
require.NoError(t, model.InitLogDB())
|
||||
for range 2 {
|
||||
require.NoError(t, model.InitLogDB())
|
||||
connection, err := model.LOG_DB.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { assert.NoError(t, connection.Close()) })
|
||||
}
|
||||
if upgrade {
|
||||
var old model.Log
|
||||
require.NoError(t, model.LOG_DB.Where("request_id = ?", "legacy-split-request").Take(&old).Error)
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -29,7 +28,7 @@ func setupChannelCreateTest(t *testing.T) int {
|
||||
t.Setenv("SQL_DSN", os.Getenv("TEST_CHANNEL_SQL_DSN"))
|
||||
t.Setenv("LOG_SQL_DSN", "")
|
||||
common.IsMasterNode, common.MemoryCacheEnabled, common.RedisEnabled = false, false, false
|
||||
common.SQLitePath = filepath.Join(t.TempDir(), "channel.db")
|
||||
common.SQLitePath = sqliteTestDatabaseDSN(t, "channel.db")
|
||||
require.NoError(t, model.InitDB())
|
||||
database := model.DB
|
||||
sqlDB, err := database.DB()
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
@@ -28,7 +27,7 @@ func TestMultiKeyEnableRestoresOnlyExhaustedChannels(t *testing.T) {
|
||||
t.Setenv("SQL_DSN", os.Getenv("TEST_CHANNEL_SQL_DSN"))
|
||||
t.Setenv("LOG_SQL_DSN", "")
|
||||
common.IsMasterNode, common.MemoryCacheEnabled, common.RedisEnabled = false, false, false
|
||||
common.SQLitePath = filepath.Join(t.TempDir(), "channel.db")
|
||||
common.SQLitePath = sqliteTestDatabaseDSN(t, "channel.db")
|
||||
require.NoError(t, model.InitDB())
|
||||
database := model.DB
|
||||
sqlDB, err := database.DB()
|
||||
|
||||
@@ -7,10 +7,12 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
perfmetrics "github.com/QuantumNous/new-api/pkg/perf_metrics"
|
||||
"github.com/QuantumNous/new-api/relaykit/dto"
|
||||
"github.com/QuantumNous/new-api/setting"
|
||||
"github.com/QuantumNous/new-api/setting/config"
|
||||
@@ -171,6 +173,94 @@ func pricingByModelName(pricings []model.Pricing) map[string]model.Pricing {
|
||||
return byName
|
||||
}
|
||||
|
||||
func modelSquareData[T any](t *testing.T, handler gin.HandlerFunc, path, userGroup string) T {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if userGroup != "" {
|
||||
common.SetContextKey(ctx, constant.ContextKeyUserGroup, userGroup)
|
||||
}
|
||||
handler(ctx)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
|
||||
require.True(t, response.Success)
|
||||
return response.Data
|
||||
}
|
||||
|
||||
func TestModelSquareGroupVisibility(t *testing.T) {
|
||||
originalGroups := setting.UserUsableGroups2JSONString()
|
||||
originalRatios := ratio_setting.GroupRatio2JSONString()
|
||||
t.Cleanup(func() {
|
||||
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(originalGroups))
|
||||
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(originalRatios))
|
||||
})
|
||||
|
||||
for _, dialect := range []struct{ kind, env string }{{"sqlite", ""}, {"mysql", "TEST_MYSQL_DSN"}, {"postgres", "TEST_POSTGRES_DSN"}} {
|
||||
t.Run(dialect.kind, func(t *testing.T) {
|
||||
if dialect.env != "" && os.Getenv(dialect.env) == "" {
|
||||
t.Skip("set " + dialect.env + " to run this database")
|
||||
}
|
||||
db := modelManagementDB(t, dialect.kind, os.Getenv(dialect.env))
|
||||
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Public"}`))
|
||||
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1,"internal":2}`))
|
||||
require.NoError(t, db.Create(&[]model.Ability{
|
||||
{Model: "shared", Group: "default", ChannelId: 1, Enabled: true},
|
||||
{Model: "shared", Group: "internal", ChannelId: 1, Enabled: true},
|
||||
{Model: "private-only", Group: "internal", ChannelId: 1, Enabled: true},
|
||||
{Model: "wildcard", Group: "all", ChannelId: 1, Enabled: true},
|
||||
{Model: "wildcard", Group: "internal", ChannelId: 1, Enabled: true},
|
||||
}).Error)
|
||||
model.InvalidatePricingCache()
|
||||
t.Cleanup(model.InvalidatePricingCache)
|
||||
|
||||
guest := pricingByModelName(modelSquareData[[]model.Pricing](t, GetPricing, "/api/pricing", ""))
|
||||
assert.Equal(t, []string{"default"}, guest["shared"].EnableGroup)
|
||||
assert.Equal(t, []string{"all"}, guest["wildcard"].EnableGroup)
|
||||
assert.NotContains(t, guest, "private-only")
|
||||
member := pricingByModelName(modelSquareData[[]model.Pricing](t, GetPricing, "/api/pricing", "internal"))
|
||||
assert.ElementsMatch(t, []string{"default", "internal"}, member["shared"].EnableGroup)
|
||||
assert.Equal(t, []string{"internal"}, member["private-only"].EnableGroup)
|
||||
|
||||
require.NoError(t, db.AutoMigrate(&model.PerfMetric{}))
|
||||
ts := time.Now().Add(-time.Hour).Unix()
|
||||
require.NoError(t, db.Create(&[]model.PerfMetric{
|
||||
{ModelName: "shared", Group: "default", BucketTs: ts, RequestCount: 1, SuccessCount: 1},
|
||||
{ModelName: "shared", Group: "internal", BucketTs: ts, RequestCount: 1},
|
||||
{ModelName: "private-only", Group: "internal", BucketTs: ts, RequestCount: 1},
|
||||
}).Error)
|
||||
const detailPath = "/api/perf-metrics?model=shared"
|
||||
const summaryPath = "/api/perf-metrics/summary?recent_model=private-only"
|
||||
detail := modelSquareData[perfmetrics.QueryResult](t, GetPerfMetrics, detailPath, "")
|
||||
require.Len(t, detail.Groups, 1)
|
||||
assert.Equal(t, "default", detail.Groups[0].Group)
|
||||
denied := modelSquareData[perfmetrics.QueryResult](t, GetPerfMetrics, detailPath+"&group=internal", "")
|
||||
assert.Empty(t, denied.Groups)
|
||||
summary := modelSquareData[perfmetrics.SummaryAllResult](t, GetPerfMetricsSummary, summaryPath, "")
|
||||
require.Len(t, summary.Models, 1)
|
||||
assert.Equal(t, "shared", summary.Models[0].ModelName)
|
||||
assert.Equal(t, 100.0, summary.Models[0].SuccessRate)
|
||||
assert.NotContains(t, summary.RecentSuccessSeries, "private-only")
|
||||
allowed := modelSquareData[perfmetrics.QueryResult](t, GetPerfMetrics, detailPath+"&group=internal", "internal")
|
||||
require.Len(t, allowed.Groups, 1)
|
||||
assert.Equal(t, "internal", allowed.Groups[0].Group)
|
||||
|
||||
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{}`))
|
||||
assert.Empty(t, modelSquareData[[]model.Pricing](t, GetPricing, "/api/pricing", ""))
|
||||
assert.Empty(t, modelSquareData[perfmetrics.QueryResult](t, GetPerfMetrics, detailPath, "").Groups)
|
||||
assert.Empty(t, modelSquareData[perfmetrics.SummaryAllResult](t, GetPerfMetricsSummary, summaryPath, "").Models)
|
||||
dashboard := modelSquareData[perfmetrics.SummaryAllResult](t, GetDashboardPerfMetricsSummary, "/api/data/perf-metrics/summary", "")
|
||||
assert.Len(t, dashboard.Models, 2)
|
||||
require.NotNil(t, dashboard.Summary)
|
||||
assert.Equal(t, 33.33, dashboard.Summary.SuccessRate)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func decodeUserModelsResponse(t *testing.T, recorder *httptest.ResponseRecorder) []string {
|
||||
t.Helper()
|
||||
|
||||
|
||||
@@ -416,8 +416,30 @@ func TestEpayRSAModeSignsOrdersAndVerifiesCallbacks(t *testing.T) {
|
||||
unsigned := maps.Clone(paid)
|
||||
delete(unsigned, "sign")
|
||||
|
||||
// A platform can sign callbacks for multiple merchants with the same key.
|
||||
// Valid signatures alone must not allow another merchant to settle our order.
|
||||
platform.Config.PartnerID = "another_merchant"
|
||||
wrongPartnerPaid, err := platform.SignParams(paidFields)
|
||||
require.NoError(t, err)
|
||||
wrongPartnerPending, err := platform.SignParams(map[string]string{
|
||||
"type": "alipay", "money": "1.00", "name": "item", "out_trade_no": "order", "trade_status": "WAIT_BUYER_PAY",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
platform.Config.PartnerID = ""
|
||||
missingPartner, err := platform.SignParams(paidFields)
|
||||
require.NoError(t, err)
|
||||
delete(missingPartner, "pid")
|
||||
for _, params := range []map[string]string{wrongPartnerPaid, wrongPartnerPending, missingPartner} {
|
||||
verified, err := client.Verify(params)
|
||||
require.NoError(t, err)
|
||||
require.True(t, verified.VerifyStatus, "merchant rejection must not rely on an invalid signature")
|
||||
}
|
||||
|
||||
assertEpayCallbacksVerifyBeforeSettlement(t, []epayCallbackCase{
|
||||
{name: "valid pending signed by platform", params: pending, validPending: true},
|
||||
{name: "valid signature for another merchant paid", params: wrongPartnerPaid},
|
||||
{name: "valid signature for another merchant pending", params: wrongPartnerPending},
|
||||
{name: "valid signature without merchant", params: missingPartner},
|
||||
{name: "tampered amount", params: tampered},
|
||||
{name: "signed with merchant key", params: merchantSigned},
|
||||
{name: "MD5 signature in RSA mode", params: md5Signed},
|
||||
|
||||
@@ -5,14 +5,37 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
perfmetrics "github.com/QuantumNous/new-api/pkg/perf_metrics"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/QuantumNous/new-api/setting/ratio_setting"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func usablePerfMetricGroups(c *gin.Context) []string {
|
||||
userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
|
||||
usableGroups := service.GetUserUsableGroups(userGroup)
|
||||
// A non-nil empty list restricts the metrics query to zero groups.
|
||||
groups := make([]string, 0, len(usableGroups))
|
||||
for group := range usableGroups {
|
||||
if group == "auto" || ratio_setting.ContainsGroupRatio(group) {
|
||||
groups = append(groups, group)
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
func GetPerfMetricsSummary(c *gin.Context) {
|
||||
getPerfMetricsSummary(c, usablePerfMetricGroups(c))
|
||||
}
|
||||
|
||||
func GetDashboardPerfMetricsSummary(c *gin.Context) {
|
||||
getPerfMetricsSummary(c, append(lo.Keys(ratio_setting.GetGroupRatioCopy()), "auto"))
|
||||
}
|
||||
|
||||
func getPerfMetricsSummary(c *gin.Context, groups []string) {
|
||||
hours := 24
|
||||
if rawHours := c.Query("hours"); rawHours != "" {
|
||||
if parsed, err := strconv.Atoi(rawHours); err == nil {
|
||||
@@ -25,8 +48,7 @@ func GetPerfMetricsSummary(c *gin.Context) {
|
||||
common.ApiErrorStatus(c, http.StatusBadRequest, common.NewMessage("Invalid parameters"))
|
||||
return
|
||||
}
|
||||
activeGroups := append(lo.Keys(ratio_setting.GetGroupRatioCopy()), "auto")
|
||||
result, err := perfmetrics.QuerySummaryAll(hours, activeGroups, recentModels...)
|
||||
result, err := perfmetrics.QuerySummaryAll(hours, groups, recentModels...)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
@@ -62,7 +84,7 @@ func GetPerfMetrics(c *gin.Context) {
|
||||
Model: modelName,
|
||||
Group: c.Query("group"),
|
||||
Hours: hours,
|
||||
AllowedGroups: append(lo.Keys(ratio_setting.GetGroupRatioCopy()), "auto"),
|
||||
AllowedGroups: usablePerfMetricGroups(c),
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
|
||||
@@ -99,6 +99,13 @@ func serveTaskPluginImageProtocol(c *gin.Context, pinned pluginruntime.PinnedEnd
|
||||
respondPluginProtocolError(c, http.StatusInternalServerError, "task_protocol_error", "Task protocol request failed")
|
||||
return
|
||||
}
|
||||
// Submission may retry with a different channel's rules. Render and inline
|
||||
// images using the final attempt's request, not the original client body.
|
||||
if value, exists := c.Get(pluginruntime.ContextKeyEffectiveImageRequest); exists {
|
||||
if effective, ok := value.(pluginruntime.ProtocolRequestContext); ok {
|
||||
protocolRequest = effective
|
||||
}
|
||||
}
|
||||
task := outcome.Task
|
||||
if task.Status != model.TaskStatusSuccess && task.Status != model.TaskStatusFailure {
|
||||
if taskErr = waitTaskPluginImageTask(c, task, deps); taskErr != nil {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
@@ -17,7 +19,9 @@ import (
|
||||
"github.com/QuantumNous/new-api/dto"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
pluginruntime "github.com/QuantumNous/new-api/pkg/jsplugin"
|
||||
"github.com/QuantumNous/new-api/plugins"
|
||||
"github.com/QuantumNous/new-api/relay"
|
||||
taskjsplugin "github.com/QuantumNous/new-api/relay/channel/task/jsplugin"
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -1713,6 +1717,308 @@ func TestServeTaskPluginImageProtocolRendersImmediateResultAndInlinesBase64(t *t
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeTaskPluginImageProtocolAppliesChannelOverrides(t *testing.T) {
|
||||
loaded := make(map[string]*pluginruntime.LoadedPlugin)
|
||||
for _, key := range []string{"doubao", "alibaba"} {
|
||||
source, err := plugins.Source(key)
|
||||
require.NoError(t, err)
|
||||
loaded[key], err = pluginruntime.NewRegistry().RegisterFactory(source, pluginruntime.Options{Key: key})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
force := `{"operations":[{"mode":"set","path":"response_format","value":"b64_json","conditions":[{"path":"original_model","mode":"contains","value":"seedream"}]}]}`
|
||||
keep := strings.Replace(force, `"mode":"set"`, `"keep_origin":true,"mode":"set"`, 1)
|
||||
bailian := strings.Replace(force, `"value":"seedream"`, `"value":"bailian"`, 1)
|
||||
for _, tc := range []struct {
|
||||
name, clientFormat string
|
||||
pluginKey string
|
||||
model string
|
||||
overrides []string
|
||||
prompts []string
|
||||
multipart bool
|
||||
async bool
|
||||
wantParameters map[string]any
|
||||
wantB64 bool
|
||||
wantCount float64
|
||||
wantStatus int
|
||||
wantCode string
|
||||
wantNoRetry bool
|
||||
}{
|
||||
{name: "original model fills missing format", overrides: []string{force}, wantB64: true},
|
||||
{name: "force replaces URL", clientFormat: "url", overrides: []string{force}, wantB64: true},
|
||||
{name: "keep origin preserves URL", clientFormat: "url", overrides: []string{keep}},
|
||||
{name: "keep origin fills missing format", overrides: []string{keep}, wantB64: true},
|
||||
{name: "unmatched condition", overrides: []string{strings.Replace(force, `"value":"seedream"`, `"value":"other"`, 1)}},
|
||||
{name: "condition uses mapped model", overrides: []string{strings.Replace(strings.Replace(force, `"original_model"`, `"model"`, 1), `"value":"seedream"`, `"value":"5-0-lite"`, 1)}, wantB64: true},
|
||||
{name: "legacy override", overrides: []string{`{"response_format":"b64_json"}`}, wantB64: true},
|
||||
{name: "multipart edit preserves upload", multipart: true, overrides: []string{`{"response_format":"b64_json","seed":7}`}, wantB64: true},
|
||||
{name: "usage follows overridden group count", overrides: []string{`{"response_format":"b64_json","sequential_image_generation":"auto","sequential_image_generation_options":{"max_images":3}}`}, wantB64: true, wantCount: 3},
|
||||
{name: "retry starts from original request", overrides: []string{
|
||||
`{"response_format":"b64_json","operations":[{"mode":"append","path":"prompt","value":" first"}]}`,
|
||||
`{"operations":[{"mode":"append","path":"prompt","value":" second"}]}`,
|
||||
}, prompts: []string{"a cat first", "a cat second"}},
|
||||
{name: "retry without rules restores client format", clientFormat: "b64_json", overrides: []string{`{"response_format":"url"}`, `{}`}, wantB64: true},
|
||||
{name: "decoder rejects overridden count", overrides: []string{`{"n":129}`}, wantStatus: 400, wantCode: "plugin_request_invalid"},
|
||||
{name: "decoder rejects overridden format", overrides: []string{`{"response_format":"invalid"}`}, wantStatus: 400, wantCode: "plugin_request_invalid"},
|
||||
{name: "model pin cannot change", overrides: []string{`{"model":"another-model"}`}, wantStatus: 400, wantCode: "channel_param_override_invalid", wantNoRetry: true},
|
||||
{name: "invalid rule stops submission", overrides: []string{`{"operations":[{"mode":"invalid","path":"response_format"}]}`}, wantStatus: 400, wantCode: "channel_param_override_invalid", wantNoRetry: true},
|
||||
{name: "return error stops submission", overrides: []string{`{"operations":[{"mode":"return_error","value":{"message":"blocked by image rule","status_code":429,"code":"image_rule_blocked"}}]}`}, wantStatus: 429, wantCode: "image_rule_blocked", wantNoRetry: true},
|
||||
{name: "alibaba/no overrides preserves URL", pluginKey: "alibaba", overrides: []string{`{}`}},
|
||||
{name: "alibaba/client Base64 without overrides", pluginKey: "alibaba", clientFormat: "b64_json", overrides: []string{`{}`}, wantB64: true},
|
||||
{name: "alibaba/Seedream condition does not match", pluginKey: "alibaba", overrides: []string{force}},
|
||||
{name: "alibaba/original alias condition", pluginKey: "alibaba", model: "bailian-image", overrides: []string{bailian}, wantB64: true},
|
||||
{name: "alibaba/mapped model condition", pluginKey: "alibaba", model: "bailian-image", overrides: []string{strings.Replace(strings.Replace(force, `"original_model"`, `"model"`, 1), `"value":"seedream"`, `"value":"qwen-image"`, 1)}, wantB64: true},
|
||||
{name: "alibaba/force replaces URL", pluginKey: "alibaba", clientFormat: "url", overrides: []string{`{"response_format":"b64_json"}`}, wantB64: true},
|
||||
{name: "alibaba/keep origin preserves URL", pluginKey: "alibaba", model: "bailian-image", clientFormat: "url", overrides: []string{strings.Replace(bailian, `"mode":"set"`, `"keep_origin":true,"mode":"set"`, 1)}},
|
||||
{name: "alibaba/Qwen parameters and usage", pluginKey: "alibaba", overrides: []string{`{"response_format":"b64_json","n":2,"size":"1024x1024"}`}, wantB64: true, wantCount: 2, wantParameters: map[string]any{"n": 2, "size": "1024*1024"}},
|
||||
{name: "alibaba/nested provider parameters and usage", pluginKey: "alibaba", overrides: []string{`{"response_format":"b64_json","operations":[{"mode":"set","path":"parameters.n","value":2},{"mode":"set","path":"parameters.size","value":"1024x1024"},{"mode":"set","path":"parameters.watermark","value":false}]}`}, wantB64: true, wantCount: 2, wantParameters: map[string]any{"n": 2, "size": "1024*1024", "watermark": false}},
|
||||
{name: "alibaba/multipart Qwen edit", pluginKey: "alibaba", model: "qwen-image-edit-plus", multipart: true, overrides: []string{`{"response_format":"b64_json","n":2,"seed":7,"watermark":false}`}, wantB64: true, wantCount: 2, wantParameters: map[string]any{"n": 2, "seed": 7, "watermark": false}},
|
||||
{name: "alibaba/legacy Wan async result", pluginKey: "alibaba", model: "wan2.2-t2i-flash", async: true, overrides: []string{`{"response_format":"b64_json","n":2,"size":"1024x1024"}`}, wantB64: true, wantCount: 2, wantParameters: map[string]any{"n": 2, "size": "1024*1024"}},
|
||||
{name: "alibaba/modern Wan async result", pluginKey: "alibaba", model: "wan2.6-t2i", async: true, overrides: []string{`{"response_format":"b64_json","n":2}`}, wantB64: true, wantCount: 2, wantParameters: map[string]any{"n": 2}},
|
||||
{name: "alibaba/provider rejects oversized count", pluginKey: "alibaba", overrides: []string{`{"n":129}`}, wantStatus: 400, wantCode: "plugin_request_invalid"},
|
||||
{name: "alibaba/provider rejects oversized nested count", pluginKey: "alibaba", overrides: []string{`{"operations":[{"mode":"set","path":"parameters.n","value":129}]}`}, wantStatus: 400, wantCode: "plugin_request_invalid"},
|
||||
{name: "alibaba/fixed count model remains restricted", pluginKey: "alibaba", model: "qwen-image-plus", overrides: []string{`{"n":2}`}, wantStatus: 400, wantCode: "plugin_request_invalid"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pluginKey, clientModel := tc.pluginKey, tc.model
|
||||
if pluginKey == "" {
|
||||
pluginKey = "doubao"
|
||||
}
|
||||
if clientModel == "" {
|
||||
clientModel = "doubao-seedream"
|
||||
if pluginKey == "alibaba" {
|
||||
clientModel = "qwen-image-3.0-pro"
|
||||
}
|
||||
}
|
||||
upstreamModel := "doubao-seedream-5-0-lite-260128"
|
||||
if pluginKey == "alibaba" {
|
||||
upstreamModel = clientModel
|
||||
if clientModel == "bailian-image" {
|
||||
upstreamModel = "qwen-image-3.0-pro"
|
||||
}
|
||||
}
|
||||
plugin := loaded[pluginKey]
|
||||
pinned := pluginruntime.PinnedEndpoint{Plugin: plugin, Model: clientModel, Protocol: pluginruntime.ProtocolOpenAIImage}
|
||||
c, recorder := newImageProtocolTestContext("")
|
||||
c.Set("resolved_task_model", pinned.Model)
|
||||
c.Set(pluginruntime.ContextKeyPinnedEndpoint, pinned)
|
||||
value := map[string]any{"model": pinned.Model, "prompt": "a cat", "n": 1}
|
||||
if tc.clientFormat != "" {
|
||||
value["response_format"] = tc.clientFormat
|
||||
}
|
||||
raw, err := common.Marshal(value)
|
||||
require.NoError(t, err)
|
||||
request := pluginruntime.ProtocolRequestContext{
|
||||
RouteRequestContext: pluginruntime.RouteRequestContext{Body: map[string]any{"kind": "json", "value": value}, BodyText: raw},
|
||||
Protocol: pluginruntime.ProtocolOpenAIImage, Operation: "generate", Model: pinned.Model,
|
||||
}
|
||||
if tc.multipart {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
fields := map[string][]string{"model": {pinned.Model}, "prompt": {"a cat"}, "n": {"1"}}
|
||||
for key, values := range fields {
|
||||
require.NoError(t, writer.WriteField(key, values[0]))
|
||||
}
|
||||
file, err := writer.CreateFormFile("image", "reference.png")
|
||||
require.NoError(t, err)
|
||||
_, err = file.Write([]byte("AAA"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", &body)
|
||||
c.Request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
request.Operation, request.BodyText = "edit", nil
|
||||
request.Body = map[string]any{"kind": "multipart", "fields": fields, "files": []any{map[string]any{"ref": "request_file:image", "field": "image", "filename": "reference.png", "mimeType": "image/png", "size": 3}}}
|
||||
}
|
||||
original, err := common.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
originalText := string(request.BodyText)
|
||||
c.Set(pluginruntime.ContextKeyProtocolRequest, request)
|
||||
deps := pluginProtocolTestDeps()
|
||||
downloads, built, polls := 0, 0, 0
|
||||
var finalAdaptor *taskjsplugin.TaskAdaptor
|
||||
deps.downloadImage = func(string) (string, string, error) {
|
||||
downloads++
|
||||
return "image/png", "QUFB", nil
|
||||
}
|
||||
deps.submit = func(c *gin.Context, info *relaycommon.RelayInfo) (*taskSubmissionOutcome, *dto.TaskError) {
|
||||
info.PublicTaskID = "task_image"
|
||||
for index, rawOverride := range tc.overrides {
|
||||
var override map[string]any
|
||||
require.NoError(t, common.UnmarshalJsonStr(rawOverride, &override))
|
||||
info.ChannelMeta = &relaycommon.ChannelMeta{
|
||||
ChannelBaseUrl: "https://provider.example", UpstreamModelName: upstreamModel, ParamOverride: override,
|
||||
}
|
||||
adaptor := taskjsplugin.New(plugin)
|
||||
adaptor.Init(info)
|
||||
if taskErr := adaptor.ValidateRequestAndSetAction(c, info); taskErr != nil {
|
||||
assert.Equal(t, tc.wantNoRetry, taskErr.NoRetry)
|
||||
return nil, taskErr
|
||||
}
|
||||
body, err := adaptor.BuildRequestBody(c, info)
|
||||
require.NoError(t, err)
|
||||
var upstream map[string]any
|
||||
require.NoError(t, common.DecodeJson(body, &upstream))
|
||||
built++
|
||||
assert.NotContains(t, upstream, "response_format", "the host owns Base64 conversion")
|
||||
assert.Equal(t, info.UpstreamModelName, upstream["model"])
|
||||
wantPrompt := "a cat"
|
||||
if len(tc.prompts) > 0 {
|
||||
wantPrompt = tc.prompts[index]
|
||||
}
|
||||
if pluginKey == "alibaba" {
|
||||
input := upstream["input"].(map[string]any)
|
||||
parameters := upstream["parameters"].(map[string]any)
|
||||
assert.NotContains(t, parameters, "response_format")
|
||||
assert.EqualValues(t, max(1, tc.wantCount), parameters["n"])
|
||||
for key, expected := range tc.wantParameters {
|
||||
assert.EqualValues(t, expected, parameters[key], key)
|
||||
}
|
||||
if tc.model == "wan2.2-t2i-flash" {
|
||||
assert.Equal(t, wantPrompt, input["prompt"])
|
||||
} else {
|
||||
messages := input["messages"].([]any)
|
||||
require.Len(t, messages, 1)
|
||||
content := messages[0].(map[string]any)["content"].([]any)
|
||||
assert.Equal(t, wantPrompt, content[len(content)-1].(map[string]any)["text"])
|
||||
if tc.multipart {
|
||||
require.Len(t, content, 2)
|
||||
assert.Equal(t, "data:image/png;base64,QUFB", content[0].(map[string]any)["image"])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
assert.Equal(t, wantPrompt, upstream["prompt"])
|
||||
if tc.multipart {
|
||||
assert.Equal(t, []any{"data:image/png;base64,QUFB"}, upstream["image"])
|
||||
assert.EqualValues(t, 7, upstream["seed"])
|
||||
}
|
||||
}
|
||||
ratios, err := adaptor.EstimateBillingValidated(c, info)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, max(1, tc.wantCount), ratios["image_count"], "usage follows the submitted request")
|
||||
finalAdaptor = adaptor
|
||||
}
|
||||
task := &model.Task{TaskID: "task_image", Platform: constant.TaskPlatform(pluginKey), UserId: info.UserId, Status: model.TaskStatusSuccess,
|
||||
Properties: model.Properties{OriginModelName: clientModel, UpstreamModelName: upstreamModel}}
|
||||
task.SetData(map[string]any{"data": []any{map[string]any{"url": "https://cdn.example/image.png"}}})
|
||||
if pluginKey == "alibaba" {
|
||||
result := `{"request_id":"request_image","output":{"choices":[{"message":{"content":[{"image":"https://cdn.example/image.png"}]}}]},"usage":{"output_image_count":1}}`
|
||||
if tc.async {
|
||||
result = `{"output":{"task_id":"upstream_image","task_status":"PENDING"}}`
|
||||
}
|
||||
parsed, taskErr := finalAdaptor.ParseResponse(c, &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(result))}, info)
|
||||
require.Nil(t, taskErr)
|
||||
require.NotNil(t, parsed)
|
||||
task.PrivateData.UpstreamTaskID, task.Data = parsed.UpstreamTaskID, parsed.TaskData
|
||||
if tc.async {
|
||||
require.Nil(t, parsed.Immediate)
|
||||
assert.Equal(t, "upstream_image", parsed.UpstreamTaskID)
|
||||
task.Status = model.TaskStatusSubmitted
|
||||
} else {
|
||||
require.NotNil(t, parsed.Immediate)
|
||||
assert.Equal(t, "SUCCESS", parsed.Immediate.Status)
|
||||
assert.EqualValues(t, 1, parsed.Immediate.UsageFacts["image_count"], "completion uses the delivered count rather than the overridden reservation")
|
||||
assert.EqualValues(t, 1, finalAdaptor.AdjustBillingOnSubmit(info, parsed.TaskData)["image_count"])
|
||||
}
|
||||
}
|
||||
return &taskSubmissionOutcome{Task: task, RelayInfo: info}, nil
|
||||
}
|
||||
if tc.async {
|
||||
deps.imagePollInterval = time.Nanosecond
|
||||
deps.pollTask = func(_ context.Context, task *model.Task) error {
|
||||
polls++
|
||||
assert.Equal(t, model.TaskStatusSubmitted, string(task.Status))
|
||||
completed := []byte(`{"output":{"task_id":"upstream_image","task_status":"SUCCEEDED","results":[{"url":"https://cdn.example/image.png"}]},"usage":{"image_count":1}}`)
|
||||
result, err := finalAdaptor.ParseTaskResult(task, &http.Response{StatusCode: http.StatusOK}, completed)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "SUCCESS", result.Status)
|
||||
assert.EqualValues(t, 1, result.UsageFacts["image_count"])
|
||||
task.Status, task.Data = model.TaskStatus(result.Status), completed
|
||||
return nil
|
||||
}
|
||||
}
|
||||
serveTaskPluginImageProtocol(c, pinned, deps)
|
||||
current, err := common.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(original), string(current), "original request maps remain unchanged")
|
||||
assert.Equal(t, originalText, string(request.BodyText), "original JSON bytes remain unchanged")
|
||||
wantStatus := tc.wantStatus
|
||||
if wantStatus == 0 {
|
||||
wantStatus = http.StatusOK
|
||||
}
|
||||
require.Equal(t, wantStatus, recorder.Code, recorder.Body.String())
|
||||
if tc.wantCode != "" {
|
||||
var response struct {
|
||||
Error struct{ Code string } `json:"error"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
|
||||
assert.Equal(t, tc.wantCode, response.Error.Code)
|
||||
assert.Zero(t, built)
|
||||
assert.Zero(t, downloads)
|
||||
return
|
||||
}
|
||||
assert.Equal(t, len(tc.overrides), built)
|
||||
wantPolls := 0
|
||||
if tc.async {
|
||||
wantPolls = 1
|
||||
}
|
||||
assert.Equal(t, wantPolls, polls)
|
||||
var response struct {
|
||||
Data []struct {
|
||||
URL string `json:"url"`
|
||||
B64 string `json:"b64_json"`
|
||||
} `json:"data"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
|
||||
require.Len(t, response.Data, 1)
|
||||
wantB64, wantDownloads := "", 0
|
||||
if tc.wantB64 {
|
||||
wantB64, wantDownloads = "QUFB", 1
|
||||
}
|
||||
assert.Equal(t, wantDownloads, downloads)
|
||||
assert.Equal(t, wantB64, response.Data[0].B64)
|
||||
assert.Equal(t, "https://cdn.example/image.png", response.Data[0].URL)
|
||||
if pluginKey == "alibaba" {
|
||||
assert.Contains(t, response.Metadata, "output", "vendor metadata remains available with Base64 output")
|
||||
usage, ok := response.Metadata["usage"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
countKey := "output_image_count"
|
||||
if tc.async {
|
||||
countKey = "image_count"
|
||||
}
|
||||
assert.EqualValues(t, 1, usage[countKey])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageProtocolOverridesPreservePluginJSONOrder(t *testing.T) {
|
||||
source := strings.Replace(imageProtocolTestPlugin, `protocols:["openai_image"]`, `requiredCapabilities:["json-order@1"],protocols:["openai_image"]`, 1)
|
||||
source = strings.Replace(source, `return {url:ctx.baseUrl+"/images"}`, `return {url:ctx.baseUrl+"/images",body:ctx.requestBody}`, 1)
|
||||
plugin, err := pluginruntime.NewRegistry().Register(source, pluginruntime.Options{})
|
||||
require.NoError(t, err)
|
||||
c, _ := newImageProtocolTestContext("")
|
||||
client := `{"model":"image-model","prompt":"a cat","metadata":{"zeta":1,"alpha":2}}`
|
||||
var value map[string]any
|
||||
require.NoError(t, common.UnmarshalJsonStr(client, &value))
|
||||
c.Set(pluginruntime.ContextKeyProtocolRequest, pluginruntime.ProtocolRequestContext{
|
||||
RouteRequestContext: pluginruntime.RouteRequestContext{Body: map[string]any{"kind": "json", "value": value}, BodyText: []byte(client)},
|
||||
Protocol: pluginruntime.ProtocolOpenAIImage, Model: "image-model",
|
||||
})
|
||||
c.Set(pluginruntime.ContextKeyPinnedEndpoint, pluginruntime.PinnedEndpoint{Plugin: plugin, Protocol: pluginruntime.ProtocolOpenAIImage, Model: "image-model"})
|
||||
info := &relaycommon.RelayInfo{
|
||||
ChannelMeta: &relaycommon.ChannelMeta{ChannelBaseUrl: "https://provider.example", UpstreamModelName: "image-model", ParamOverride: map[string]any{"response_format": "b64_json"}},
|
||||
OriginModelName: "image-model", TaskRelayInfo: &relaycommon.TaskRelayInfo{},
|
||||
}
|
||||
adaptor := taskjsplugin.New(plugin)
|
||||
adaptor.Init(info)
|
||||
require.Nil(t, adaptor.ValidateRequestAndSetAction(c, info))
|
||||
body, err := adaptor.BuildRequestBody(c, info)
|
||||
require.NoError(t, err)
|
||||
raw, err := io.ReadAll(body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `{"model":"image-model","prompt":"a cat","metadata":{"zeta":1,"alpha":2},"response_format":"b64_json"}`, string(raw))
|
||||
}
|
||||
|
||||
// An asynchronous vendor task is polled inside the request until it is
|
||||
// terminal; a failure and the protocol timeout become OpenAI error envelopes
|
||||
// while the durable task stays with the background poller.
|
||||
|
||||
+21
-33
@@ -1,9 +1,8 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"maps"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/QuantumNous/new-api/setting/ratio_setting"
|
||||
@@ -21,46 +20,35 @@ func filterPricingByUsableGroups(pricing []model.Pricing, usableGroup map[string
|
||||
|
||||
filtered := make([]model.Pricing, 0, len(pricing))
|
||||
for _, item := range pricing {
|
||||
if common.StringsContains(item.EnableGroup, "all") {
|
||||
filtered = append(filtered, item)
|
||||
continue
|
||||
}
|
||||
// The pricing cache is shared by all viewers.
|
||||
groups := make([]string, 0, len(item.EnableGroup))
|
||||
for _, group := range item.EnableGroup {
|
||||
if _, ok := usableGroup[group]; ok {
|
||||
filtered = append(filtered, item)
|
||||
break
|
||||
if _, ok := usableGroup[group]; ok || group == "all" {
|
||||
groups = append(groups, group)
|
||||
}
|
||||
}
|
||||
if len(groups) > 0 {
|
||||
item.EnableGroup = groups
|
||||
filtered = append(filtered, item)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func GetPricing(c *gin.Context) {
|
||||
pricing := model.GetPricing()
|
||||
userId, exists := c.Get("id")
|
||||
usableGroup := map[string]string{}
|
||||
groupRatio := map[string]float64{}
|
||||
maps.Copy(groupRatio, ratio_setting.GetGroupRatioCopy())
|
||||
var group string
|
||||
if exists {
|
||||
user, err := model.GetUserCache(userId.(int))
|
||||
if err == nil {
|
||||
group = user.Group
|
||||
for g := range groupRatio {
|
||||
ratio, ok := ratio_setting.GetGroupGroupRatio(group, g)
|
||||
if ok {
|
||||
groupRatio[g] = ratio
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
usableGroup = service.GetUserUsableGroups(group)
|
||||
pricing = filterPricingByUsableGroups(pricing, usableGroup)
|
||||
// check groupRatio contains usableGroup
|
||||
for group := range ratio_setting.GetGroupRatioCopy() {
|
||||
userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
|
||||
usableGroup := service.GetUserUsableGroups(userGroup)
|
||||
pricing := filterPricingByUsableGroups(model.GetPricing(), usableGroup)
|
||||
groupRatio := ratio_setting.GetGroupRatioCopy()
|
||||
for group := range groupRatio {
|
||||
if _, ok := usableGroup[group]; !ok {
|
||||
delete(groupRatio, group)
|
||||
continue
|
||||
}
|
||||
if userGroup != "" {
|
||||
if ratio, ok := ratio_setting.GetGroupGroupRatio(userGroup, group); ok {
|
||||
groupRatio[group] = ratio
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +59,7 @@ func GetPricing(c *gin.Context) {
|
||||
"group_ratio": groupRatio,
|
||||
"usable_group": usableGroup,
|
||||
"supported_endpoint": model.GetSupportedEndpointMap(),
|
||||
"auto_groups": service.GetUserAutoGroup(group),
|
||||
"auto_groups": service.GetUserAutoGroup(userGroup),
|
||||
"pricing_version": "a42d372ccf0b5dd13ecf71203521f9d2",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -665,6 +665,10 @@ func executeTaskSubmissionWith(
|
||||
}
|
||||
|
||||
for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
|
||||
relayInfo.RetryIndex = retryParam.GetRetry()
|
||||
relayInfo.RuntimeHeadersOverride = nil
|
||||
relayInfo.UseRuntimeHeadersOverride = false
|
||||
|
||||
stage = "select_channel"
|
||||
if requestErr := c.Request.Context().Err(); requestErr != nil {
|
||||
diagnostics.cancelled("before_attempt", retryParam.GetRetry()+1)
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -58,7 +57,7 @@ func setupResponsesWSRequestTest(t *testing.T) (*model.User, *model.Token) {
|
||||
t.Setenv("SQL_DSN", os.Getenv("TEST_RESPONSES_SQL_DSN"))
|
||||
t.Setenv("LOG_SQL_DSN", os.Getenv("TEST_RESPONSES_LOG_SQL_DSN"))
|
||||
common.IsMasterNode, common.MemoryCacheEnabled, common.RedisEnabled = false, false, false
|
||||
common.SQLitePath = filepath.Join(t.TempDir(), "responses.db")
|
||||
common.SQLitePath = sqliteTestDatabaseDSN(t, "responses.db")
|
||||
require.NoError(t, model.InitDB())
|
||||
db := model.DB
|
||||
sqlDB, err := db.DB()
|
||||
|
||||
@@ -15,12 +15,12 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/textproto"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/MoeForge/moego/regexp"
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/i18n"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
|
||||
@@ -61,7 +61,7 @@ func setupSecurityEnrollmentTest(t *testing.T) (*model.User, service.AuthIdentit
|
||||
// Deferred transactions can fail to upgrade their read lock when concurrent
|
||||
// proof consumption overlaps account deletion or session revocation.
|
||||
var err error
|
||||
db, err = gorm.Open(sqlite.Open(t.TempDir()+"/security.db?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)&_txlock=immediate"), &gorm.Config{})
|
||||
db, err = gorm.Open(sqlite.Open(sqliteTestDatabaseDSN(t, "security.db")), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
db, _ = newAuditTestDatabase(t, dialect, dsn)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/Calcium-Ion/go-epay/epay"
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/logger"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/QuantumNous/new-api/setting/operation_setting"
|
||||
@@ -151,6 +152,11 @@ func SubscriptionEpayNotify(c *gin.Context) {
|
||||
_, _ = c.Writer.Write([]byte("fail"))
|
||||
return
|
||||
}
|
||||
if !epayCallbackPartnerMatches(client, params) {
|
||||
logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook partner id mismatch path=%q client_ip=%s callback_pid=%q", c.Request.RequestURI, c.ClientIP(), params["pid"]))
|
||||
_, _ = c.Writer.Write([]byte("fail"))
|
||||
return
|
||||
}
|
||||
|
||||
if verifyInfo.TradeStatus != epay.StatusTradeSuccess {
|
||||
_, _ = c.Writer.Write([]byte("fail"))
|
||||
@@ -206,6 +212,11 @@ func SubscriptionEpayReturn(c *gin.Context) {
|
||||
c.Redirect(http.StatusFound, paymentReturnPath("/wallet?pay=fail"))
|
||||
return
|
||||
}
|
||||
if !epayCallbackPartnerMatches(client, params) {
|
||||
logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook partner id mismatch path=%q client_ip=%s callback_pid=%q", c.Request.RequestURI, c.ClientIP(), params["pid"]))
|
||||
c.Redirect(http.StatusFound, paymentReturnPath("/wallet?pay=fail"))
|
||||
return
|
||||
}
|
||||
if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
|
||||
LockOrder(verifyInfo.ServiceTradeNo)
|
||||
defer UnlockOrder(verifyInfo.ServiceTradeNo)
|
||||
|
||||
@@ -9,11 +9,11 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/MoeForge/moego/regexp"
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -156,6 +157,20 @@ func GetEpayClient() *epay.Client {
|
||||
return withUrl
|
||||
}
|
||||
|
||||
func epayCallbackPartnerMatches(client *epay.Client, params map[string]string) bool {
|
||||
if client == nil || client.Config == nil {
|
||||
return false
|
||||
}
|
||||
if !strings.EqualFold(client.Config.SignType, epay.SignTypeRSA) {
|
||||
return true
|
||||
}
|
||||
expectedPID := client.Config.PartnerID
|
||||
if strings.TrimSpace(expectedPID) == "" {
|
||||
return false
|
||||
}
|
||||
return params["pid"] == expectedPID
|
||||
}
|
||||
|
||||
func getPayMoney(amount int64, group string) float64 {
|
||||
dAmount := decimal.NewFromInt(amount)
|
||||
// 充值金额以“展示类型”为准:
|
||||
@@ -467,6 +482,13 @@ func EpayNotify(c *gin.Context) {
|
||||
}
|
||||
return
|
||||
}
|
||||
if !epayCallbackPartnerMatches(client, params) {
|
||||
if _, writeErr := c.Writer.Write([]byte("fail")); writeErr != nil {
|
||||
logger.LogError(c.Request.Context(), common.LogText("Epay webhook failed to write response path=%q client_ip=%s error=%q", c.Request.RequestURI, c.ClientIP(), writeErr.Error()))
|
||||
}
|
||||
logger.LogWarn(c.Request.Context(), common.LogText("Epay webhook partner id mismatch path=%q client_ip=%s callback_pid=%q", c.Request.RequestURI, c.ClientIP(), params["pid"]))
|
||||
return
|
||||
}
|
||||
logger.LogInfo(c.Request.Context(), common.LogText("Epay webhook signature verified trade_no=%s callback_type=%s trade_status=%s client_ip=%s verify_info=%q", verifyInfo.ServiceTradeNo, verifyInfo.Type, verifyInfo.TradeStatus, c.ClientIP(), common.GetJsonString(verifyInfo)))
|
||||
|
||||
if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
|
||||
|
||||
@@ -467,9 +467,9 @@ func TestManageUserQuotaTargetsAndWalletBounds(t *testing.T) {
|
||||
|
||||
func TestManageUserQuotaMiddlewareKeepsOneOperationPerRequest(t *testing.T) {
|
||||
db := setupManageUserTestDB(t)
|
||||
pat := "quota-middleware-test-token"
|
||||
operator := model.User{Id: 9999, Username: "root-operator", Role: common.RoleRootUser, Status: common.UserStatusEnabled, AuthVersion: 1, AccessToken: &pat, Quota: 1000}
|
||||
operator := model.User{Id: 9999, Username: "root-operator", Role: common.RoleRootUser, Status: common.UserStatusEnabled, AuthVersion: 1, Quota: 1000}
|
||||
require.NoError(t, db.Create(&operator).Error)
|
||||
pat, _ := createScopedAccessToken(t, operator.Id, 0, "user:write")
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequestId(), middleware.AccessTokenAudit())
|
||||
router.POST("/api/user/manage", middleware.AdminAuth(), ManageUser)
|
||||
@@ -528,12 +528,6 @@ func TestManageUserQuotaConcurrentSnapshots(t *testing.T) {
|
||||
var ready sync.WaitGroup
|
||||
ready.Add(2)
|
||||
release := make(chan struct{})
|
||||
require.NoError(t, db.Callback().Query().Before("gorm:query").Register("test:concurrent_quota_start", func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "users" {
|
||||
ready.Done()
|
||||
<-release
|
||||
}
|
||||
}))
|
||||
type result struct {
|
||||
adjustment *model.UserQuotaAdjustment
|
||||
err error
|
||||
@@ -542,6 +536,10 @@ func TestManageUserQuotaConcurrentSnapshots(t *testing.T) {
|
||||
results := make(chan result, 2)
|
||||
for _, value := range []int{10, 20} {
|
||||
go func(value int) {
|
||||
// Synchronize before BEGIN IMMEDIATE takes SQLite's writer lock.
|
||||
// Waiting at the first SELECT would prevent the other writer entering.
|
||||
ready.Done()
|
||||
<-release
|
||||
adjustment, err := model.AdjustUserQuota(user.Id, common.RoleRootUser, "add", value)
|
||||
results <- result{adjustment, err, value}
|
||||
}(value)
|
||||
@@ -561,8 +559,7 @@ func TestManageUserQuotaConcurrentSnapshots(t *testing.T) {
|
||||
assert.Equal(t, result.value, result.adjustment.After-result.adjustment.Before)
|
||||
committed = append(committed, *result.adjustment)
|
||||
}
|
||||
require.NoError(t, db.Callback().Query().Remove("test:concurrent_quota_start"))
|
||||
require.NotEmpty(t, committed)
|
||||
require.Len(t, committed, 2, "both concurrent adjustments must commit under the database's writer lock")
|
||||
sort.Slice(committed, func(i, j int) bool { return committed[i].Before < committed[j].Before })
|
||||
balance := 1000
|
||||
for _, adjustment := range committed {
|
||||
|
||||
+31
-11
@@ -219,15 +219,30 @@ func proxyTaskMedia(c *gin.Context, task *model.Task, descriptor *relaychannel.T
|
||||
}
|
||||
setting := channel.GetSetting()
|
||||
proxy := strings.TrimSpace(setting.Proxy)
|
||||
if err := validateTaskMediaURL(rawURL, proxy); err != nil {
|
||||
return &taskMediaProxyError{
|
||||
status: http.StatusBadGateway, code: "artifact_request_rejected",
|
||||
message: "Artifact request was rejected", err: err,
|
||||
var trustedOrigin *url.URL
|
||||
if taskHasPluginExecution(task) && !descriptor.Credentialless {
|
||||
baseURL := channel.GetBaseURL()
|
||||
if baseURL == "" {
|
||||
baseURL = constant.GetChannelBaseURL(channel.Type)
|
||||
}
|
||||
channelURL, parseErr := url.Parse(baseURL)
|
||||
if parseErr == nil && channelURL.User == nil && channelURL.Fragment == "" && sameTaskMediaOrigin(channelURL, parsedURL) {
|
||||
// A validated plugin request to the operator-configured channel uses
|
||||
// the same private upstream transport as submission and polling.
|
||||
trustedOrigin = channelURL
|
||||
}
|
||||
}
|
||||
if trustedOrigin == nil {
|
||||
if err := validateTaskMediaURL(rawURL, proxy); err != nil {
|
||||
return &taskMediaProxyError{
|
||||
status: http.StatusBadGateway, code: "artifact_request_rejected",
|
||||
message: "Artifact request was rejected", err: err,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
client := service.GetSSRFProtectedHTTPClient()
|
||||
if proxy != "" {
|
||||
if trustedOrigin != nil || proxy != "" {
|
||||
client, err = service.GetHttpClientWithProxySettings(proxy, setting)
|
||||
if err != nil {
|
||||
return &taskMediaProxyError{
|
||||
@@ -262,7 +277,7 @@ func proxyTaskMedia(c *gin.Context, task *model.Task, descriptor *relaychannel.T
|
||||
req.Header.Set(name, value)
|
||||
}
|
||||
|
||||
client = taskMediaRedirectClient(client, proxy, c, clientHeaders, descriptor.Credentialless)
|
||||
client = taskMediaRedirectClient(client, proxy, c, clientHeaders, descriptor.Credentialless, trustedOrigin)
|
||||
clientWithoutBodyTimeout := *client
|
||||
clientWithoutBodyTimeout.Timeout = 0
|
||||
resp, err := doTaskMediaRequest(&clientWithoutBodyTimeout, req, taskMediaResponseHeaderTimeout)
|
||||
@@ -491,7 +506,7 @@ func applyTaskMediaRequestHeaders(destination http.Header, headers map[string]st
|
||||
return nil
|
||||
}
|
||||
|
||||
func taskMediaRedirectClient(base *http.Client, proxy string, c *gin.Context, clientHeaders map[string]string, credentialless bool) *http.Client {
|
||||
func taskMediaRedirectClient(base *http.Client, proxy string, c *gin.Context, clientHeaders map[string]string, credentialless bool, trustedOrigin *url.URL) *http.Client {
|
||||
cloned := *base
|
||||
cloned.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
@@ -501,7 +516,11 @@ func taskMediaRedirectClient(base *http.Client, proxy string, c *gin.Context, cl
|
||||
req.URL.Host == "" || req.URL.User != nil || req.URL.Fragment != "" {
|
||||
return fmt.Errorf("%w: invalid redirect URL", errTaskMediaRequestRejected)
|
||||
}
|
||||
if err := validateTaskMediaURL(req.URL.String(), proxy); err != nil {
|
||||
if trustedOrigin != nil {
|
||||
if !sameTaskMediaOrigin(trustedOrigin, req.URL) {
|
||||
return fmt.Errorf("%w: redirect outside channel origin", errTaskMediaRequestRejected)
|
||||
}
|
||||
} else if err := validateTaskMediaURL(req.URL.String(), proxy); err != nil {
|
||||
return fmt.Errorf("%w: %v", errTaskMediaRequestRejected, err)
|
||||
}
|
||||
if isSelfTaskMediaURL(c, req.URL) {
|
||||
@@ -558,11 +577,12 @@ func normalizeTaskMediaHost(scheme, host string) string {
|
||||
if err != nil {
|
||||
return strings.TrimSuffix(host, ".")
|
||||
}
|
||||
hostname = strings.TrimSuffix(strings.ToLower(hostname), ".")
|
||||
if (strings.EqualFold(scheme, "http") && port == "80") || (strings.EqualFold(scheme, "https") && port == "443") {
|
||||
return hostname
|
||||
// Keep an IPv6 literal bracketed, as it is when the port is omitted.
|
||||
host = strings.TrimSuffix(host, ":"+port)
|
||||
return strings.TrimSuffix(host, ".")
|
||||
}
|
||||
return net.JoinHostPort(hostname, port)
|
||||
return net.JoinHostPort(strings.TrimSuffix(hostname, "."), port)
|
||||
}
|
||||
|
||||
func isSelfTaskMediaURL(c *gin.Context, target *url.URL) bool {
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
relaychannel "github.com/QuantumNous/new-api/relay/channel"
|
||||
"github.com/QuantumNous/new-api/relaykit/dto"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/QuantumNous/new-api/setting/system_setting"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func setupPrivateChannelMediaTest(t *testing.T) *model.Task {
|
||||
t.Helper()
|
||||
task := setupGenericTaskTest(t)
|
||||
previousFetch := *system_setting.GetFetchSetting()
|
||||
previousCache := common.MemoryCacheEnabled
|
||||
common.MemoryCacheEnabled = false
|
||||
*system_setting.GetFetchSetting() = system_setting.FetchSetting{
|
||||
EnableSSRFProtection: true, ApplyIPFilterForDomain: true,
|
||||
AllowedPorts: []string{"443"},
|
||||
}
|
||||
service.InitHttpClient()
|
||||
t.Cleanup(func() {
|
||||
common.MemoryCacheEnabled = previousCache
|
||||
*system_setting.GetFetchSetting() = previousFetch
|
||||
service.InitHttpClient()
|
||||
})
|
||||
task.Platform = constant.TaskPlatform("google")
|
||||
task.PrivateData.Execution = &model.TaskExecutionSnapshot{TaskPlugin: &model.TaskPluginSnapshot{
|
||||
Key: "google", Name: "Google Veo (Gemini API)", Version: "1.2.0", APIVersion: 1,
|
||||
}}
|
||||
return task
|
||||
}
|
||||
|
||||
func TestPrivateChannelMediaDownloadEndpoints(t *testing.T) {
|
||||
for _, endpoint := range []string{"video", "artifact"} {
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
t.Run(endpoint+"/"+method, func(t *testing.T) {
|
||||
task := setupPrivateChannelMediaTest(t)
|
||||
var requests atomic.Int32
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
assert.Equal(t, method, r.Method)
|
||||
assert.Equal(t, "provider-key", r.Header.Get("x-goog-api-key"))
|
||||
assert.Equal(t, "bytes=0-3", r.Header.Get("Range"))
|
||||
assert.Equal(t, `"video-etag"`, r.Header.Get("If-Range"))
|
||||
assert.Empty(t, r.Header.Get("Authorization"), "the caller's token must stay at the gateway")
|
||||
if r.URL.Path == "/start" {
|
||||
http.Redirect(w, r, "/video", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "video/mp4")
|
||||
w.Header().Set("Content-Length", "4")
|
||||
w.Header().Set("Content-Range", "bytes 0-3/10")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
if r.Method != http.MethodHead {
|
||||
_, _ = w.Write([]byte("data"))
|
||||
}
|
||||
}))
|
||||
defer upstream.Close()
|
||||
require.NoError(t, model.DB.Model(&model.Channel{}).Where("id = ?", task.ChannelId).Updates(map[string]any{
|
||||
"type": constant.ChannelTypeGemini, "base_url": upstream.URL, "key": "provider-key",
|
||||
}).Error)
|
||||
task.SetData(map[string]any{"response": map[string]any{
|
||||
"generateVideoResponse": map[string]any{
|
||||
"generatedSamples": []any{map[string]any{"video": map[string]any{"uri": upstream.URL + "/start"}}},
|
||||
},
|
||||
}})
|
||||
require.NoError(t, model.DB.Save(task).Error)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Set("id", task.UserId)
|
||||
c.Set("token_id", 1)
|
||||
path := "/v1/videos/" + task.TaskID + "/content"
|
||||
handler := VideoProxy
|
||||
c.Params = gin.Params{{Key: "task_id", Value: task.TaskID}}
|
||||
if endpoint == "artifact" {
|
||||
path = "/v1/tasks/" + task.TaskID + "/artifacts/video/content"
|
||||
handler = TaskArtifactContent
|
||||
c.Params = gin.Params{{Key: "key", Value: task.TaskID}, {Key: "artifact_key", Value: "video"}}
|
||||
}
|
||||
c.Request = httptest.NewRequest(method, path, nil)
|
||||
c.Request.Header.Set("Authorization", "Bearer caller-token")
|
||||
c.Request.Header.Set("Range", "bytes=0-3")
|
||||
c.Request.Header.Set("If-Range", `"video-etag"`)
|
||||
handler(c)
|
||||
|
||||
assert.Equal(t, http.StatusPartialContent, recorder.Code, recorder.Body.String())
|
||||
assert.Equal(t, int32(2), requests.Load(), "same-origin redirects must work without relaxing global SSRF settings")
|
||||
assert.Equal(t, "video/mp4", recorder.Header().Get("Content-Type"))
|
||||
assert.Equal(t, "4", recorder.Header().Get("Content-Length"))
|
||||
assert.Equal(t, "bytes 0-3/10", recorder.Header().Get("Content-Range"))
|
||||
assert.Equal(t, "private, no-store", recorder.Header().Get("Cache-Control"))
|
||||
if method == http.MethodHead {
|
||||
assert.Empty(t, recorder.Body.String())
|
||||
} else {
|
||||
assert.Equal(t, "data", recorder.Body.String())
|
||||
}
|
||||
assert.False(t, system_setting.GetFetchSetting().AllowPrivateIp)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateChannelMediaDoesNotTrustOtherURLs(t *testing.T) {
|
||||
for _, name := range []string{"credentialless", "legacy", "other-channel", "other-scheme", "userinfo", "fragment"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
task := setupPrivateChannelMediaTest(t)
|
||||
var requests atomic.Int32
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
baseURL := upstream.URL
|
||||
descriptor := &relaychannel.TaskContentRequest{URL: upstream.URL + "/video", Method: http.MethodGet}
|
||||
switch name {
|
||||
case "credentialless":
|
||||
descriptor.Credentialless = true
|
||||
case "legacy":
|
||||
task.PrivateData.Execution = nil
|
||||
case "other-channel":
|
||||
baseURL = "http://127.0.0.1:1"
|
||||
case "other-scheme":
|
||||
baseURL = strings.Replace(baseURL, "http:", "https:", 1)
|
||||
case "userinfo":
|
||||
descriptor.URL = strings.Replace(descriptor.URL, "http://", "http://user:password@", 1)
|
||||
case "fragment":
|
||||
descriptor.URL += "#fragment"
|
||||
}
|
||||
require.NoError(t, model.DB.Model(&model.Channel{}).Where("id = ?", task.ChannelId).Update("base_url", baseURL).Error)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/content", nil)
|
||||
err := proxyTaskMedia(c, task, descriptor)
|
||||
var proxyErr *taskMediaProxyError
|
||||
require.ErrorAs(t, err, &proxyErr)
|
||||
assert.Equal(t, "artifact_request_rejected", proxyErr.code)
|
||||
assert.Zero(t, requests.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateChannelMediaRejectsCrossOriginRedirect(t *testing.T) {
|
||||
task := setupPrivateChannelMediaTest(t)
|
||||
// Even a globally permitted destination must not inherit the channel's trust.
|
||||
system_setting.GetFetchSetting().AllowPrivateIp = true
|
||||
system_setting.GetFetchSetting().AllowedPorts = []string{"1-65535"}
|
||||
var destinationRequests, sourceRequests atomic.Int32
|
||||
destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
destinationRequests.Add(1)
|
||||
}))
|
||||
defer destination.Close()
|
||||
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sourceRequests.Add(1)
|
||||
http.Redirect(w, r, destination.URL, http.StatusFound)
|
||||
}))
|
||||
defer source.Close()
|
||||
require.NoError(t, model.DB.Model(&model.Channel{}).Where("id = ?", task.ChannelId).Update("base_url", source.URL).Error)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/content", nil)
|
||||
err := proxyTaskMedia(c, task, &relaychannel.TaskContentRequest{
|
||||
URL: source.URL, Method: http.MethodGet, Headers: map[string]string{"Authorization": "Bearer provider-key"},
|
||||
})
|
||||
var proxyErr *taskMediaProxyError
|
||||
require.ErrorAs(t, err, &proxyErr)
|
||||
assert.Equal(t, "artifact_request_rejected", proxyErr.code)
|
||||
assert.Equal(t, int32(1), sourceRequests.Load())
|
||||
assert.Zero(t, destinationRequests.Load(), "no request or credentials may reach the redirect target")
|
||||
}
|
||||
|
||||
func TestPrivateChannelMediaUsesChannelProxy(t *testing.T) {
|
||||
task := setupPrivateChannelMediaTest(t)
|
||||
var requests atomic.Int32
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
assert.Equal(t, "http://private-upstream.invalid:8080/video", r.URL.String())
|
||||
assert.Equal(t, "Bearer provider-key", r.Header.Get("Authorization"))
|
||||
_, _ = w.Write([]byte("data"))
|
||||
}))
|
||||
defer proxy.Close()
|
||||
channel, err := model.CacheGetChannel(task.ChannelId)
|
||||
require.NoError(t, err)
|
||||
channel.SetSetting(dto.ChannelSettings{Proxy: proxy.URL})
|
||||
require.NoError(t, model.DB.Model(channel).Updates(map[string]any{
|
||||
"base_url": "http://private-upstream.invalid:8080", "setting": channel.Setting,
|
||||
}).Error)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/content", nil)
|
||||
require.NoError(t, proxyTaskMedia(c, task, &relaychannel.TaskContentRequest{
|
||||
URL: "http://private-upstream.invalid:8080/video", Headers: map[string]string{"Authorization": "Bearer provider-key"},
|
||||
}))
|
||||
assert.Equal(t, http.StatusOK, recorder.Code)
|
||||
assert.Equal(t, "data", recorder.Body.String())
|
||||
assert.Equal(t, int32(1), requests.Load())
|
||||
}
|
||||
|
||||
func TestPrivateChannelMediaUsesChannelTLSSettings(t *testing.T) {
|
||||
for _, skipVerify := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "verify", true: "channel-opt-out"}[skipVerify], func(t *testing.T) {
|
||||
task := setupPrivateChannelMediaTest(t)
|
||||
var requests atomic.Int32
|
||||
upstream := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
_, _ = w.Write([]byte("data"))
|
||||
}))
|
||||
defer upstream.Close()
|
||||
channel, err := model.CacheGetChannel(task.ChannelId)
|
||||
require.NoError(t, err)
|
||||
channel.SetSetting(dto.ChannelSettings{TLSInsecureSkipVerify: skipVerify})
|
||||
require.NoError(t, model.DB.Model(channel).Updates(map[string]any{
|
||||
"base_url": upstream.URL, "setting": channel.Setting,
|
||||
}).Error)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/content", nil)
|
||||
err = proxyTaskMedia(c, task, &relaychannel.TaskContentRequest{URL: upstream.URL + "/video"})
|
||||
if !skipVerify {
|
||||
var proxyErr *taskMediaProxyError
|
||||
require.ErrorAs(t, err, &proxyErr)
|
||||
assert.Equal(t, "artifact_upstream_error", proxyErr.code)
|
||||
assert.Zero(t, requests.Load(), "private upstream trust must not disable certificate validation")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, recorder.Code)
|
||||
assert.Equal(t, "data", recorder.Body.String())
|
||||
assert.Equal(t, int32(1), requests.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskMediaChannelOriginComparison(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
base, target string
|
||||
allowed bool
|
||||
}{
|
||||
{"https://provider.example/v1", "https://PROVIDER.example:443/video", true},
|
||||
{"http://provider.example/v1", "http://provider.example:80/video", true},
|
||||
{"http://[::1]:80", "http://[::1]/video", true},
|
||||
{"http://[::1]:8080", "http://[::1]:8080/video", true},
|
||||
{"https://provider.example", "http://provider.example/video", false},
|
||||
{"http://provider.example:8080", "http://provider.example:8081/video", false},
|
||||
{"http://provider.example", "http://provider.example.evil.test/video", false},
|
||||
} {
|
||||
t.Run(tc.target, func(t *testing.T) {
|
||||
base, err := url.Parse(tc.base)
|
||||
require.NoError(t, err)
|
||||
target, err := url.Parse(tc.target)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.allowed, sameTaskMediaOrigin(base, target))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,12 @@ services:
|
||||
- REDIS_CONN_STRING=redis://redis
|
||||
- TZ=Asia/Shanghai
|
||||
- BATCH_UPDATE_ENABLED=true
|
||||
# 上游监控凭据加密:首次配置运行 openssl rand -base64 32 生成密钥,再取消下一行注释并替换占位值。
|
||||
# Upstream credential encryption: generate with openssl rand -base64 32, then uncomment and replace the placeholder.
|
||||
# - UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
|
||||
# 修改后执行 / Apply with: docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api
|
||||
# 单纯重启不会更新环境变量。密钥独立备份,所有节点使用同一持久密钥;已有凭据时沿用原密钥。
|
||||
# A restart does not reload environment changes. Back up the key separately; reuse the same persistent key on all nodes and for existing credentials.
|
||||
# Local HTTP dev mode: keep Secure=false and leave TRUSTED_URL unset. This disables the refresh/logout OriginGuard so the :5173 -> :3000 dev proxy works.
|
||||
- SESSION_COOKIE_SECURE=false
|
||||
# For HTTPS only: set Secure=true and list every exact trusted HTTPS browser Origin. This does not configure relay CORS.
|
||||
|
||||
@@ -40,6 +40,12 @@ services:
|
||||
# - STREAMING_TIMEOUT=300 # 流模式无响应超时时间,单位秒,默认120秒,如果出现空补全可以尝试改为更大值 (Streaming timeout in seconds, default is 120s. Increase if experiencing empty completions)
|
||||
# - RELAY_IDLE_CONN_TIMEOUT=90 # Relay HTTP 客户端空闲连接超时时间,单位秒,默认跟随 Go 标准库,设置为0表示不限制 (Relay HTTP client idle keep-alive timeout in seconds, defaults to Go standard library; set 0 to disable)
|
||||
# - SESSION_SECRET=random_string # 多机部署时设置,必须修改这个随机字符串!! (multi-node deployment, set this to a random string!!!!!!!)
|
||||
# 上游监控凭据加密:首次配置运行 openssl rand -base64 32 生成密钥,再取消下一行注释并替换占位值。
|
||||
# Upstream credential encryption: generate with openssl rand -base64 32, then uncomment and replace the placeholder.
|
||||
# - UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
|
||||
# 修改后执行 / Apply with: docker compose up -d --no-deps --force-recreate new-api
|
||||
# 单纯重启不会更新环境变量。密钥独立备份,所有节点使用同一持久密钥;已有凭据时沿用原密钥。
|
||||
# A restart does not reload environment changes. Back up the key separately; reuse the same persistent key on all nodes and for existing credentials.
|
||||
# - SESSION_COOKIE_SECURE=true # true:启用 Secure Refresh Cookie 和严格 refresh/logout OriginGuard;false/未配置:关闭 OriginGuard,仅用于本地 HTTP (true: Secure cookie + strict refresh/logout OriginGuard; false/unset: guard disabled for local HTTP only)
|
||||
# - SESSION_COOKIE_TRUSTED_URL=https://example.com,https://admin.example.com # Secure=true 时必填的精确 HTTPS Origin;不是 relay CORS 白名单,不支持通配符/路径 (Required exact HTTPS origins when Secure=true; not a relay CORS allowlist, no wildcard/path)
|
||||
# - TRUSTED_PROXIES=172.20.0.0/16 # 未配置时信任回环/RFC1918/fc00::/7 并告警,none 为严格模式,显式列表替代默认值 (Unset trusts loopback/RFC 1918/fc00::/7 with a warning; none trusts no proxies; an explicit list replaces defaults)
|
||||
|
||||
Vendored
+1
-1
@@ -132,7 +132,7 @@ export declare const native: Record<string, ((ctx: NativeDecodeContext) => TaskI
|
||||
export declare const protocols: {
|
||||
openai_responses?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; renderEvents?(ctx: unknown, task: TaskView, previousState: unknown): unknown; renderFinal?(ctx: unknown, task: TaskView): unknown};
|
||||
openai_video?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; render(ctx: unknown, task: TaskView): unknown};
|
||||
/** render returns the OpenAI ImageResponse; the host adds `created` when absent and resolves response_format b64_json. */
|
||||
/** The final decode and render receive the current channel's parameter overrides. render returns the OpenAI ImageResponse; the host adds `created` when absent and resolves the effective response_format b64_json. */
|
||||
openai_image?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; render(ctx: unknown, task: TaskView): {created?: number; data: readonly ImageResponseEntry[]} & Record<string, unknown>};
|
||||
};
|
||||
export declare function buildSubmitRequest(ctx: DriverContext): RequestDescriptor;
|
||||
|
||||
@@ -728,6 +728,14 @@ submission. Content requests keep the host of their URL; credentialless content
|
||||
requests and `utils.fetch` are sent as the plugin builds them. An invalid header
|
||||
value fails the request.
|
||||
|
||||
Credentialed `buildContentRequest` URLs on the task channel's base URL origin
|
||||
(same scheme, hostname and effective port) use that channel's HTTP client and
|
||||
transport settings, including private upstreams. Redirects must stay on that
|
||||
origin. This trust applies only to plugin tasks, not to credentialless requests
|
||||
or legacy result URLs. Other content URLs, including extra `meta.allowedHosts`,
|
||||
keep the global fetch SSRF checks; an allowed credential recipient does not
|
||||
grant private-network access.
|
||||
|
||||
`buildSubmitRequest` returns a request descriptor. JSON bodies (the default) may embed a file placeholder at any object or array depth. The host replaces each placeholder with an encoded string before the request is sent; JavaScript never sees file bytes.
|
||||
|
||||
```js
|
||||
@@ -804,6 +812,18 @@ The host registry owns these bindings:
|
||||
|
||||
`protocols.openai_image` requires `decodeRequest` and `render` and defines no modes. Both operations are synchronous from the client's point of view. The host extracts and pins `ctx.model` (`ctx.operation` is `generate` or `edit`), the decoder returns the usual submit intent, and `buildSubmitRequest` runs against the vendor exactly as for native routes. A vendor answering synchronously returns a terminal `immediate` from `parseSubmitResponse`; a vendor task API returns a task id, and the host then polls the task inside the client request through the same query hooks and completion settlement the background poller uses (`buildQueryRequest`, `parseTaskResult`, `extractUsageOnComplete`), every few seconds until the task is terminal or the protocol timeout (`TASK_PLUGIN_PROTOCOL_TIMEOUT_SECONDS`, default 600 seconds) elapses. On timeout the client receives 504 `task_timeout`; the task remains durable and settles when the poller finishes it. A client that disconnects while waiting leaves the task to the poller as well. A terminal `FAILURE` is answered with 400 and the task's failure reason. On `SUCCESS` the host calls `render(ctx, task)` with the request context and the terminal `TaskView`; the hook must return an object whose `data` is an array of OpenAI image entries (`{url}` or `{b64_json}`, optionally `revised_prompt`). The host adds `created` when absent and owns `response_format`: for `b64_json` it downloads every `data[].url` and adds `b64_json` (the URL is kept; a failed download logs a warning and leaves the URL). `render` receives no `artifacts`; image URLs come from the vendor result. Billing follows the ordinary task contract: reserve on the requested count from `extractUsage`, settle to the actual count from `extractUsageOnSubmit` (immediate results, legacy pricing), `extractUsageOnComplete` (immediate results and polled results, task expressions); the consume log records the billed count as `other.image_count` when the facts carry `image_count`.
|
||||
|
||||
For `openai_image`, channel parameter overrides apply to the JSON body or
|
||||
multipart text fields before the selected plugin's final `decodeRequest` call.
|
||||
The initial candidate decode still validates the client's request for routing.
|
||||
The final decoder validates the overridden request, and driver and usage hooks
|
||||
receive its normalized result. Conditions use `original_model` for the client's
|
||||
model and `model` / `upstream_model` for the channel-mapped model. An override
|
||||
cannot change or remove that model; use channel model mapping instead. Uploaded
|
||||
file references are preserved. Each retry derives a fresh request from the
|
||||
original body, and `render` and the host's `b64_json` conversion use the final
|
||||
attempt's effective request. The original request stays unchanged, including
|
||||
JSON member order for plugins declaring `json-order@1`.
|
||||
|
||||
Responses protocol media uses host-injected `ctx.artifacts[key].url`. OpenAI Video renderers may return provider fields and URLs from `task.data`; the host preserves those extensions and metadata, but overwrites `id`, `object`, `model`, `status`, `progress`, `created_at`, and `completed_at` and removes legacy `task_id`. Renderers must return a JSON object. Returning `task.data` exposes the latest persisted upstream snapshot, subject to the host's task-ID replacement and inline-video redaction; it does not perform a fresh upstream query or forward HTTP headers/status codes.
|
||||
|
||||
## Persisted data and driver hooks
|
||||
|
||||
@@ -83,8 +83,8 @@ require (
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
go.opentelemetry.io/otel v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
)
|
||||
|
||||
@@ -168,8 +168,7 @@ require (
|
||||
|
||||
require (
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.46.0
|
||||
github.com/HugoSmits86/nativewebp v1.3.0
|
||||
github.com/MoeForge/moego v0.1.0-alpha.3
|
||||
github.com/MoeForge/moego v0.1.0-alpha.5
|
||||
github.com/MoeForge/moejs v0.1.0
|
||||
github.com/QuantumNous/new-api/relaykit v0.0.0
|
||||
github.com/QuantumNous/new-api/tokenkit v0.0.0
|
||||
|
||||
@@ -642,8 +642,6 @@ github.com/ClickHouse/clickhouse-go/v2 v2.46.0 h1:s3eRy+hYmu5uzotB6ZhDofgHu8kDgG
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.46.0/go.mod h1:giJfUVlMkcfUEPVfRpt51zZaGEx9i17gCos8gBl392c=
|
||||
github.com/DmitriyVTitov/size v1.5.0 h1:/PzqxYrOyOUX1BXj6J9OuVRVGe+66VL4D9FlUaW515g=
|
||||
github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0=
|
||||
github.com/HugoSmits86/nativewebp v1.3.0 h1:n1egtEzSV4KwFtealr7dzdYq1wI/uj/bOQ/QcTcIyVE=
|
||||
github.com/HugoSmits86/nativewebp v1.3.0/go.mod h1:YNQuWenlVmSUUASVNhTDwf4d7FwYQGbGhklC8p72Vr8=
|
||||
github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk=
|
||||
github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=
|
||||
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
|
||||
@@ -674,8 +672,8 @@ github.com/Microsoft/hcsshim v0.9.6/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfy
|
||||
github.com/Microsoft/hcsshim v0.11.0/go.mod h1:OEthFdQv/AD2RAdzR6Mm1N1KPCztGKDurW1Z8b8VGMM=
|
||||
github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU=
|
||||
github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:mw7qgWloBUl75W/gVH3cQszUg1+gUITj7D6NY7ywVnY=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.3 h1:sn8Kg4qY/gqGXU4CCJWfgzouaim6alkvXcob0uFDohg=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.3/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.5 h1:/pFyEhm0GYdOGfwawNjzLx+DoDQVoCI0dLsu8Sbpac8=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.5/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA=
|
||||
github.com/MoeForge/moejs v0.1.0 h1:w5/bM4wVRrnMdLbQG32BM+yVcoA9wjQqdGlX3XekzG4=
|
||||
github.com/MoeForge/moejs v0.1.0/go.mod h1:GDaH0vQSxKDN7FCyBaLEZgqsGKRyIYBfje/p74aZQ3k=
|
||||
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
|
||||
@@ -2097,8 +2095,8 @@ go.opentelemetry.io/otel v1.10.0/go.mod h1:NbvWjCthWHKBEUMpf0/v8ZRZlni86PpGFEMA9
|
||||
go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU=
|
||||
go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4=
|
||||
go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY=
|
||||
go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c=
|
||||
go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp v0.20.0/go.mod h1:YIieizyaN77rtLJra0buKiNBOm9XQfkPEKBeuhoMwAM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.3.0/go.mod h1:VpP4/RMn8bv8gNo9uK7/IMY4mtWLELsS+JIP0inH0h4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.7.0/go.mod h1:M1hVZHNxcbkAlcvrOMlpQ4YOO3Awf+4N2dxkZL3xm04=
|
||||
@@ -2141,8 +2139,8 @@ go.opentelemetry.io/otel/trace v1.10.0/go.mod h1:Sij3YYczqAdz+EhmGhE6TpTxUO5/F/A
|
||||
go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
|
||||
go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0=
|
||||
go.opentelemetry.io/otel/trace v1.19.0/go.mod h1:mfaSyvGyEJEI0nyV2I4qhNQnbBOUUmYZpYojqMnX2vo=
|
||||
go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0=
|
||||
go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||
go.opentelemetry.io/proto/otlp v0.9.0/go.mod h1:1vKfU9rv61e9EVGthD1zNvUbiwPcimSsOPU9brfSHJg=
|
||||
go.opentelemetry.io/proto/otlp v0.11.0/go.mod h1:QpEjXPrNQzrFDZgoTo49dgHR9RYRSrg3NAKnUGl9YpQ=
|
||||
|
||||
@@ -73,6 +73,27 @@ func SetupLogger() {
|
||||
}
|
||||
}
|
||||
|
||||
// CloseLogger closes the current log file and restores the standard output writers.
|
||||
// It is safe to call more than once.
|
||||
func CloseLogger() error {
|
||||
setupLogLock.Lock()
|
||||
defer setupLogLock.Unlock()
|
||||
common.LogWriterMu.Lock()
|
||||
defer common.LogWriterMu.Unlock()
|
||||
currentLogPathMu.Lock()
|
||||
defer currentLogPathMu.Unlock()
|
||||
|
||||
if currentLogFile == nil {
|
||||
return nil
|
||||
}
|
||||
file := currentLogFile
|
||||
currentLogFile = nil
|
||||
currentLogPath = ""
|
||||
gin.DefaultWriter = os.Stdout
|
||||
gin.DefaultErrorWriter = os.Stderr
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
func LogInfo(ctx context.Context, msg string) {
|
||||
logHelper(ctx, loggerINFO, msg)
|
||||
}
|
||||
|
||||
@@ -259,6 +259,7 @@ var accessTokenRouteRules = map[string]accessTokenRouteRule{
|
||||
"GET /api/log/export": accessTokenScopeRule("log:read"),
|
||||
"GET /api/log/self/export": accessTokenScopeRule("usage:read"),
|
||||
"GET /api/data/": accessTokenScopeRule("log:read"),
|
||||
"GET /api/data/perf-metrics/summary": accessTokenScopeRule("log:read"),
|
||||
"GET /api/data/users": accessTokenScopeRule("log:read"),
|
||||
"GET /api/data/self": accessTokenScopeRule("usage:read"),
|
||||
"GET /api/data/flow": accessTokenScopeRule("log:read"),
|
||||
|
||||
@@ -66,12 +66,16 @@ func TestAccessAndPanicLogsFollowLogRotation(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
*common.LogDir = t.TempDir()
|
||||
t.Cleanup(func() {
|
||||
assert.NoError(t, logger.CloseLogger())
|
||||
gin.SetMode(previousMode)
|
||||
common.LogWriterMu.Lock()
|
||||
gin.DefaultWriter, gin.DefaultErrorWriter = previousWriter, previousErrorWriter
|
||||
common.LogWriterMu.Unlock()
|
||||
*common.LogDir = previousLogDir
|
||||
})
|
||||
|
||||
logger.SetupLogger()
|
||||
beforeRotationWriter := gin.DefaultWriter
|
||||
router := gin.New()
|
||||
router.Use(PanicRecover())
|
||||
SetUpLogger(router)
|
||||
@@ -87,6 +91,8 @@ func TestAccessAndPanicLogsFollowLogRotation(t *testing.T) {
|
||||
// reuse the old name when both calls land in the same second; the checks
|
||||
// below hold either way because only the new descriptor stays open.
|
||||
logger.SetupLogger()
|
||||
_, err = beforeRotationWriter.Write(nil)
|
||||
assert.ErrorIs(t, err, os.ErrClosed)
|
||||
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/ok/after-rotation", nil))
|
||||
panicResponse := httptest.NewRecorder()
|
||||
router.ServeHTTP(panicResponse, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
@@ -98,6 +104,19 @@ func TestAccessAndPanicLogsFollowLogRotation(t *testing.T) {
|
||||
assert.Contains(t, string(content), "[Recovery]")
|
||||
assert.Contains(t, string(content), "rotation-panic-marker\n")
|
||||
assert.Contains(t, string(content), "middleware/logger_test.go")
|
||||
|
||||
currentWriter := gin.DefaultWriter
|
||||
require.NoError(t, logger.CloseLogger())
|
||||
assert.Empty(t, logger.GetCurrentLogPath())
|
||||
assert.Same(t, os.Stdout, gin.DefaultWriter)
|
||||
assert.Same(t, os.Stderr, gin.DefaultErrorWriter)
|
||||
_, err = currentWriter.Write(nil)
|
||||
assert.ErrorIs(t, err, os.ErrClosed)
|
||||
require.NoError(t, logger.CloseLogger())
|
||||
_, err = common.LogWriter.Write(nil)
|
||||
assert.NoError(t, err)
|
||||
_, err = common.ErrorLogWriter.Write(nil)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestSetUpLoggerOmitsQueryCredentialsTakenOutByHandlers(t *testing.T) {
|
||||
|
||||
+3
-5
@@ -398,8 +398,7 @@ func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*
|
||||
|
||||
func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
|
||||
var tasks []*Task
|
||||
err := DB.Where("progress != ?", "100%").
|
||||
Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess}).
|
||||
err := DB.Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess}).
|
||||
Where("submit_time < ?", cutoffUnix).
|
||||
Order("submit_time").
|
||||
Limit(limit).
|
||||
@@ -413,8 +412,8 @@ func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
|
||||
func GetAllUnFinishSyncTasks(limit int) []*Task {
|
||||
var tasks []*Task
|
||||
var err error
|
||||
// get all tasks progress is not 100%
|
||||
err = DB.Where("progress != ?", "100%").Where("status != ?", TaskStatusFailure).Where("status != ?", TaskStatusSuccess).Limit(limit).Order("id").Find(&tasks).Error
|
||||
// Upstream progress can reach 100% before the task enters a terminal state.
|
||||
err = DB.Where("status != ?", TaskStatusFailure).Where("status != ?", TaskStatusSuccess).Limit(limit).Order("id").Find(&tasks).Error
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -428,7 +427,6 @@ func GetAllUnFinishSyncTasks(limit int) []*Task {
|
||||
func HasUnfinishedSyncTasks() bool {
|
||||
var id int64
|
||||
err := DB.Model(&Task{}).
|
||||
Where("progress != ?", "100%").
|
||||
Where("status != ?", TaskStatusFailure).
|
||||
Where("status != ?", TaskStatusSuccess).
|
||||
Limit(1).
|
||||
|
||||
@@ -3,6 +3,7 @@ package model
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -13,7 +14,10 @@ import (
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
@@ -103,6 +107,76 @@ func insertTask(t *testing.T, task *Task) {
|
||||
require.NoError(t, DB.Create(task).Error)
|
||||
}
|
||||
|
||||
func TestUnfinishedTaskQueriesDatabaseMatrix(t *testing.T) {
|
||||
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
|
||||
t.Run(dialect, func(t *testing.T) {
|
||||
var driver gorm.Dialector
|
||||
switch dialect {
|
||||
case "sqlite":
|
||||
driver = sqlite.Open(":memory:")
|
||||
case "mysql":
|
||||
dsn := os.Getenv("TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_MYSQL_DSN is not configured")
|
||||
}
|
||||
driver = mysql.Open(dsn)
|
||||
case "postgres":
|
||||
dsn := os.Getenv("TEST_POSTGRES_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_POSTGRES_DSN is not configured")
|
||||
}
|
||||
driver = postgres.New(postgres.Config{DSN: dsn, PreferSimpleProtocol: true})
|
||||
}
|
||||
db, err := gorm.Open(driver, &gorm.Config{NamingStrategy: schema.NamingStrategy{TablePrefix: fmt.Sprintf("task_polling_%d_", time.Now().UnixNano())}})
|
||||
require.NoError(t, err)
|
||||
sqlDB, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
previousDB := DB
|
||||
DB = db
|
||||
t.Cleanup(func() {
|
||||
DB = previousDB
|
||||
assert.NoError(t, db.Migrator().DropTable(&Task{}))
|
||||
assert.NoError(t, sqlDB.Close())
|
||||
})
|
||||
require.NoError(t, db.AutoMigrate(&Task{}))
|
||||
var version string
|
||||
versionQuery := "SELECT version()"
|
||||
if dialect == "sqlite" {
|
||||
versionQuery = "SELECT sqlite_version()"
|
||||
}
|
||||
require.NoError(t, db.Raw(versionQuery).Scan(&version).Error)
|
||||
t.Logf("database version: %s", version)
|
||||
assert.False(t, HasUnfinishedSyncTasks())
|
||||
|
||||
const cutoff int64 = 1_800_000_000
|
||||
for _, status := range []TaskStatus{TaskStatusNotStart, TaskStatusSubmitted, TaskStatusQueued, TaskStatusInProgress, TaskStatusSuccess, TaskStatusFailure} {
|
||||
for _, progress := range []string{"99%", "100%"} {
|
||||
t.Run(string(status)+"/"+progress, func(t *testing.T) {
|
||||
task := &Task{TaskID: "query_candidate", Status: status, Progress: progress, SubmitTime: cutoff - 1}
|
||||
insertTask(t, task)
|
||||
t.Cleanup(func() { assert.NoError(t, db.Delete(task).Error) })
|
||||
unfinished := status != TaskStatusSuccess && status != TaskStatusFailure
|
||||
assert.Equal(t, unfinished, HasUnfinishedSyncTasks())
|
||||
if unfinished {
|
||||
require.Len(t, GetAllUnFinishSyncTasks(1), 1)
|
||||
assert.Equal(t, task.ID, GetAllUnFinishSyncTasks(1)[0].ID)
|
||||
require.Len(t, GetTimedOutUnfinishedTasks(cutoff, 1), 1)
|
||||
assert.Equal(t, task.ID, GetTimedOutUnfinishedTasks(cutoff, 1)[0].ID)
|
||||
} else {
|
||||
assert.Empty(t, GetAllUnFinishSyncTasks(1))
|
||||
assert.Empty(t, GetTimedOutUnfinishedTasks(cutoff, 1))
|
||||
}
|
||||
require.NoError(t, db.Model(task).Update("submit_time", cutoff).Error)
|
||||
assert.Empty(t, GetTimedOutUnfinishedTasks(cutoff, 1), "the timeout cutoff is exclusive")
|
||||
assert.Equal(t, unfinished, HasUnfinishedSyncTasks())
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTaskForProtocolObservationScopesOwnerAndPlatform(t *testing.T) {
|
||||
truncateTables(t)
|
||||
task := &Task{
|
||||
|
||||
@@ -246,6 +246,9 @@ const (
|
||||
ContextKeyPinnedEndpoint = "task_plugin_pinned_endpoint"
|
||||
ContextKeyRouteRequest = "task_plugin_route_request"
|
||||
ContextKeyProtocolRequest = "task_plugin_protocol_request"
|
||||
// ContextKeyEffectiveImageRequest holds the current attempt's image request
|
||||
// after channel overrides. ProtocolRequest remains the immutable retry source.
|
||||
ContextKeyEffectiveImageRequest = "task_plugin_effective_image_request"
|
||||
// ContextKeyRequestBodyText holds, for a plugin that preserves JSON
|
||||
// order, the decoded requestBody as JSON text (json.RawMessage) beside
|
||||
// the Go value in task_request.
|
||||
@@ -490,6 +493,7 @@ var reservedRouteNamespaces = []string{
|
||||
"/subscriptions",
|
||||
"/system-info",
|
||||
"/task-plugins",
|
||||
"/upstream-monitor",
|
||||
"/usage-logs",
|
||||
"/users",
|
||||
"/wallet",
|
||||
|
||||
@@ -470,6 +470,8 @@ func TestKling4(t *testing.T) {
|
||||
{"1792x1024", "", map[string]any{"resolution": "1080p", "aspect_ratio": "16:9", "duration": float64(5)}},
|
||||
{"1024x1792", "", map[string]any{"resolution": "1080p", "aspect_ratio": "9:16", "duration": float64(5)}},
|
||||
{"2560x1080", "", map[string]any{"resolution": "1080p", "aspect_ratio": "21:9", "duration": float64(5)}},
|
||||
{"1440x1080", "", map[string]any{"resolution": "1080p", "aspect_ratio": "4:3", "duration": float64(5)}},
|
||||
{"1080x1440", "", map[string]any{"resolution": "1080p", "aspect_ratio": "3:4", "duration": float64(5)}},
|
||||
{"720x1280", "https://cdn.example/a.png", map[string]any{"resolution": "720p", "duration": float64(5)}},
|
||||
} {
|
||||
body := map[string]any{"model": "kling-4.0", "prompt": "a cat", "size": tc.size, "seconds": 5}
|
||||
|
||||
@@ -85,7 +85,7 @@ const KLING4_ACTIONS = { "text-to-video": "text_to_video", "image-to-video": "im
|
||||
// kling-v3, then of Kling 4.0. The host protocols send the one nearest the
|
||||
// request's size; without a size Kling uses its default, 16:9.
|
||||
const KLING_ASPECT_RATIOS = ["16:9", "9:16", "1:1"];
|
||||
const KLING4_ASPECT_RATIOS = ["16:9", "9:16", "1:1", "21:9"];
|
||||
const KLING4_ASPECT_RATIOS = ["16:9", "9:16", "1:1", "21:9", "4:3", "3:4"];
|
||||
|
||||
// Kling's numeric error codes for the statuses the gateway answers with
|
||||
// (kling.ai/document-api/api/get-started/error-codes).
|
||||
|
||||
@@ -337,6 +337,17 @@ func awaitH2ServerResult(t *testing.T, resultCh <-chan h2ServerResult) h2ServerR
|
||||
}
|
||||
}
|
||||
|
||||
// closeH2TestConnection preserves queued HTTP/2 frames instead of resetting
|
||||
// TCP when unread client control frames remain, which Windows can otherwise do.
|
||||
func closeH2TestConnection(conn net.Conn) error {
|
||||
defer conn.Close()
|
||||
if err := conn.(*net.TCPConn).CloseWrite(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := io.Copy(io.Discard, conn)
|
||||
return err
|
||||
}
|
||||
|
||||
// runResetOnFirstStreamServer speaks just enough raw HTTP/2 to emulate an
|
||||
// upstream that accepts the first request, waits until the request body has
|
||||
// been fully written, and then resets the stream with REFUSED_STREAM (the
|
||||
@@ -372,6 +383,7 @@ func runResetOnFirstStreamServer(ln net.Listener, expectRetry bool) <-chan h2Ser
|
||||
return
|
||||
}
|
||||
if !expectRetry {
|
||||
res.err = closeH2TestConnection(conn)
|
||||
break attempts
|
||||
}
|
||||
continue
|
||||
@@ -379,6 +391,8 @@ func runResetOnFirstStreamServer(ln net.Listener, expectRetry bool) <-chan h2Ser
|
||||
|
||||
if err := writeH2TestResponse(framer, streamID); err != nil {
|
||||
res.err = err
|
||||
} else {
|
||||
res.err = closeH2TestConnection(conn)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -409,20 +423,21 @@ func runGoAwayAfterFirstRequestServer(ln net.Listener) <-chan h2ServerResult {
|
||||
|
||||
if attempt == 0 {
|
||||
err = framer.WriteGoAway(0, http2.ErrCodeNo, nil)
|
||||
} else {
|
||||
err = writeH2TestResponse(framer, streamID)
|
||||
}
|
||||
if err == nil {
|
||||
err = closeH2TestConnection(conn)
|
||||
} else {
|
||||
conn.Close()
|
||||
if err != nil {
|
||||
res.err = err
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
err = writeH2TestResponse(framer, streamID)
|
||||
conn.Close()
|
||||
if err != nil {
|
||||
res.err = err
|
||||
return
|
||||
}
|
||||
if attempt == 1 {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
}()
|
||||
return resCh
|
||||
|
||||
@@ -56,6 +56,8 @@ type requestDescriptor struct {
|
||||
// BodyText is the body as JSON.stringify wrote it, for a plugin that
|
||||
// preserves JSON order: the upstream gets the members in that order.
|
||||
BodyText json.RawMessage `json:"-"`
|
||||
|
||||
multipartContentType string
|
||||
}
|
||||
|
||||
// orderedRequestDescriptor is requestDescriptor as a plugin that preserves
|
||||
@@ -163,10 +165,25 @@ func New(plugin *pluginruntime.LoadedPlugin) *TaskAdaptor { return &TaskAdaptor{
|
||||
func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) { a.info = info }
|
||||
|
||||
func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError {
|
||||
c.Set(pluginruntime.ContextKeyEffectiveImageRequest, nil)
|
||||
if pinnedValue, exists := c.Get(pluginruntime.ContextKeyPinnedEndpoint); exists {
|
||||
if pinned, ok := pinnedValue.(pluginruntime.PinnedEndpoint); ok && pinned.Plugin == a.plugin {
|
||||
if protocolValue, present := c.Get(pluginruntime.ContextKeyProtocolRequest); present {
|
||||
if protocolContext, valid := protocolValue.(pluginruntime.ProtocolRequestContext); valid {
|
||||
if pinned.Protocol == pluginruntime.ProtocolOpenAIImage {
|
||||
var err error
|
||||
protocolContext, err = applyImageProtocolParamOverride(protocolContext, info)
|
||||
if err != nil {
|
||||
taskErr := service.TaskErrorWrapperLocal(err, "channel_param_override_invalid", http.StatusBadRequest)
|
||||
taskErr.NoRetry = true
|
||||
if fixed, ok := relaycommon.AsParamOverrideReturnError(err); ok {
|
||||
taskErr.Code, taskErr.Message = fixed.Code, fixed.Message
|
||||
taskErr.StatusCode, taskErr.NoRetry = fixed.StatusCode, fixed.SkipRetry
|
||||
}
|
||||
return taskErr
|
||||
}
|
||||
c.Set(pluginruntime.ContextKeyEffectiveImageRequest, protocolContext)
|
||||
}
|
||||
resolvedValue, requestBodyText, callErr := a.plugin.Engine.CallPathWithMemberJSON(
|
||||
context.WithoutCancel(c.Request.Context()), 0, a.plugin.Meta.JSONTextMember("requestBody"),
|
||||
"protocols", []string{pinned.Protocol, "decodeRequest"}, protocolContext.JSValueFor(a.plugin.Meta),
|
||||
@@ -348,17 +365,16 @@ func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, erro
|
||||
return requestURL, pluginruntime.ValidateRequestURL(requestURL, info.ChannelBaseUrl, a.plugin.Meta.AllowedHosts)
|
||||
}
|
||||
|
||||
func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
|
||||
func (a *TaskAdaptor) BuildRequestHeader(_ *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
|
||||
if a.submit == nil {
|
||||
return fmt.Errorf("plugin submit request was not built")
|
||||
}
|
||||
for name, value := range a.submit.Headers {
|
||||
req.Header.Set(name, value)
|
||||
}
|
||||
// BuildRequestBody rebuilt the multipart body with a new boundary and put its
|
||||
// Content-Type on the client request; a plugin's own Content-Type cannot match it.
|
||||
if a.submit.BodyType == "multipart" {
|
||||
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
||||
// The upstream Content-Type must carry the boundary used to encode the body.
|
||||
if a.submit.multipartContentType != "" {
|
||||
req.Header.Set("Content-Type", a.submit.multipartContentType)
|
||||
}
|
||||
applyTaskCredential(a.credential, &url.URL{}, req.Header)
|
||||
return nil
|
||||
@@ -370,11 +386,7 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
|
||||
return nil, err
|
||||
}
|
||||
if descriptor.BodyType == "multipart" {
|
||||
form, parseErr := common.ParseMultipartFormReusable(c)
|
||||
if parseErr != nil {
|
||||
return nil, parseErr
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
var form *multipart.Form
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
for _, part := range descriptor.Parts {
|
||||
@@ -394,6 +406,14 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Text-only multipart output may originate from a JSON request.
|
||||
if form == nil {
|
||||
form, err = common.ParseMultipartFormReusable(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
}
|
||||
field, index, validRef := pluginruntime.ParseFileReference(part.FileRef)
|
||||
files := form.File[field]
|
||||
if !validRef || index >= len(files) {
|
||||
@@ -427,7 +447,7 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
|
||||
if err = writer.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
descriptor.multipartContentType = writer.FormDataContentType()
|
||||
return bytes.NewReader(body.Bytes()), nil
|
||||
}
|
||||
if descriptor.Body == nil {
|
||||
|
||||
@@ -89,6 +89,63 @@ func TestTaskAdaptorRejectsDeprecatedClientResponse(t *testing.T) {
|
||||
assert.Contains(t, taskErr.Error.Error(), "must not return clientResponse")
|
||||
}
|
||||
|
||||
func TestTaskAdaptorBuildsMultipartFromJSON(t *testing.T) {
|
||||
source := `
|
||||
export const meta = {apiVersion:1,key:"json-multipart",name:"JSON Multipart",version:"1.0.0",author:{name:"Test"},models:["m"],fetchMode:"per_task"};
|
||||
export function buildSubmitRequest(ctx) {
|
||||
const parts = [{name:"model",value:"m"},{name:"prompt",value:ctx.requestBody.prompt},{name:"tag",value:"first"},{name:"tag",value:"second"},{name:"empty",value:""}];
|
||||
if (ctx.requestBody.reference) parts.push({name:"input_reference",fileRef:"request_file:input_reference"});
|
||||
return {url:ctx.baseUrl+"/submit",headers:{"Content-Type":ctx.requestHeaders["Content-Type"]},bodyType:"multipart",parts};
|
||||
}
|
||||
export function parseSubmitResponse(){return {taskId:"1"}} export function buildQueryRequest(){return {url:"https://example.com"}} export function parseTaskResult(){return {status:"SUCCESS"}}
|
||||
`
|
||||
plugin, err := pluginruntime.NewRegistry().Register(source, pluginruntime.Options{})
|
||||
require.NoError(t, err)
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
reference bool
|
||||
wantError string
|
||||
}{
|
||||
{name: "text fields"},
|
||||
{name: "file reference requires an upload", reference: true, wantError: "multipart boundary not found"},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
adaptor := New(plugin)
|
||||
info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{ChannelBaseUrl: "https://provider.example"}, TaskRelayInfo: &relaycommon.TaskRelayInfo{}}
|
||||
adaptor.Init(info)
|
||||
request := map[string]any{"model": "m", "prompt": "paper plane", "reference": testCase.reference}
|
||||
encoded, err := common.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/videos", bytes.NewReader(encoded))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("task_request", request)
|
||||
|
||||
body, err := adaptor.BuildRequestBody(c, info)
|
||||
if testCase.wantError != "" {
|
||||
require.EqualError(t, err, testCase.wantError)
|
||||
assert.Nil(t, body)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
upstreamRequest := httptest.NewRequest(http.MethodPost, "https://provider.example/submit", body)
|
||||
require.NoError(t, adaptor.BuildRequestHeader(c, upstreamRequest, info))
|
||||
assert.Equal(t, "application/json", c.GetHeader("Content-Type"))
|
||||
mediaType, params, err := mime.ParseMediaType(upstreamRequest.Header.Get("Content-Type"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "multipart/form-data", mediaType)
|
||||
require.NotEmpty(t, params["boundary"])
|
||||
require.NoError(t, upstreamRequest.ParseMultipartForm(1024))
|
||||
t.Cleanup(func() { require.NoError(t, upstreamRequest.MultipartForm.RemoveAll()) })
|
||||
assert.Equal(t, map[string][]string{
|
||||
"model": {"m"}, "prompt": {"paper plane"}, "tag": {"first", "second"}, "empty": {""},
|
||||
}, upstreamRequest.MultipartForm.Value)
|
||||
assert.Empty(t, upstreamRequest.MultipartForm.File)
|
||||
t.Log("JSON input produced a decodable multipart request with repeated and empty text fields")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskAdaptorBuildsMultipartFromOpaqueFileReference(t *testing.T) {
|
||||
// The plugin forwards the client's Content-Type, whose boundary is not the one of the rebuilt body.
|
||||
source := `
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package jsplugin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
pluginruntime "github.com/QuantumNous/new-api/pkg/jsplugin"
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// applyImageProtocolParamOverride derives an attempt-local request before the
|
||||
// plugin's final decoder, so validation, usage and response rendering agree.
|
||||
// The original request and its file references remain available for retries.
|
||||
func applyImageProtocolParamOverride(request pluginruntime.ProtocolRequestContext, info *relaycommon.RelayInfo) (pluginruntime.ProtocolRequestContext, error) {
|
||||
if info == nil || info.ChannelMeta == nil || len(info.ParamOverride) == 0 {
|
||||
return request, nil
|
||||
}
|
||||
body, ok := request.Body.(map[string]any)
|
||||
if !ok {
|
||||
return request, fmt.Errorf("invalid image protocol request body")
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
fields, _ := body["fields"].(map[string][]string)
|
||||
switch body["kind"] {
|
||||
case string(pluginruntime.BodyJSON):
|
||||
if len(request.BodyText) > 0 {
|
||||
data = append([]byte(nil), request.BodyText...)
|
||||
} else {
|
||||
data, err = common.Marshal(body["value"])
|
||||
}
|
||||
case string(pluginruntime.BodyMultipart), string(pluginruntime.BodyForm):
|
||||
values := make(map[string]any, len(fields))
|
||||
for key, entries := range fields {
|
||||
if len(entries) == 1 {
|
||||
values[key] = entries[0]
|
||||
} else {
|
||||
values[key] = entries
|
||||
}
|
||||
}
|
||||
data, err = common.Marshal(values)
|
||||
default:
|
||||
return request, fmt.Errorf("unsupported image protocol request body")
|
||||
}
|
||||
if err != nil {
|
||||
return request, err
|
||||
}
|
||||
// Match model conditions against the mapped name, as ordinary image relay
|
||||
// does. The decoder still receives the pinned client model afterwards.
|
||||
upstreamModel := info.UpstreamModelName
|
||||
if upstreamModel == "" {
|
||||
upstreamModel = request.Model
|
||||
}
|
||||
data, err = sjson.SetBytes(data, "model", upstreamModel)
|
||||
if err != nil {
|
||||
return request, err
|
||||
}
|
||||
data, err = relaycommon.ApplyParamOverrideWithRelayInfo(data, info)
|
||||
if err != nil {
|
||||
return request, err
|
||||
}
|
||||
model := gjson.GetBytes(data, "model")
|
||||
if model.Type != gjson.String || model.String() != upstreamModel {
|
||||
return request, fmt.Errorf("image protocol parameter overrides cannot change the pinned model; use channel model mapping")
|
||||
}
|
||||
data, err = sjson.SetBytes(data, "model", request.Model)
|
||||
if err != nil {
|
||||
return request, err
|
||||
}
|
||||
// Never mutate maps that have already been exposed to a plugin hook.
|
||||
body = maps.Clone(body)
|
||||
if body["kind"] == string(pluginruntime.BodyJSON) {
|
||||
var value map[string]any
|
||||
if err = common.Unmarshal(data, &value); err != nil {
|
||||
return request, err
|
||||
}
|
||||
body["value"] = value
|
||||
request.BodyText = data
|
||||
request.RequestBody = value
|
||||
} else {
|
||||
values := gjson.ParseBytes(data)
|
||||
if !values.IsObject() {
|
||||
return request, fmt.Errorf("image protocol parameter overrides must preserve an object request")
|
||||
}
|
||||
effectiveFields := make(map[string][]string)
|
||||
for key, value := range values.Map() {
|
||||
if value.Type == gjson.String {
|
||||
effectiveFields[key] = []string{value.String()}
|
||||
} else if len(fields[key]) > 1 && value.IsArray() {
|
||||
var entries []string
|
||||
if err = common.Unmarshal([]byte(value.Raw), &entries); err != nil {
|
||||
return request, err
|
||||
}
|
||||
effectiveFields[key] = entries
|
||||
} else {
|
||||
// Multipart scalars, objects and arrays reach the decoder in the
|
||||
// same text form as fields supplied by the client.
|
||||
effectiveFields[key] = []string{value.Raw}
|
||||
}
|
||||
}
|
||||
body["fields"] = effectiveFields
|
||||
request.BodyText = nil
|
||||
request.RequestBody = effectiveFields
|
||||
}
|
||||
request.Body = body
|
||||
return request, nil
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
"github.com/QuantumNous/new-api/relaykit/types"
|
||||
|
||||
"github.com/HugoSmits86/nativewebp"
|
||||
"github.com/MoeForge/moego/webp"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -348,7 +348,7 @@ func TestFetchSendsAttachments(t *testing.T) {
|
||||
// canvas says, so a forged canvas would pass the pixel bound.
|
||||
func TestReencodeWebPCanvasMatchesFrame(t *testing.T) {
|
||||
var encoded bytes.Buffer
|
||||
require.NoError(t, nativewebp.Encode(&encoded, image.NewGray(image.Rect(0, 0, 64, 64)), nil))
|
||||
require.NoError(t, webp.Encode(&encoded, image.NewGray(image.Rect(0, 0, 64, 64))))
|
||||
require.Equal(t, "VP8L", string(encoded.Bytes()[12:16]))
|
||||
withCanvas := func(width, height int) inlineMedia {
|
||||
vp8x := []byte("VP8X\x0a\x00\x00\x00\x00\x00\x00\x00")
|
||||
|
||||
@@ -9,9 +9,11 @@ import (
|
||||
_ "image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/HugoSmits86/nativewebp"
|
||||
"github.com/MoeForge/moego/webp"
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/pkg/requestpatch"
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
@@ -21,6 +23,7 @@ import (
|
||||
"golang.org/x/image/vp8"
|
||||
"golang.org/x/image/vp8l"
|
||||
_ "golang.org/x/image/webp"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
// Limits of media.reencode.
|
||||
@@ -29,8 +32,19 @@ const (
|
||||
maxReencodePixels = 40_000_000
|
||||
)
|
||||
|
||||
// reencodeSlots bounds the re-encodes running at once in the process.
|
||||
var reencodeSlots = make(chan struct{}, 4)
|
||||
type imageReencodePool struct {
|
||||
slots *semaphore.Weighted
|
||||
encode func(context.Context, inlineMedia, requestpatch.Effect) ([]requestpatch.Operation, *relaycommon.RequestPluginMediaChange, error)
|
||||
}
|
||||
|
||||
// Read the process limit after startup has loaded .env.
|
||||
var processImageEncoders = sync.OnceValue(func() *imageReencodePool {
|
||||
limit := common.GetEnvOrDefault("IMAGE_REENCODE_CONCURRENCY", 0)
|
||||
if limit <= 0 {
|
||||
limit = runtime.GOMAXPROCS(0)
|
||||
}
|
||||
return &imageReencodePool{slots: semaphore.NewWeighted(int64(limit)), encode: reencodeMedia}
|
||||
})
|
||||
|
||||
// inlineMedia is one inline media string of a JSON body: a base64 data URL,
|
||||
// or the data of a Claude base64 source, a Gemini inline data part or a chat
|
||||
@@ -165,22 +179,59 @@ func escapePointer(token string) string {
|
||||
return strings.ReplaceAll(strings.ReplaceAll(token, "~", "~0"), "/", "~1")
|
||||
}
|
||||
|
||||
type mediaReencodeResult struct {
|
||||
ops []requestpatch.Operation
|
||||
change *relaycommon.RequestPluginMediaChange
|
||||
err error
|
||||
}
|
||||
|
||||
// reencode returns one result per effect, in the order the plugin supplied.
|
||||
// Each request waits for only its next image so other requests can take a turn.
|
||||
func (p *imageReencodePool) reencode(ctx context.Context, media []inlineMedia, effects []requestpatch.Effect) []mediaReencodeResult {
|
||||
results := make([]mediaReencodeResult, len(effects))
|
||||
admission, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
var workers sync.WaitGroup
|
||||
for i, effect := range effects {
|
||||
item := media[effect.Media]
|
||||
if item.size() > maxReencodeBytes {
|
||||
continue
|
||||
}
|
||||
if err := p.slots.Acquire(admission, 1); err != nil {
|
||||
results[i].err = err
|
||||
break
|
||||
}
|
||||
result := &results[i]
|
||||
encode := func() {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
result.err = fmt.Errorf("media %s cannot be encoded", item.path)
|
||||
}
|
||||
if result.err != nil {
|
||||
// Stop admitting work. Earlier images finish so their errors
|
||||
// are still reported in effect order.
|
||||
stop()
|
||||
}
|
||||
p.slots.Release(1)
|
||||
}()
|
||||
result.ops, result.change, result.err = p.encode(ctx, item, effect)
|
||||
}
|
||||
if i == len(effects)-1 {
|
||||
encode()
|
||||
} else {
|
||||
workers.Go(encode)
|
||||
}
|
||||
}
|
||||
workers.Wait()
|
||||
return results
|
||||
}
|
||||
|
||||
// reencodeMedia decodes an inline image and encodes it again as a
|
||||
// media.reencode effect asks. It returns the json.patch operations that
|
||||
// replace the media string and its mime type, and the change for the public
|
||||
// record; none when the new bytes are not smaller or the image is an
|
||||
// animated GIF or over the limits.
|
||||
func reencodeMedia(ctx context.Context, item inlineMedia, effect requestpatch.Effect) ([]requestpatch.Operation, *relaycommon.RequestPluginMediaChange, error) {
|
||||
if item.size() > maxReencodeBytes {
|
||||
return nil, nil, nil
|
||||
}
|
||||
select {
|
||||
case reencodeSlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
defer func() { <-reencodeSlots }()
|
||||
|
||||
raw, err := base64.StdEncoding.DecodeString(item.data)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("media %s is not valid base64", item.path)
|
||||
@@ -244,8 +295,7 @@ func reencodeMedia(ctx context.Context, item inlineMedia, effect requestpatch.Ef
|
||||
case "png":
|
||||
err = png.Encode(&encoded, img)
|
||||
case "webp":
|
||||
// nativewebp writes lossless WebP only.
|
||||
err = nativewebp.Encode(&encoded, img, nil)
|
||||
err = webp.Encode(&encoded, img)
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("format %q is not supported", effect.Format)
|
||||
}
|
||||
|
||||
+21
-10
@@ -518,7 +518,8 @@ func (p *Plan) runInstance(ctx context.Context, call Call, instance *request_plu
|
||||
var rewritten []int
|
||||
var patches []requestpatch.Effect
|
||||
refused := false
|
||||
for index, effect := range effects {
|
||||
for index := 0; index < len(effects); index++ {
|
||||
effect := effects[index]
|
||||
switch effect.Type {
|
||||
case requestpatch.EffectReasoningSet:
|
||||
if effort, err := reasoning.ParseEffort(effect.Effort); err != nil || effort == "" {
|
||||
@@ -529,18 +530,28 @@ func (p *Plan) runInstance(ctx context.Context, call Call, instance *request_plu
|
||||
next.record.ReasoningEffort = effect.Effort
|
||||
}
|
||||
case requestpatch.EffectMediaReencode:
|
||||
if effect.Media < 0 || effect.Media >= len(media) {
|
||||
end := index
|
||||
for end < len(effects) {
|
||||
candidate := effects[end]
|
||||
if candidate.Type != requestpatch.EffectMediaReencode || candidate.Media < 0 || candidate.Media >= len(media) {
|
||||
break
|
||||
}
|
||||
end++
|
||||
}
|
||||
if end == index {
|
||||
return change{}, errorInvalidEffect, fmt.Errorf("effects[%d].media %d does not exist", index, effect.Media)
|
||||
}
|
||||
ops, reencode, err := reencodeMedia(ctx, media[effect.Media], effect)
|
||||
if err != nil {
|
||||
return change{}, errorMedia, fmt.Errorf("effects[%d]: %w", index, err)
|
||||
}
|
||||
mediaOps = append(mediaOps, ops...)
|
||||
if reencode != nil {
|
||||
reencode.Index = effect.Media
|
||||
next.record.Media = append(next.record.Media, *reencode)
|
||||
for offset, result := range processImageEncoders().reencode(ctx, media, effects[index:end]) {
|
||||
if result.err != nil {
|
||||
return change{}, errorMedia, fmt.Errorf("effects[%d]: %w", index+offset, result.err)
|
||||
}
|
||||
mediaOps = append(mediaOps, result.ops...)
|
||||
if result.change != nil {
|
||||
result.change.Index = effects[index+offset].Media
|
||||
next.record.Media = append(next.record.Media, *result.change)
|
||||
}
|
||||
}
|
||||
index = end - 1
|
||||
case requestpatch.EffectMediaText:
|
||||
if !attachments.exists(effect.Media) {
|
||||
return change{}, errorInvalidEffect, fmt.Errorf("effects[%d].media %d does not exist", index, effect.Media)
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
@@ -37,6 +38,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/image/webp"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
// stagePlugin runs every stage as its instance config says: throw, allocate
|
||||
@@ -484,12 +486,91 @@ func TestMediaReencode(t *testing.T) {
|
||||
assert.Less(t, len(content.Get("1.source.data").Str), len(large))
|
||||
// A re-encode that is not smaller keeps the image.
|
||||
assert.Equal(t, "data:image/png;base64,"+small, content.Get("2.image_url.url").Str)
|
||||
require.Len(t, outcome.Record, 1)
|
||||
require.Len(t, outcome.Record[0].Media, 2)
|
||||
assert.Equal(t, 0, outcome.Record[0].Media[0].Index)
|
||||
assert.Equal(t, 1, outcome.Record[0].Media[1].Index)
|
||||
// The hook saw placeholders, sizes and, at outbound, dimensions.
|
||||
assert.JSONEq(t, `[
|
||||
{"index":0,"path":"/messages/0/content/0/image_url/url","mimeType":"image/png","bytes":`+strconv.Itoa(len(large)*3/4-strings.Count(large[len(large)-2:], "="))+`,"width":256,"height":256},
|
||||
{"index":1,"path":"/messages/0/content/1/source/data","mimeType":"image/png","bytes":`+strconv.Itoa(len(large)*3/4-strings.Count(large[len(large)-2:], "="))+`,"width":256,"height":256},
|
||||
{"index":2,"path":"/messages/0/content/2/image_url/url","mimeType":"image/png","bytes":`+strconv.Itoa(len(small)*3/4-strings.Count(small[len(small)-2:], "="))+`,"width":1,"height":1}]`,
|
||||
gjson.GetBytes(outcome.Body, "echo_rp.media").Raw)
|
||||
|
||||
// One good image followed by two unreadable ones. Report the first bad
|
||||
// image in request order and discard the whole instance's changes.
|
||||
bad := []byte(`{"images":["data:image/png;base64,` + large + `","data:image/png;base64,AQ==","data:image/png;base64,Ag=="]}`)
|
||||
outcome = NewPlan().Run(context.Background(), Call{Stage: StageOutbound, Body: bad})
|
||||
require.NotNil(t, outcome.Failed)
|
||||
assert.Equal(t, errorMedia, outcome.Failed.Class)
|
||||
assert.Contains(t, outcome.Failed.Detail, "effects[1]: media /images/1 ")
|
||||
assert.Equal(t, bad, outcome.Body)
|
||||
require.Len(t, outcome.Record, 1)
|
||||
assert.Empty(t, outcome.Record[0].Media)
|
||||
}
|
||||
|
||||
func TestMediaReencodeSharesCapacityAcrossRequests(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
type imageJob struct {
|
||||
path string
|
||||
finish chan struct{}
|
||||
}
|
||||
started := make(chan imageJob, 5)
|
||||
pool := imageReencodePool{
|
||||
slots: semaphore.NewWeighted(2),
|
||||
encode: func(ctx context.Context, item inlineMedia, _ requestpatch.Effect) ([]requestpatch.Operation, *relaycommon.RequestPluginMediaChange, error) {
|
||||
job := imageJob{path: item.path, finish: make(chan struct{})}
|
||||
started <- job
|
||||
select {
|
||||
case <-job.finish:
|
||||
return nil, nil, nil
|
||||
case <-ctx.Done():
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
},
|
||||
}
|
||||
submit := func(ctx context.Context, paths ...string) <-chan []mediaReencodeResult {
|
||||
media := make([]inlineMedia, len(paths))
|
||||
effects := make([]requestpatch.Effect, len(paths))
|
||||
for i, path := range paths {
|
||||
media[i].path = path
|
||||
effects[i] = requestpatch.Effect{Type: requestpatch.EffectMediaReencode, Media: i}
|
||||
}
|
||||
done := make(chan []mediaReencodeResult, 1)
|
||||
go func() { done <- pool.reencode(ctx, media, effects) }()
|
||||
synctest.Wait()
|
||||
return done
|
||||
}
|
||||
|
||||
batch := submit(ctx, "/a", "/b", "/c", "/d")
|
||||
require.Len(t, started, 2)
|
||||
first, second := <-started, <-started
|
||||
assert.ElementsMatch(t, []string{"/a", "/b"}, []string{first.path, second.path})
|
||||
single := submit(ctx, "/single")
|
||||
waiting, leave := context.WithCancel(ctx)
|
||||
abandoned := submit(waiting, "/canceled")
|
||||
leave()
|
||||
require.ErrorIs(t, (<-abandoned)[0].err, context.Canceled)
|
||||
require.Empty(t, started)
|
||||
|
||||
close(first.finish)
|
||||
third := <-started
|
||||
require.Equal(t, "/c", third.path)
|
||||
close(second.finish)
|
||||
other := <-started
|
||||
require.Equal(t, "/single", other.path)
|
||||
close(other.finish)
|
||||
require.NoError(t, (<-single)[0].err)
|
||||
last := <-started
|
||||
require.Equal(t, "/d", last.path)
|
||||
close(last.finish)
|
||||
close(third.finish)
|
||||
for _, result := range <-batch {
|
||||
require.NoError(t, result.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDryRun(t *testing.T) {
|
||||
@@ -621,7 +702,7 @@ func TestMediaReencodeLosslessWebP(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 192, 128))
|
||||
for y := range 128 {
|
||||
for x := range 192 {
|
||||
source.SetNRGBA(x, y, color.NRGBA{R: uint8(x), G: uint8(y * 2), B: uint8((x + y) % 7 * 30), A: 255})
|
||||
source.SetNRGBA(x, y, color.NRGBA{R: uint8(x), G: uint8(y * 2), B: uint8((x + y) % 7 * 30), A: uint8((x + y) * 3)})
|
||||
}
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ module github.com/QuantumNous/new-api/relaykit
|
||||
go 1.25.1
|
||||
|
||||
require (
|
||||
github.com/MoeForge/moego v0.1.0-alpha.3
|
||||
github.com/MoeForge/moego v0.1.0-alpha.5
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/samber/lo v1.53.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
github.com/MoeForge/moego v0.1.0-alpha.3 h1:sn8Kg4qY/gqGXU4CCJWfgzouaim6alkvXcob0uFDohg=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.3/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.5 h1:/pFyEhm0GYdOGfwawNjzLx+DoDQVoCI0dLsu8Sbpac8=
|
||||
github.com/MoeForge/moego v0.1.0-alpha.5/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
|
||||
@@ -13,9 +13,9 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/MoeForge/moego/regexp"
|
||||
"github.com/QuantumNous/new-api/relaykit/dto"
|
||||
"github.com/QuantumNous/new-api/relaykit/relayconvert/convmeta"
|
||||
"github.com/QuantumNous/new-api/relaykit/types"
|
||||
|
||||
@@ -58,10 +58,11 @@ func ResponseOpenAI2Gemini(openAIResponse *dto.OpenAITextResponse, info convmeta
|
||||
Candidates: make([]dto.GeminiChatCandidate, 0, len(openAIResponse.Choices)),
|
||||
HasUsageMetadata: true,
|
||||
UsageMetadata: dto.GeminiUsageMetadata{
|
||||
PromptTokenCount: openAIResponse.PromptTokens,
|
||||
CandidatesTokenCount: openAIResponse.CompletionTokens,
|
||||
TotalTokenCount: totalTokens,
|
||||
BillingUsage: openAIBillingUsageFromUsage(&openAIResponse.Usage),
|
||||
PromptTokenCount: openAIResponse.PromptTokens,
|
||||
CandidatesTokenCount: openAIResponse.CompletionTokens,
|
||||
TotalTokenCount: totalTokens,
|
||||
CachedContentTokenCount: geminiCachedContentTokenCount(&openAIResponse.Usage),
|
||||
BillingUsage: openAIBillingUsageFromUsage(&openAIResponse.Usage),
|
||||
},
|
||||
}
|
||||
if metadata, ok := geminiBillingMetadataFromOpenAIUsage(&openAIResponse.Usage); ok {
|
||||
@@ -160,6 +161,7 @@ func StreamResponseOpenAI2Gemini(openAIResponse *dto.ChatCompletionsStreamRespon
|
||||
geminiResponse.UsageMetadata.PromptTokenCount = openAIResponse.Usage.PromptTokens
|
||||
geminiResponse.UsageMetadata.CandidatesTokenCount = openAIResponse.Usage.CompletionTokens
|
||||
geminiResponse.UsageMetadata.TotalTokenCount = openAIResponse.Usage.TotalTokens
|
||||
geminiResponse.UsageMetadata.CachedContentTokenCount = geminiCachedContentTokenCount(openAIResponse.Usage)
|
||||
geminiResponse.UsageMetadata.BillingUsage = openAIBillingUsageFromUsage(openAIResponse.Usage)
|
||||
if metadata, ok := geminiBillingMetadataFromOpenAIUsage(openAIResponse.Usage); ok {
|
||||
geminiResponse.UsageMetadata = metadata
|
||||
@@ -495,6 +497,7 @@ func newGeminiStreamResponse(candidates []dto.GeminiChatCandidate, usage *dto.Us
|
||||
response.UsageMetadata.PromptTokenCount = usage.PromptTokens
|
||||
response.UsageMetadata.CandidatesTokenCount = usage.CompletionTokens
|
||||
response.UsageMetadata.TotalTokenCount = usage.TotalTokens
|
||||
response.UsageMetadata.CachedContentTokenCount = geminiCachedContentTokenCount(usage)
|
||||
response.UsageMetadata.BillingUsage = openAIBillingUsageFromUsage(usage)
|
||||
if metadata, ok := geminiBillingMetadataFromOpenAIUsage(usage); ok {
|
||||
response.UsageMetadata = metadata
|
||||
@@ -502,6 +505,23 @@ func newGeminiStreamResponse(candidates []dto.GeminiChatCandidate, usage *dto.Us
|
||||
return response
|
||||
}
|
||||
|
||||
// geminiCachedContentTokenCount returns the cache-read tokens included in the
|
||||
// prompt count. Chat usage carries them in PromptTokensDetails; stream state
|
||||
// stores usage normalized by UsageFromChatUsage, which carries them in
|
||||
// InputTokensDetails.
|
||||
func geminiCachedContentTokenCount(usage *dto.Usage) int {
|
||||
if usage == nil {
|
||||
return 0
|
||||
}
|
||||
if usage.PromptTokensDetails.CachedTokens > 0 {
|
||||
return usage.PromptTokensDetails.CachedTokens
|
||||
}
|
||||
if usage.InputTokensDetails != nil && usage.InputTokensDetails.CachedTokens > 0 {
|
||||
return usage.InputTokensDetails.CachedTokens
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func geminiFunctionArguments(raw string) map[string]any {
|
||||
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "null" {
|
||||
return map[string]any{}
|
||||
|
||||
@@ -56,9 +56,7 @@ func geminiCapabilitiesFor(model string) geminiCapabilities {
|
||||
return geminiCapabilities{kind: geminiThinkingBudget, supportsDisable: true, minBudget: 512, maxBudget: 24576}
|
||||
case strings.HasPrefix(model, "gemini-2.5-"):
|
||||
return geminiCapabilities{kind: geminiThinkingBudget, supportsDisable: true, maxBudget: 24576}
|
||||
case strings.HasPrefix(model, "gemini-3"),
|
||||
strings.HasPrefix(model, "gemini-4-argon"),
|
||||
strings.HasPrefix(model, "gemini-4-hydrogen"):
|
||||
case strings.HasPrefix(model, "gemini-3"), strings.HasPrefix(model, "gemini-4-"):
|
||||
return geminiCapabilities{kind: geminiThinkingLevel}
|
||||
default:
|
||||
return geminiCapabilities{}
|
||||
@@ -514,22 +512,15 @@ func geminiLevelForEffort(model string, effort Effort) (string, error) {
|
||||
return string(EffortLow), nil
|
||||
}
|
||||
return string(EffortHigh), nil
|
||||
case strings.HasPrefix(model, "gemini-4-argon"):
|
||||
// Argon accepts max but rejects xhigh.
|
||||
switch effort {
|
||||
case EffortMinimal:
|
||||
return string(EffortLow), nil
|
||||
case EffortXHigh:
|
||||
return string(EffortHigh), nil
|
||||
case EffortMax:
|
||||
return string(EffortMax), nil
|
||||
}
|
||||
case strings.HasPrefix(model, "gemini-4-hydrogen"):
|
||||
case strings.HasPrefix(model, "gemini-4-"):
|
||||
switch effort {
|
||||
case EffortMinimal:
|
||||
return string(EffortLow), nil
|
||||
case EffortXHigh, EffortMax:
|
||||
return string(effort), nil
|
||||
if strings.HasPrefix(model, "gemini-4-neon") || strings.HasPrefix(model, "gemini-4-hydrogen") {
|
||||
return string(EffortXHigh), nil
|
||||
}
|
||||
return string(EffortHigh), nil
|
||||
}
|
||||
case strings.HasPrefix(model, "gemini-3.1-pro"), model == "gemini-pro-latest":
|
||||
if effort == EffortMinimal {
|
||||
|
||||
@@ -65,11 +65,28 @@ func TestRenderGeminiMapsAndClampsInsteadOfRejecting(t *testing.T) {
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "max on gemini 4 argon is kept",
|
||||
name: "max on gemini 4 argon moves to high",
|
||||
model: "gemini-4-argon",
|
||||
intent: Intent{Mode: ModeEnabled, Effort: EffortMax},
|
||||
wantLevel: "max",
|
||||
wantEffort: EffortMax,
|
||||
wantLevel: "high",
|
||||
wantEffort: EffortHigh,
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "max on gemini 4 neon moves to xhigh",
|
||||
model: "gemini-4-neon",
|
||||
intent: Intent{Mode: ModeEnabled, Effort: EffortMax},
|
||||
wantLevel: "xhigh",
|
||||
wantEffort: EffortXHigh,
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "xhigh on gemini 4 carbon moves to high",
|
||||
model: "gemini-4-carbon",
|
||||
intent: Intent{Mode: ModeEnabled, Effort: EffortXHigh},
|
||||
wantLevel: "high",
|
||||
wantEffort: EffortHigh,
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "xhigh on gemini 4 argon moves to high",
|
||||
@@ -264,18 +281,20 @@ func TestNormalizeGeminiThinkingConfigRewritesNativeConfig(t *testing.T) {
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "max on gemini 4 argon is kept",
|
||||
name: "max on gemini 4 argon moves to high",
|
||||
model: "gemini-4-argon",
|
||||
config: dto.GeminiThinkingConfig{ThinkingLevel: "max"},
|
||||
wantLevel: "max",
|
||||
wantEffort: EffortMax,
|
||||
wantLevel: "high",
|
||||
wantEffort: EffortHigh,
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "max on gemini 4 hydrogen is kept",
|
||||
name: "max on gemini 4 hydrogen moves to xhigh",
|
||||
model: "gemini-4-hydrogen",
|
||||
config: dto.GeminiThinkingConfig{ThinkingLevel: "max"},
|
||||
wantLevel: "max",
|
||||
wantEffort: EffortMax,
|
||||
wantLevel: "xhigh",
|
||||
wantEffort: EffortXHigh,
|
||||
wantCodes: []string{"gemini_level_adjusted"},
|
||||
},
|
||||
{
|
||||
name: "unknown level is rejected",
|
||||
|
||||
@@ -560,6 +560,97 @@ func TestConvertStreamResponseStatefulDirectResponsesToClaude(t *testing.T) {
|
||||
assert.Equal(t, 5, state.Usage().TotalTokens)
|
||||
}
|
||||
|
||||
// Gemini promptTokenCount includes cache reads; cachedContentTokenCount must
|
||||
// report them on every route that builds Gemini usage from chat usage.
|
||||
func TestConvertResponseToGeminiReportsCachedContentTokens(t *testing.T) {
|
||||
const claudeUsage = `{"input_tokens":2054,"cache_creation_input_tokens":0,"cache_read_input_tokens":12981,"output_tokens":42}`
|
||||
const chatUsage = `{"prompt_tokens":1000,"completion_tokens":5,"total_tokens":1005,"prompt_tokens_details":{"cached_tokens":800}}`
|
||||
tests := []struct {
|
||||
name string
|
||||
from types.RelayFormat
|
||||
response any
|
||||
stream []any
|
||||
stateless any
|
||||
wantPrompt int
|
||||
wantCached int
|
||||
}{
|
||||
{
|
||||
name: "claude",
|
||||
from: types.RelayFormatClaude,
|
||||
response: claudeStreamChunk(`{"id":"msg_1","type":"message","role":"assistant","model":"claude-test","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":` + claudeUsage + `}`),
|
||||
stream: []any{
|
||||
claudeStreamChunk(`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-test","content":[],"usage":{"input_tokens":2054,"cache_creation_input_tokens":0,"cache_read_input_tokens":12981,"output_tokens":1}}}`),
|
||||
claudeStreamChunk(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`),
|
||||
claudeStreamChunk(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`),
|
||||
claudeStreamChunk(`{"type":"content_block_stop","index":0}`),
|
||||
claudeStreamChunk(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":` + claudeUsage + `}`),
|
||||
claudeStreamChunk(`{"type":"message_stop"}`),
|
||||
},
|
||||
wantPrompt: 15035,
|
||||
wantCached: 12981,
|
||||
},
|
||||
{
|
||||
name: "chat",
|
||||
from: types.RelayFormatOpenAI,
|
||||
response: &dto.OpenAITextResponse{
|
||||
Choices: []dto.OpenAITextResponseChoice{{Message: dto.Message{Role: "assistant", Content: "hi"}, FinishReason: "stop"}},
|
||||
Usage: dto.Usage{
|
||||
PromptTokens: 1000,
|
||||
CompletionTokens: 5,
|
||||
TotalTokens: 1005,
|
||||
PromptTokensDetails: dto.InputTokenDetails{CachedTokens: 800},
|
||||
},
|
||||
},
|
||||
stream: []any{
|
||||
chatStreamChunk(`{"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}]}`),
|
||||
chatStreamChunk(`{"id":"c1","choices":[],"usage":` + chatUsage + `}`),
|
||||
},
|
||||
stateless: chatStreamChunk(`{"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":` + chatUsage + `}`),
|
||||
wantPrompt: 1000,
|
||||
wantCached: 800,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
info := &convmeta.Values{}
|
||||
result, err := ConvertResponse(nil, info, types.RelayFormatGemini, tt.response)
|
||||
require.NoError(t, err)
|
||||
gemini, ok := result.Value.(*dto.GeminiChatResponse)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, tt.wantPrompt, gemini.UsageMetadata.PromptTokenCount)
|
||||
assert.Equal(t, tt.wantCached, gemini.UsageMetadata.CachedContentTokenCount)
|
||||
|
||||
state, err := NewResponseStreamState(tt.from, types.RelayFormatGemini, ResponseStreamOptions{})
|
||||
require.NoError(t, err)
|
||||
var results []ResponseResult
|
||||
for _, chunk := range tt.stream {
|
||||
chunkResults, err := ConvertStreamResponseChunk(nil, info, state, chunk)
|
||||
require.NoError(t, err)
|
||||
results = append(results, chunkResults...)
|
||||
}
|
||||
finals, err := FinalizeStreamResponse(nil, info, state)
|
||||
require.NoError(t, err)
|
||||
results = append(results, finals...)
|
||||
require.NotEmpty(t, results)
|
||||
// Gemini clients read usage from the last chunk.
|
||||
last, ok := results[len(results)-1].Value.(*dto.GeminiChatResponse)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, tt.wantPrompt, last.UsageMetadata.PromptTokenCount)
|
||||
assert.Equal(t, tt.wantCached, last.UsageMetadata.CachedContentTokenCount)
|
||||
|
||||
if tt.stateless == nil {
|
||||
return
|
||||
}
|
||||
result, err = ConvertStreamResponse(nil, info, types.RelayFormatGemini, tt.stateless)
|
||||
require.NoError(t, err)
|
||||
chunk, ok := result.Value.(*dto.GeminiChatResponse)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, tt.wantPrompt, chunk.UsageMetadata.PromptTokenCount)
|
||||
assert.Equal(t, tt.wantCached, chunk.UsageMetadata.CachedContentTokenCount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseUsageMatrixChatAndResponsesDetails(t *testing.T) {
|
||||
chat := textRegistryChatResponse()
|
||||
chat.Usage = dto.Usage{
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -11,6 +13,7 @@ import (
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/middleware"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/QuantumNous/new-api/service/authz"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -157,6 +160,41 @@ func TestAccessTokenRouteRulesCoverEveryDashboardRoute(t *testing.T) {
|
||||
assert.Equal(t, "session", setupRule.Kind(), "browser readiness remains private to root browser sessions")
|
||||
}
|
||||
|
||||
func TestDashboardPerfMetricsRequiresAdminReadAccess(t *testing.T) {
|
||||
setupRelayRouterTestDB(t)
|
||||
require.NoError(t, model.DB.AutoMigrate(&model.UserAccessToken{}, &model.AuditLog{}, &model.PerfMetric{}))
|
||||
engine := gin.New()
|
||||
SetApiRouter(engine)
|
||||
for _, tc := range []struct {
|
||||
name, scope string
|
||||
role, want int
|
||||
}{
|
||||
{"guest", "", 0, http.StatusUnauthorized},
|
||||
{"member", "log:read", common.RoleCommonUser, http.StatusForbidden},
|
||||
{"admin-profile", "profile:read", common.RoleAdminUser, http.StatusForbidden},
|
||||
{"admin-log", "log:read", common.RoleAdminUser, http.StatusOK},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/data/perf-metrics/summary", nil)
|
||||
if tc.role != 0 {
|
||||
user := model.User{Username: tc.name, AffCode: tc.name, Role: tc.role, Group: "default", Status: common.UserStatusEnabled}
|
||||
require.NoError(t, model.DB.Create(&user).Error)
|
||||
suffix, err := common.GenerateRandomCharsKey(43)
|
||||
require.NoError(t, err)
|
||||
raw := model.AccessTokenPrefix + suffix
|
||||
token := model.UserAccessToken{Name: tc.name, TokenHash: model.AccessTokenFingerprint(raw), TokenHint: model.AccessTokenHint(raw)}
|
||||
require.NoError(t, token.SetScopes([]string{tc.scope}))
|
||||
require.NoError(t, model.CreateUserAccessToken(user.Id, &token, service.AccessTokenMaxPerUser))
|
||||
req.Header.Set("Authorization", "Bearer "+raw)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, tc.want, recorder.Code)
|
||||
assert.Contains(t, recorder.Header().Get("Cache-Control"), "no-store")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessTokenCatalogCoversEveryPermission(t *testing.T) {
|
||||
catalog := service.AccessTokenCatalog(1, common.RoleRootUser)
|
||||
scopes := map[string]bool{}
|
||||
|
||||
@@ -36,9 +36,9 @@ func SetApiRouter(router *gin.Engine) {
|
||||
apiRouter.GET("/about", controller.GetAbout)
|
||||
//apiRouter.GET("/midjourney", controller.GetMidjourney)
|
||||
apiRouter.GET("/home_page_content", controller.GetHomePageContent)
|
||||
apiRouter.GET("/pricing", middleware.HeaderNavModuleAuth("pricing"), controller.GetPricing)
|
||||
apiRouter.GET("/pricing", middleware.DisableCache(), middleware.HeaderNavModuleAuth("pricing"), controller.GetPricing)
|
||||
perfMetricsRoute := apiRouter.Group("/perf-metrics")
|
||||
perfMetricsRoute.Use(middleware.HeaderNavModulePublicOrUserAuth("pricing"))
|
||||
perfMetricsRoute.Use(middleware.DisableCache(), middleware.HeaderNavModulePublicOrUserAuth("pricing"))
|
||||
{
|
||||
perfMetricsRoute.GET("/summary", controller.GetPerfMetricsSummary)
|
||||
perfMetricsRoute.GET("", controller.GetPerfMetrics)
|
||||
@@ -360,6 +360,7 @@ func SetApiRouter(router *gin.Engine) {
|
||||
}
|
||||
|
||||
dataRoute := apiRouter.Group("/data")
|
||||
dataRoute.GET("/perf-metrics/summary", middleware.DisableCache(), middleware.AdminAuth(), controller.GetDashboardPerfMetricsSummary)
|
||||
dataRoute.GET("/", middleware.AdminAuth(), controller.GetAllQuotaDates)
|
||||
dataRoute.GET("/users", middleware.AdminAuth(), controller.GetQuotaDatesByUser)
|
||||
dataRoute.GET("/self", middleware.UserAuth(), controller.GetUserQuotaDates)
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/textproto"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -36,6 +35,7 @@ import (
|
||||
"github.com/QuantumNous/new-api/setting/ratio_setting"
|
||||
"github.com/QuantumNous/new-api/setting/request_plugin_setting"
|
||||
|
||||
"github.com/MoeForge/moego/regexp"
|
||||
"github.com/bytedance/gopkg/util/gopool"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
@@ -748,6 +748,69 @@ func TestRunTaskPollingOnceDoesNotRefundHistoricalFailedTask(t *testing.T) {
|
||||
assert.Equal(t, int64(0), countLogs(t))
|
||||
}
|
||||
|
||||
func TestRunTaskPollingOnceContinuesAtFullProgress(t *testing.T) {
|
||||
previousLimit := constant.TaskQueryLimit
|
||||
constant.TaskQueryLimit = 100
|
||||
t.Cleanup(func() { constant.TaskQueryLimit = previousLimit })
|
||||
for _, action := range []string{constant.TaskActionTextToVideo, constant.TaskActionImageToVideo} {
|
||||
for _, progress := range []string{"99%", "100%"} {
|
||||
for _, terminal := range []string{model.TaskStatusSuccess, model.TaskStatusFailure} {
|
||||
t.Run(action+"/"+progress+"/"+terminal, func(t *testing.T) {
|
||||
truncate(t)
|
||||
const channelID, userID, initialQuota, taskQuota = 405, 405, 10_000, 1_200
|
||||
seedUser(t, userID, initialQuota)
|
||||
seedTaskPollingChannel(t, channelID, true)
|
||||
task := seedPollingTask(t, channelID, "task_progress", "upstream_progress")
|
||||
task.Action = action
|
||||
task.UserId = userID
|
||||
task.Quota = taskQuota
|
||||
task.SubmitTime = time.Now().Unix()
|
||||
require.NoError(t, model.DB.Save(task).Error)
|
||||
adaptor := &scriptedPollingAdaptor{parse: &relaycommon.TaskInfo{
|
||||
TaskID: task.GetUpstreamTaskID(), Status: model.TaskStatusInProgress, Progress: progress,
|
||||
}}
|
||||
previousFactory := GetTaskAdaptorFunc
|
||||
GetTaskAdaptorFunc = func(constant.TaskPlatform) TaskPollingAdaptor { return adaptor }
|
||||
t.Cleanup(func() { GetTaskAdaptorFunc = previousFactory })
|
||||
|
||||
assert.Equal(t, 1, RunTaskPollingOnce(context.Background(), nil).UnfinishedTasks)
|
||||
var persisted model.Task
|
||||
require.NoError(t, model.DB.First(&persisted, task.ID).Error)
|
||||
assert.EqualValues(t, model.TaskStatusInProgress, persisted.Status)
|
||||
assert.Equal(t, progress, persisted.Progress)
|
||||
assert.Zero(t, persisted.FinishTime)
|
||||
assert.Equal(t, initialQuota, getUserQuota(t, userID))
|
||||
assert.Zero(t, countLogs(t))
|
||||
require.True(t, model.HasUnfinishedSyncTasks(), "the scheduler must run again even at 100%")
|
||||
|
||||
adaptor.parse = &relaycommon.TaskInfo{TaskID: task.GetUpstreamTaskID(), Status: terminal, Progress: "100%"}
|
||||
if terminal == model.TaskStatusFailure {
|
||||
adaptor.parse.Reason = "upstream finalization failed"
|
||||
}
|
||||
assert.Equal(t, 1, RunTaskPollingOnce(context.Background(), nil).UnfinishedTasks)
|
||||
require.NoError(t, model.DB.First(&persisted, task.ID).Error)
|
||||
assert.EqualValues(t, terminal, persisted.Status)
|
||||
assert.NotZero(t, persisted.FinishTime)
|
||||
if terminal == model.TaskStatusFailure {
|
||||
assert.Zero(t, persisted.Quota)
|
||||
assert.Equal(t, initialQuota+taskQuota, getUserQuota(t, userID))
|
||||
assert.EqualValues(t, 1, countLogs(t))
|
||||
} else {
|
||||
assert.Equal(t, taskQuota, persisted.Quota)
|
||||
assert.Equal(t, initialQuota, getUserQuota(t, userID))
|
||||
assert.Zero(t, countLogs(t))
|
||||
}
|
||||
quota, logs := getUserQuota(t, userID), countLogs(t)
|
||||
assert.False(t, model.HasUnfinishedSyncTasks())
|
||||
assert.Zero(t, RunTaskPollingOnce(context.Background(), nil).UnfinishedTasks)
|
||||
assert.Equal(t, quota, getUserQuota(t, userID))
|
||||
assert.Equal(t, logs, countLogs(t), "terminal tasks must not be settled or refunded again")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSweepTimedOutTasksHonorsRefundRolloutBoundary(t *testing.T) {
|
||||
truncate(t)
|
||||
|
||||
@@ -805,7 +868,7 @@ func TestSweepTimedOutTasksAtTheDefaultDeadline(t *testing.T) {
|
||||
require.NoError(t, model.DB.Create(running).Error)
|
||||
stuck := makeTask(userID, 0, taskQuota, 0, BillingSourceWallet, 0)
|
||||
stuck.TaskID = "running_for_73_hours"
|
||||
stuck.Progress = "50%"
|
||||
stuck.Progress = "100%"
|
||||
stuck.SubmitTime = time.Now().Add(-73 * time.Hour).Unix()
|
||||
require.NoError(t, model.DB.Create(stuck).Error)
|
||||
|
||||
@@ -823,6 +886,10 @@ func TestSweepTimedOutTasksAtTheDefaultDeadline(t *testing.T) {
|
||||
assert.EqualValues(t, model.TaskStatusFailure, reloadedStuck.Status)
|
||||
assert.Equal(t, "Task timed out", reloadedStuck.FailReason)
|
||||
assert.Equal(t, initialQuota+taskQuota, getUserQuota(t, userID))
|
||||
assert.Zero(t, reloadedStuck.Quota)
|
||||
sweepTimedOutTasks(context.Background())
|
||||
assert.Equal(t, initialQuota+taskQuota, getUserQuota(t, userID))
|
||||
assert.EqualValues(t, 1, countLogs(t), "a timed out task is refunded only once")
|
||||
}
|
||||
|
||||
type scriptedPollingAdaptor struct {
|
||||
|
||||
@@ -23,7 +23,7 @@ import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { getPerfMetricsSummary } from '@/features/performance-metrics/api'
|
||||
import { getDashboardPerfMetricsSummary } from '@/features/performance-metrics/api'
|
||||
import {
|
||||
formatLatency,
|
||||
formatThroughput,
|
||||
@@ -41,10 +41,10 @@ const TOP_MODEL_LIMIT = 6
|
||||
export function PerformanceOverview() {
|
||||
const { t } = useTranslation()
|
||||
const metricsQuery = useQuery({
|
||||
queryKey: ['perf-metrics-summary', PERFORMANCE_WINDOW_HOURS],
|
||||
queryKey: ['dashboard-perf-metrics-summary', PERFORMANCE_WINDOW_HOURS],
|
||||
queryFn: async () =>
|
||||
requireServerSuccess(
|
||||
await getPerfMetricsSummary(PERFORMANCE_WINDOW_HOURS)
|
||||
await getDashboardPerfMetricsSummary(PERFORMANCE_WINDOW_HOURS)
|
||||
),
|
||||
staleTime: 60 * 1000,
|
||||
retry: false,
|
||||
|
||||
@@ -23,7 +23,7 @@ import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { getPerfMetricsSummary } from '@/features/performance-metrics/api'
|
||||
import { getDashboardPerfMetricsSummary } from '@/features/performance-metrics/api'
|
||||
import {
|
||||
formatLatency,
|
||||
formatThroughput,
|
||||
@@ -40,10 +40,10 @@ const TOP_MODEL_LIMIT = 6
|
||||
export function PerformanceHealthPanel() {
|
||||
const { t } = useTranslation()
|
||||
const metricsQuery = useQuery({
|
||||
queryKey: ['perf-metrics-summary', PERFORMANCE_WINDOW_HOURS],
|
||||
queryKey: ['dashboard-perf-metrics-summary', PERFORMANCE_WINDOW_HOURS],
|
||||
queryFn: async () =>
|
||||
requireServerSuccess(
|
||||
await getPerfMetricsSummary(PERFORMANCE_WINDOW_HOURS)
|
||||
await getDashboardPerfMetricsSummary(PERFORMANCE_WINDOW_HOURS)
|
||||
),
|
||||
staleTime: 60 * 1000,
|
||||
retry: false,
|
||||
|
||||
@@ -24,6 +24,7 @@ import { PerformanceOverview } from '@/features/dashboard/components/models/perf
|
||||
import { PerformanceHealthPanel } from '@/features/dashboard/components/overview/performance-health-panel'
|
||||
import { ModelDetailsPerformance } from '@/features/pricing/components/model-details-performance'
|
||||
import { UptimeSparkline } from '@/features/pricing/components/model-details-uptime-sparkline'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
const chart = vi.hoisted(() =>
|
||||
vi.fn(
|
||||
@@ -122,16 +123,18 @@ function renderModelDetails() {
|
||||
|
||||
describe('server performance summaries', () => {
|
||||
it.each([PerformanceHealthPanel, PerformanceOverview])(
|
||||
'uses the weighted server result across models',
|
||||
(Component) => {
|
||||
client.setQueryData(['perf-metrics-summary', 24], {
|
||||
success: true,
|
||||
'shows the site-wide weighted summary on the administrator dashboard',
|
||||
async (Component) => {
|
||||
const request = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
summary,
|
||||
models: groups.map((group) => ({
|
||||
...group,
|
||||
model_name: group.group,
|
||||
})),
|
||||
success: true,
|
||||
data: {
|
||||
summary,
|
||||
models: groups.map((group) => ({
|
||||
...group,
|
||||
model_name: group.group,
|
||||
})),
|
||||
},
|
||||
},
|
||||
})
|
||||
render(
|
||||
@@ -139,7 +142,10 @@ describe('server performance summaries', () => {
|
||||
<Component />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
expect(screen.getByText('99.01%')).toBeVisible()
|
||||
expect(await screen.findByText('99.01%')).toBeVisible()
|
||||
expect(request).toHaveBeenCalledWith('/api/data/perf-metrics/summary', {
|
||||
params: { hours: 24 },
|
||||
})
|
||||
expect(screen.queryByText('50.00%')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('1.01s')).toBeVisible()
|
||||
}
|
||||
@@ -193,7 +199,7 @@ describe('server performance summaries', () => {
|
||||
})
|
||||
|
||||
it('keeps an empty summary unknown instead of inventing a zero success rate', () => {
|
||||
client.setQueryData(['perf-metrics-summary', 24], {
|
||||
client.setQueryData(['dashboard-perf-metrics-summary', 24], {
|
||||
success: true,
|
||||
data: { models: [], summary: null },
|
||||
})
|
||||
|
||||
@@ -20,6 +20,18 @@ import { api } from '@/lib/api'
|
||||
|
||||
import type { PerformanceMetricsData, PerfSummaryAllData } from './types'
|
||||
|
||||
export async function getDashboardPerfMetricsSummary(
|
||||
hours = 24
|
||||
): Promise<PerfSummaryAllData> {
|
||||
const res = await api.get<PerfSummaryAllData>(
|
||||
'/api/data/perf-metrics/summary',
|
||||
{
|
||||
params: { hours },
|
||||
}
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function getPerfMetricsSummary(
|
||||
hours = 24,
|
||||
recentModels?: string[]
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
waitFor,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import i18next from 'i18next'
|
||||
import { useState } from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
@@ -41,15 +42,17 @@ import {
|
||||
} from '@/stores/system-config-store'
|
||||
|
||||
import { adjustSyncPrice } from '../models/upstream-price-adjustment'
|
||||
import { SyncPriceCell } from '../models/upstream-price-cells'
|
||||
import { UpstreamRatioSync } from '../models/upstream-ratio-sync'
|
||||
import {
|
||||
getSyncExpressionPricing,
|
||||
getSyncPriceLines,
|
||||
type PricingSourceSelections,
|
||||
} from '../models/upstream-ratio-sync-helpers'
|
||||
import { UpstreamRatioSyncTable } from '../models/upstream-ratio-sync-table'
|
||||
import type { PricingSyncModels } from '../types'
|
||||
|
||||
const expression = 'tier("base", p * 2 + c * 8 + cr * 0)'
|
||||
const expression = 'tier("base", p * 2 + cr * 0 + c * 8)'
|
||||
const differences = {
|
||||
m: {
|
||||
model_ratio: {
|
||||
@@ -179,7 +182,7 @@ describe('pricing synchronization', () => {
|
||||
|
||||
it('shows every parsed tier and falls back to the full expression when pricing cannot be parsed safely', () => {
|
||||
const tiered =
|
||||
'len <= 128000 ? tier("base", p * 2 + c * 8 + cr * 0.2) : tier("long", p * 4 + c * 12 + cr * 0.4)'
|
||||
'len <= 272000 ? tier("0_272k", p * 2 + cr * 0.2 + cc * 2.5 + cc12h * 5 + c * 12) : tier("272k_plus", p * 4 + cr * 0.4 + cc * 5 + cc12h * 10 + c * 18)'
|
||||
const custom = 'tier("custom", p * 2 + c * 8) * max(1, param("factor"))'
|
||||
render(
|
||||
<TableFixture
|
||||
@@ -200,12 +203,80 @@ describe('pricing synchronization', () => {
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByText(tiered)).not.toBeInTheDocument()
|
||||
expect(screen.getByText(/128,000/)).toBeVisible()
|
||||
expect(screen.getByText('$0.2')).toBeVisible()
|
||||
expect(screen.getByText('$0.4')).toBeVisible()
|
||||
expect(screen.getByText('Full input length <= 272,000')).toBeVisible()
|
||||
expect(screen.getByText('272k_plus')).toBeVisible()
|
||||
expect(screen.getAllByText('Cache Write (12h)')).toHaveLength(2)
|
||||
expect(
|
||||
screen.getAllByRole('definition').map((cell) => cell.textContent)
|
||||
).toEqual([
|
||||
'$2',
|
||||
'$12',
|
||||
'$0.2',
|
||||
'$2.5',
|
||||
'$5',
|
||||
'$4',
|
||||
'$18',
|
||||
'$0.4',
|
||||
'$5',
|
||||
'$10',
|
||||
])
|
||||
expect(screen.getByText(custom)).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows an explicit zero price only in the tier that defines it', () => {
|
||||
const parsed = getSyncExpressionPricing(
|
||||
'len <= 100 ? tier("short", p * 2 + c * 8 + cr * 0) : tier("long", p * 4 + c * 12)',
|
||||
(key) => key
|
||||
)
|
||||
expect(
|
||||
parsed?.tiers.map((tier) =>
|
||||
tier.lines.filter((line) => line.label === 'Cache Read')
|
||||
)
|
||||
).toEqual([[{ label: 'Cache Read', value: '$0' }], []])
|
||||
})
|
||||
|
||||
it('updates the tier threshold when the interface language changes', async () => {
|
||||
const billingExpr =
|
||||
'len <= 272000 ? tier("short", p * 1) : tier("long", p * 2)'
|
||||
render(
|
||||
<SyncPriceCell
|
||||
values={{ billing_mode: 'tiered_expr', billing_expr: billingExpr }}
|
||||
/>
|
||||
)
|
||||
const thresholds = {
|
||||
en: '272,000',
|
||||
zhCN: '272,000',
|
||||
zhTW: '272,000',
|
||||
fr: '272\u202f000',
|
||||
ja: '272,000',
|
||||
ru: '272\u00a0000',
|
||||
vi: '272.000',
|
||||
'invalid locale': (272000).toLocaleString(),
|
||||
}
|
||||
try {
|
||||
for (const [language, threshold] of Object.entries(thresholds)) {
|
||||
await act(() => i18next.changeLanguage(language))
|
||||
expect(screen.getByText(/^Full input length/).textContent).toBe(
|
||||
`Full input length <= ${threshold}`
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
await act(() => i18next.changeLanguage('en'))
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
'tier("invalid", p * 1e309 + c * 8)',
|
||||
'tier("base", p * 2) * (header("speed") == "fast" ? 1e309 : 1)',
|
||||
'len <= 100 ? tier("token", p * 2) : tier("request", fixed(0.1))',
|
||||
'tier("base", p * 2 + c * 8) * image_count',
|
||||
])(
|
||||
'keeps the source when it cannot be quoted per million tokens: %s',
|
||||
(source) => {
|
||||
expect(getSyncExpressionPricing(source, (key) => key)).toBeNull()
|
||||
}
|
||||
)
|
||||
|
||||
it('shows a mobile comparison list and preserves source-wide selection', async () => {
|
||||
const original = window.matchMedia
|
||||
vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
|
||||
@@ -1180,15 +1251,13 @@ it('disables both batch shortcuts when the configured exchange rate becomes inva
|
||||
})
|
||||
)
|
||||
await act(async () =>
|
||||
useSystemConfigStore
|
||||
.getState()
|
||||
.setConfig({
|
||||
currency: {
|
||||
...DEFAULT_CURRENCY_CONFIG,
|
||||
quotaDisplayType: 'CNY',
|
||||
usdExchangeRate: 0,
|
||||
},
|
||||
})
|
||||
useSystemConfigStore.getState().setConfig({
|
||||
currency: {
|
||||
...DEFAULT_CURRENCY_CONFIG,
|
||||
quotaDisplayType: 'CNY',
|
||||
usdExchangeRate: 0,
|
||||
},
|
||||
})
|
||||
)
|
||||
expect(
|
||||
screen.getByRole('button', { name: /Multiply by exchange rate/ })
|
||||
|
||||
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import i18next from 'i18next'
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
import {
|
||||
@@ -25,9 +26,12 @@ import {
|
||||
} from '@/features/model-pricing/currency'
|
||||
import {
|
||||
BILLING_PRICING_VARS,
|
||||
parseTiersFromExpr,
|
||||
splitBillingExprAndRequestRules,
|
||||
} from '@/features/pricing/lib/billing-expr'
|
||||
import { tryParseVisualConfig } from '@/features/pricing/lib/tier-expr'
|
||||
import { formatBillingCondition } from '@/features/pricing/lib/billing-expression/condition-display'
|
||||
import { compileBillingExpression } from '@/features/pricing/lib/billing-expression/parser'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
|
||||
import type { PricingSyncValues } from '../types'
|
||||
import {
|
||||
@@ -163,47 +167,46 @@ export function getSyncExpressionPricing(
|
||||
t: (key: string) => string,
|
||||
currency = USD_PRICING_CURRENCY
|
||||
) {
|
||||
if (compileBillingExpression(expression).status !== 'ready') return null
|
||||
const { billingExpr, requestRuleExpr } =
|
||||
splitBillingExprAndRequestRules(expression)
|
||||
const config = tryParseVisualConfig(billingExpr)
|
||||
if (!config) return null
|
||||
// Do not turn malformed or overflowing upstream numbers into free prices.
|
||||
const body = billingExpr.replaceAll(/"(?:\\.|[^"\\])*"/g, '')
|
||||
for (const match of body.matchAll(/\*\s*([+\-\d.eE]+)/g)) {
|
||||
if (!Number.isFinite(Number(match[1])) || Number(match[1]) < 0) return null
|
||||
const tiers = parseTiersFromExpr(billingExpr)
|
||||
// Sync metrics quote prices per million tokens, including the currency preview.
|
||||
if (
|
||||
tiers.length === 0 ||
|
||||
tiers.some((tier) => tier.billingUnit === 'request' || tier.imageCount)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const fields = BILLING_PRICING_VARS.filter(
|
||||
(field) =>
|
||||
field.tierField && new RegExp(`\\b${field.key}\\s*\\*`).test(body)
|
||||
)
|
||||
const conditionLabels = {
|
||||
p: t('Input tokens'),
|
||||
c: t('Output tokens'),
|
||||
len: t('Length'),
|
||||
len: t('Full input length'),
|
||||
}
|
||||
const locale = toIntlLocale(i18next.resolvedLanguage || i18next.language)
|
||||
return {
|
||||
requestRuleExpr,
|
||||
tiers: config.tiers.map((tier) => ({
|
||||
tiers: tiers.map((tier) => ({
|
||||
label: tier.label,
|
||||
condition: tier.conditions
|
||||
.map(
|
||||
(condition) =>
|
||||
`${conditionLabels[condition.var]} ${condition.op} ${Number(condition.value).toLocaleString()}`
|
||||
)
|
||||
.join(' ∧ '),
|
||||
lines: fields.flatMap((field) =>
|
||||
field.tierField
|
||||
? [
|
||||
{
|
||||
label: t(field.shortLabel),
|
||||
value: formatSyncPriceAmount(
|
||||
Number(tier[field.tierField]),
|
||||
currency
|
||||
),
|
||||
},
|
||||
]
|
||||
: []
|
||||
),
|
||||
condition: tier.conditionText
|
||||
? (formatBillingCondition(tier.conditionText, t, locale) ??
|
||||
t(tier.conditionText))
|
||||
: tier.conditions
|
||||
.map(
|
||||
(condition) =>
|
||||
`${conditionLabels[condition.var]} ${condition.op} ${condition.value.toLocaleString(locale)}`
|
||||
)
|
||||
.join(' ∧ '),
|
||||
lines: BILLING_PRICING_VARS.flatMap((variable) => {
|
||||
const price = variable.field && tier[variable.field]
|
||||
if (typeof price !== 'number') return []
|
||||
return [
|
||||
{
|
||||
label: t(variable.shortLabel),
|
||||
value: formatSyncPriceAmount(price, currency),
|
||||
},
|
||||
]
|
||||
}),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
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 { createHash, webcrypto } from 'node:crypto'
|
||||
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, test, vi } from 'vitest'
|
||||
|
||||
import { MarketplacePanel } from '../components/marketplace-panel'
|
||||
import { DEFAULT_MARKETPLACE_INDEX_URL } from '../lib/marketplace'
|
||||
import type {
|
||||
MarketplaceIndex,
|
||||
MarketplacePlugin,
|
||||
TaskPluginListItem,
|
||||
} from '../types'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listMarketplaceSources: vi.fn(),
|
||||
listTaskPlugins: vi.fn(),
|
||||
getTaskPlugin: vi.fn(),
|
||||
installMarketplacePlugin: vi.fn(),
|
||||
activateTaskPlugin: vi.fn(),
|
||||
}))
|
||||
vi.mock('../api', async (original) => ({
|
||||
...(await original<typeof import('../api')>()),
|
||||
...api,
|
||||
}))
|
||||
|
||||
const clients: QueryClient[] = []
|
||||
const source = { name: 'Official', index_url: DEFAULT_MARKETPLACE_INDEX_URL }
|
||||
const code = (key: string, version: string) => `// ${key} ${version}`
|
||||
const hash = (value: string) => createHash('sha256').update(value).digest('hex')
|
||||
|
||||
function openMarket(keys: string[]) {
|
||||
const plugins: MarketplacePlugin[] = keys.map((key) => ({
|
||||
key,
|
||||
name: key,
|
||||
latest: '2',
|
||||
task: key !== 'provider',
|
||||
provider: key === 'provider',
|
||||
versions: ['1', '2'].map((version) => ({
|
||||
version,
|
||||
path: `${key}/${version}.js`,
|
||||
sha256: hash(code(key, version)),
|
||||
})),
|
||||
}))
|
||||
const index: MarketplaceIndex = {
|
||||
name: 'Official catalog',
|
||||
indexVersion: 1,
|
||||
plugins,
|
||||
}
|
||||
const installed: TaskPluginListItem[] = keys.map((key) => ({
|
||||
meta: {
|
||||
key,
|
||||
name: key,
|
||||
version: '1',
|
||||
apiVersion: 1,
|
||||
author: { name: 'test' },
|
||||
models: null,
|
||||
fetchMode: 'per_task',
|
||||
},
|
||||
enabled: key !== 'disabled',
|
||||
active: true,
|
||||
source_hash: hash(code(key, '1')),
|
||||
source: 'override',
|
||||
runtime_status: 'registered',
|
||||
remark: '',
|
||||
in_flight_count: 0,
|
||||
channel_count: 0,
|
||||
}))
|
||||
api.listMarketplaceSources.mockResolvedValue([source])
|
||||
api.listTaskPlugins.mockImplementation(async () => installed)
|
||||
api.getTaskPlugin.mockImplementation(async (key: string) => ({
|
||||
source: code(key, '1'),
|
||||
}))
|
||||
const normalFetch = async (input: RequestInfo | URL) => {
|
||||
if (String(input) === source.index_url) return Response.json(index)
|
||||
const file = plugins.find((p) => String(input).endsWith(`/${p.key}/2.js`))
|
||||
return file
|
||||
? new Response(code(file.key, '2'))
|
||||
: new Response('', { status: 404 })
|
||||
}
|
||||
const fetchMock = vi.fn(normalFetch)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
vi.stubGlobal('crypto', webcrypto)
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
clients.push(client)
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MarketplacePanel kind='task' onKindChange={() => undefined} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return { user: userEvent.setup(), fetchMock, normalFetch, index, installed }
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const client of clients) client.clear()
|
||||
clients.length = 0
|
||||
vi.unstubAllGlobals()
|
||||
vi.resetAllMocks()
|
||||
})
|
||||
|
||||
test('opens one review for the whole source, including other plugin kinds, and lets the administrator read a diff without installing', async () => {
|
||||
const { user, fetchMock } = openMarket(['alpha', 'disabled', 'provider'])
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'Update all (2)' })
|
||||
)
|
||||
const bulk = screen.getByRole('dialog', { name: 'Update installed plugins' })
|
||||
expect(
|
||||
within(bulk).getByRole('button', { name: 'Review provider' })
|
||||
).toBeVisible()
|
||||
expect(fetchMock.mock.calls.every(([url]) => url === source.index_url)).toBe(
|
||||
true
|
||||
)
|
||||
const skips = within(bulk).getByRole('button', { name: 'Skipped (1)' })
|
||||
await user.click(skips)
|
||||
expect(skips).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(within(bulk).getByText('Plugin is disabled')).toBeVisible()
|
||||
await user.click(within(bulk).getByRole('button', { name: 'Review alpha' }))
|
||||
const review = screen.getByRole('dialog', { name: 'alpha' })
|
||||
expect(
|
||||
within(review).getByRole('tab', { name: 'Changelog' })
|
||||
).toHaveAttribute('aria-selected', 'true')
|
||||
expect(within(review).queryByRole('combobox')).toBeNull()
|
||||
await waitFor(() =>
|
||||
expect(review.contains(document.activeElement)).toBe(true)
|
||||
)
|
||||
expect(
|
||||
within(review).queryByRole('button', { name: 'Install and enable' })
|
||||
).toBeNull()
|
||||
await user.click(
|
||||
within(review).getByRole('tab', { name: 'Version differences' })
|
||||
)
|
||||
expect(await within(review).findByText('+ // alpha 2')).toBeVisible()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
within(bulk).getByRole('button', { name: 'Review alpha' })
|
||||
).toHaveFocus()
|
||||
)
|
||||
await user.click(within(bulk).getByRole('button', { name: 'Cancel' }))
|
||||
expect(api.installMarketplacePlugin).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('continues after integrity and activation failures and reports the installed versions and skipped rows', async () => {
|
||||
const { user, fetchMock, normalFetch } = openMarket([
|
||||
'alpha',
|
||||
'beta',
|
||||
'disabled',
|
||||
'gamma',
|
||||
])
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'Update all (3)' })
|
||||
)
|
||||
const bulk = screen.getByRole('dialog', { name: 'Update installed plugins' })
|
||||
let finish!: (value: Response) => void
|
||||
const pending = new Promise<Response>((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
fetchMock.mockImplementation(async (url) =>
|
||||
String(url).endsWith('/alpha/2.js') ? pending : normalFetch(url)
|
||||
)
|
||||
api.installMarketplacePlugin.mockImplementation(
|
||||
async (request: { source: string }) => {
|
||||
const key = request.source === code('beta', '2') ? 'beta' : 'gamma'
|
||||
return {
|
||||
meta: { key, version: '2' },
|
||||
plugin: { active: key === 'gamma' },
|
||||
}
|
||||
}
|
||||
)
|
||||
api.activateTaskPlugin.mockRejectedValue(new Error('route conflict'))
|
||||
await user.click(within(bulk).getByRole('button', { name: 'Update all (3)' }))
|
||||
expect(await within(bulk).findByRole('progressbar')).toBeVisible()
|
||||
expect(within(bulk).getAllByText('Queued').length).toBeGreaterThan(0)
|
||||
expect(
|
||||
within(bulk).getByRole('button', { name: 'Updating...' })
|
||||
).toBeDisabled()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(bulk).toBeVisible()
|
||||
finish(new Response('wrong bytes'))
|
||||
expect(
|
||||
await screen.findByText('1 updated · 2 failed · 1 skipped')
|
||||
).toBeVisible()
|
||||
expect(within(bulk).getByText('Integrity check failed')).toBeVisible()
|
||||
expect(within(bulk).getByText('Updated successfully')).toBeVisible()
|
||||
expect(
|
||||
within(bulk).getByText('Uploaded, but activation failed.')
|
||||
).toBeVisible()
|
||||
expect(within(bulk).getByText('route conflict')).toBeVisible()
|
||||
expect(
|
||||
api.installMarketplacePlugin.mock.calls.map(([request]) => [
|
||||
request.source,
|
||||
request.sourceSha256,
|
||||
request.marketplaceIndexUrl,
|
||||
])
|
||||
).toEqual(
|
||||
['beta', 'gamma'].map((key) => [
|
||||
code(key, '2'),
|
||||
hash(code(key, '2')),
|
||||
source.index_url,
|
||||
])
|
||||
)
|
||||
expect(api.activateTaskPlugin.mock.calls).toEqual([['beta', '2']])
|
||||
})
|
||||
|
||||
test('rechecks disabled plugins, republished targets and withdrawals before sending any uploads', async () => {
|
||||
const { user, index, installed } = openMarket(['alpha', 'beta', 'gamma'])
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'Update all (3)' })
|
||||
)
|
||||
const bulk = screen.getByRole('dialog', { name: 'Update installed plugins' })
|
||||
installed[0] = { ...installed[0], enabled: false }
|
||||
index.plugins[1].versions[1].sha256 = hash('another build')
|
||||
index.revoked = [{ sha256: hash(code('gamma', '2')) }]
|
||||
await user.click(within(bulk).getByRole('button', { name: 'Update all (3)' }))
|
||||
expect(
|
||||
await screen.findByText('0 updated · 0 failed · 3 skipped')
|
||||
).toBeVisible()
|
||||
expect(within(bulk).getByText('Plugin is disabled')).toBeVisible()
|
||||
expect(within(bulk).getByText('This release was withdrawn.')).toBeVisible()
|
||||
expect(
|
||||
within(bulk).getByText(
|
||||
'The installed plugin or the marketplace release changed after review.'
|
||||
)
|
||||
).toBeVisible()
|
||||
expect(api.installMarketplacePlugin).not.toHaveBeenCalled()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
})
|
||||
|
||||
test('explains skipped plugins without offering an empty batch', async () => {
|
||||
const { user } = openMarket(['disabled'])
|
||||
await user.click(await screen.findByRole('button', { name: 'Skipped (1)' }))
|
||||
const bulk = screen.getByRole('dialog', { name: 'Update installed plugins' })
|
||||
expect(within(bulk).getByText('Plugin is disabled')).toBeVisible()
|
||||
expect(within(bulk).queryByRole('button', { name: /Update all/ })).toBeNull()
|
||||
expect(api.installMarketplacePlugin).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('keeps the batch available to retry when the source cannot be rechecked', async () => {
|
||||
const { user, fetchMock } = openMarket(['alpha'])
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'Update all (1)' })
|
||||
)
|
||||
const bulk = screen.getByRole('dialog', { name: 'Update installed plugins' })
|
||||
fetchMock.mockResolvedValueOnce(new Response('', { status: 503 }))
|
||||
await user.click(within(bulk).getByRole('button', { name: 'Update all (1)' }))
|
||||
expect(await within(bulk).findByRole('alert')).toHaveTextContent('503')
|
||||
expect(api.installMarketplacePlugin).not.toHaveBeenCalled()
|
||||
api.installMarketplacePlugin.mockResolvedValue({ plugin: { active: true } })
|
||||
await user.click(within(bulk).getByRole('button', { name: 'Update all (1)' }))
|
||||
expect(
|
||||
await within(bulk).findByText('1 updated · 0 failed · 0 skipped')
|
||||
).toBeVisible()
|
||||
expect(api.installMarketplacePlugin).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
deriveInstallState,
|
||||
findMarketplaceVersion,
|
||||
findRevokedEntry,
|
||||
getMarketplaceUpdates,
|
||||
GITHUB_MARKETPLACE_INDEX_URL,
|
||||
indexHasIntegrityHashes,
|
||||
isStaleFactoryOverride,
|
||||
@@ -516,6 +517,79 @@ describe('install state derivation', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('bulk update eligibility', () => {
|
||||
const oldHash = 'a'.repeat(64)
|
||||
const newHash = 'b'.repeat(64)
|
||||
const plugin = marketplacePlugin({
|
||||
versions: [
|
||||
{ version: '1.0.0', path: 'old.js', sha256: oldHash },
|
||||
{ version: '1.2.0', path: 'new.js', sha256: newHash },
|
||||
],
|
||||
})
|
||||
const index: MarketplaceIndex = {
|
||||
indexVersion: 1,
|
||||
name: 'Test',
|
||||
plugins: [plugin],
|
||||
}
|
||||
const local = installedPlugin('doubao', '1.0.0', {
|
||||
source_hash: oldHash.toUpperCase(),
|
||||
})
|
||||
|
||||
test('includes each eligible key once and leaves current, unlisted and uninstalled plugins alone', () => {
|
||||
const updates = getMarketplaceUpdates(
|
||||
{ ...index, plugins: [plugin, plugin] },
|
||||
[local]
|
||||
)
|
||||
assert.deepEqual(
|
||||
updates.map((item) => [item.plugin.key, item.target.version, item.skip]),
|
||||
[['doubao', '1.2.0', undefined]]
|
||||
)
|
||||
for (const installed of [
|
||||
[],
|
||||
[installedPlugin('doubao', '1.2.0')],
|
||||
[installedPlugin('doubao', 'local')],
|
||||
]) {
|
||||
assert.deepEqual(getMarketplaceUpdates(index, installed), [])
|
||||
}
|
||||
})
|
||||
test('explains why a known version needs individual handling', () => {
|
||||
assert.equal(
|
||||
getMarketplaceUpdates(index, [{ ...local, enabled: false }])[0].skip,
|
||||
'disabled'
|
||||
)
|
||||
assert.equal(
|
||||
getMarketplaceUpdates(index, [
|
||||
{ ...local, source_hash: 'c'.repeat(64) },
|
||||
])[0].skip,
|
||||
'modified'
|
||||
)
|
||||
for (const hash of [oldHash, newHash]) {
|
||||
assert.equal(
|
||||
getMarketplaceUpdates({ ...index, revoked: [{ sha256: hash }] }, [
|
||||
local,
|
||||
])[0].skip,
|
||||
'revoked'
|
||||
)
|
||||
}
|
||||
for (const entry of plugin.versions) {
|
||||
const versions = plugin.versions.map((v) =>
|
||||
v.version === entry.version ? { ...v, sha256: 'invalid' } : v
|
||||
)
|
||||
assert.equal(
|
||||
getMarketplaceUpdates(
|
||||
{ ...index, plugins: [{ ...plugin, versions }] },
|
||||
[local]
|
||||
)[0].skip,
|
||||
'unverified'
|
||||
)
|
||||
}
|
||||
assert.equal(
|
||||
getMarketplaceUpdates(index, [{ ...local, source_hash: '' }])[0].skip,
|
||||
'unverified'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('marketplace built-in version', () => {
|
||||
test('factory-served built-in version is the installed meta version', () => {
|
||||
assert.equal(
|
||||
|
||||
@@ -28,26 +28,20 @@ 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,
|
||||
getTaskPlugin,
|
||||
installMarketplacePlugin,
|
||||
} from '../api'
|
||||
import { getTaskPlugin } from '../api'
|
||||
import {
|
||||
findMarketplaceVersion,
|
||||
marketplaceSourceKind,
|
||||
resolvePluginSourceUrl,
|
||||
type InstallState,
|
||||
} from '../lib/marketplace'
|
||||
import { toastPluginChange } from '../lib/plugin-change-toast'
|
||||
import { fetchPluginIconDataUri } from '../lib/plugin-icon-file'
|
||||
import {
|
||||
computeSourceSha256,
|
||||
fetchPluginSourceText,
|
||||
PluginSourceFetchError,
|
||||
} from '../lib/plugin-url'
|
||||
downloadMarketplaceRelease,
|
||||
installMarketplaceRelease,
|
||||
invalidateMarketplaceInstalls,
|
||||
marketplaceErrorMessage,
|
||||
} from '../lib/marketplace-install'
|
||||
import { toastPluginChange } from '../lib/plugin-change-toast'
|
||||
import type { MarketplacePlugin, MarketplaceSource } from '../types'
|
||||
import { CommunityPluginReach } from './community-plugin-reach'
|
||||
import { JavaScriptViewer } from './javascript-viewer'
|
||||
@@ -77,6 +71,7 @@ export type MarketplaceInstallTarget = {
|
||||
|
||||
type MarketplaceInstallDialogProps = {
|
||||
target: MarketplaceInstallTarget | null
|
||||
reviewOnly?: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
@@ -86,6 +81,7 @@ export function MarketplaceInstallDialog(props: MarketplaceInstallDialogProps) {
|
||||
<MarketplaceInstallContent
|
||||
key={`${props.target.source.index_url}-${props.target.plugin.key}-${props.target.version}`}
|
||||
target={props.target}
|
||||
reviewOnly={props.reviewOnly}
|
||||
onOpenChange={props.onOpenChange}
|
||||
/>
|
||||
)
|
||||
@@ -101,7 +97,9 @@ function MarketplaceInstallContent(
|
||||
const pluginKey = target.plugin.key
|
||||
const entry = findMarketplaceVersion(target.plugin, selectedVersion)
|
||||
const hasInstalledPlugin = target.installState.status !== 'not_installed'
|
||||
const [reviewTab, setReviewTab] = useState('details')
|
||||
const [reviewTab, setReviewTab] = useState(
|
||||
props.reviewOnly ? 'changelog' : 'details'
|
||||
)
|
||||
const sourceKind = marketplaceSourceKind(target.source.index_url)
|
||||
|
||||
const sourceQuery = useQuery({
|
||||
@@ -118,31 +116,7 @@ function MarketplaceInstallContent(
|
||||
meta: { errorToast: false },
|
||||
queryFn: async () => {
|
||||
if (!entry) throw new Error('missing marketplace entry')
|
||||
const url = resolvePluginSourceUrl(target.source.index_url, entry.path)
|
||||
if (!url) {
|
||||
throw new Error(
|
||||
t('The source gives an invalid address for this plugin.')
|
||||
)
|
||||
}
|
||||
const text = await fetchPluginSourceText(url)
|
||||
// Computed for display only. The upload request carries the index hash and
|
||||
// the server re-hashes what it received, so a tampered browser cannot pass
|
||||
// a mismatched source off as verified.
|
||||
const digest = await computeSourceSha256(text)
|
||||
// The logo is cosmetic: a missing or malformed icon file must never block
|
||||
// the install, so a failed fetch simply yields no icon.
|
||||
const iconUrl = target.plugin.iconFile
|
||||
? resolvePluginSourceUrl(
|
||||
target.source.index_url,
|
||||
target.plugin.iconFile.path
|
||||
)
|
||||
: null
|
||||
const icon = iconUrl
|
||||
? await fetchPluginIconDataUri(iconUrl, {
|
||||
sha256: target.plugin.iconFile?.sha256,
|
||||
})
|
||||
: null
|
||||
return { url, text, digest, icon }
|
||||
return downloadMarketplaceRelease(target.source, target.plugin, entry)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -164,32 +138,9 @@ function MarketplaceInstallContent(
|
||||
) {
|
||||
throw new Error('source not fetched')
|
||||
}
|
||||
const detail = await installMarketplacePlugin({
|
||||
source: sourceQuery.data.text,
|
||||
sourceSha256: entry.sha256,
|
||||
remark: `${target.source.name} v${selectedVersion}`,
|
||||
icon: sourceQuery.data.icon ?? undefined,
|
||||
marketplaceIndexUrl: target.source.index_url,
|
||||
})
|
||||
if (detail.plugin && !detail.plugin.active) {
|
||||
const notice = await activateTaskPlugin(
|
||||
detail.meta.key,
|
||||
detail.meta.version
|
||||
)
|
||||
return { ...detail, pricing_issues: notice?.pricing_issues ?? [] }
|
||||
}
|
||||
return detail
|
||||
},
|
||||
onSettled: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['task-plugins'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['task-plugin', pluginKey] })
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['task-plugin-versions', pluginKey],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: MODEL_PRICING_ISSUES_QUERY_KEY,
|
||||
})
|
||||
return installMarketplaceRelease(target.source, entry, sourceQuery.data)
|
||||
},
|
||||
onSettled: () => invalidateMarketplaceInstalls(queryClient, [pluginKey]),
|
||||
onSuccess: (detail) => {
|
||||
toastPluginChange(
|
||||
t('Installed {{name}} v{{version}}', {
|
||||
@@ -202,16 +153,9 @@ function MarketplaceInstallContent(
|
||||
},
|
||||
})
|
||||
|
||||
const fetchError = sourceQuery.error
|
||||
let fetchErrorMessage = ''
|
||||
if (fetchError instanceof PluginSourceFetchError) {
|
||||
fetchErrorMessage =
|
||||
fetchError.reason === 'too_large'
|
||||
? t('Plugin source exceeds the 8 MiB limit.')
|
||||
: t('Could not download the plugin code. Try again later.')
|
||||
} else if (fetchError) {
|
||||
fetchErrorMessage = fetchError.message
|
||||
}
|
||||
const fetchErrorMessage = sourceQuery.error
|
||||
? marketplaceErrorMessage(sourceQuery.error)
|
||||
: ''
|
||||
|
||||
const digestMismatch = Boolean(
|
||||
entry?.sha256 &&
|
||||
@@ -248,7 +192,7 @@ function MarketplaceInstallContent(
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
initialFocus={false}
|
||||
initialFocus={props.reviewOnly ? undefined : false}
|
||||
onOpenChange={props.onOpenChange}
|
||||
contentClassName='sm:max-w-3xl'
|
||||
headerClassName='gap-1.5 pr-6'
|
||||
@@ -264,7 +208,9 @@ function MarketplaceInstallContent(
|
||||
size={36}
|
||||
/>
|
||||
<span className='min-w-0 text-lg font-semibold break-words'>
|
||||
{t('Install {{name}}', { name: target.plugin.name })}
|
||||
{props.reviewOnly
|
||||
? target.plugin.name
|
||||
: t('Install {{name}}', { name: target.plugin.name })}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
@@ -275,68 +221,72 @@ function MarketplaceInstallContent(
|
||||
footer={
|
||||
<>
|
||||
<Button variant='outline' onClick={() => props.onOpenChange(false)}>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={
|
||||
!entry ||
|
||||
!sourceQuery.data ||
|
||||
sourceQuery.isFetching ||
|
||||
sourceQuery.isError ||
|
||||
digestMismatch ||
|
||||
installMutation.isPending
|
||||
}
|
||||
onClick={() => installMutation.mutate()}
|
||||
>
|
||||
<Download />
|
||||
{confirmLabel}
|
||||
{props.reviewOnly ? t('Back') : t('Cancel')}
|
||||
</Button>
|
||||
{!props.reviewOnly && (
|
||||
<Button
|
||||
disabled={
|
||||
!entry ||
|
||||
!sourceQuery.data ||
|
||||
sourceQuery.isFetching ||
|
||||
sourceQuery.isError ||
|
||||
digestMismatch ||
|
||||
installMutation.isPending
|
||||
}
|
||||
onClick={() => installMutation.mutate()}
|
||||
>
|
||||
<Download />
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<MarketplaceAuthorLine plugin={target.plugin} />
|
||||
<div className='space-y-2'>
|
||||
<Combobox
|
||||
aria-label={t('Select version')}
|
||||
value={selectedVersion}
|
||||
disabled={
|
||||
target.plugin.versions.length <= 1 || installMutation.isPending
|
||||
}
|
||||
options={target.plugin.versions.map((version) => {
|
||||
const labels = [version.version]
|
||||
if (version.version === target.plugin.latest) {
|
||||
labels.push(t('Latest version'))
|
||||
{!props.reviewOnly && (
|
||||
<Combobox
|
||||
aria-label={t('Select version')}
|
||||
value={selectedVersion}
|
||||
disabled={
|
||||
target.plugin.versions.length <= 1 || installMutation.isPending
|
||||
}
|
||||
if (
|
||||
target.installState.status !== 'not_installed' &&
|
||||
version.version === target.installState.installedVersion
|
||||
) {
|
||||
labels.push(t('Active version'))
|
||||
}
|
||||
return { value: version.version, label: labels.join(' · ') }
|
||||
})}
|
||||
onValueChange={(version) => {
|
||||
if (
|
||||
!version ||
|
||||
version === selectedVersion ||
|
||||
installMutation.isPending
|
||||
) {
|
||||
return
|
||||
}
|
||||
installMutation.reset()
|
||||
setSelectedVersion(version)
|
||||
if (
|
||||
target.installState.status !== 'not_installed' &&
|
||||
reviewTab !== 'changelog'
|
||||
) {
|
||||
setReviewTab(
|
||||
version === target.installState.installedVersion
|
||||
? 'details'
|
||||
: 'diff'
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
options={target.plugin.versions.map((version) => {
|
||||
const labels = [version.version]
|
||||
if (version.version === target.plugin.latest) {
|
||||
labels.push(t('Latest version'))
|
||||
}
|
||||
if (
|
||||
target.installState.status !== 'not_installed' &&
|
||||
version.version === target.installState.installedVersion
|
||||
) {
|
||||
labels.push(t('Active version'))
|
||||
}
|
||||
return { value: version.version, label: labels.join(' · ') }
|
||||
})}
|
||||
onValueChange={(version) => {
|
||||
if (
|
||||
!version ||
|
||||
version === selectedVersion ||
|
||||
installMutation.isPending
|
||||
) {
|
||||
return
|
||||
}
|
||||
installMutation.reset()
|
||||
setSelectedVersion(version)
|
||||
if (
|
||||
target.installState.status !== 'not_installed' &&
|
||||
reviewTab !== 'changelog'
|
||||
) {
|
||||
setReviewTab(
|
||||
version === target.installState.installedVersion
|
||||
? 'details'
|
||||
: 'diff'
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{target.installState.status !== 'not_installed' && (
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('Current v{{from}} → install v{{to}}', {
|
||||
|
||||
@@ -17,7 +17,7 @@ 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 { RefreshCw, TriangleAlert } from 'lucide-react'
|
||||
import { ListRestart, RefreshCw, TriangleAlert } from 'lucide-react'
|
||||
import { useId, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -32,12 +32,15 @@ import {
|
||||
} from '@/components/ui/empty'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
import { formatNumber } from '@/lib/format'
|
||||
|
||||
import { listMarketplaceSources, listTaskPlugins } from '../api'
|
||||
import {
|
||||
COMMUNITY_MARKETPLACE_INDEX_URL,
|
||||
deriveInstallState,
|
||||
fetchMarketplaceIndex,
|
||||
getMarketplaceUpdates,
|
||||
indexHasIntegrityHashes,
|
||||
marketplaceSourceKind,
|
||||
} from '../lib/marketplace'
|
||||
@@ -59,6 +62,10 @@ import {
|
||||
import { MarketplacePluginCard } from './marketplace-plugin-card'
|
||||
import { MarketplaceSourceMenu } from './marketplace-source-menu'
|
||||
import { MarketplaceSourcesDialog } from './marketplace-sources-dialog'
|
||||
import {
|
||||
MarketplaceUpdatesDialog,
|
||||
type MarketplaceUpdateSelection,
|
||||
} from './marketplace-updates-dialog'
|
||||
import { PluginCodeLookup, type PluginCodeMatch } from './plugin-code-lookup'
|
||||
import {
|
||||
PluginKindSwitch,
|
||||
@@ -79,13 +86,16 @@ const marketplacePluginParts = (plugin: MarketplacePlugin) =>
|
||||
type MarketplaceGroup = 'official' | 'community'
|
||||
|
||||
export function MarketplacePanel(props: MarketplacePanelProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
|
||||
const [sourcesOpen, setSourcesOpen] = useState(false)
|
||||
const [group, setGroup] = useState<MarketplaceGroup | null>(null)
|
||||
const [selectedSourceUrl, setSelectedSourceUrl] = useState('')
|
||||
const [installTarget, setInstallTarget] =
|
||||
useState<MarketplaceInstallTarget | null>(null)
|
||||
const [codeMatch, setCodeMatch] = useState<PluginCodeMatch | null>(null)
|
||||
const [updateSelection, setUpdateSelection] =
|
||||
useState<MarketplaceUpdateSelection | null>(null)
|
||||
|
||||
const sourcesQuery = useQuery({
|
||||
queryKey: ['task-plugin-marketplace-sources'],
|
||||
@@ -128,6 +138,14 @@ export function MarketplacePanel(props: MarketplacePanelProps) {
|
||||
},
|
||||
})
|
||||
const indexPlugins = indexQuery.data?.plugins
|
||||
const updates = useMemo(
|
||||
() =>
|
||||
indexQuery.data && installedQuery.data
|
||||
? getMarketplaceUpdates(indexQuery.data, installedQuery.data)
|
||||
: [],
|
||||
[indexQuery.data, installedQuery.data]
|
||||
)
|
||||
const updateCount = updates.filter((item) => !item.skip).length
|
||||
const kindCounts = useMemo(
|
||||
() => countPluginKinds((indexPlugins ?? []).map(marketplacePluginParts)),
|
||||
[indexPlugins]
|
||||
@@ -244,7 +262,7 @@ export function MarketplacePanel(props: MarketplacePanelProps) {
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className='flex max-w-full items-center gap-2'>
|
||||
<div className='flex max-w-full flex-wrap items-center gap-2'>
|
||||
<MarketplaceSourceMenu
|
||||
sources={groupSources}
|
||||
selected={selectedSource}
|
||||
@@ -260,6 +278,30 @@ export function MarketplacePanel(props: MarketplacePanelProps) {
|
||||
<RefreshCw />
|
||||
{t('Refresh')}
|
||||
</Button>
|
||||
{updates.length > 0 && (
|
||||
<Button
|
||||
size='sm'
|
||||
variant={updateCount ? 'default' : 'outline'}
|
||||
disabled={
|
||||
indexQuery.isError ||
|
||||
installedQuery.isError ||
|
||||
indexQuery.isFetching ||
|
||||
installedQuery.isFetching
|
||||
}
|
||||
onClick={() =>
|
||||
setUpdateSelection({ source: selectedSource, updates })
|
||||
}
|
||||
>
|
||||
<ListRestart aria-hidden='true' />
|
||||
{updateCount
|
||||
? t('Update all ({{total}})', {
|
||||
total: formatNumber(updateCount, locale),
|
||||
})
|
||||
: t('Skipped ({{total}})', {
|
||||
total: formatNumber(updates.length, locale),
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -293,6 +335,12 @@ export function MarketplacePanel(props: MarketplacePanelProps) {
|
||||
open={sourcesOpen}
|
||||
onOpenChange={setSourcesOpen}
|
||||
/>
|
||||
{updateSelection && (
|
||||
<MarketplaceUpdatesDialog
|
||||
{...updateSelection}
|
||||
onClose={() => setUpdateSelection(null)}
|
||||
/>
|
||||
)}
|
||||
<MarketplaceInstallDialog
|
||||
key={`${installTarget?.plugin.key ?? ''}-${installTarget?.version ?? ''}`}
|
||||
target={installTarget}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
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 { ArrowRight, CheckCircle2, CircleAlert } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
import type { MarketplaceUpdate } from '../lib/marketplace'
|
||||
import type { TaskPluginDetail } from '../types'
|
||||
import { PluginIcon } from './plugin-icon'
|
||||
import { PricingIssueList } from './pricing-issue-list'
|
||||
|
||||
export type UpdateResult =
|
||||
| { status: 'updated'; issues: TaskPluginDetail['pricing_issues'] }
|
||||
| { status: 'failed' | 'activation-failed'; message: string }
|
||||
| {
|
||||
status: 'skipped'
|
||||
reason: NonNullable<MarketplaceUpdate['skip']> | 'changed'
|
||||
}
|
||||
|
||||
export function MarketplaceUpdateRow(props: {
|
||||
item: MarketplaceUpdate
|
||||
result?: UpdateResult
|
||||
current: boolean
|
||||
busy: boolean
|
||||
skipMessage?: string
|
||||
onReview: (item: MarketplaceUpdate) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const item = props.item
|
||||
const key = item.plugin.key
|
||||
const result = props.result
|
||||
let action = (
|
||||
<Button
|
||||
size='sm'
|
||||
variant='ghost'
|
||||
aria-label={t('Review {{name}}', { name: item.plugin.name })}
|
||||
onClick={() => props.onReview(item)}
|
||||
>
|
||||
{t('Review changes')}
|
||||
</Button>
|
||||
)
|
||||
if (result?.status === 'updated') {
|
||||
action = (
|
||||
<span className='text-emerald-700 dark:text-emerald-400'>
|
||||
<CheckCircle2 />
|
||||
{t('Updated successfully')}
|
||||
</span>
|
||||
)
|
||||
} else if (result?.status === 'skipped') {
|
||||
action = <span className='text-muted-foreground'>{t('Skipped')}</span>
|
||||
} else if (result) {
|
||||
action = (
|
||||
<span className='text-destructive'>
|
||||
<CircleAlert />
|
||||
{t('Failed')}
|
||||
</span>
|
||||
)
|
||||
} else if (props.busy) {
|
||||
action = props.current ? (
|
||||
<span>
|
||||
<Spinner aria-hidden='true' />
|
||||
{t('Updating')}
|
||||
</span>
|
||||
) : (
|
||||
<span className='text-muted-foreground'>{t('Queued')}</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<li className='space-y-2 px-3.5 py-3'>
|
||||
<div className='grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 sm:grid-cols-[minmax(0,1fr)_auto_7rem]'>
|
||||
<div className='flex min-w-0 items-center gap-2.5'>
|
||||
<PluginIcon
|
||||
plugin={{
|
||||
...item.plugin,
|
||||
hasIcon: item.installed.has_icon,
|
||||
}}
|
||||
size={28}
|
||||
/>
|
||||
<div className='min-w-0'>
|
||||
<p className='text-sm font-medium break-words'>
|
||||
{item.plugin.name}
|
||||
</p>
|
||||
<p
|
||||
className='text-muted-foreground truncate font-mono text-xs'
|
||||
title={key}
|
||||
>
|
||||
{key}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className='col-start-1 row-start-2 flex flex-wrap items-center gap-1.5 pl-9 font-mono text-xs break-all sm:col-start-2 sm:row-start-1 sm:pl-0'>
|
||||
<span className='text-muted-foreground'>
|
||||
v{item.installed.meta.version}
|
||||
</span>
|
||||
<ArrowRight
|
||||
aria-hidden='true'
|
||||
className='text-muted-foreground size-3'
|
||||
/>
|
||||
<span className='bg-muted rounded px-1.5 py-0.5'>
|
||||
v{item.target.version}
|
||||
</span>
|
||||
</div>
|
||||
<div className='col-start-2 row-start-1 justify-self-end text-xs sm:col-start-3 [&_svg]:size-3.5 [&>span]:inline-flex [&>span]:items-center [&>span]:gap-1.5'>
|
||||
{action}
|
||||
</div>
|
||||
</div>
|
||||
{result?.status === 'skipped' && (
|
||||
<p className='text-muted-foreground text-xs'>{props.skipMessage}</p>
|
||||
)}
|
||||
{(result?.status === 'failed' ||
|
||||
result?.status === 'activation-failed') && (
|
||||
<div className='text-destructive text-xs break-words'>
|
||||
{result.status === 'activation-failed' && (
|
||||
<p className='font-medium'>
|
||||
{t('Uploaded, but activation failed.')}
|
||||
</p>
|
||||
)}
|
||||
<p>{result.message}</p>
|
||||
</div>
|
||||
)}
|
||||
{result?.status === 'updated' &&
|
||||
result.issues &&
|
||||
result.issues.length > 0 && (
|
||||
<div className='text-xs text-amber-700 dark:text-amber-400'>
|
||||
<PricingIssueList issues={result.issues} />
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
/*
|
||||
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 { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ChevronDown,
|
||||
CircleAlert,
|
||||
ListRestart,
|
||||
ShieldAlert,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
import { formatNumber } from '@/lib/format'
|
||||
|
||||
import { listTaskPlugins } from '../api'
|
||||
import {
|
||||
fetchMarketplaceIndex,
|
||||
getMarketplaceUpdates,
|
||||
marketplaceSourceKind,
|
||||
type MarketplaceUpdate,
|
||||
} from '../lib/marketplace'
|
||||
import {
|
||||
downloadMarketplaceRelease,
|
||||
installMarketplaceRelease,
|
||||
invalidateMarketplaceInstalls,
|
||||
MarketplaceActivationError,
|
||||
marketplaceErrorMessage,
|
||||
} from '../lib/marketplace-install'
|
||||
import type { MarketplaceSource } from '../types'
|
||||
import { MarketplaceInstallDialog } from './marketplace-install-dialog'
|
||||
import {
|
||||
MarketplaceUpdateRow,
|
||||
type UpdateResult,
|
||||
} from './marketplace-update-row'
|
||||
|
||||
export type MarketplaceUpdateSelection = {
|
||||
source: MarketplaceSource
|
||||
updates: MarketplaceUpdate[]
|
||||
}
|
||||
|
||||
export function MarketplaceUpdatesDialog(
|
||||
props: MarketplaceUpdateSelection & { onClose: () => void }
|
||||
) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
|
||||
const client = useQueryClient()
|
||||
const [review, setReview] = useState<MarketplaceUpdate | null>(null)
|
||||
const [currentKey, setCurrentKey] = useState('')
|
||||
const [results, setResults] = useState(new Map<string, UpdateResult>())
|
||||
const ready = props.updates.filter((item) => !item.skip)
|
||||
const skipped = props.updates.filter((item) => item.skip)
|
||||
|
||||
const mutation = useMutation({
|
||||
retry: false,
|
||||
meta: { errorToast: false },
|
||||
mutationFn: async () => {
|
||||
// A version may have been withdrawn or disabled while the list was open.
|
||||
// Only apply the versions and hashes the administrator actually reviewed.
|
||||
const [index, installed] = await Promise.all([
|
||||
client.fetchQuery({
|
||||
queryKey: ['task-plugin-marketplace', props.source.index_url],
|
||||
queryFn: () => fetchMarketplaceIndex(props.source.index_url),
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
meta: { errorToast: false },
|
||||
}),
|
||||
client.fetchQuery({
|
||||
queryKey: ['task-plugins'],
|
||||
queryFn: listTaskPlugins,
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
meta: { errorToast: false },
|
||||
}),
|
||||
])
|
||||
const fresh = new Map(
|
||||
getMarketplaceUpdates(index, installed).map((item) => [
|
||||
item.plugin.key,
|
||||
item,
|
||||
])
|
||||
)
|
||||
for (const item of ready) {
|
||||
const key = item.plugin.key
|
||||
const next = fresh.get(key)
|
||||
let result: UpdateResult
|
||||
if (
|
||||
!next ||
|
||||
next.skip ||
|
||||
next.installed.meta.version !== item.installed.meta.version ||
|
||||
next.installed.source_hash.toLowerCase() !==
|
||||
item.installed.source_hash.toLowerCase() ||
|
||||
next.target.version !== item.target.version ||
|
||||
next.target.sha256?.toLowerCase() !==
|
||||
item.target.sha256?.toLowerCase()
|
||||
) {
|
||||
result = { status: 'skipped', reason: next?.skip ?? 'changed' }
|
||||
} else {
|
||||
setCurrentKey(key)
|
||||
try {
|
||||
const download = await downloadMarketplaceRelease(
|
||||
props.source,
|
||||
next.plugin,
|
||||
next.target
|
||||
)
|
||||
const detail = await installMarketplaceRelease(
|
||||
props.source,
|
||||
next.target,
|
||||
download
|
||||
)
|
||||
result = { status: 'updated', issues: detail.pricing_issues }
|
||||
} catch (error) {
|
||||
result = {
|
||||
status:
|
||||
error instanceof MarketplaceActivationError
|
||||
? 'activation-failed'
|
||||
: 'failed',
|
||||
message: marketplaceErrorMessage(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
setResults((previous) => new Map(previous).set(key, result))
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
setCurrentKey('')
|
||||
invalidateMarketplaceInstalls(
|
||||
client,
|
||||
ready.map((item) => item.plugin.key)
|
||||
)
|
||||
},
|
||||
})
|
||||
const busy = mutation.isPending
|
||||
const finished = mutation.isSuccess
|
||||
const outcomes = [...results.values()]
|
||||
const updated = outcomes.filter((item) => item.status === 'updated').length
|
||||
const skippedAfterReview = outcomes.filter(
|
||||
(item) => item.status === 'skipped'
|
||||
).length
|
||||
const skipLabels = {
|
||||
disabled: t('Plugin is disabled'),
|
||||
revoked: t('This release was withdrawn.'),
|
||||
unverified: t('A release has no verifiable SHA-256 hash.'),
|
||||
modified: t('Installed code differs from the published release.'),
|
||||
changed: t(
|
||||
'The installed plugin or the marketplace release changed after review.'
|
||||
),
|
||||
}
|
||||
const sourceKind = marketplaceSourceKind(props.source.index_url)
|
||||
const confirmLabel = t('Update all ({{total}})', {
|
||||
total: formatNumber(ready.length, locale),
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !busy) props.onClose()
|
||||
}}
|
||||
showCloseButton={!busy}
|
||||
title={finished ? t('Update results') : t('Update installed plugins')}
|
||||
description={t('Updates from {{source}}', {
|
||||
source: props.source.name,
|
||||
})}
|
||||
contentClassName='sm:max-w-2xl'
|
||||
bodyClassName='space-y-4'
|
||||
footer={
|
||||
<>
|
||||
<Button variant='outline' onClick={props.onClose} disabled={busy}>
|
||||
{finished || !ready.length ? t('Close') : t('Cancel')}
|
||||
</Button>
|
||||
{!finished && ready.length > 0 && (
|
||||
<Button disabled={busy} onClick={() => mutation.mutate()}>
|
||||
{busy ? (
|
||||
<Spinner aria-hidden='true' />
|
||||
) : (
|
||||
<ListRestart aria-hidden='true' />
|
||||
)}
|
||||
{busy ? t('Updating...') : confirmLabel}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{finished && (
|
||||
<p role='status' className='text-sm font-medium'>
|
||||
{t('{{updated}} updated · {{failed}} failed · {{skipped}} skipped', {
|
||||
updated: formatNumber(updated, locale),
|
||||
failed: formatNumber(
|
||||
outcomes.length - updated - skippedAfterReview,
|
||||
locale
|
||||
),
|
||||
skipped: formatNumber(skipped.length + skippedAfterReview, locale),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{busy && (
|
||||
<Progress
|
||||
value={results.size}
|
||||
max={ready.length}
|
||||
aria-label={t('Updating...')}
|
||||
/>
|
||||
)}
|
||||
{mutation.isError && (
|
||||
<Alert variant='destructive' role='alert'>
|
||||
<CircleAlert />
|
||||
<AlertDescription>
|
||||
{marketplaceErrorMessage(mutation.error)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{ready.length > 0 && (
|
||||
<ul className='divide-y overflow-hidden rounded-lg border'>
|
||||
{ready.map((item) => {
|
||||
const key = item.plugin.key
|
||||
const result = results.get(key)
|
||||
return (
|
||||
<MarketplaceUpdateRow
|
||||
key={key}
|
||||
item={item}
|
||||
result={result}
|
||||
current={currentKey === key}
|
||||
busy={busy}
|
||||
skipMessage={
|
||||
result?.status === 'skipped'
|
||||
? skipLabels[result.reason]
|
||||
: undefined
|
||||
}
|
||||
onReview={setReview}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{skipped.length > 0 && (
|
||||
<Collapsible defaultOpen={ready.length === 0}>
|
||||
<CollapsibleTrigger
|
||||
render={
|
||||
<Button variant='ghost' size='sm' className='group max-w-full' />
|
||||
}
|
||||
>
|
||||
<ChevronDown
|
||||
aria-hidden='true'
|
||||
className='transition-transform group-aria-expanded:rotate-180'
|
||||
/>
|
||||
{t('Skipped ({{total}})', {
|
||||
total: formatNumber(skipped.length, locale),
|
||||
})}
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<ul className='text-muted-foreground divide-y px-3 text-xs'>
|
||||
{skipped.map((item) => (
|
||||
<li
|
||||
key={item.plugin.key}
|
||||
className='flex flex-wrap justify-between gap-x-4 gap-y-1 py-2'
|
||||
>
|
||||
<span className='font-mono break-all'>{item.plugin.key}</span>
|
||||
<span>{item.skip && skipLabels[item.skip]}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
{!finished && ready.length > 0 && (
|
||||
<div className='text-muted-foreground flex items-start gap-2 text-xs leading-relaxed'>
|
||||
<ShieldAlert className='mt-0.5 size-4 shrink-0' aria-hidden='true' />
|
||||
<div>
|
||||
<p>
|
||||
{t(
|
||||
'Plugins can access channel credentials. Review the source and differences before installing.'
|
||||
)}
|
||||
</p>
|
||||
{sourceKind === 'community' && (
|
||||
<p>
|
||||
{t(
|
||||
'Installing sends the plugin name, its version and a random ID of this gateway to newapi.ai to count installs.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{review && (
|
||||
<MarketplaceInstallDialog
|
||||
reviewOnly
|
||||
target={{
|
||||
source: props.source,
|
||||
plugin: review.plugin,
|
||||
version: review.target.version,
|
||||
installState: {
|
||||
status: 'upgradable',
|
||||
installedVersion: review.installed.meta.version,
|
||||
latestVersion: review.target.version,
|
||||
},
|
||||
}}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setReview(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
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 type { QueryClient } from '@tanstack/react-query'
|
||||
import i18next from 'i18next'
|
||||
|
||||
import { MODEL_PRICING_ISSUES_QUERY_KEY } from '@/features/system-settings/models/pricing-issues'
|
||||
import { getServerErrorMessage } from '@/lib/server-error-message'
|
||||
|
||||
import { activateTaskPlugin, installMarketplacePlugin } from '../api'
|
||||
import type {
|
||||
MarketplaceIndexVersion,
|
||||
MarketplacePlugin,
|
||||
MarketplaceSource,
|
||||
} from '../types'
|
||||
import { resolvePluginSourceUrl } from './marketplace'
|
||||
import { fetchPluginIconDataUri } from './plugin-icon-file'
|
||||
import {
|
||||
computeSourceSha256,
|
||||
fetchPluginSourceText,
|
||||
PluginSourceFetchError,
|
||||
} from './plugin-url'
|
||||
|
||||
export async function downloadMarketplaceRelease(
|
||||
source: MarketplaceSource,
|
||||
plugin: MarketplacePlugin,
|
||||
entry: MarketplaceIndexVersion
|
||||
) {
|
||||
const url = resolvePluginSourceUrl(source.index_url, entry.path)
|
||||
if (!url) {
|
||||
throw new Error(
|
||||
i18next.t('The source gives an invalid address for this plugin.')
|
||||
)
|
||||
}
|
||||
const text = await fetchPluginSourceText(url)
|
||||
const iconUrl =
|
||||
plugin.iconFile &&
|
||||
resolvePluginSourceUrl(source.index_url, plugin.iconFile.path)
|
||||
const [digest, icon] = await Promise.all([
|
||||
computeSourceSha256(text),
|
||||
iconUrl
|
||||
? fetchPluginIconDataUri(iconUrl, { sha256: plugin.iconFile?.sha256 })
|
||||
: null,
|
||||
])
|
||||
return { text, digest, icon }
|
||||
}
|
||||
|
||||
export class MarketplaceActivationError extends Error {}
|
||||
|
||||
export function marketplaceErrorMessage(error: unknown) {
|
||||
if (error instanceof PluginSourceFetchError) {
|
||||
return error.reason === 'too_large'
|
||||
? i18next.t('Plugin source exceeds the 8 MiB limit.')
|
||||
: i18next.t('Could not download the plugin code. Try again later.')
|
||||
}
|
||||
return getServerErrorMessage(error)
|
||||
}
|
||||
|
||||
export async function installMarketplaceRelease(
|
||||
source: MarketplaceSource,
|
||||
entry: MarketplaceIndexVersion,
|
||||
download: Awaited<ReturnType<typeof downloadMarketplaceRelease>>
|
||||
) {
|
||||
if (
|
||||
entry.sha256 &&
|
||||
download.digest &&
|
||||
entry.sha256.toLowerCase() !== download.digest.toLowerCase()
|
||||
) {
|
||||
throw new Error(i18next.t('Integrity check failed'))
|
||||
}
|
||||
const detail = await installMarketplacePlugin({
|
||||
source: download.text,
|
||||
sourceSha256: entry.sha256,
|
||||
remark: `${source.name} v${entry.version}`,
|
||||
icon: download.icon ?? undefined,
|
||||
marketplaceIndexUrl: source.index_url,
|
||||
})
|
||||
if (!detail.plugin || detail.plugin.active) return detail
|
||||
|
||||
try {
|
||||
const notice = await activateTaskPlugin(
|
||||
detail.meta.key,
|
||||
detail.meta.version
|
||||
)
|
||||
return { ...detail, pricing_issues: notice?.pricing_issues ?? [] }
|
||||
} catch (error) {
|
||||
throw new MarketplaceActivationError(getServerErrorMessage(error), {
|
||||
cause: error,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function invalidateMarketplaceInstalls(
|
||||
client: QueryClient,
|
||||
keys: string[]
|
||||
) {
|
||||
void client.invalidateQueries({ queryKey: ['task-plugins'] })
|
||||
void client.invalidateQueries({ queryKey: MODEL_PRICING_ISSUES_QUERY_KEY })
|
||||
for (const key of keys) {
|
||||
void client.invalidateQueries({ queryKey: ['task-plugin', key] })
|
||||
void client.invalidateQueries({ queryKey: ['task-plugin-versions', key] })
|
||||
}
|
||||
}
|
||||
@@ -553,3 +553,49 @@ export function findRevokedEntry(
|
||||
if (!hash) return undefined
|
||||
return index?.revoked?.find((entry) => entry.sha256 === hash)
|
||||
}
|
||||
|
||||
export type MarketplaceUpdate = {
|
||||
plugin: MarketplacePlugin
|
||||
installed: TaskPluginListItem
|
||||
target: MarketplaceIndexVersion
|
||||
skip?: 'disabled' | 'revoked' | 'unverified' | 'modified'
|
||||
}
|
||||
|
||||
/** Only replace a listed release when the installed bytes still match that release. */
|
||||
export function getMarketplaceUpdates(
|
||||
index: MarketplaceIndex,
|
||||
installed: TaskPluginListItem[]
|
||||
): MarketplaceUpdate[] {
|
||||
const updates: MarketplaceUpdate[] = []
|
||||
const byKey = new Map(installed.map((item) => [item.meta.key, item]))
|
||||
for (const plugin of index.plugins) {
|
||||
const local = byKey.get(plugin.key)
|
||||
if (!local || local.meta.version === plugin.latest) continue
|
||||
byKey.delete(plugin.key)
|
||||
const current = findMarketplaceVersion(plugin, local.meta.version)
|
||||
const target = findMarketplaceVersion(plugin, plugin.latest)
|
||||
if (!current || !target) continue
|
||||
|
||||
let skip: MarketplaceUpdate['skip']
|
||||
if (
|
||||
findRevokedEntry(index, local.source_hash) ||
|
||||
findRevokedEntry(index, target.sha256)
|
||||
) {
|
||||
skip = 'revoked'
|
||||
} else if (!local.enabled) {
|
||||
skip = 'disabled'
|
||||
} else if (
|
||||
![current.sha256, target.sha256, local.source_hash].every(
|
||||
(hash) => hash && /^[0-9a-f]{64}$/i.test(hash)
|
||||
)
|
||||
) {
|
||||
skip = 'unverified'
|
||||
} else if (
|
||||
local.source_hash.toLowerCase() !== current.sha256?.toLowerCase()
|
||||
) {
|
||||
skip = 'modified'
|
||||
}
|
||||
updates.push({ plugin, installed: local, target, skip })
|
||||
}
|
||||
return updates
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { act, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createInstance } from 'i18next'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { BindingsPanel } from '../components/bindings-panel'
|
||||
import en from '@/i18n/locales/en.json'
|
||||
import fr from '@/i18n/locales/fr.json'
|
||||
import zh from '@/i18n/locales/zh.json'
|
||||
|
||||
import { BindingDialog, BindingsPanel } from '../components/bindings-panel'
|
||||
import type { MonitorAccount, MonitorSnapshot, MonitorState } from '../types'
|
||||
|
||||
const account: MonitorAccount = {
|
||||
@@ -148,7 +154,9 @@ describe('cost binding selectors', () => {
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2)
|
||||
await user.type(group, 'shop-a')
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'shop-a (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Local model' }))
|
||||
expect(screen.getAllByRole('option')).toHaveLength(3)
|
||||
@@ -177,6 +185,192 @@ describe('cost binding selectors', () => {
|
||||
)
|
||||
})
|
||||
|
||||
test('group options and selected labels show full captured ratios, preserve zero and keep missing ratios unknown', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
const latest = input.snapshots.find((item) => item.id === 'newest')
|
||||
if (!latest) throw new Error('Missing confirmed snapshot')
|
||||
latest.data.groups = [
|
||||
{
|
||||
name: 'shop-a',
|
||||
display_name: 'Shared display name',
|
||||
ratio: 0.085123456789,
|
||||
},
|
||||
{ name: 'shop-b', display_name: 'Shared display name', ratio: 0 },
|
||||
{ name: 'unknown', ratio: null },
|
||||
]
|
||||
render(<BindingsPanel state={input} onSave={vi.fn()} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Add binding' }))
|
||||
const group = screen.getByRole('combobox', { name: 'Upstream group' })
|
||||
await user.click(group)
|
||||
const precise =
|
||||
'shop-a (Shared display name) · Upstream ratio 0.085123456789'
|
||||
expect(screen.getByRole('option', { name: precise })).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-b (Shared display name) · Upstream ratio 0',
|
||||
})
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('option', { name: 'unknown · Upstream ratio Unknown' })
|
||||
).toBeVisible()
|
||||
await user.click(screen.getByRole('option', { name: precise }))
|
||||
expect(group).toHaveValue(precise)
|
||||
})
|
||||
|
||||
test('selected group ratio labels follow interface language changes without replacing the saved group code', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
const latest = input.snapshots.find((item) => item.id === 'newest')
|
||||
if (!latest) throw new Error('Missing confirmed snapshot')
|
||||
latest.data.groups[0].ratio = 0.085123456789
|
||||
input.config.bindings = [
|
||||
{
|
||||
id: 'binding',
|
||||
channel_id: 1,
|
||||
account_id: 'bee',
|
||||
upstream_group: 'shop-a',
|
||||
local_model: '',
|
||||
upstream_model: '',
|
||||
},
|
||||
]
|
||||
const translations = createInstance()
|
||||
await translations.init({
|
||||
lng: 'en',
|
||||
fallbackLng: 'en',
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
resources: { en, fr, zhCN: zh },
|
||||
})
|
||||
const onSave = vi.fn().mockResolvedValue(undefined)
|
||||
render(
|
||||
<I18nextProvider i18n={translations}>
|
||||
<BindingsPanel state={input} onSave={onSave} />
|
||||
</I18nextProvider>
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
const group = screen.getByRole('combobox', { name: 'Upstream group' })
|
||||
expect(group).toHaveValue(
|
||||
'shop-a (Shared display name) · Upstream ratio 0.085123456789'
|
||||
)
|
||||
await act(() => translations.changeLanguage('fr'))
|
||||
expect(group).toHaveValue(
|
||||
'shop-a (Shared display name) · Coefficient fournisseur 0,085123456789'
|
||||
)
|
||||
await act(() => translations.changeLanguage('zhCN'))
|
||||
expect(group).toHaveValue(
|
||||
'shop-a (Shared display name) · 上游倍率 0.085123456789'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
await waitFor(() =>
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bindings: [expect.objectContaining({ upstream_group: 'shop-a' })],
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
test('channel search filters names, preserves selection on no match and saves the selected numeric ID', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
input.channels[1].name = '美团 LongChat'
|
||||
input.config.bindings = [
|
||||
{
|
||||
id: 'binding',
|
||||
channel_id: 1,
|
||||
account_id: 'bee',
|
||||
upstream_group: 'shop-a',
|
||||
local_model: 'local-gpt',
|
||||
upstream_model: 'gpt-upstream',
|
||||
},
|
||||
]
|
||||
const onSave = vi.fn().mockResolvedValue(undefined)
|
||||
render(<BindingsPanel state={input} onSave={onSave} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
const channel = screen.getByRole('combobox', { name: 'Channel' })
|
||||
expect(channel).toHaveValue('OpenAI')
|
||||
await user.click(channel)
|
||||
await user.type(channel, 'no-matching-channel')
|
||||
expect(screen.getByText('No results found')).toBeVisible()
|
||||
expect(screen.queryByRole('option')).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(channel).toHaveValue('OpenAI')
|
||||
await user.click(channel)
|
||||
await user.type(channel, 'LONGchat')
|
||||
expect(screen.getAllByRole('option')).toHaveLength(1)
|
||||
expect(screen.getByRole('option', { name: '美团 LongChat' })).toBeVisible()
|
||||
await user.keyboard('{ArrowDown}{Enter}')
|
||||
expect(channel).toHaveValue('美团 LongChat')
|
||||
await user.click(screen.getByRole('combobox', { name: 'Local model' }))
|
||||
expect(
|
||||
screen.getByRole('option', { name: 'All channel models' })
|
||||
).toHaveAttribute('aria-selected', 'true')
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'local-gpt' })
|
||||
).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(
|
||||
screen.getByRole('combobox', { name: 'Upstream model' })
|
||||
).toHaveValue('Channel mapping')
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bindings: [
|
||||
expect.objectContaining({
|
||||
channel_id: 2,
|
||||
upstream_group: 'shop-a',
|
||||
local_model: '',
|
||||
upstream_model: '',
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
test('a channel moved out of the quick-binding group after refresh cannot be saved', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
const onSave = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const view = render(
|
||||
<BindingDialog
|
||||
localGroup='default'
|
||||
state={input}
|
||||
onSave={onSave}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
const save = screen.getByRole('button', { name: 'Save' })
|
||||
expect(save).toBeEnabled()
|
||||
view.rerender(
|
||||
<BindingDialog
|
||||
localGroup='default'
|
||||
state={{
|
||||
...input,
|
||||
channels: input.channels.map((channel) => ({
|
||||
...channel,
|
||||
group: 'another-group',
|
||||
})),
|
||||
}}
|
||||
onSave={onSave}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)
|
||||
expect(save).toBeDisabled()
|
||||
await user.click(save)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('clears incompatible selections when switching account, channel or model scope', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
@@ -215,7 +409,9 @@ describe('cost binding selectors', () => {
|
||||
await user.click(group)
|
||||
expect(screen.getAllByRole('option')).toHaveLength(1)
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'other-code (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'other-code (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
await user.click(upstream)
|
||||
expect(screen.getByRole('option', { name: 'other-model' })).toBeVisible()
|
||||
@@ -233,7 +429,9 @@ describe('cost binding selectors', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Add binding' }))
|
||||
await user.click(screen.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'shop-a (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Local model' }))
|
||||
await user.click(screen.getByRole('option', { name: 'local-gpt' }))
|
||||
@@ -322,7 +520,9 @@ describe('cost binding selectors', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Add binding' }))
|
||||
await user.click(screen.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'shop-a (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
const models = screen.getByRole('combobox', { name: 'Local model' })
|
||||
await user.click(models)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { act, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createInstance } from 'i18next'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import en from '@/i18n/locales/en.json'
|
||||
import fr from '@/i18n/locales/fr.json'
|
||||
import ja from '@/i18n/locales/ja.json'
|
||||
import ru from '@/i18n/locales/ru.json'
|
||||
import viLocale from '@/i18n/locales/vi.json'
|
||||
import zhTW from '@/i18n/locales/zh-TW.json'
|
||||
import zh from '@/i18n/locales/zh.json'
|
||||
|
||||
import { EncryptionKeyNotice } from '../components/encryption-key-notice'
|
||||
|
||||
const resources = { en, zhCN: zh, zhTW, fr, ru, ja, vi: viLocale }
|
||||
|
||||
describe('upstream credential key setup', () => {
|
||||
test('a missing or invalid key shows expandable configuration steps with copyable commands and no preset secret', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clipboard = vi.spyOn(navigator.clipboard, 'writeText')
|
||||
render(<EncryptionKeyNotice ready={false} />)
|
||||
const alert = screen.getByRole('alert')
|
||||
expect(alert).toHaveTextContent('Credential encryption is not configured')
|
||||
const summary = within(alert).getByText(
|
||||
'How to configure the encryption key'
|
||||
)
|
||||
const details = summary.closest('details')
|
||||
expect(details).not.toHaveAttribute('open')
|
||||
await user.click(summary)
|
||||
expect(details).toHaveAttribute('open')
|
||||
const steps = within(alert).getByRole('list')
|
||||
expect(within(steps).getAllByRole('listitem')).toHaveLength(3)
|
||||
expect(steps).toHaveTextContent('docker-compose.yml')
|
||||
expect(steps).toHaveTextContent('docker-compose.dev.yml')
|
||||
expect(steps).toHaveTextContent('- UPSTREAM_MONITOR_KEY=<BASE64_KEY>')
|
||||
expect(alert).toHaveTextContent('restore the original key')
|
||||
expect(alert).toHaveTextContent('working directory')
|
||||
const commands = [
|
||||
'openssl rand -base64 32',
|
||||
'docker compose up -d --no-deps --force-recreate new-api',
|
||||
'docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api',
|
||||
]
|
||||
const copy = within(alert).getAllByRole('button', {
|
||||
name: 'Copy to clipboard',
|
||||
})
|
||||
expect(copy).toHaveLength(commands.length)
|
||||
for (const [index, command] of commands.entries()) {
|
||||
expect(alert).toHaveTextContent(command)
|
||||
await user.click(copy[index])
|
||||
expect(clipboard).toHaveBeenLastCalledWith(command)
|
||||
}
|
||||
expect(alert.textContent).not.toMatch(/[A-Za-z0-9+/]{43}=/)
|
||||
})
|
||||
|
||||
test('a valid key removes the warning and setup steps after state refresh', () => {
|
||||
const view = render(<EncryptionKeyNotice ready={false} />)
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument()
|
||||
view.rerender(<EncryptionKeyNotice ready />)
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByText('How to configure the encryption key')
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('setup instructions follow all seven interface languages while commands stay exact', async () => {
|
||||
const translations = createInstance()
|
||||
await translations.init({
|
||||
lng: 'en',
|
||||
fallbackLng: 'en',
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
resources,
|
||||
})
|
||||
render(
|
||||
<I18nextProvider i18n={translations}>
|
||||
<EncryptionKeyNotice ready={false} />
|
||||
</I18nextProvider>
|
||||
)
|
||||
for (const [language, resource] of Object.entries(resources)) {
|
||||
await act(() => translations.changeLanguage(language))
|
||||
const alert = screen.getByRole('alert')
|
||||
const key = 'How to configure the encryption key'
|
||||
expect(within(alert).getByText(resource.translation[key])).toBeVisible()
|
||||
expect(alert).toHaveTextContent('openssl rand -base64 32')
|
||||
expect(alert).toHaveTextContent('- UPSTREAM_MONITOR_KEY=<BASE64_KEY>')
|
||||
expect(alert).toHaveTextContent(
|
||||
'docker compose up -d --no-deps --force-recreate new-api'
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -486,6 +486,7 @@ describe('profit comparisons', () => {
|
||||
name: 'Channel cost bindings',
|
||||
})
|
||||
expect(drawer).toHaveAttribute('data-side', 'right')
|
||||
expect(drawer).toHaveClass('w-full', 'sm:w-[90vw]', 'sm:max-w-7xl')
|
||||
expect(bindings).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(
|
||||
within(drawer).getByRole('button', { name: 'Add binding' })
|
||||
@@ -501,6 +502,165 @@ describe('profit comparisons', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('quick binding opens the shared dialog with only exact local-group channels and saves without dropping existing bindings', async () => {
|
||||
const user = userEvent.setup()
|
||||
const state = stateWithRows([
|
||||
baseRow,
|
||||
{ ...baseRow, local_group: 'premium' },
|
||||
{ ...baseRow, local_group: 'no-channels' },
|
||||
])
|
||||
state.channels = [
|
||||
{ id: 1, name: 'Standard channel', group: 'standard', models: 'model-a' },
|
||||
{
|
||||
id: 2,
|
||||
name: 'Shared channel',
|
||||
group: 'standard, premium',
|
||||
models: 'shared-model',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'Premium channel',
|
||||
group: 'premium',
|
||||
models: 'premium-model',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: 'Wrong group',
|
||||
group: 'premium-plus',
|
||||
models: 'wrong-model',
|
||||
},
|
||||
]
|
||||
state.config.accounts = [
|
||||
{
|
||||
id: 'account-a',
|
||||
site_id: 'site-a',
|
||||
name: 'Account A',
|
||||
username: 'operator',
|
||||
external_id: '42',
|
||||
has_password: true,
|
||||
device_id: '',
|
||||
flow_id: '',
|
||||
interval_minutes: 0,
|
||||
enabled: true,
|
||||
purchase_factor: 1,
|
||||
fee_rate: 0,
|
||||
fee_bearer: 'self',
|
||||
},
|
||||
]
|
||||
const existing = {
|
||||
id: 'existing',
|
||||
channel_id: 1,
|
||||
account_id: 'account-a',
|
||||
upstream_group: 'base',
|
||||
local_model: 'model-a',
|
||||
upstream_model: 'source-a',
|
||||
}
|
||||
state.config.bindings = [existing]
|
||||
state.snapshots = [
|
||||
{
|
||||
id: 'capture',
|
||||
job_id: 'job',
|
||||
account_id: 'account-a',
|
||||
confirmed: true,
|
||||
complete: true,
|
||||
created_at: 1,
|
||||
data: {
|
||||
account_id: '42',
|
||||
balances: [],
|
||||
models: [],
|
||||
groups: [{ name: 'base', ratio: 0.5 }],
|
||||
topups: [],
|
||||
warnings: [],
|
||||
},
|
||||
},
|
||||
]
|
||||
const get = vi
|
||||
.spyOn(api, 'get')
|
||||
.mockResolvedValue({ data: { success: true, data: state } })
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
|
||||
})
|
||||
const view = render(
|
||||
<QueryClientProvider client={client}>
|
||||
<UpstreamMonitor />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
try {
|
||||
const quick = await screen.findByRole('button', {
|
||||
name: 'Bind channels in premium',
|
||||
})
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Bind channels in no-channels' })
|
||||
).toBeDisabled()
|
||||
const local = within(screen.getByRole('region', { name: 'Local groups' }))
|
||||
expect(
|
||||
local.getByRole('button', { name: /^standard/, pressed: true })
|
||||
).toBeVisible()
|
||||
quick.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
const dialog = within(
|
||||
await screen.findByRole('dialog', { name: 'Channel cost binding' })
|
||||
)
|
||||
expect(dialog.getByText('Channels in local group premium')).toBeVisible()
|
||||
const channel = dialog.getByRole('combobox', { name: 'Channel' })
|
||||
expect(channel).toHaveValue('Shared channel')
|
||||
await user.click(channel)
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2)
|
||||
expect(
|
||||
screen.getByRole('option', { name: 'Shared channel' })
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'Standard channel' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'Wrong group' })
|
||||
).not.toBeInTheDocument()
|
||||
await user.type(channel, 'premium')
|
||||
await user.click(screen.getByRole('option', { name: 'Premium channel' }))
|
||||
await user.click(dialog.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'base · Upstream ratio 0.5' })
|
||||
)
|
||||
await user.click(dialog.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(put).toHaveBeenCalledWith(
|
||||
'/api/upstream_monitor/config',
|
||||
expect.objectContaining({
|
||||
bindings: [
|
||||
existing,
|
||||
expect.objectContaining({
|
||||
channel_id: 3,
|
||||
account_id: 'account-a',
|
||||
upstream_group: 'base',
|
||||
local_model: '',
|
||||
upstream_model: '',
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'Channel cost binding' })
|
||||
).not.toBeInTheDocument()
|
||||
)
|
||||
expect(
|
||||
local.getByRole('button', { name: /^standard/, pressed: true })
|
||||
).toBeVisible()
|
||||
expect(state.config.bindings).toEqual([existing])
|
||||
expect(
|
||||
get.mock.calls.filter(([url]) => url === '/api/upstream_monitor/state')
|
||||
.length
|
||||
).toBeGreaterThan(1)
|
||||
} finally {
|
||||
view.unmount()
|
||||
client.clear()
|
||||
}
|
||||
})
|
||||
|
||||
test('details show the matched tier, unit prices, and the same trial values in JSON', async () => {
|
||||
const user = userEvent.setup()
|
||||
const row = {
|
||||
@@ -892,7 +1052,7 @@ describe('profit comparisons', () => {
|
||||
upstreamKey: '',
|
||||
})
|
||||
})
|
||||
test('switching local groups updates selected upstream and models with keyboard access', async () => {
|
||||
test('group headers count distinct list entries and update upstream counts when switching local groups', async () => {
|
||||
const user = userEvent.setup()
|
||||
const second = {
|
||||
...baseRow,
|
||||
@@ -901,27 +1061,55 @@ describe('profit comparisons', () => {
|
||||
site_name: 'Site B',
|
||||
local_model: 'model-b',
|
||||
}
|
||||
render(
|
||||
const view = render(
|
||||
<ProfitPanel
|
||||
state={stateWithRows([baseRow, second])}
|
||||
state={stateWithRows([
|
||||
baseRow,
|
||||
{ ...baseRow, channel_id: 2, local_model: 'another-model' },
|
||||
{ ...baseRow, account_id: 'another-account', site_name: 'Site C' },
|
||||
second,
|
||||
])}
|
||||
onSnapshot={vi.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('model-a')).toBeInTheDocument()
|
||||
const local = screen.getByRole('region', { name: 'Local groups' })
|
||||
const upstream = screen.getByRole('region', { name: 'Upstream groups' })
|
||||
expect(
|
||||
within(within(local).getByRole('heading')).getByText('2')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(within(upstream).getByRole('heading')).getByText('2')
|
||||
).toBeVisible()
|
||||
expect(within(local).getAllByRole('button')).toHaveLength(2)
|
||||
expect(within(upstream).getAllByRole('button')).toHaveLength(2)
|
||||
const premium = within(local).getByRole('button', { name: /premium/ })
|
||||
premium.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
expect(premium).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getByText('model-b')).toBeInTheDocument()
|
||||
expect(screen.queryByText('model-a')).not.toBeInTheDocument()
|
||||
const upstream = screen.getByRole('region', { name: 'Upstream groups' })
|
||||
expect(
|
||||
within(upstream).getByRole('button', { pressed: true })
|
||||
).toHaveTextContent('Site B')
|
||||
expect(
|
||||
within(within(local).getByRole('heading')).getByText('2')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(within(upstream).getByRole('heading')).getByText('1')
|
||||
).toBeVisible()
|
||||
expect(screen.getByTestId('profit-columns')).toHaveClass(
|
||||
'lg:grid-cols-[20fr_20fr_60fr]'
|
||||
)
|
||||
view.rerender(
|
||||
<ProfitPanel state={stateWithRows([second])} onSnapshot={vi.fn()} />
|
||||
)
|
||||
expect(
|
||||
within(within(local).getByRole('heading')).getByText('1')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(within(upstream).getByRole('heading')).getByText('1')
|
||||
).toBeVisible()
|
||||
})
|
||||
test('profit list omits repeated account names, channel names and the comparable badge', () => {
|
||||
const state = stateWithRows([baseRow])
|
||||
@@ -1260,6 +1448,61 @@ describe('profit comparisons', () => {
|
||||
expect(within(accounts).getByRole('table')).toBeVisible()
|
||||
})
|
||||
|
||||
test('upstream account balances retain captured fractional precision, signs and unknown values', () => {
|
||||
const state = stateWithRows([])
|
||||
state.config.accounts = [
|
||||
{
|
||||
id: 'account',
|
||||
site_id: 'site',
|
||||
name: 'Precision account',
|
||||
username: 'operator',
|
||||
external_id: '42',
|
||||
has_password: false,
|
||||
device_id: '',
|
||||
flow_id: '',
|
||||
interval_minutes: 0,
|
||||
enabled: true,
|
||||
purchase_factor: 1,
|
||||
fee_rate: 0,
|
||||
fee_bearer: 'self',
|
||||
},
|
||||
]
|
||||
state.snapshots = [
|
||||
{
|
||||
id: 'snapshot',
|
||||
job_id: 'job',
|
||||
account_id: 'account',
|
||||
confirmed: true,
|
||||
complete: true,
|
||||
created_at: 100,
|
||||
data: {
|
||||
account_id: '42',
|
||||
groups: [],
|
||||
models: [],
|
||||
topups: [],
|
||||
warnings: [],
|
||||
balances: [
|
||||
{ kind: 'wallet', amount: 4.000123456, currency: 'USD' },
|
||||
{ kind: 'available', amount: -0.00022783, currency: 'CNY' },
|
||||
{ kind: 'tiny', amount: 8.5123456789e-14, currency: 'JPY' },
|
||||
{ kind: 'zero', amount: 0, currency: 'USD' },
|
||||
{ kind: 'unknown', amount: null, currency: 'USD' },
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
render(<SitesPanel state={state} onSave={vi.fn()} onRun={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('wallet: 4.000123456 USD')).toBeVisible()
|
||||
expect(screen.getByText('available: -0.00022783 CNY')).toBeVisible()
|
||||
expect(
|
||||
screen.getByText('tiny: 0.000000000000085123456789 JPY')
|
||||
).toBeVisible()
|
||||
expect(screen.getByText('zero: 0 USD')).toBeVisible()
|
||||
expect(screen.getByText('unknown: — USD')).toBeVisible()
|
||||
})
|
||||
|
||||
test.each([false, true])(
|
||||
'all models with estimates=%s shows labeled unconnected inventory without changing scenario totals',
|
||||
async (estimated) => {
|
||||
|
||||
@@ -17,7 +17,12 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { parseModelsList } from '@/features/channels/lib/channel-utils'
|
||||
import {
|
||||
parseGroupsList,
|
||||
parseModelsList,
|
||||
} from '@/features/channels/lib/channel-utils'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
import { formatNumber } from '@/lib/format'
|
||||
import { handleServerError } from '@/lib/handle-server-error'
|
||||
|
||||
import { bindingSchema, newMonitorID } from '../lib/config'
|
||||
@@ -35,18 +40,27 @@ function includeSavedOption(
|
||||
: options
|
||||
}
|
||||
|
||||
function BindingDialog(props: {
|
||||
export function BindingDialog(props: {
|
||||
binding?: MonitorBinding
|
||||
localGroup?: string
|
||||
state: MonitorState
|
||||
onSave: SaveMonitorConfig
|
||||
onClose: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
|
||||
const binding = props.binding
|
||||
const localGroup = props.localGroup
|
||||
const channels =
|
||||
localGroup === undefined
|
||||
? props.state.channels
|
||||
: props.state.channels.filter((channel) =>
|
||||
parseGroupsList(channel.group).includes(localGroup)
|
||||
)
|
||||
const form = useForm<z.infer<typeof bindingSchema>>({
|
||||
resolver: zodResolver(bindingSchema),
|
||||
defaultValues: {
|
||||
channel_id: binding?.channel_id ?? props.state.channels[0]?.id ?? 0,
|
||||
channel_id: binding?.channel_id ?? channels[0]?.id ?? 0,
|
||||
account_id:
|
||||
binding?.account_id ?? props.state.config.accounts[0]?.id ?? '',
|
||||
upstream_group: binding?.upstream_group ?? '',
|
||||
@@ -60,11 +74,19 @@ function BindingDialog(props: {
|
||||
const localModels = form.watch('local_models')
|
||||
const localModel = localModels.length === 1 ? localModels[0] : undefined
|
||||
const snapshot = latestMonitorSnapshots(props.state.snapshots).get(accountID)
|
||||
const channel = props.state.channels.find((item) => item.id === channelID)
|
||||
const channel = channels.find((item) => item.id === channelID)
|
||||
const groupOptions = includeSavedOption(
|
||||
(snapshot?.data.groups ?? []).map((item) => ({
|
||||
value: item.name,
|
||||
label: monitorGroupLabel(item.name, item.display_name),
|
||||
label: `${monitorGroupLabel(item.name, item.display_name)} · ${t(
|
||||
'Upstream ratio {{ratio}}',
|
||||
{
|
||||
ratio:
|
||||
item.ratio === null
|
||||
? t('Unknown')
|
||||
: formatNumber(item.ratio, locale, { fullPrecision: true }),
|
||||
}
|
||||
)}`,
|
||||
})),
|
||||
binding?.account_id === accountID ? binding.upstream_group : undefined
|
||||
)
|
||||
@@ -93,6 +115,13 @@ function BindingDialog(props: {
|
||||
const clearUpstreamModel = () =>
|
||||
form.setValue('upstream_model', '', { shouldDirty: true })
|
||||
const submit = async (values: z.infer<typeof bindingSchema>) => {
|
||||
if (
|
||||
props.localGroup !== undefined &&
|
||||
!channels.some((channel) => channel.id === values.channel_id)
|
||||
) {
|
||||
form.setError('channel_id', { message: t('Select an option') })
|
||||
return
|
||||
}
|
||||
const { local_models, ...scope } = values
|
||||
const existing = props.state.config.bindings.filter(
|
||||
(item) => item.id !== binding?.id
|
||||
@@ -146,6 +175,11 @@ function BindingDialog(props: {
|
||||
if (!open) props.onClose()
|
||||
}}
|
||||
title={t('Channel cost binding')}
|
||||
description={
|
||||
props.localGroup === undefined
|
||||
? undefined
|
||||
: t('Channels in local group {{group}}', { group: props.localGroup })
|
||||
}
|
||||
footer={
|
||||
<>
|
||||
<Button variant='outline' onClick={props.onClose}>
|
||||
@@ -155,7 +189,10 @@ function BindingDialog(props: {
|
||||
type='submit'
|
||||
form='monitor-binding-form'
|
||||
disabled={
|
||||
form.formState.isSubmitting || !group || !localModels.length
|
||||
form.formState.isSubmitting ||
|
||||
!group ||
|
||||
!localModels.length ||
|
||||
(props.localGroup !== undefined && !channel)
|
||||
}
|
||||
>
|
||||
{t('Save')}
|
||||
@@ -173,11 +210,12 @@ function BindingDialog(props: {
|
||||
control={form.control}
|
||||
name='channel_id'
|
||||
label={t('Channel')}
|
||||
searchable
|
||||
onValueChange={() => {
|
||||
form.setValue('local_models', [''], { shouldDirty: true })
|
||||
clearUpstreamModel()
|
||||
}}
|
||||
options={props.state.channels.map((channel) => ({
|
||||
options={channels.map((channel) => ({
|
||||
value: String(channel.id),
|
||||
label: channel.name,
|
||||
}))}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { CopyButton } from '@/components/copy-button'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
|
||||
export function EncryptionKeyNotice(props: { ready: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
if (props.ready) return null
|
||||
|
||||
const generateCommand = 'openssl rand -base64 32'
|
||||
const recreateCommand =
|
||||
'docker compose up -d --no-deps --force-recreate new-api'
|
||||
const recreateDevCommand =
|
||||
'docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api'
|
||||
|
||||
return (
|
||||
<Alert
|
||||
variant='destructive'
|
||||
className='max-h-[50%] shrink-0 overflow-y-auto'
|
||||
>
|
||||
<AlertTitle>{t('Credential encryption is not configured')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t(
|
||||
'An administrator must configure the upstream monitor encryption key before saving credentials or running tasks.'
|
||||
)}
|
||||
<details className='text-foreground mt-2 min-w-0'>
|
||||
<summary className='focus-visible:ring-ring cursor-pointer rounded-sm font-medium focus-visible:ring-2 focus-visible:outline-none'>
|
||||
{t('How to configure the encryption key')}
|
||||
</summary>
|
||||
<ol className='mt-3 list-decimal space-y-3 pl-5'>
|
||||
<li>
|
||||
{t(
|
||||
'For first-time setup, generate a random 32-byte Base64 key on the server:'
|
||||
)}
|
||||
<div className='bg-muted mt-1 flex min-w-0 items-start gap-2 rounded-md p-2'>
|
||||
<code className='min-w-0 flex-1 self-center break-all'>
|
||||
{generateCommand}
|
||||
</code>
|
||||
<CopyButton value={generateCommand} className='size-7' />
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:'
|
||||
)}
|
||||
<code className='bg-muted mt-1 block rounded-md p-2 break-all'>
|
||||
{'- UPSTREAM_MONITOR_KEY=<BASE64_KEY>'}
|
||||
</code>
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:'
|
||||
)}
|
||||
<div className='bg-muted mt-1 flex min-w-0 items-start gap-2 rounded-md p-2'>
|
||||
<code className='min-w-0 flex-1 self-center break-all'>
|
||||
{recreateCommand}
|
||||
</code>
|
||||
<CopyButton value={recreateCommand} className='size-7' />
|
||||
</div>
|
||||
<div className='mt-2'>
|
||||
{t('For docker-compose.dev.yml, use:')}
|
||||
</div>
|
||||
<div className='bg-muted mt-1 flex min-w-0 items-start gap-2 rounded-md p-2'>
|
||||
<code className='min-w-0 flex-1 self-center break-all'>
|
||||
{recreateDevCommand}
|
||||
</code>
|
||||
<CopyButton value={recreateDevCommand} className='size-7' />
|
||||
</div>
|
||||
<div className='mt-2'>
|
||||
{t(
|
||||
'Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.'
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<div className='mt-3'>
|
||||
{t(
|
||||
'For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.'
|
||||
)}
|
||||
</div>
|
||||
<div className='mt-3'>
|
||||
{t(
|
||||
'Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.'
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Link2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -9,9 +10,16 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { parseGroupsList } from '@/features/channels/lib/channel-utils'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
import { formatLocalCurrencyAmount } from '@/lib/currency'
|
||||
import { formatNumber, formatTimestamp } from '@/lib/format'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { monitorGroupLabel } from '../lib/groups'
|
||||
import { latestMonitorSnapshots } from '../lib/jobs'
|
||||
@@ -38,6 +46,7 @@ export const profitColumnsClassName =
|
||||
export function ProfitPanel(props: {
|
||||
state: MonitorState
|
||||
onSnapshot: (id: string) => void
|
||||
onBind?: (group: string) => void
|
||||
}) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
|
||||
@@ -194,39 +203,73 @@ export function ProfitPanel(props: {
|
||||
className='flex min-h-0 min-w-0 flex-col rounded-xl border'
|
||||
aria-label={t('Local groups')}
|
||||
>
|
||||
<h3 className='shrink-0 border-b px-3 py-2 text-sm font-medium'>
|
||||
{t('Local groups')}
|
||||
<h3 className='flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2 text-sm font-medium'>
|
||||
<span>{t('Local groups')}</span>
|
||||
<Badge variant='secondary' className='tabular-nums'>
|
||||
{formatNumber(localGroups.length, locale)}
|
||||
</Badge>
|
||||
</h3>
|
||||
<div className='max-h-72 min-h-0 space-y-1 overflow-y-auto overscroll-contain p-2 lg:max-h-none lg:flex-1'>
|
||||
{localGroups.map((group) => (
|
||||
<Button
|
||||
<div
|
||||
key={group}
|
||||
variant={
|
||||
selection.localGroup === group ? 'secondary' : 'ghost'
|
||||
}
|
||||
className='h-auto w-full justify-start px-3 py-2 text-left whitespace-normal'
|
||||
aria-pressed={selection.localGroup === group}
|
||||
onClick={() => {
|
||||
setLocalGroup(group)
|
||||
setUpstreamKey('')
|
||||
}}
|
||||
className={cn(
|
||||
'flex min-w-0 items-center rounded-md',
|
||||
selection.localGroup === group && 'bg-secondary'
|
||||
)}
|
||||
>
|
||||
<span className='min-w-0'>
|
||||
<span className='block break-all'>{group}</span>
|
||||
<span className='text-muted-foreground block text-xs'>
|
||||
{t('Ratio {{ratio}} · {{count}} routes', {
|
||||
ratio: formatNumber(
|
||||
rows.find((row) => row.local_group === group)
|
||||
?.local_ratio,
|
||||
locale,
|
||||
{ fullPrecision: true }
|
||||
),
|
||||
count: rows.filter((row) => row.local_group === group)
|
||||
.length,
|
||||
})}
|
||||
<Button
|
||||
variant='ghost'
|
||||
className='h-auto min-w-0 flex-1 justify-start px-3 py-2 text-left whitespace-normal'
|
||||
aria-pressed={selection.localGroup === group}
|
||||
onClick={() => {
|
||||
setLocalGroup(group)
|
||||
setUpstreamKey('')
|
||||
}}
|
||||
>
|
||||
<span className='min-w-0'>
|
||||
<span className='block break-all'>{group}</span>
|
||||
<span className='text-muted-foreground block text-xs'>
|
||||
{t('Ratio {{ratio}} · {{count}} routes', {
|
||||
ratio: formatNumber(
|
||||
rows.find((row) => row.local_group === group)
|
||||
?.local_ratio,
|
||||
locale,
|
||||
{ fullPrecision: true }
|
||||
),
|
||||
count: rows.filter((row) => row.local_group === group)
|
||||
.length,
|
||||
})}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
</Button>
|
||||
{props.onBind && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon-sm'
|
||||
className='mr-1 shrink-0'
|
||||
aria-label={t('Bind channels in {{group}}', {
|
||||
group,
|
||||
})}
|
||||
disabled={
|
||||
!props.state.config.accounts.length ||
|
||||
!props.state.channels.some((channel) =>
|
||||
parseGroupsList(channel.group).includes(group)
|
||||
)
|
||||
}
|
||||
onClick={() => props.onBind?.(group)}
|
||||
>
|
||||
<Link2 className='size-4' />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{t('Bind')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
@@ -234,8 +277,11 @@ export function ProfitPanel(props: {
|
||||
className='flex min-h-0 min-w-0 flex-col rounded-xl border'
|
||||
aria-label={t('Upstream groups')}
|
||||
>
|
||||
<h3 className='shrink-0 border-b px-3 py-2 text-sm font-medium'>
|
||||
{t('Upstream groups')}
|
||||
<h3 className='flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2 text-sm font-medium'>
|
||||
<span>{t('Upstream groups')}</span>
|
||||
<Badge variant='secondary' className='tabular-nums'>
|
||||
{formatNumber(upstreams.length, locale)}
|
||||
</Badge>
|
||||
</h3>
|
||||
<div className='max-h-72 min-h-0 space-y-1 overflow-y-auto overscroll-contain p-2 lg:max-h-none lg:flex-1'>
|
||||
{upstreams.map(([key, row]) => {
|
||||
|
||||
@@ -203,6 +203,7 @@ export function SitesPanel(props: {
|
||||
locale,
|
||||
showSymbol: false,
|
||||
abbreviate: false,
|
||||
fullPrecision: true,
|
||||
})}{' '}
|
||||
{balance.currency}
|
||||
</p>
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
import { ErrorState } from '@/components/error-state'
|
||||
import { SectionPageLayout } from '@/components/layout'
|
||||
import { LoadingState } from '@/components/loading-state'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Sheet,
|
||||
@@ -24,8 +23,9 @@ import {
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
|
||||
import { getMonitorState, monitorQueryKey, saveMonitorConfig } from './api'
|
||||
import { BindingsPanel } from './components/bindings-panel'
|
||||
import { BindingDialog, BindingsPanel } from './components/bindings-panel'
|
||||
import { DevicesPanel } from './components/devices-panel'
|
||||
import { EncryptionKeyNotice } from './components/encryption-key-notice'
|
||||
import { FlowsPanel } from './components/flows-panel'
|
||||
import { JobDetail } from './components/job-detail'
|
||||
import { JobsPanel } from './components/jobs-panel'
|
||||
@@ -41,6 +41,7 @@ export function UpstreamMonitor() {
|
||||
const { t } = useTranslation()
|
||||
const client = useQueryClient()
|
||||
const [tab, setTab] = useState('profit')
|
||||
const [bindingGroup, setBindingGroup] = useState<string | null>(null)
|
||||
const [run, setRun] = useState<MonitorAccount | null>(null)
|
||||
const [configure, setConfigure] = useState<{ flow?: MonitorFlow } | null>(
|
||||
null
|
||||
@@ -81,7 +82,9 @@ export function UpstreamMonitor() {
|
||||
{t('Channel cost bindings')}
|
||||
</SheetTrigger>
|
||||
<SheetContent
|
||||
className={sideDrawerContentClassName('sm:w-4/5 sm:max-w-5xl')}
|
||||
className={sideDrawerContentClassName(
|
||||
'sm:w-[90vw] sm:max-w-7xl'
|
||||
)}
|
||||
>
|
||||
<SheetHeader
|
||||
className={sideDrawerHeaderClassName('pr-12 sm:pr-12')}
|
||||
@@ -105,18 +108,7 @@ export function UpstreamMonitor() {
|
||||
)}
|
||||
{state && (
|
||||
<div className='flex h-full min-h-0 flex-col gap-3'>
|
||||
{!state.key_ready && (
|
||||
<Alert variant='destructive'>
|
||||
<AlertTitle>
|
||||
{t('Credential encryption is not configured')}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t(
|
||||
'An administrator must configure the upstream monitor encryption key before saving credentials or running tasks.'
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<EncryptionKeyNotice ready={state.key_ready} />
|
||||
<Tabs
|
||||
value={tab}
|
||||
onValueChange={setTab}
|
||||
@@ -149,7 +141,11 @@ export function UpstreamMonitor() {
|
||||
value='profit'
|
||||
className='min-h-0 flex-1 overflow-y-auto pt-2 lg:overflow-hidden'
|
||||
>
|
||||
<ProfitPanel state={state} onSnapshot={setSnapshotID} />
|
||||
<ProfitPanel
|
||||
state={state}
|
||||
onSnapshot={setSnapshotID}
|
||||
onBind={setBindingGroup}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value='sites'
|
||||
@@ -199,6 +195,14 @@ export function UpstreamMonitor() {
|
||||
)}
|
||||
</SectionPageLayout.Content>
|
||||
</SectionPageLayout>
|
||||
{bindingGroup !== null && state && (
|
||||
<BindingDialog
|
||||
localGroup={bindingGroup}
|
||||
state={state}
|
||||
onSave={save}
|
||||
onClose={() => setBindingGroup(null)}
|
||||
/>
|
||||
)}
|
||||
{run && state && (
|
||||
<RunDialog
|
||||
account={run}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Bind channels in {{group}}",
|
||||
"Channels in local group {{group}}": "Channels in local group {{group}}",
|
||||
"How to configure the encryption key": "How to configure the encryption key",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "For first-time setup, generate a random 32-byte Base64 key on the server:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:",
|
||||
"For docker-compose.dev.yml, use:": "For docker-compose.dev.yml, use:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.",
|
||||
"Select at most 500 estimate mappings.": "Select at most 500 estimate mappings.",
|
||||
"Select each upstream model and group only once.": "Select each upstream model and group only once.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "{{target}} test succeeded",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time",
|
||||
"{{unit}} tokens": "{{unit}} tokens",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "{{updated}} updated · {{failed}} failed · {{skipped}} skipped",
|
||||
"{{value}} more attachments": "{{value}} more attachments",
|
||||
"{{value}} more changes": "{{value}} more changes",
|
||||
"{{value}} more steps are not shown": "{{value}} more steps are not shown",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.",
|
||||
"A password is stored. Leave blank to keep it.": "A password is stored. Leave blank to keep it.",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.",
|
||||
"A release has no verifiable SHA-256 hash.": "A release has no verifiable SHA-256 hash.",
|
||||
"A repair task is already running. Please try again later": "A repair task is already running. Please try again later",
|
||||
"A required upstream unit price is unknown": "A required upstream unit price is unknown",
|
||||
"A security operation is already in progress.": "A security operation is already in progress.",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "Install, configure, test, and remove task plugins.",
|
||||
"Installed": "Installed",
|
||||
"Installed {{name}} v{{version}}": "Installed {{name}} v{{version}}",
|
||||
"Installed code differs from the published release.": "Installed code differs from the published release.",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "Installed v{{from}} → marketplace v{{to}}",
|
||||
"Installed v{{installed}} not listed": "Installed v{{installed}} not listed",
|
||||
"Installed version is not listed by this source": "Installed version is not listed by this source",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "Plugin icon exceeds the 512 KiB limit.",
|
||||
"Plugin icon must be an .svg or .png file.": "Plugin icon must be an .svg or .png file.",
|
||||
"Plugin installation failed": "Plugin installation failed",
|
||||
"Plugin is disabled": "Plugin is disabled",
|
||||
"Plugin is still in use": "Plugin is still in use",
|
||||
"Plugin key": "Plugin key",
|
||||
"Plugin kind": "Plugin kind",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "Revenue factor",
|
||||
"review": "review",
|
||||
"Review": "Review",
|
||||
"Review {{name}}": "Review {{name}}",
|
||||
"Review & initialize": "Review & initialize",
|
||||
"Review and confirm the selected prices.": "Review and confirm the selected prices.",
|
||||
"Review and sign out devices currently using your account.": "Review and sign out devices currently using your account.",
|
||||
"Review and upgrade": "Review and upgrade",
|
||||
"Review changes": "Review changes",
|
||||
"Review confirmation": "Review confirmation",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.",
|
||||
"Review model rates before scaling traffic": "Review model rates before scaling traffic",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "Skip SMTP TLS certificate verification",
|
||||
"Skip to Main": "Skip to Main",
|
||||
"Skip Upstream TLS Verification": "Skip Upstream TLS Verification",
|
||||
"Skipped": "Skipped",
|
||||
"Skipped ({{total}})": "Skipped ({{total}})",
|
||||
"Skipped when it fails": "Skipped when it fails",
|
||||
"Slug": "Slug",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "Slug can only contain letters, numbers, hyphens, and underscores",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:",
|
||||
"The gateway rejected this plugin": "The gateway rejected this plugin",
|
||||
"The guide must start with a level-1 heading": "The guide must start with a level-1 heading",
|
||||
"The installed plugin or the marketplace release changed after review.": "The installed plugin or the marketplace release changed after review.",
|
||||
"The keys and API addresses of the channels that use it": "The keys and API addresses of the channels that use it",
|
||||
"The language in the metadata does not match the file": "The language in the metadata does not match the file",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "The legacy token stops working on {{date}}. Create a new token to replace it.",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "This plugin is disabled or not installed, so the instance does not run. It keeps its settings.",
|
||||
"This project must be used in compliance with the": "This project must be used in compliance with the",
|
||||
"This provider is unavailable for this model.": "This provider is unavailable for this model.",
|
||||
"This release was withdrawn.": "This release was withdrawn.",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "This removes {{count}} failed models from this channel. This action cannot be undone.",
|
||||
"This removes the cost association. The channel remains available.": "This removes the cost association. The channel remains available.",
|
||||
"This reply would be stopped": "This reply would be stopped",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "Up to date",
|
||||
"Up to date on {{count}} nodes": "Up to date on {{count}} nodes",
|
||||
"Update": "Update",
|
||||
"Update all ({{total}})": "Update all ({{total}})",
|
||||
"Update All Balances": "Update All Balances",
|
||||
"Update API Key": "Update API Key",
|
||||
"Update API token": "Update API token",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "Update completed",
|
||||
"Update configuration": "Update configuration",
|
||||
"Update failed": "Update failed",
|
||||
"Update installed plugins": "Update installed plugins",
|
||||
"Update Model": "Update Model",
|
||||
"Update model configuration and click save when you're done.": "Update model configuration and click save when you're done.",
|
||||
"Update plan info": "Update Plan Info",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "Updated successfully",
|
||||
"Updated system setting {{key}}": "Updated system setting {{key}}",
|
||||
"Updated user {{username}} (ID: {{id}})": "Updated user {{username}} (ID: {{id}})",
|
||||
"Updates from {{source}}": "Updates from {{source}}",
|
||||
"Updates have not been checked yet.": "Updates have not been checked yet.",
|
||||
"Updates with the system": "Updates with the system",
|
||||
"Updating": "Updating",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "Upload photo",
|
||||
"Upload plugin": "Upload plugin",
|
||||
"Upload structured results instead of response bodies": "Upload structured results instead of response bodies",
|
||||
"Uploaded, but activation failed.": "Uploaded, but activation failed.",
|
||||
"Uploading...": "Uploading...",
|
||||
"Uppercase and lowercase letters": "Uppercase and lowercase letters",
|
||||
"Upscale": "Upscale",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Lier les canaux du groupe {{group}}",
|
||||
"Channels in local group {{group}}": "Canaux du groupe local {{group}}",
|
||||
"How to configure the encryption key": "Comment configurer la clé de chiffrement",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "Lors de la première configuration, générez sur le serveur une clé aléatoire de 32 octets encodée en Base64 :",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "Dans docker-compose.yml ou docker-compose.dev.yml, repérez la section environment du service new-api. Décommentez UPSTREAM_MONITOR_KEY et remplacez la valeur d’exemple par la clé générée :",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Recréez le conteneur backend pour appliquer la variable d’environnement ; redémarrer le conteneur existant ne charge pas les modifications :",
|
||||
"For docker-compose.dev.yml, use:": "Pour docker-compose.dev.yml, utilisez :",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Remplacez new-api dans ces commandes si votre service backend porte un autre nom. Actualisez cette page après le démarrage du backend.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "Pour un déploiement par exécutable, définissez UPSTREAM_MONITOR_KEY dans l’environnement du backend ou dans le fichier .env de son répertoire de travail, puis redémarrez le backend.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Sauvegardez la clé séparément de la base de données et utilisez la même clé sur tous les nœuds backend. Si des identifiants sont déjà enregistrés, restaurez la clé d’origine au lieu d’en générer une nouvelle.",
|
||||
"Select at most 500 estimate mappings.": "Sélectionnez au maximum 500 correspondances d’estimation.",
|
||||
"Select each upstream model and group only once.": "Sélectionnez chaque combinaison de modèle et groupe amont une seule fois.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Utilisez des noms exacts non vides respectant les limites UTF-8, sans espaces de début ou de fin ni caractères de contrôle.",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "Test de {{target}} réussi",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "{{total}} modèles · {{syncable}} synchronisables · {{skipped}} ignorés cette fois",
|
||||
"{{unit}} tokens": "{{unit}} jetons",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "Mises à jour réussies : {{updated}} · Échecs : {{failed}} · Ignorées : {{skipped}}",
|
||||
"{{value}} more attachments": "{{value}} autres pièces jointes",
|
||||
"{{value}} more changes": "{{value}} autres modifications",
|
||||
"{{value}} more steps are not shown": "{{value}} étapes supplémentaires ne sont pas affichées",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "Une clé d’accès créée pour www.example.com ne fonctionne pas sur example.com. Gardez l’ancien site accessible pour permettre aux utilisateurs de s’y authentifier.",
|
||||
"A password is stored. Leave blank to keep it.": "Un mot de passe est enregistré. Laissez vide pour le conserver.",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "Un plugin peut lire les clés des canaux et modifier ce qui est envoyé au fournisseur. Vérifiez son code et ses changements avant de l’activer.",
|
||||
"A release has no verifiable SHA-256 hash.": "La somme SHA-256 de la version ne peut pas être vérifiée.",
|
||||
"A repair task is already running. Please try again later": "Une tâche de réparation est déjà en cours. Veuillez réessayer plus tard",
|
||||
"A required upstream unit price is unknown": "Un tarif unitaire fournisseur requis est inconnu",
|
||||
"A security operation is already in progress.": "Une opération de sécurité est déjà en cours.",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "Installer, configurer, tester et supprimer des plugins de tâche.",
|
||||
"Installed": "Installés",
|
||||
"Installed {{name}} v{{version}}": "{{name}} v{{version}} installé",
|
||||
"Installed code differs from the published release.": "Le code installé diffère de la version publiée.",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "Installé v{{from}} → marché v{{to}}",
|
||||
"Installed v{{installed}} not listed": "v{{installed}} installée, absente de cette source",
|
||||
"Installed version is not listed by this source": "La version installée n’est pas proposée par cette source",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "L'icône du plugin dépasse la limite de 512 Kio.",
|
||||
"Plugin icon must be an .svg or .png file.": "L'icône du plugin doit être un fichier .svg ou .png.",
|
||||
"Plugin installation failed": "Échec de l’installation du plugin",
|
||||
"Plugin is disabled": "Plugin désactivé",
|
||||
"Plugin is still in use": "Le plugin est encore utilisé",
|
||||
"Plugin key": "Clé du plugin",
|
||||
"Plugin kind": "Type de plugin",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "Facteur de revenu",
|
||||
"review": "À vérifier",
|
||||
"Review": "Vérifier",
|
||||
"Review {{name}}": "Examiner {{name}}",
|
||||
"Review & initialize": "Vérifier et initialiser",
|
||||
"Review and confirm the selected prices.": "Vérifiez et confirmez les prix sélectionnés.",
|
||||
"Review and sign out devices currently using your account.": "Consultez et déconnectez les appareils qui utilisent actuellement votre compte.",
|
||||
"Review and upgrade": "Examiner et mettre à jour",
|
||||
"Review changes": "Voir les changements",
|
||||
"Review confirmation": "Vérifier la confirmation",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "Vérifiez chaque ajout et écrasement avant l’application. Les prix, canaux et droits des groupes restent inchangés.",
|
||||
"Review model rates before scaling traffic": "Consulter les tarifs des modèles avant d'augmenter le trafic",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "Ignorer la vérification du certificat TLS SMTP",
|
||||
"Skip to Main": "Aller au contenu principal",
|
||||
"Skip Upstream TLS Verification": "Ignorer la vérification TLS du serveur amont",
|
||||
"Skipped": "Ignoré",
|
||||
"Skipped ({{total}})": "Ignorés ({{total}})",
|
||||
"Skipped when it fails": "Ignoré en cas d’erreur",
|
||||
"Slug": "Slug",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "Le slug ne peut contenir que des lettres, des chiffres, des tirets et des underscores",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "Les modèles suivants dans la redirection du modèle n'ont pas été ajoutés à la liste \"Modèles\" et peuvent échouer lors de l'invocation en raison de modèles disponibles manquants :",
|
||||
"The gateway rejected this plugin": "La passerelle a rejeté ce plugin",
|
||||
"The guide must start with a level-1 heading": "Le guide doit commencer par un titre de niveau 1",
|
||||
"The installed plugin or the marketplace release changed after review.": "Le plugin installé ou la version du catalogue a changé depuis la vérification.",
|
||||
"The keys and API addresses of the channels that use it": "Les clés et adresses d'API des canaux qui l'utilisent",
|
||||
"The language in the metadata does not match the file": "La langue des métadonnées ne correspond pas au fichier",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "L’ancien jeton cessera de fonctionner le {{date}}. Créez un nouveau jeton pour le remplacer.",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "Ce plugin est désactivé ou n'est pas installé : l'instance ne s'exécute pas, mais conserve ses paramètres.",
|
||||
"This project must be used in compliance with the": "Ce projet doit être utilisé conformément aux",
|
||||
"This provider is unavailable for this model.": "Ce fournisseur est indisponible pour ce modèle.",
|
||||
"This release was withdrawn.": "Cette version a été retirée.",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "Cela supprime {{count}} modèles en échec de ce canal. Cette action est irréversible.",
|
||||
"This removes the cost association. The channel remains available.": "La liaison de coût sera supprimée. Le canal restera disponible.",
|
||||
"This reply would be stopped": "Cette réponse serait interrompue",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "À jour",
|
||||
"Up to date on {{count}} nodes": "À jour sur {{count}} nœuds",
|
||||
"Update": "Mettre à jour",
|
||||
"Update all ({{total}})": "Tout mettre à jour ({{total}})",
|
||||
"Update All Balances": "Mettre à jour tous les soldes",
|
||||
"Update API Key": "Mettre à jour la clé API",
|
||||
"Update API token": "Modifier un jeton API",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "Mise à jour terminée",
|
||||
"Update configuration": "Mettre à jour la configuration",
|
||||
"Update failed": "Échec de la mise à jour",
|
||||
"Update installed plugins": "Mettre à jour les plugins installés",
|
||||
"Update Model": "Mettre à jour le modèle",
|
||||
"Update model configuration and click save when you're done.": "Mettez à jour la configuration du modèle et cliquez sur Enregistrer lorsque vous avez terminé.",
|
||||
"Update plan info": "Mettre à jour les informations du plan",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "Mise à jour réussie",
|
||||
"Updated system setting {{key}}": "Paramètre système {{key}} mis à jour",
|
||||
"Updated user {{username}} (ID: {{id}})": "Utilisateur {{username}} mis à jour (ID : {{id}})",
|
||||
"Updates from {{source}}": "Mises à jour depuis {{source}}",
|
||||
"Updates have not been checked yet.": "Les mises à jour n’ont pas encore été vérifiées.",
|
||||
"Updates with the system": "Mise à jour système",
|
||||
"Updating": "Mise à jour en cours",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "Téléverser une photo",
|
||||
"Upload plugin": "Importer un plugin",
|
||||
"Upload structured results instead of response bodies": "Envoyez les résultats structurés plutôt que le corps des réponses",
|
||||
"Uploaded, but activation failed.": "Version envoyée, mais l’activation a échoué.",
|
||||
"Uploading...": "Importation...",
|
||||
"Uppercase and lowercase letters": "Majuscules et minuscules",
|
||||
"Upscale": "Agrandir",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "{{group}} のチャネルを紐付け",
|
||||
"Channels in local group {{group}}": "ローカルグループ {{group}} のチャネル",
|
||||
"How to configure the encryption key": "暗号化キーの設定方法",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "初回設定時は、サーバー上で32バイトのランダムなキーをBase64形式で生成してください:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "docker-compose.yml または docker-compose.dev.yml で、new-api サービスの environment セクションを探してください。UPSTREAM_MONITOR_KEY のコメントを解除し、プレースホルダーを生成したキーに置き換えてください:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "環境変数を適用するには、バックエンドのコンテナを再作成してください。既存コンテナの再起動では変更は読み込まれません:",
|
||||
"For docker-compose.dev.yml, use:": "docker-compose.dev.yml を使用する場合:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "バックエンドのサービス名が異なる場合は、これらのコマンド内の new-api を置き換えてください。バックエンドの起動後、このページを再読み込みしてください。",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "実行ファイルを直接起動する構成では、バックエンドの環境変数または作業ディレクトリの .env ファイルに UPSTREAM_MONITOR_KEY を設定し、バックエンドを再起動してください。",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "キーはデータベースとは別にバックアップし、すべてのバックエンドノードで同じキーを使用してください。認証情報が保存済みの場合は、新しいキーを生成せず、元のキーを復元してください。",
|
||||
"Select at most 500 estimate mappings.": "推定マッピングは500件以下で選択してください。",
|
||||
"Select each upstream model and group only once.": "上流モデルとグループの組み合わせは1回だけ選択してください。",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "UTF-8の上限内で空でない正確なモデル名とグループ名を使用し、前後の空白や制御文字を含めないでください。",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "{{target}} のテストに成功しました",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "全 {{total}} 件 · 同期可能 {{syncable}} 件 · 今回の対象外 {{skipped}} 件",
|
||||
"{{unit}} tokens": "{{unit}} トークン",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "更新 {{updated}} 件 · 失敗 {{failed}} 件 · スキップ {{skipped}} 件",
|
||||
"{{value}} more attachments": "ほかに {{value}} 件の添付ファイル",
|
||||
"{{value}} more changes": "ほかに {{value}} 件の変更",
|
||||
"{{value}} more steps are not shown": "ほかに {{value}} 件の処理記録は表示されていません",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "www.example.com で作成したパスキーは example.com では使用できません。ユーザーが引き続き認証できるよう、以前のウェブサイトを維持してください。",
|
||||
"A password is stored. Leave blank to keep it.": "パスワードは保存済みです。空欄なら現在の値を保持します。",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "プラグインはチャネルのキーを読み取り、上流に送る内容を変更できます。有効化する前にコードと変更点を確認してください。",
|
||||
"A release has no verifiable SHA-256 hash.": "バージョンの SHA-256 ハッシュを検証できません。",
|
||||
"A repair task is already running. Please try again later": "修復タスクが既に実行中です。後でもう一度お試しください",
|
||||
"A required upstream unit price is unknown": "必要な上流単価が不明です",
|
||||
"A security operation is already in progress.": "セキュリティ操作を実行中です。",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "タスクプラグインのインストール、設定、テスト、削除を行います。",
|
||||
"Installed": "インストール済み",
|
||||
"Installed {{name}} v{{version}}": "{{name}} v{{version}} をインストールしました",
|
||||
"Installed code differs from the published release.": "インストール済みのコードが公開版と異なります。",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "インストール済み v{{from}} → マーケット v{{to}}",
|
||||
"Installed v{{installed}} not listed": "導入済み v{{installed}} は未掲載",
|
||||
"Installed version is not listed by this source": "インストール済みのバージョンはこのソースに掲載されていません",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "プラグインアイコンが 512 KiB の上限を超えています。",
|
||||
"Plugin icon must be an .svg or .png file.": "プラグインアイコンは .svg または .png ファイルである必要があります。",
|
||||
"Plugin installation failed": "プラグインのインストールに失敗しました",
|
||||
"Plugin is disabled": "プラグインは無効です",
|
||||
"Plugin is still in use": "プラグインは使用中です",
|
||||
"Plugin key": "プラグインキー",
|
||||
"Plugin kind": "プラグインの種類",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "収益換算係数",
|
||||
"review": "要確認",
|
||||
"Review": "確認",
|
||||
"Review {{name}}": "{{name}} の変更を確認",
|
||||
"Review & initialize": "確認して初期化",
|
||||
"Review and confirm the selected prices.": "選択した価格変更を確認します。",
|
||||
"Review and sign out devices currently using your account.": "現在アカウントを使用しているデバイスを確認し、サインアウトできます。",
|
||||
"Review and upgrade": "確認してアップグレード",
|
||||
"Review changes": "変更を確認",
|
||||
"Review confirmation": "確認内容を表示",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "追加・上書きする内容を適用前に確認してください。料金、チャネル、グループ権限は変更されません。",
|
||||
"Review model rates before scaling traffic": "トラフィック拡大前にモデル料金を確認",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "SMTP TLS証明書の検証をスキップ",
|
||||
"Skip to Main": "メインコンテンツへスキップ",
|
||||
"Skip Upstream TLS Verification": "上流の TLS 証明書の検証をスキップ",
|
||||
"Skipped": "スキップ",
|
||||
"Skipped ({{total}})": "スキップ({{total}})",
|
||||
"Skipped when it fails": "エラー時はスキップ",
|
||||
"Slug": "スラッグ",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "スラッグには英数字、ハイフン、アンダースコアのみ使用できます",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "モデルリダイレクト内の以下のモデルは\"モデル\"リストに追加されていないため、利用可能なモデルが不足して呼び出しが失敗する可能性があります:",
|
||||
"The gateway rejected this plugin": "ゲートウェイがこのプラグインを拒否しました",
|
||||
"The guide must start with a level-1 heading": "ガイドはレベル 1 の見出しで始めてください",
|
||||
"The installed plugin or the marketplace release changed after review.": "確認後に、インストール済みのプラグインまたはマーケットのバージョンが変更されました。",
|
||||
"The keys and API addresses of the channels that use it": "このプラグインを使うチャネルのキーと API アドレス",
|
||||
"The language in the metadata does not match the file": "メタデータの言語がファイルと一致しません",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "旧形式のトークンは {{date}} に使用できなくなります。新しいトークンを作成して置き換えてください。",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "このプラグインは停止中か未インストールのため、インスタンスは実行されません。設定は保持されます。",
|
||||
"This project must be used in compliance with the": "このプロジェクトは、以下を遵守して使用する必要があります",
|
||||
"This provider is unavailable for this model.": "このプロバイダーでは現在このモデルを利用できません。",
|
||||
"This release was withdrawn.": "このバージョンは公開が取り消されました。",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "この操作はこのチャンネルから失敗した {{count}} 個のモデルを削除します。元に戻せません。",
|
||||
"This removes the cost association. The channel remains available.": "コストの関連付けを削除します。チャネルは引き続き利用できます。",
|
||||
"This reply would be stopped": "この回答は停止されます",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "最新",
|
||||
"Up to date on {{count}} nodes": "{{count}} ノードで反映済み",
|
||||
"Update": "更新",
|
||||
"Update all ({{total}})": "すべて更新({{total}})",
|
||||
"Update All Balances": "すべての残高を更新",
|
||||
"Update API Key": "API キーを更新",
|
||||
"Update API token": "API トークンを更新",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "更新が完了しました",
|
||||
"Update configuration": "設定を更新",
|
||||
"Update failed": "更新に失敗しました",
|
||||
"Update installed plugins": "インストール済みプラグインの更新",
|
||||
"Update Model": "モデルを更新",
|
||||
"Update model configuration and click save when you're done.": "モデル設定を更新し、完了したら保存をクリックしてください。",
|
||||
"Update plan info": "プラン情報を更新",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "正常に更新されました",
|
||||
"Updated system setting {{key}}": "システム設定 {{key}} を更新しました",
|
||||
"Updated user {{username}} (ID: {{id}})": "ユーザー {{username}} を更新しました(ID: {{id}})",
|
||||
"Updates from {{source}}": "更新元:{{source}}",
|
||||
"Updates have not been checked yet.": "更新はまだ確認されていません。",
|
||||
"Updates with the system": "システムとともに更新",
|
||||
"Updating": "更新中",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "写真をアップロード",
|
||||
"Upload plugin": "プラグインをアップロード",
|
||||
"Upload structured results instead of response bodies": "レスポンス本文ではなく構造化された結果を送信してください",
|
||||
"Uploaded, but activation failed.": "アップロードは完了しましたが、有効化に失敗しました。",
|
||||
"Uploading...": "アップロード中...",
|
||||
"Uppercase and lowercase letters": "英大文字と小文字",
|
||||
"Upscale": "アップスケール",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Привязать каналы группы {{group}}",
|
||||
"Channels in local group {{group}}": "Каналы локальной группы {{group}}",
|
||||
"How to configure the encryption key": "Как настроить ключ шифрования",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "При первоначальной настройке сгенерируйте на сервере случайный 32-байтовый ключ в кодировке Base64:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "В docker-compose.yml или docker-compose.dev.yml найдите раздел environment сервиса new-api. Раскомментируйте UPSTREAM_MONITOR_KEY и замените значение-заглушку сгенерированным ключом:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Пересоздайте контейнер бэкенда, чтобы применить переменную окружения; перезапуск существующего контейнера не загружает изменения:",
|
||||
"For docker-compose.dev.yml, use:": "Для docker-compose.dev.yml используйте:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Замените new-api в этих командах, если сервис бэкенда называется иначе. Обновите эту страницу после запуска бэкенда.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "При запуске исполняемого файла напрямую задайте UPSTREAM_MONITOR_KEY в окружении бэкенда или в файле .env в его рабочем каталоге, затем перезапустите бэкенд.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Храните резервную копию ключа отдельно от базы данных и используйте один и тот же ключ на всех узлах бэкенда. Если учётные данные уже сохранены, восстановите исходный ключ вместо создания нового.",
|
||||
"Select at most 500 estimate mappings.": "Выберите не более 500 сопоставлений для оценки.",
|
||||
"Select each upstream model and group only once.": "Каждую пару модели и группы поставщика выбирайте только один раз.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Используйте точные непустые имена моделей и групп в пределах UTF-8, без пробелов по краям и управляющих символов.",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "Тест {{target}} успешно выполнен",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "Моделей: {{total}} · доступно: {{syncable}} · пропускается: {{skipped}}",
|
||||
"{{unit}} tokens": "{{unit}} токенов",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "Обновлено {{updated}} · Ошибок {{failed}} · Пропущено {{skipped}}",
|
||||
"{{value}} more attachments": "Ещё вложений: {{value}}",
|
||||
"{{value}} more changes": "Ещё изменений: {{value}}",
|
||||
"{{value}} more steps are not shown": "Ещё шагов не показано: {{value}}",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "Ключ доступа, созданный для www.example.com, не работает на example.com. Сохраните доступ к прежнему сайту, чтобы пользователи могли проходить проверку на нём.",
|
||||
"A password is stored. Leave blank to keep it.": "Пароль сохранён. Оставьте поле пустым, чтобы сохранить его.",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "Плагин может читать ключи каналов и менять то, что отправляется провайдеру. Проверьте его код и изменения перед активацией.",
|
||||
"A release has no verifiable SHA-256 hash.": "Не удалось проверить хеш SHA-256 версии.",
|
||||
"A repair task is already running. Please try again later": "Задача восстановления уже выполняется. Попробуйте позже",
|
||||
"A required upstream unit price is unknown": "Неизвестна необходимая цена единицы у поставщика",
|
||||
"A security operation is already in progress.": "Операция безопасности уже выполняется.",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "Установка, настройка, проверка и удаление плагинов задач.",
|
||||
"Installed": "Установленные",
|
||||
"Installed {{name}} v{{version}}": "{{name}} v{{version}} установлен",
|
||||
"Installed code differs from the published release.": "Установленный код отличается от опубликованной версии.",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "Установлено v{{from}} → магазин v{{to}}",
|
||||
"Installed v{{installed}} not listed": "v{{installed}} установлена, нет в источнике",
|
||||
"Installed version is not listed by this source": "Установленной версии нет в этом источнике",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "Иконка плагина превышает лимит 512 КиБ.",
|
||||
"Plugin icon must be an .svg or .png file.": "Иконка плагина должна быть файлом .svg или .png.",
|
||||
"Plugin installation failed": "Не удалось установить плагин",
|
||||
"Plugin is disabled": "Плагин отключён",
|
||||
"Plugin is still in use": "Плагин всё ещё используется",
|
||||
"Plugin key": "Ключ плагина",
|
||||
"Plugin kind": "Вид плагина",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "Коэффициент дохода",
|
||||
"review": "Требует проверки",
|
||||
"Review": "Проверить",
|
||||
"Review {{name}}": "Посмотреть изменения в {{name}}",
|
||||
"Review & initialize": "Проверить и инициализировать",
|
||||
"Review and confirm the selected prices.": "Проверьте и подтвердите выбранные цены.",
|
||||
"Review and sign out devices currently using your account.": "Просмотрите устройства, использующие вашу учётную запись, и завершите их сеансы.",
|
||||
"Review and upgrade": "Проверить и обновить",
|
||||
"Review changes": "Посмотреть изменения",
|
||||
"Review confirmation": "Проверить подтверждение",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "Перед применением проверьте каждое добавление и перезапись. Цены, каналы и права групп не изменятся.",
|
||||
"Review model rates before scaling traffic": "Проверьте тарифы моделей перед масштабированием трафика",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "Пропустить проверку TLS-сертификата SMTP",
|
||||
"Skip to Main": "Перейти к основному содержимому",
|
||||
"Skip Upstream TLS Verification": "Пропустить проверку TLS-сертификата upstream-сервера",
|
||||
"Skipped": "Пропущено",
|
||||
"Skipped ({{total}})": "Пропущено ({{total}})",
|
||||
"Skipped when it fails": "Пропускается при сбое",
|
||||
"Slug": "Идентификатор",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "Slug может содержать только буквы, цифры, дефисы и подчёркивания",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "Следующие модели в перенаправлении модели не были добавлены в список \"Модели\" и могут не работать при вызове из-за отсутствия доступных моделей:",
|
||||
"The gateway rejected this plugin": "Шлюз отклонил этот плагин",
|
||||
"The guide must start with a level-1 heading": "Руководство должно начинаться с заголовка первого уровня",
|
||||
"The installed plugin or the marketplace release changed after review.": "После проверки изменился установленный плагин или версия в каталоге.",
|
||||
"The keys and API addresses of the channels that use it": "Ключи и адреса API каналов, которые его используют",
|
||||
"The language in the metadata does not match the file": "Язык в метаданных не совпадает с файлом",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "Устаревший токен перестанет работать {{date}}. Создайте новый токен ему на замену.",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "Этот плагин отключён или не установлен, поэтому экземпляр не запускается. Его настройки сохраняются.",
|
||||
"This project must be used in compliance with the": "Этот проект должен использоваться в соответствии с",
|
||||
"This provider is unavailable for this model.": "Этот провайдер сейчас недоступен для данной модели.",
|
||||
"This release was withdrawn.": "Эта версия отозвана.",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "Это удалит {{count}} неуспешных моделей из этого канала. Действие необратимо.",
|
||||
"This removes the cost association. The channel remains available.": "Будет удалена привязка затрат. Канал останется доступным.",
|
||||
"This reply would be stopped": "Этот ответ будет остановлен",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "Актуален",
|
||||
"Up to date on {{count}} nodes": "Актуально на узлах: {{count}}",
|
||||
"Update": "Обновить",
|
||||
"Update all ({{total}})": "Обновить все ({{total}})",
|
||||
"Update All Balances": "Обновить все балансы",
|
||||
"Update API Key": "Обновить API-ключ",
|
||||
"Update API token": "Изменение токена API",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "Обновление завершено",
|
||||
"Update configuration": "Обновить конфигурацию",
|
||||
"Update failed": "Обновление не удалось",
|
||||
"Update installed plugins": "Обновление установленных плагинов",
|
||||
"Update Model": "Обновить модель",
|
||||
"Update model configuration and click save when you're done.": "Обновите конфигурацию модели и нажмите сохранить, когда закончите.",
|
||||
"Update plan info": "Обновить информацию о плане",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "Обновлено успешно",
|
||||
"Updated system setting {{key}}": "Обновлён системный параметр {{key}}",
|
||||
"Updated user {{username}} (ID: {{id}})": "Обновлён пользователь {{username}} (ID: {{id}})",
|
||||
"Updates from {{source}}": "Источник обновлений — {{source}}",
|
||||
"Updates have not been checked yet.": "Обновления ещё не проверялись.",
|
||||
"Updates with the system": "Обновляется с системой",
|
||||
"Updating": "Обновляется",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "Загрузить фото",
|
||||
"Upload plugin": "Загрузить плагин",
|
||||
"Upload structured results instead of response bodies": "Отправляйте структурированные результаты вместо содержимого ответов",
|
||||
"Uploaded, but activation failed.": "Версия загружена, но активировать её не удалось.",
|
||||
"Uploading...": "Загрузка...",
|
||||
"Uppercase and lowercase letters": "Заглавные и строчные буквы",
|
||||
"Upscale": "Увеличение",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Liên kết các kênh trong {{group}}",
|
||||
"Channels in local group {{group}}": "Các kênh thuộc nhóm cục bộ {{group}}",
|
||||
"How to configure the encryption key": "Cách cấu hình khóa mã hóa",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "Khi thiết lập lần đầu, hãy tạo khóa ngẫu nhiên 32 byte được mã hóa Base64 trên máy chủ:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "Trong docker-compose.yml hoặc docker-compose.dev.yml, tìm mục environment của dịch vụ new-api. Bỏ dấu chú thích của UPSTREAM_MONITOR_KEY và thay giá trị giữ chỗ bằng khóa vừa tạo:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Tạo lại container backend để áp dụng biến môi trường; khởi động lại container hiện có sẽ không nạp các thay đổi:",
|
||||
"For docker-compose.dev.yml, use:": "Với docker-compose.dev.yml, dùng:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Thay new-api trong các lệnh này nếu dịch vụ backend của bạn có tên khác. Làm mới trang này sau khi backend khởi động.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "Khi triển khai bằng cách chạy trực tiếp tệp thực thi, hãy đặt UPSTREAM_MONITOR_KEY trong môi trường backend hoặc tệp .env ở thư mục làm việc của backend, rồi khởi động lại backend.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Sao lưu khóa riêng biệt với cơ sở dữ liệu và dùng cùng một khóa trên mọi nút backend. Nếu đã lưu thông tin xác thực, hãy khôi phục khóa gốc thay vì tạo khóa thay thế.",
|
||||
"Select at most 500 estimate mappings.": "Chọn tối đa 500 ánh xạ ước tính.",
|
||||
"Select each upstream model and group only once.": "Chỉ chọn mỗi cặp mô hình và nhóm thượng nguồn một lần.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Dùng tên mô hình và nhóm chính xác, không rỗng, trong giới hạn UTF-8, không có khoảng trắng đầu cuối hoặc ký tự điều khiển.",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "Kiểm tra {{target}} thành công",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "{{total}} mô hình · {{syncable}} có thể đồng bộ · {{skipped}} bỏ qua lần này",
|
||||
"{{unit}} tokens": "{{unit}} token",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "Đã cập nhật {{updated}} · Thất bại {{failed}} · Bỏ qua {{skipped}}",
|
||||
"{{value}} more attachments": "Còn {{value}} tệp đính kèm khác",
|
||||
"{{value}} more changes": "Còn {{value}} thay đổi khác",
|
||||
"{{value}} more steps are not shown": "Còn {{value}} bước không được hiển thị",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "Khóa truy cập tạo cho www.example.com không thể dùng trên example.com. Hãy duy trì trang web cũ để người dùng vẫn có thể xác minh tại đó.",
|
||||
"A password is stored. Leave blank to keep it.": "Đã lưu mật khẩu. Để trống để giữ nguyên.",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "Plugin có thể đọc khóa của kênh và thay đổi nội dung gửi lên nhà cung cấp. Hãy kiểm tra mã và các thay đổi trước khi kích hoạt.",
|
||||
"A release has no verifiable SHA-256 hash.": "Không thể xác minh mã SHA-256 của phiên bản.",
|
||||
"A repair task is already running. Please try again later": "Đã có tác vụ sửa chữa đang chạy. Vui lòng thử lại sau",
|
||||
"A required upstream unit price is unknown": "Chưa rõ đơn giá thượng nguồn bắt buộc",
|
||||
"A security operation is already in progress.": "Một thao tác bảo mật đang được thực hiện.",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "Cài đặt, cấu hình, kiểm tra và gỡ bỏ plugin tác vụ.",
|
||||
"Installed": "Đã cài đặt",
|
||||
"Installed {{name}} v{{version}}": "Đã cài {{name}} v{{version}}",
|
||||
"Installed code differs from the published release.": "Mã đã cài khác với phiên bản đã phát hành.",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "Đã cài v{{from}} → chợ v{{to}}",
|
||||
"Installed v{{installed}} not listed": "Đã cài v{{installed}}, nguồn không có",
|
||||
"Installed version is not listed by this source": "Nguồn này không có phiên bản đã cài đặt",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "Biểu tượng plugin vượt quá giới hạn 512 KiB.",
|
||||
"Plugin icon must be an .svg or .png file.": "Biểu tượng plugin phải là tệp .svg hoặc .png.",
|
||||
"Plugin installation failed": "Cài đặt plugin thất bại",
|
||||
"Plugin is disabled": "Plugin đã tắt",
|
||||
"Plugin is still in use": "Plugin vẫn đang được sử dụng",
|
||||
"Plugin key": "Khóa plugin",
|
||||
"Plugin kind": "Loại plugin",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "Hệ số doanh thu",
|
||||
"review": "Cần xem xét",
|
||||
"Review": "Xem lại",
|
||||
"Review {{name}}": "Xem thay đổi của {{name}}",
|
||||
"Review & initialize": "Xem lại và khởi tạo",
|
||||
"Review and confirm the selected prices.": "Kiểm tra và xác nhận các giá đã chọn.",
|
||||
"Review and sign out devices currently using your account.": "Xem lại và đăng xuất các thiết bị hiện đang sử dụng tài khoản của bạn.",
|
||||
"Review and upgrade": "Xem lại và nâng cấp",
|
||||
"Review changes": "Xem thay đổi",
|
||||
"Review confirmation": "Kiểm tra và xác nhận",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "Kiểm tra từng mục thêm và ghi đè trước khi áp dụng. Giá, kênh và quyền nhóm không thay đổi.",
|
||||
"Review model rates before scaling traffic": "Xem giá mô hình trước khi mở rộng lưu lượng",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "Bỏ qua xác minh chứng chỉ TLS SMTP",
|
||||
"Skip to Main": "Bỏ qua đến nội dung chính",
|
||||
"Skip Upstream TLS Verification": "Bỏ qua xác minh chứng chỉ TLS của upstream",
|
||||
"Skipped": "Đã bỏ qua",
|
||||
"Skipped ({{total}})": "Đã bỏ qua ({{total}})",
|
||||
"Skipped when it fails": "Bỏ qua khi lỗi",
|
||||
"Slug": "Slug",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "Slug chỉ có thể chứa chữ cái, số, dấu gạch ngang và dấu gạch dưới",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "Các mô hình sau trong chuyển hướng mô hình chưa được thêm vào danh sách \"Mô hình\" và có thể gọi thất bại do thiếu các mô hình có sẵn:",
|
||||
"The gateway rejected this plugin": "Cổng đã từ chối plugin này",
|
||||
"The guide must start with a level-1 heading": "Hướng dẫn phải bắt đầu bằng tiêu đề cấp 1",
|
||||
"The installed plugin or the marketplace release changed after review.": "Plugin đã cài hoặc bản phát hành trên kho đã thay đổi sau khi xem xét.",
|
||||
"The keys and API addresses of the channels that use it": "Khóa và địa chỉ API của các kênh dùng nó",
|
||||
"The language in the metadata does not match the file": "Ngôn ngữ trong siêu dữ liệu không khớp với tệp",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "Token cũ sẽ ngừng hoạt động vào {{date}}. Hãy tạo token mới để thay thế.",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "Plugin này đã tắt hoặc chưa được cài, nên phiên bản không chạy. Cài đặt vẫn được giữ.",
|
||||
"This project must be used in compliance with the": "Dự án này phải được sử dụng tuân thủ theo",
|
||||
"This provider is unavailable for this model.": "Nhà cung cấp này hiện không hỗ trợ mô hình này.",
|
||||
"This release was withdrawn.": "Phiên bản này đã bị thu hồi.",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "Thao tác này sẽ xóa {{count}} mô hình thất bại khỏi kênh này. Không thể hoàn tác.",
|
||||
"This removes the cost association. The channel remains available.": "Thao tác xóa liên kết chi phí. Kênh vẫn khả dụng.",
|
||||
"This reply would be stopped": "Câu trả lời này sẽ bị dừng",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "Đã mới nhất",
|
||||
"Up to date on {{count}} nodes": "Đã áp dụng trên {{count}} nút",
|
||||
"Update": "Cập nhật",
|
||||
"Update all ({{total}})": "Cập nhật tất cả ({{total}})",
|
||||
"Update All Balances": "Cập nhật tất cả số dư",
|
||||
"Update API Key": "Cập nhật Khóa API",
|
||||
"Update API token": "Cập nhật mã thông báo API",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "Cập nhật hoàn tất",
|
||||
"Update configuration": "Cập nhật cấu hình",
|
||||
"Update failed": "Cập nhật thất bại",
|
||||
"Update installed plugins": "Cập nhật các plugin đã cài",
|
||||
"Update Model": "Cập nhật mô hình",
|
||||
"Update model configuration and click save when you're done.": "Cập nhật cấu hình mô hình và nhấp lưu khi bạn hoàn tất.",
|
||||
"Update plan info": "Cập nhật thông tin gói",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "Cập nhật thành công",
|
||||
"Updated system setting {{key}}": "Đã cập nhật cài đặt hệ thống {{key}}",
|
||||
"Updated user {{username}} (ID: {{id}})": "Đã cập nhật người dùng {{username}} (ID: {{id}})",
|
||||
"Updates from {{source}}": "Nguồn cập nhật là {{source}}",
|
||||
"Updates have not been checked yet.": "Chưa kiểm tra cập nhật.",
|
||||
"Updates with the system": "Cập nhật cùng hệ thống",
|
||||
"Updating": "Đang cập nhật",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "Tải ảnh lên",
|
||||
"Upload plugin": "Tải plugin lên",
|
||||
"Upload structured results instead of response bodies": "Hãy gửi kết quả có cấu trúc thay vì nội dung phản hồi",
|
||||
"Uploaded, but activation failed.": "Đã tải lên phiên bản mới nhưng kích hoạt thất bại.",
|
||||
"Uploading...": "Đang tải lên...",
|
||||
"Uppercase and lowercase letters": "Có chữ hoa và chữ thường",
|
||||
"Upscale": "Phóng to",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "綁定 {{group}} 下的渠道",
|
||||
"Channels in local group {{group}}": "本站群組:{{group}}",
|
||||
"How to configure the encryption key": "如何設定加密金鑰",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "首次設定時,請在伺服器上產生一個以 Base64 編碼的 32 位元組隨機金鑰:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "在 docker-compose.yml 或 docker-compose.dev.yml 中找到 new-api 服務的 environment 設定區段。取消 UPSTREAM_MONITOR_KEY 的註解,並將預留值替換為產生的金鑰:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "請重新建立後端容器以套用環境變數;重新啟動現有容器不會載入這些變更:",
|
||||
"For docker-compose.dev.yml, use:": "使用 docker-compose.dev.yml 時,請執行:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "若後端服務名稱不同,請替換這些命令中的 new-api。後端啟動後,請重新整理此頁面。",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "直接執行可執行檔部署時,請在後端環境變數或其工作目錄中的 .env 檔案內設定 UPSTREAM_MONITOR_KEY,然後重新啟動後端。",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "請將金鑰與資料庫分開備份,並在所有後端節點上使用相同金鑰。若已儲存憑證,請還原原本金鑰,勿產生新金鑰取代。",
|
||||
"Select at most 500 estimate mappings.": "最多選擇 500 條估算對應。",
|
||||
"Select each upstream model and group only once.": "每個上游模型和群組組合只能選擇一次。",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "請使用非空且符合 UTF-8 位元組限制的精確模型名和群組名,不得包含首尾空格或控制字元。",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "{{target}} 測試成功",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "共 {{total}} 個模型 · 可同步 {{syncable}} · 本次不處理 {{skipped}}",
|
||||
"{{unit}} tokens": "{{unit}} token",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "已更新 {{updated}} 個 · 失敗 {{failed}} 個 · 略過 {{skipped}} 個",
|
||||
"{{value}} more attachments": "另有 {{value}} 個附件",
|
||||
"{{value}} more changes": "另有 {{value}} 處",
|
||||
"{{value}} more steps are not shown": "另有 {{value}} 筆處理記錄未顯示",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "為 www.example.com 建立的通行金鑰無法在 example.com 使用。請保留舊網站,讓使用者仍能在該網站驗證。",
|
||||
"A password is stored. Leave blank to keep it.": "已儲存密碼,留空則保留。",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "外掛可以讀取渠道金鑰,並修改發往上游的內容。啟用前請檢查它的程式碼和變更。",
|
||||
"A release has no verifiable SHA-256 hash.": "缺少可驗證的 SHA-256 雜湊值。",
|
||||
"A repair task is already running. Please try again later": "已經有一個修復任務在執行中,請稍後再試",
|
||||
"A required upstream unit price is unknown": "缺少必要的上游單價",
|
||||
"A security operation is already in progress.": "已有安全操作正在進行。",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "安裝、設定、測試和移除任務外掛。",
|
||||
"Installed": "已安裝",
|
||||
"Installed {{name}} v{{version}}": "已安裝 {{name}} v{{version}}",
|
||||
"Installed code differs from the published release.": "本機原始碼與已發布版本不同。",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "已安裝 v{{from}} → 市集 v{{to}}",
|
||||
"Installed v{{installed}} not listed": "已裝 v{{installed}},該來源未收錄",
|
||||
"Installed version is not listed by this source": "該來源未列出已安裝的版本",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "外掛圖示超過 512 KiB 限制。",
|
||||
"Plugin icon must be an .svg or .png file.": "外掛圖示必須是 .svg 或 .png 檔案。",
|
||||
"Plugin installation failed": "外掛安裝失敗",
|
||||
"Plugin is disabled": "外掛已停用",
|
||||
"Plugin is still in use": "外掛仍在使用中",
|
||||
"Plugin key": "外掛键",
|
||||
"Plugin kind": "外掛類型",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "收入換算係數",
|
||||
"review": "待審核",
|
||||
"Review": "查看",
|
||||
"Review {{name}}": "檢視「{{name}}」的變更",
|
||||
"Review & initialize": "審核並初始化",
|
||||
"Review and confirm the selected prices.": "確認所選模型的價格變更。",
|
||||
"Review and sign out devices currently using your account.": "查看並登出目前正在使用您帳號的裝置。",
|
||||
"Review and upgrade": "審查並升級",
|
||||
"Review changes": "檢視變更",
|
||||
"Review confirmation": "檢查並確認",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "套用前逐項檢查新增及覆寫內容,定價、渠道及分組權限不會變更。",
|
||||
"Review model rates before scaling traffic": "擴展流量前查看模型費率",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "跳過 SMTP TLS 證書驗證",
|
||||
"Skip to Main": "跳到主內容",
|
||||
"Skip Upstream TLS Verification": "忽略上游證書驗證",
|
||||
"Skipped": "已略過",
|
||||
"Skipped ({{total}})": "已略過({{total}})",
|
||||
"Skipped when it fails": "出錯時略過",
|
||||
"Slug": "標識符",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "Slug 只能包含字母、數字、連字符和底線",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "模型重新導向裡的下列模型尚未新增到「模型」列表,呼叫時會因為缺少可用模型而失敗:",
|
||||
"The gateway rejected this plugin": "閘道拒絕了該外掛",
|
||||
"The guide must start with a level-1 heading": "使用說明必須以一級標題開頭",
|
||||
"The installed plugin or the marketplace release changed after review.": "檢視清單後,已安裝外掛或市集版本已有變更。",
|
||||
"The keys and API addresses of the channels that use it": "使用它的渠道的金鑰和 API 位址",
|
||||
"The language in the metadata does not match the file": "中繼資料裡的語言和檔案不一致",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "舊版令牌將於 {{date}} 停用,請建立新令牌替換。",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "此外掛已停用或未安裝,實例不會執行,設定會保留。",
|
||||
"This project must be used in compliance with the": "此項目的使用必須遵守",
|
||||
"This provider is unavailable for this model.": "此服務方目前無法提供此模型。",
|
||||
"This release was withdrawn.": "此版本已下架。",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "此操作將從該渠道移除 {{count}} 個測試失敗的模型,且無法撤銷。",
|
||||
"This removes the cost association. The channel remains available.": "此操作會移除成本關聯,通道仍然可用。",
|
||||
"This reply would be stopped": "這則回覆會被中止",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "已是最新",
|
||||
"Up to date on {{count}} nodes": "已在 {{count}} 個節點生效",
|
||||
"Update": "更新",
|
||||
"Update all ({{total}})": "全部更新({{total}})",
|
||||
"Update All Balances": "更新所有餘額",
|
||||
"Update API Key": "更新 API 金鑰",
|
||||
"Update API token": "更新 API 權杖",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "更新完成",
|
||||
"Update configuration": "更新設定",
|
||||
"Update failed": "更新失敗",
|
||||
"Update installed plugins": "更新已安裝的外掛",
|
||||
"Update Model": "更新模型",
|
||||
"Update model configuration and click save when you're done.": "更新模型設定,完成後點擊儲存。",
|
||||
"Update plan info": "更新套餐資訊",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "更新成功",
|
||||
"Updated system setting {{key}}": "修改系統設定 {{key}}",
|
||||
"Updated user {{username}} (ID: {{id}})": "更新用戶 {{username}}(ID: {{id}})",
|
||||
"Updates from {{source}}": "來自{{source}}",
|
||||
"Updates have not been checked yet.": "尚未檢查更新。",
|
||||
"Updates with the system": "隨系統更新",
|
||||
"Updating": "更新中",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "上傳相片",
|
||||
"Upload plugin": "上傳外掛",
|
||||
"Upload structured results instead of response bodies": "請上傳結構化結果,不要上傳回應本文",
|
||||
"Uploaded, but activation failed.": "新版已上傳,啟用失敗。",
|
||||
"Uploading...": "上傳中...",
|
||||
"Uppercase and lowercase letters": "同時包含大寫和小寫字母",
|
||||
"Upscale": "放大",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "绑定 {{group}} 下的渠道",
|
||||
"Channels in local group {{group}}": "本站分组:{{group}}",
|
||||
"How to configure the encryption key": "如何配置加密密钥",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "首次配置时,请在服务器上生成一个以 Base64 编码的 32 字节随机密钥:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "在 docker-compose.yml 或 docker-compose.dev.yml 中找到 new-api 服务的 environment 配置段。取消 UPSTREAM_MONITOR_KEY 的注释,并将占位值替换为生成的密钥:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "请重新创建后端容器以应用环境变量;重启现有容器不会加载这些更改:",
|
||||
"For docker-compose.dev.yml, use:": "使用 docker-compose.dev.yml 时,请执行:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "若后端服务名称不同,请替换这些命令中的 new-api。后端启动后,请刷新此页面。",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "直接运行可执行文件部署时,请在后端环境变量或其工作目录中的 .env 文件内设置 UPSTREAM_MONITOR_KEY,然后重启后端。",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "请将密钥与数据库分开备份,并在所有后端节点上使用同一密钥。若已保存凭据,请恢复原密钥,不要生成新密钥替换。",
|
||||
"Select at most 500 estimate mappings.": "最多选择 500 条估算映射。",
|
||||
"Select each upstream model and group only once.": "每个上游模型和分组组合只能选择一次。",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "请使用非空且符合 UTF-8 字节限制的精确模型名和分组名,不得包含首尾空格或控制字符。",
|
||||
@@ -391,6 +401,7 @@
|
||||
"{{target}} test succeeded": "{{target}} 测试成功",
|
||||
"{{total}} models · {{syncable}} syncable · {{skipped}} skipped this time": "共 {{total}} 个模型 · 可同步 {{syncable}} · 本次不处理 {{skipped}}",
|
||||
"{{unit}} tokens": "{{unit}} token",
|
||||
"{{updated}} updated · {{failed}} failed · {{skipped}} skipped": "已更新 {{updated}} 个 · 失败 {{failed}} 个 · 跳过 {{skipped}} 个",
|
||||
"{{value}} more attachments": "另有 {{value}} 个附件",
|
||||
"{{value}} more changes": "另有 {{value}} 处",
|
||||
"{{value}} more steps are not shown": "另有 {{value}} 条处理记录未显示",
|
||||
@@ -478,6 +489,7 @@
|
||||
"A Passkey created for www.example.com cannot be used on example.com. Keep the old website available so users can still verify there.": "为 www.example.com 创建的通行密钥无法在 example.com 使用。请保留旧网站,让用户仍能在那里验证。",
|
||||
"A password is stored. Leave blank to keep it.": "已保存密码,留空则保留。",
|
||||
"A plugin can read channel keys and change what is sent upstream. Check its code and changes before activating it.": "插件可以读取渠道密钥,并修改发往上游的内容。激活前请检查它的代码和改动。",
|
||||
"A release has no verifiable SHA-256 hash.": "缺少可验证的 SHA-256 校验值。",
|
||||
"A repair task is already running. Please try again later": "已经有一个修复任务在运行中,请稍后再试",
|
||||
"A required upstream unit price is unknown": "缺少必需的上游单价",
|
||||
"A security operation is already in progress.": "已有安全操作正在进行。",
|
||||
@@ -3866,6 +3878,7 @@
|
||||
"Install, configure, test, and remove task plugins.": "安装、配置、测试和移除任务插件。",
|
||||
"Installed": "已安装",
|
||||
"Installed {{name}} v{{version}}": "已安装 {{name}} v{{version}}",
|
||||
"Installed code differs from the published release.": "本地源码与已发布版本不一致。",
|
||||
"Installed v{{from}} → marketplace v{{to}}": "已安装 v{{from}} → 市场 v{{to}}",
|
||||
"Installed v{{installed}} not listed": "已装 v{{installed}},该源未收录",
|
||||
"Installed version is not listed by this source": "该源未列出已安装的版本",
|
||||
@@ -5638,6 +5651,7 @@
|
||||
"Plugin icon exceeds the 512 KiB limit.": "插件图标超过 512 KiB 限制。",
|
||||
"Plugin icon must be an .svg or .png file.": "插件图标必须是 .svg 或 .png 文件。",
|
||||
"Plugin installation failed": "插件安装失败",
|
||||
"Plugin is disabled": "插件已停用",
|
||||
"Plugin is still in use": "插件仍在使用中",
|
||||
"Plugin key": "插件键",
|
||||
"Plugin kind": "插件类型",
|
||||
@@ -6365,10 +6379,12 @@
|
||||
"Revenue factor": "收入换算系数",
|
||||
"review": "待审核",
|
||||
"Review": "查看",
|
||||
"Review {{name}}": "查看「{{name}}」的变更",
|
||||
"Review & initialize": "审核并初始化",
|
||||
"Review and confirm the selected prices.": "确认所选模型的价格变更。",
|
||||
"Review and sign out devices currently using your account.": "查看并退出当前正在使用您账号的设备。",
|
||||
"Review and upgrade": "审查并升级",
|
||||
"Review changes": "查看变更",
|
||||
"Review confirmation": "检查并确认",
|
||||
"Review every addition and overwrite before applying. Pricing, channels, and group access are not changed.": "应用前逐项检查新增和覆盖内容,定价、渠道及分组权限不会改变。",
|
||||
"Review model rates before scaling traffic": "扩展流量前查看模型费率",
|
||||
@@ -6909,6 +6925,8 @@
|
||||
"Skip SMTP TLS certificate verification": "跳过 SMTP TLS 证书验证",
|
||||
"Skip to Main": "跳到主内容",
|
||||
"Skip Upstream TLS Verification": "忽略上游证书校验",
|
||||
"Skipped": "已跳过",
|
||||
"Skipped ({{total}})": "已跳过({{total}})",
|
||||
"Skipped when it fails": "出错时跳过",
|
||||
"Slug": "标识符",
|
||||
"Slug can only contain letters, numbers, hyphens, and underscores": "Slug 只能包含字母、数字、连字符和下划线",
|
||||
@@ -7351,6 +7369,7 @@
|
||||
"The following models in the model redirect have not been added to the \"Models\" list and may fail during invocation due to missing available models:": "模型重定向里的下列模型尚未添加到\"模型\"列表,调用时会因为缺少可用模型而失败:",
|
||||
"The gateway rejected this plugin": "网关拒绝了该插件",
|
||||
"The guide must start with a level-1 heading": "使用说明必须以一级标题开头",
|
||||
"The installed plugin or the marketplace release changed after review.": "查看清单后,已安装插件或市场版本发生了变化。",
|
||||
"The keys and API addresses of the channels that use it": "使用它的渠道的密钥和 API 地址",
|
||||
"The language in the metadata does not match the file": "元数据里的语言和文件不一致",
|
||||
"The legacy token stops working on {{date}}. Create a new token to replace it.": "旧版令牌将于 {{date}} 停用,请创建新令牌替换。",
|
||||
@@ -7534,6 +7553,7 @@
|
||||
"This plugin is disabled or not installed, so the instance does not run. It keeps its settings.": "此插件已停用或未安装,实例不会运行,设置会保留。",
|
||||
"This project must be used in compliance with the": "此项目的使用必须遵守",
|
||||
"This provider is unavailable for this model.": "此服务方当前无法提供该模型。",
|
||||
"This release was withdrawn.": "此版本已下架。",
|
||||
"This removes {{count}} failed models from this channel. This action cannot be undone.": "此操作将从该渠道移除 {{count}} 个测试失败的模型,且无法撤销。",
|
||||
"This removes the cost association. The channel remains available.": "此操作会移除成本关联,渠道仍然可用。",
|
||||
"This reply would be stopped": "这条回复会被中止",
|
||||
@@ -7928,6 +7948,7 @@
|
||||
"Up to date": "已是最新",
|
||||
"Up to date on {{count}} nodes": "已在 {{count}} 个节点生效",
|
||||
"Update": "更新",
|
||||
"Update all ({{total}})": "更新全部({{total}})",
|
||||
"Update All Balances": "更新所有余额",
|
||||
"Update API Key": "更新 API 密钥",
|
||||
"Update API token": "更新 API 令牌",
|
||||
@@ -7941,6 +7962,7 @@
|
||||
"Update completed": "更新完成",
|
||||
"Update configuration": "更新配置",
|
||||
"Update failed": "更新失败",
|
||||
"Update installed plugins": "更新已安装插件",
|
||||
"Update Model": "更新模型",
|
||||
"Update model configuration and click save when you're done.": "更新模型配置,完成后点击保存。",
|
||||
"Update plan info": "更新套餐信息",
|
||||
@@ -7976,6 +7998,7 @@
|
||||
"Updated successfully": "更新成功",
|
||||
"Updated system setting {{key}}": "修改系统设置 {{key}}",
|
||||
"Updated user {{username}} (ID: {{id}})": "更新用户 {{username}}(ID: {{id}})",
|
||||
"Updates from {{source}}": "来自{{source}}",
|
||||
"Updates have not been checked yet.": "尚未检查更新。",
|
||||
"Updates with the system": "随系统更新",
|
||||
"Updating": "更新中",
|
||||
@@ -7998,6 +8021,7 @@
|
||||
"Upload photo": "上传照片",
|
||||
"Upload plugin": "上传插件",
|
||||
"Upload structured results instead of response bodies": "请上传结构化结果,不要上传响应正文",
|
||||
"Uploaded, but activation failed.": "新版已上传,激活失败。",
|
||||
"Uploading...": "上传中...",
|
||||
"Uppercase and lowercase letters": "同时包含大写和小写字母",
|
||||
"Upscale": "放大",
|
||||
|
||||
Reference in new issue
Block a user